blob: 866fb83b140bb0b6e4c6f2c499746d3f5966176e [file] [log] [blame]
Chris Lattner28537df2002-05-07 18:07:59 +00001//===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner28537df2002-05-07 18:07:59 +00009//
10// This family of functions perform manipulations on basic blocks, and
11// instructions contained within basic blocks.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnera5b11702008-04-21 01:28:02 +000016#include "llvm/Analysis/AliasAnalysis.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000017#include "llvm/Analysis/CFG.h"
Chris Lattnerf6ae9042011-01-11 08:13:40 +000018#include "llvm/Analysis/LoopInfo.h"
19#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Constant.h"
21#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000022#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Function.h"
24#include "llvm/IR/Instructions.h"
25#include "llvm/IR/IntrinsicInst.h"
26#include "llvm/IR/Type.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000027#include "llvm/IR/ValueHandle.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/Transforms/Scalar.h"
30#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28537df2002-05-07 18:07:59 +000031#include <algorithm>
Chris Lattnerdf3c3422004-01-09 06:12:26 +000032using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000033
Chris Lattner7eb270e2008-12-03 06:40:52 +000034/// DeleteDeadBlock - Delete the specified block, which must have no
35/// predecessors.
36void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner37e01362008-12-03 07:45:15 +000037 assert((pred_begin(BB) == pred_end(BB) ||
38 // Can delete self loop.
39 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattnerbcc904a2008-12-03 06:37:44 +000040 TerminatorInst *BBTerm = BB->getTerminator();
Jakub Staszak190db2f2013-01-14 23:16:36 +000041
Chris Lattnerbcc904a2008-12-03 06:37:44 +000042 // Loop through all of our successors and make sure they know that one
43 // of their predecessors is going away.
44 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
45 BBTerm->getSuccessor(i)->removePredecessor(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +000046
Chris Lattnerbcc904a2008-12-03 06:37:44 +000047 // Zap all the instructions in the block.
48 while (!BB->empty()) {
49 Instruction &I = BB->back();
50 // If this instruction is used, replace uses with an arbitrary value.
51 // Because control flow can't get here, we don't care what we replace the
52 // value with. Note that since this block is unreachable, and all values
53 // contained within it must dominate their uses, that all uses will
54 // eventually be removed (they are themselves dead).
55 if (!I.use_empty())
Owen Andersonb292b8c2009-07-30 23:03:37 +000056 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattnerbcc904a2008-12-03 06:37:44 +000057 BB->getInstList().pop_back();
58 }
Jakub Staszak190db2f2013-01-14 23:16:36 +000059
Chris Lattnerbcc904a2008-12-03 06:37:44 +000060 // Zap the block!
61 BB->eraseFromParent();
Chris Lattnerbcc904a2008-12-03 06:37:44 +000062}
63
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000064/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
65/// any single-entry PHI nodes in it, fold them away. This handles the case
66/// when all entries to the PHI nodes in a block are guaranteed equal, such as
67/// when the block has exactly one predecessor.
Chandler Carruth5eee8952015-01-18 01:45:07 +000068void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, AliasAnalysis *AA,
69 MemoryDependenceAnalysis *MemDep) {
Chris Lattnerf6ae9042011-01-11 08:13:40 +000070 if (!isa<PHINode>(BB->begin())) return;
Jakub Staszak190db2f2013-01-14 23:16:36 +000071
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000072 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
73 if (PN->getIncomingValue(0) != PN)
74 PN->replaceAllUsesWith(PN->getIncomingValue(0));
75 else
Owen Andersonb292b8c2009-07-30 23:03:37 +000076 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Jakub Staszak190db2f2013-01-14 23:16:36 +000077
Chris Lattnerf6ae9042011-01-11 08:13:40 +000078 if (MemDep)
79 MemDep->removeInstruction(PN); // Memdep updates AA itself.
80 else if (AA && isa<PointerType>(PN->getType()))
81 AA->deleteValue(PN);
Jakub Staszak190db2f2013-01-14 23:16:36 +000082
Chris Lattnerdc3f6f22008-12-03 19:44:02 +000083 PN->eraseFromParent();
84 }
85}
86
87
Dan Gohmanff089952009-05-02 18:29:22 +000088/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
89/// is dead. Also recursively delete any operands that become dead as
90/// a result. This includes tracing the def-use list from the PHI to see if
Dan Gohman48f82222009-05-04 22:30:44 +000091/// it is ultimately unused or if it reaches an unused cycle.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +000092bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
Dan Gohmanff089952009-05-02 18:29:22 +000093 // Recursively deleting a PHI may cause multiple PHIs to be deleted
94 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
95 SmallVector<WeakVH, 8> PHIs;
96 for (BasicBlock::iterator I = BB->begin();
97 PHINode *PN = dyn_cast<PHINode>(I); ++I)
98 PHIs.push_back(PN);
99
Dan Gohmancb99fe92010-01-05 15:45:31 +0000100 bool Changed = false;
Dan Gohmanff089952009-05-02 18:29:22 +0000101 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
102 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000103 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
Dan Gohmancb99fe92010-01-05 15:45:31 +0000104
105 return Changed;
Dan Gohmanff089952009-05-02 18:29:22 +0000106}
107
Dan Gohman2d02ff82009-10-31 17:33:01 +0000108/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
109/// if possible. The return value indicates success or failure.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000110bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT,
111 LoopInfo *LI, AliasAnalysis *AA,
112 MemoryDependenceAnalysis *MemDep) {
Dan Gohman941020e2010-08-17 17:07:02 +0000113 // Don't merge away blocks who have their address taken.
114 if (BB->hasAddressTaken()) return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000115
Dan Gohman941020e2010-08-17 17:07:02 +0000116 // Can't merge if there are multiple predecessors, or no predecessors.
117 BasicBlock *PredBB = BB->getUniquePredecessor();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000118 if (!PredBB) return false;
Dan Gohman941020e2010-08-17 17:07:02 +0000119
Dan Gohman2d02ff82009-10-31 17:33:01 +0000120 // Don't break self-loops.
121 if (PredBB == BB) return false;
122 // Don't break invokes.
123 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000124
Dan Gohman2d02ff82009-10-31 17:33:01 +0000125 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
Chris Lattner930b7162011-01-08 19:08:40 +0000126 BasicBlock *OnlySucc = BB;
Dan Gohman2d02ff82009-10-31 17:33:01 +0000127 for (; SI != SE; ++SI)
128 if (*SI != OnlySucc) {
Craig Topperf40110f2014-04-25 05:29:35 +0000129 OnlySucc = nullptr; // There are multiple distinct successors!
Dan Gohman2d02ff82009-10-31 17:33:01 +0000130 break;
131 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000132
Dan Gohman2d02ff82009-10-31 17:33:01 +0000133 // Can't merge if there are multiple successors.
134 if (!OnlySucc) return false;
Devang Patel0f7a3502008-09-09 01:06:56 +0000135
Dan Gohman2d02ff82009-10-31 17:33:01 +0000136 // Can't merge if there is PHI loop.
137 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
138 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
139 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
140 if (PN->getIncomingValue(i) == PN)
141 return false;
142 } else
143 break;
144 }
145
146 // Begin by getting rid of unneeded PHIs.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000147 if (isa<PHINode>(BB->front()))
Chandler Carruth5eee8952015-01-18 01:45:07 +0000148 FoldSingleEntryPHINodes(BB, AA, MemDep);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000149
Owen Andersonc0623812008-07-17 00:01:40 +0000150 // Delete the unconditional branch from the predecessor...
151 PredBB->getInstList().pop_back();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000152
Owen Andersonc0623812008-07-17 00:01:40 +0000153 // Make all PHI nodes that referred to BB now refer to Pred as their
154 // source...
155 BB->replaceAllUsesWith(PredBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000156
Jay Foad61ea0e42011-06-23 09:09:15 +0000157 // Move all definitions in the successor to the predecessor...
158 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
Jakub Staszak190db2f2013-01-14 23:16:36 +0000159
Dan Gohman2d02ff82009-10-31 17:33:01 +0000160 // Inherit predecessors name if it exists.
Owen Anderson27405ef2008-07-17 19:42:29 +0000161 if (!PredBB->hasName())
162 PredBB->takeName(BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000163
Owen Andersonc0623812008-07-17 00:01:40 +0000164 // Finally, erase the old block and update dominator info.
Chandler Carruthb5c11532015-01-18 02:11:23 +0000165 if (DT)
166 if (DomTreeNode *DTN = DT->getNode(BB)) {
167 DomTreeNode *PredDTN = DT->getNode(PredBB);
168 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
169 for (SmallVectorImpl<DomTreeNode *>::iterator DI = Children.begin(),
170 DE = Children.end();
171 DI != DE; ++DI)
172 DT->changeImmediateDominator(*DI, PredDTN);
Owen Andersonc0623812008-07-17 00:01:40 +0000173
Chandler Carruthb5c11532015-01-18 02:11:23 +0000174 DT->eraseNode(BB);
Owen Andersonc0623812008-07-17 00:01:40 +0000175 }
Chandler Carruthb5c11532015-01-18 02:11:23 +0000176
177 if (LI)
178 LI->removeBlock(BB);
179
180 if (MemDep)
181 MemDep->invalidateCachedPredecessors();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000182
Owen Andersonc0623812008-07-17 00:01:40 +0000183 BB->eraseFromParent();
Dan Gohman2d02ff82009-10-31 17:33:01 +0000184 return true;
Owen Andersonc0623812008-07-17 00:01:40 +0000185}
186
Chris Lattner7ceb0812005-04-21 16:04:49 +0000187/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
188/// with a value, then remove and delete the original instruction.
189///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000190void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
191 BasicBlock::iterator &BI, Value *V) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000192 Instruction &I = *BI;
Chris Lattner28537df2002-05-07 18:07:59 +0000193 // Replaces all of the uses of the instruction with uses of the value
Chris Lattnerfda72b12002-06-25 16:12:52 +0000194 I.replaceAllUsesWith(V);
Chris Lattner28537df2002-05-07 18:07:59 +0000195
Chris Lattner8dd4cae2007-02-11 01:37:51 +0000196 // Make sure to propagate a name if there is one already.
197 if (I.hasName() && !V->hasName())
198 V->takeName(&I);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000199
Misha Brukman7eb05a12003-08-18 14:43:39 +0000200 // Delete the unnecessary instruction now...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000201 BI = BIL.erase(BI);
Chris Lattner28537df2002-05-07 18:07:59 +0000202}
203
204
Chris Lattner7ceb0812005-04-21 16:04:49 +0000205/// ReplaceInstWithInst - Replace the instruction specified by BI with the
206/// instruction specified by I. The original instruction is deleted and BI is
207/// updated to point to the new instruction.
208///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000209void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
210 BasicBlock::iterator &BI, Instruction *I) {
Craig Toppere73658d2014-04-28 04:05:08 +0000211 assert(I->getParent() == nullptr &&
Chris Lattner28537df2002-05-07 18:07:59 +0000212 "ReplaceInstWithInst: Instruction already inserted into basic block!");
213
214 // Insert the new instruction into the basic block...
Chris Lattnerfda72b12002-06-25 16:12:52 +0000215 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner28537df2002-05-07 18:07:59 +0000216
217 // Replace all uses of the old instruction, and delete it.
218 ReplaceInstWithValue(BIL, BI, I);
219
220 // Move BI back to point to the newly inserted instruction
Chris Lattnerfda72b12002-06-25 16:12:52 +0000221 BI = New;
Chris Lattner28537df2002-05-07 18:07:59 +0000222}
223
Chris Lattner7ceb0812005-04-21 16:04:49 +0000224/// ReplaceInstWithInst - Replace the instruction specified by From with the
225/// instruction specified by To.
226///
Chris Lattnerdf3c3422004-01-09 06:12:26 +0000227void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattnerfda72b12002-06-25 16:12:52 +0000228 BasicBlock::iterator BI(From);
229 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner28537df2002-05-07 18:07:59 +0000230}
Chris Lattnerb17274e2002-07-29 22:32:08 +0000231
Jakub Staszak190db2f2013-01-14 23:16:36 +0000232/// SplitEdge - Split the edge connecting specified block. Pass P must
233/// not be NULL.
Bob Wilson3de492e2010-02-16 19:49:17 +0000234BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
Bob Wilsonaff96b22010-02-16 21:06:42 +0000235 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000236
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000237 auto *AA = P->getAnalysisIfAvailable<AliasAnalysis>();
Chandler Carruth32c52c72015-01-18 02:39:37 +0000238 auto *DTWP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
239 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
240 auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
241 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000242 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
243 auto Options = CriticalEdgeSplittingOptions(AA, DT, LI);
244 if (PreserveLCSSA)
245 Options.setPreserveLCSSA();
246
247 // If this is a critical edge, let SplitCriticalEdge do it.
248 TerminatorInst *LatchTerm = BB->getTerminator();
249 if (SplitCriticalEdge(LatchTerm, SuccNum, Options))
250 return LatchTerm->getSuccessor(SuccNum);
Chandler Carruth32c52c72015-01-18 02:39:37 +0000251
Devang Pateld7767cc2007-07-06 21:39:20 +0000252 // If the edge isn't critical, then BB has a single successor or Succ has a
253 // single pred. Split the block.
Devang Pateld7767cc2007-07-06 21:39:20 +0000254 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
255 // If the successor only has a single pred, split the top of the successor
256 // block.
257 assert(SP == BB && "CFG broken");
Craig Topperf40110f2014-04-25 05:29:35 +0000258 SP = nullptr;
Chandler Carruth32c52c72015-01-18 02:39:37 +0000259 return SplitBlock(Succ, Succ->begin(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000260 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000261
Chris Lattner30d95f92011-01-08 18:47:43 +0000262 // Otherwise, if BB has a single successor, split it at the bottom of the
263 // block.
264 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
Jakub Staszak190db2f2013-01-14 23:16:36 +0000265 "Should have a single succ!");
Chandler Carruth32c52c72015-01-18 02:39:37 +0000266 return SplitBlock(BB, BB->getTerminator(), DT, LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000267}
268
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000269unsigned
270llvm::SplitAllCriticalEdges(Function &F,
271 const CriticalEdgeSplittingOptions &Options) {
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000272 unsigned NumBroken = 0;
273 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
274 TerminatorInst *TI = I->getTerminator();
275 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
276 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chandler Carruth37df2cf2015-01-19 12:09:11 +0000277 if (SplitCriticalEdge(TI, i, Options))
Kostya Serebryanye5ea4242014-11-19 00:17:31 +0000278 ++NumBroken;
279 }
280 return NumBroken;
281}
282
Devang Pateld7767cc2007-07-06 21:39:20 +0000283/// SplitBlock - Split the specified block at the specified instruction - every
284/// thing before SplitPt stays in Old and everything starting with SplitPt moves
285/// to a new block. The two blocks are joined by an unconditional branch and
286/// the loop info is updated.
287///
Chandler Carruth32c52c72015-01-18 02:39:37 +0000288BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
289 DominatorTree *DT, LoopInfo *LI) {
Devang Pateld7767cc2007-07-06 21:39:20 +0000290 BasicBlock::iterator SplitIt = SplitPt;
Bill Wendling79a68732011-08-17 21:21:31 +0000291 while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
Devang Pateld7767cc2007-07-06 21:39:20 +0000292 ++SplitIt;
293 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
294
Dan Gohman3ddbc242009-09-08 15:45:00 +0000295 // The new block lives in whichever loop the old one did. This preserves
296 // LCSSA as well, because we force the split point to be after any PHI nodes.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000297 if (LI)
298 if (Loop *L = LI->getLoopFor(Old))
299 L->addBasicBlockToLoop(New, *LI);
Devang Pateld7767cc2007-07-06 21:39:20 +0000300
Chandler Carruth32c52c72015-01-18 02:39:37 +0000301 if (DT)
Gabor Greif2f5f6962010-09-10 22:25:58 +0000302 // Old dominates New. New node dominates all other nodes dominated by Old.
Chandler Carruth32c52c72015-01-18 02:39:37 +0000303 if (DomTreeNode *OldNode = DT->getNode(Old)) {
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000304 std::vector<DomTreeNode *> Children;
305 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
Jakub Staszak190db2f2013-01-14 23:16:36 +0000306 I != E; ++I)
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000307 Children.push_back(*I);
Devang Patel186e0d82007-07-19 02:29:24 +0000308
Chandler Carruth32c52c72015-01-18 02:39:37 +0000309 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
Devang Patel186e0d82007-07-19 02:29:24 +0000310 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
Jakub Staszak190db2f2013-01-14 23:16:36 +0000311 E = Children.end(); I != E; ++I)
Chandler Carruth32c52c72015-01-18 02:39:37 +0000312 DT->changeImmediateDominator(*I, NewNode);
Rafael Espindolad3e65e72011-08-24 18:07:01 +0000313 }
Devang Pateld7767cc2007-07-06 21:39:20 +0000314
Devang Pateld7767cc2007-07-06 21:39:20 +0000315 return New;
316}
Chris Lattnera5b11702008-04-21 01:28:02 +0000317
Bill Wendling0a693f42011-08-18 05:25:23 +0000318/// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
319/// analysis information.
Bill Wendling60291352011-08-18 17:57:57 +0000320static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
Bill Wendlingec3823d2011-08-18 20:39:32 +0000321 ArrayRef<BasicBlock *> Preds,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000322 DominatorTree *DT, LoopInfo *LI,
323 bool PreserveLCSSA, bool &HasLoopExit) {
324 // Update dominator tree if available.
325 if (DT)
326 DT->splitBlock(NewBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000327
Chandler Carruthb5797b62015-01-18 09:21:15 +0000328 // The rest of the logic is only relevant for updating the loop structures.
329 if (!LI)
330 return;
331
332 Loop *L = LI->getLoopFor(OldBB);
Bill Wendling0a693f42011-08-18 05:25:23 +0000333
334 // If we need to preserve loop analyses, collect some information about how
335 // this split will affect loops.
336 bool IsLoopEntry = !!L;
337 bool SplitMakesNewLoopHeader = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000338 for (ArrayRef<BasicBlock *>::iterator i = Preds.begin(), e = Preds.end();
339 i != e; ++i) {
340 BasicBlock *Pred = *i;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000341
Chandler Carruthb5797b62015-01-18 09:21:15 +0000342 // If we need to preserve LCSSA, determine if any of the preds is a loop
343 // exit.
344 if (PreserveLCSSA)
345 if (Loop *PL = LI->getLoopFor(Pred))
346 if (!PL->contains(OldBB))
347 HasLoopExit = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000348
Chandler Carruthb5797b62015-01-18 09:21:15 +0000349 // If we need to preserve LoopInfo, note whether any of the preds crosses
350 // an interesting loop boundary.
351 if (!L)
352 continue;
353 if (L->contains(Pred))
354 IsLoopEntry = false;
355 else
356 SplitMakesNewLoopHeader = true;
Bill Wendling0a693f42011-08-18 05:25:23 +0000357 }
358
Chandler Carruthb5797b62015-01-18 09:21:15 +0000359 // Unless we have a loop for OldBB, nothing else to do here.
360 if (!L)
361 return;
Bill Wendling0a693f42011-08-18 05:25:23 +0000362
363 if (IsLoopEntry) {
364 // Add the new block to the nearest enclosing loop (and not an adjacent
365 // loop). To find this, examine each of the predecessors and determine which
366 // loops enclose them, and select the most-nested loop which contains the
367 // loop containing the block being split.
Craig Topperf40110f2014-04-25 05:29:35 +0000368 Loop *InnermostPredLoop = nullptr;
Bill Wendlingec3823d2011-08-18 20:39:32 +0000369 for (ArrayRef<BasicBlock*>::iterator
370 i = Preds.begin(), e = Preds.end(); i != e; ++i) {
371 BasicBlock *Pred = *i;
372 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
Bill Wendling0a693f42011-08-18 05:25:23 +0000373 // Seek a loop which actually contains the block being split (to avoid
374 // adjacent loops).
375 while (PredLoop && !PredLoop->contains(OldBB))
376 PredLoop = PredLoop->getParentLoop();
377
378 // Select the most-nested of these loops which contains the block.
379 if (PredLoop && PredLoop->contains(OldBB) &&
380 (!InnermostPredLoop ||
381 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
382 InnermostPredLoop = PredLoop;
383 }
Bill Wendlingec3823d2011-08-18 20:39:32 +0000384 }
Bill Wendling0a693f42011-08-18 05:25:23 +0000385
386 if (InnermostPredLoop)
Chandler Carruth691addc2015-01-18 01:25:51 +0000387 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000388 } else {
Chandler Carruth691addc2015-01-18 01:25:51 +0000389 L->addBasicBlockToLoop(NewBB, *LI);
Bill Wendling0a693f42011-08-18 05:25:23 +0000390 if (SplitMakesNewLoopHeader)
391 L->moveToHeader(NewBB);
392 }
393}
394
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000395/// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
396/// from NewBB. This also updates AliasAnalysis, if available.
397static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000398 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
399 AliasAnalysis *AA, bool HasLoopExit) {
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000400 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000401 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000402 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
403 PHINode *PN = cast<PHINode>(I++);
404
405 // Check to see if all of the values coming in are the same. If so, we
406 // don't need to create a new PHI node, unless it's needed for LCSSA.
Craig Topperf40110f2014-04-25 05:29:35 +0000407 Value *InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000408 if (!HasLoopExit) {
409 InVal = PN->getIncomingValueForBlock(Preds[0]);
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000410 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
411 if (!PredSet.count(PN->getIncomingBlock(i)))
412 continue;
413 if (!InVal)
414 InVal = PN->getIncomingValue(i);
415 else if (InVal != PN->getIncomingValue(i)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000416 InVal = nullptr;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000417 break;
418 }
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000419 }
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000420 }
421
422 if (InVal) {
423 // If all incoming values for the new PHI would be the same, just don't
424 // make a new PHI. Instead, just remove the incoming values from the old
425 // PHI.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000426
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000427 // NOTE! This loop walks backwards for a reason! First off, this minimizes
428 // the cost of removal if we end up removing a large number of values, and
429 // second off, this ensures that the indices for the incoming values
430 // aren't invalidated when we remove one.
431 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
432 if (PredSet.count(PN->getIncomingBlock(i)))
433 PN->removeIncomingValue(i, false);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000434
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000435 // Add an incoming value to the PHI node in the loop for the preheader
436 // edge.
437 PN->addIncoming(InVal, NewBB);
438 continue;
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000439 }
440
Chandler Carruth5bdf72c2014-04-28 10:37:30 +0000441 // If the values coming into the block are not the same, we need a new
442 // PHI.
443 // Create the new PHI node, insert it into NewBB at the end of the block
444 PHINode *NewPHI =
445 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
446 if (AA)
447 AA->copyValue(PN, NewPHI);
448
449 // NOTE! This loop walks backwards for a reason! First off, this minimizes
450 // the cost of removal if we end up removing a large number of values, and
451 // second off, this ensures that the indices for the incoming values aren't
452 // invalidated when we remove one.
453 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
454 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
455 if (PredSet.count(IncomingBB)) {
456 Value *V = PN->removeIncomingValue(i, false);
457 NewPHI->addIncoming(V, IncomingBB);
458 }
459 }
460
461 PN->addIncoming(NewPHI, NewBB);
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000462 }
463}
464
Chris Lattnera5b11702008-04-21 01:28:02 +0000465/// SplitBlockPredecessors - This method transforms BB by introducing a new
466/// basic block into the function, and moving some of the predecessors of BB to
467/// be predecessors of the new block. The new predecessors are indicated by the
468/// Preds array, which has NumPreds elements in it. The new block is given a
469/// suffix of 'Suffix'.
470///
Dan Gohman3ddbc242009-09-08 15:45:00 +0000471/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
Cameron Zwarichb7036542011-01-18 04:11:31 +0000472/// LoopInfo, and LCCSA but no other analyses. In particular, it does not
473/// preserve LoopSimplify (because it's complicated to handle the case where one
474/// of the edges being split is an exit of a loop with other exits).
Dan Gohman3ddbc242009-09-08 15:45:00 +0000475///
Jakub Staszak190db2f2013-01-14 23:16:36 +0000476BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
Chandler Carruthb5797b62015-01-18 09:21:15 +0000477 ArrayRef<BasicBlock *> Preds,
478 const char *Suffix, AliasAnalysis *AA,
479 DominatorTree *DT, LoopInfo *LI,
480 bool PreserveLCSSA) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000481 // Create new basic block, insert right before the original block.
Owen Anderson55f1c092009-08-13 21:58:54 +0000482 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
483 BB->getParent(), BB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000484
Chris Lattnera5b11702008-04-21 01:28:02 +0000485 // The new block unconditionally branches to the old block.
486 BranchInst *BI = BranchInst::Create(BB, NewBB);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000487
Chris Lattnera5b11702008-04-21 01:28:02 +0000488 // Move the edges from Preds to point to NewBB instead of BB.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000489 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Dan Gohman00c79382009-11-05 18:25:44 +0000490 // This is slightly more strict than necessary; the minimum requirement
491 // is that there be no more than one indirectbr branching to BB. And
492 // all BlockAddress uses would need to be updated.
493 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
494 "Cannot split an edge from an IndirectBrInst");
Chris Lattnera5b11702008-04-21 01:28:02 +0000495 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000496 }
497
Chris Lattnera5b11702008-04-21 01:28:02 +0000498 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
499 // node becomes an incoming value for BB's phi node. However, if the Preds
500 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
501 // account for the newly created predecessor.
Jakub Staszakf5b32e52011-12-09 21:19:53 +0000502 if (Preds.size() == 0) {
Chris Lattnera5b11702008-04-21 01:28:02 +0000503 // Insert dummy values as the incoming value.
504 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Andersonb292b8c2009-07-30 23:03:37 +0000505 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattnera5b11702008-04-21 01:28:02 +0000506 return NewBB;
507 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000508
Bill Wendling0a693f42011-08-18 05:25:23 +0000509 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
510 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000511 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA,
512 HasLoopExit);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000513
Bill Wendlingb267e2a2011-08-18 20:51:04 +0000514 // Update the PHI nodes in BB with the values coming from NewBB.
Chandler Carruthb5797b62015-01-18 09:21:15 +0000515 UpdatePHINodes(BB, NewBB, Preds, BI, AA, HasLoopExit);
Chris Lattnera5b11702008-04-21 01:28:02 +0000516 return NewBB;
517}
Chris Lattner72f16e72008-11-27 08:10:05 +0000518
Bill Wendlingca7d3092011-08-19 00:05:40 +0000519/// SplitLandingPadPredecessors - This method transforms the landing pad,
520/// OrigBB, by introducing two new basic blocks into the function. One of those
521/// new basic blocks gets the predecessors listed in Preds. The other basic
522/// block gets the remaining predecessors of OrigBB. The landingpad instruction
523/// OrigBB is clone into both of the new basic blocks. The new blocks are given
524/// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000525///
Bill Wendlingca7d3092011-08-19 00:05:40 +0000526/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
527/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
528/// it does not preserve LoopSimplify (because it's complicated to handle the
529/// case where one of the edges being split is an exit of a loop with other
530/// exits).
Jakub Staszak190db2f2013-01-14 23:16:36 +0000531///
Bill Wendlingca7d3092011-08-19 00:05:40 +0000532void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000533 ArrayRef<BasicBlock *> Preds,
Bill Wendlingca7d3092011-08-19 00:05:40 +0000534 const char *Suffix1, const char *Suffix2,
Chandler Carruth0eae1122015-01-19 03:03:39 +0000535 SmallVectorImpl<BasicBlock *> &NewBBs,
536 AliasAnalysis *AA, DominatorTree *DT,
537 LoopInfo *LI, bool PreserveLCSSA) {
Bill Wendlingca7d3092011-08-19 00:05:40 +0000538 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
539
540 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
541 // it right before the original block.
542 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
543 OrigBB->getName() + Suffix1,
544 OrigBB->getParent(), OrigBB);
545 NewBBs.push_back(NewBB1);
546
547 // The new block unconditionally branches to the old block.
548 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
549
550 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
551 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
552 // This is slightly more strict than necessary; the minimum requirement
553 // is that there be no more than one indirectbr branching to BB. And
554 // all BlockAddress uses would need to be updated.
555 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
556 "Cannot split an edge from an IndirectBrInst");
557 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
558 }
559
Bill Wendlingca7d3092011-08-19 00:05:40 +0000560 bool HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000561 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA,
562 HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000563
564 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
Chandler Carruthb5797b62015-01-18 09:21:15 +0000565 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, AA, HasLoopExit);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000566
Bill Wendlingca7d3092011-08-19 00:05:40 +0000567 // Move the remaining edges from OrigBB to point to NewBB2.
568 SmallVector<BasicBlock*, 8> NewBB2Preds;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000569 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
570 i != e; ) {
571 BasicBlock *Pred = *i++;
Bill Wendling38d81302011-08-19 23:46:30 +0000572 if (Pred == NewBB1) continue;
Bill Wendlingca7d3092011-08-19 00:05:40 +0000573 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
574 "Cannot split an edge from an IndirectBrInst");
Bill Wendlingca7d3092011-08-19 00:05:40 +0000575 NewBB2Preds.push_back(Pred);
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000576 e = pred_end(OrigBB);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000577 }
578
Craig Topperf40110f2014-04-25 05:29:35 +0000579 BasicBlock *NewBB2 = nullptr;
Bill Wendling38d81302011-08-19 23:46:30 +0000580 if (!NewBB2Preds.empty()) {
581 // Create another basic block for the rest of OrigBB's predecessors.
582 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
583 OrigBB->getName() + Suffix2,
584 OrigBB->getParent(), OrigBB);
585 NewBBs.push_back(NewBB2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000586
Bill Wendling38d81302011-08-19 23:46:30 +0000587 // The new block unconditionally branches to the old block.
588 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
589
590 // Move the remaining edges from OrigBB to point to NewBB2.
591 for (SmallVectorImpl<BasicBlock*>::iterator
592 i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
593 (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
594
595 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
596 HasLoopExit = false;
Chandler Carruthb5797b62015-01-18 09:21:15 +0000597 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI,
598 PreserveLCSSA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000599
600 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
Chandler Carruthb5797b62015-01-18 09:21:15 +0000601 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, AA, HasLoopExit);
Bill Wendling38d81302011-08-19 23:46:30 +0000602 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000603
604 LandingPadInst *LPad = OrigBB->getLandingPadInst();
605 Instruction *Clone1 = LPad->clone();
606 Clone1->setName(Twine("lpad") + Suffix1);
607 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
608
Bill Wendling38d81302011-08-19 23:46:30 +0000609 if (NewBB2) {
610 Instruction *Clone2 = LPad->clone();
611 Clone2->setName(Twine("lpad") + Suffix2);
612 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
Bill Wendlingca7d3092011-08-19 00:05:40 +0000613
Bill Wendling38d81302011-08-19 23:46:30 +0000614 // Create a PHI node for the two cloned landingpad instructions.
615 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
616 PN->addIncoming(Clone1, NewBB1);
617 PN->addIncoming(Clone2, NewBB2);
618 LPad->replaceAllUsesWith(PN);
619 LPad->eraseFromParent();
620 } else {
621 // There is no second clone. Just replace the landing pad with the first
622 // clone.
623 LPad->replaceAllUsesWith(Clone1);
624 LPad->eraseFromParent();
625 }
Bill Wendlingca7d3092011-08-19 00:05:40 +0000626}
627
Evan Chengd983eba2011-01-29 04:46:23 +0000628/// FoldReturnIntoUncondBranch - This method duplicates the specified return
629/// instruction into a predecessor which ends in an unconditional branch. If
630/// the return instruction returns a value defined by a PHI, propagate the
631/// right value into the return. It returns the new return instruction in the
632/// predecessor.
633ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
634 BasicBlock *Pred) {
635 Instruction *UncondBranch = Pred->getTerminator();
636 // Clone the return and add it to the end of the predecessor.
637 Instruction *NewRet = RI->clone();
638 Pred->getInstList().push_back(NewRet);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000639
Evan Chengd983eba2011-01-29 04:46:23 +0000640 // If the return instruction returns a value, and if the value was a
641 // PHI node in "BB", propagate the right value into the return.
642 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
Evan Cheng249716e2012-07-27 21:21:26 +0000643 i != e; ++i) {
644 Value *V = *i;
Craig Topperf40110f2014-04-25 05:29:35 +0000645 Instruction *NewBC = nullptr;
Evan Cheng249716e2012-07-27 21:21:26 +0000646 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
647 // Return value might be bitcasted. Clone and insert it before the
648 // return instruction.
649 V = BCI->getOperand(0);
650 NewBC = BCI->clone();
651 Pred->getInstList().insert(NewRet, NewBC);
652 *i = NewBC;
653 }
654 if (PHINode *PN = dyn_cast<PHINode>(V)) {
655 if (PN->getParent() == BB) {
656 if (NewBC)
657 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
658 else
659 *i = PN->getIncomingValueForBlock(Pred);
660 }
661 }
662 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000663
Evan Chengd983eba2011-01-29 04:46:23 +0000664 // Update any PHI nodes in the returning block to realize that we no
665 // longer branch to them.
666 BB->removePredecessor(Pred);
667 UncondBranch->eraseFromParent();
668 return cast<ReturnInst>(NewRet);
Chris Lattner351134b2009-05-04 02:25:58 +0000669}
Devang Patela8e74112011-04-29 22:28:59 +0000670
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000671/// SplitBlockAndInsertIfThen - Split the containing block at the
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000672/// specified instruction - everything before and including SplitBefore stays
673/// in the old basic block, and everything after SplitBefore is moved to a
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000674/// new block. The two blocks are connected by a conditional branch
675/// (with value of Cmp being the condition).
676/// Before:
677/// Head
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000678/// SplitBefore
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000679/// Tail
680/// After:
681/// Head
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000682/// if (Cond)
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000683/// ThenBlock
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000684/// SplitBefore
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000685/// Tail
686///
687/// If Unreachable is true, then ThenBlock ends with
688/// UnreachableInst, otherwise it branches to Tail.
689/// Returns the NewBasicBlock's terminator.
690
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000691TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
692 Instruction *SplitBefore,
693 bool Unreachable,
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000694 MDNode *BranchWeights,
695 DominatorTree *DT) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000696 BasicBlock *Head = SplitBefore->getParent();
697 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
698 TerminatorInst *HeadOldTerm = Head->getTerminator();
699 LLVMContext &C = Head->getContext();
700 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
701 TerminatorInst *CheckTerm;
702 if (Unreachable)
703 CheckTerm = new UnreachableInst(C, ThenBlock);
704 else
705 CheckTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000706 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000707 BranchInst *HeadNewTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000708 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000709 HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000710 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
711 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
Peter Collingbourne818f5c42014-07-15 04:40:27 +0000712
713 if (DT) {
714 if (DomTreeNode *OldNode = DT->getNode(Head)) {
715 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
716
717 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
718 for (auto Child : Children)
719 DT->changeImmediateDominator(Child, NewNode);
720
721 // Head dominates ThenBlock.
722 DT->addNewBlock(ThenBlock, Head);
723 }
724 }
725
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000726 return CheckTerm;
727}
Tom Stellardaa664d92013-08-06 02:43:45 +0000728
Kostya Serebryany530e2072013-12-23 14:15:08 +0000729/// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
730/// but also creates the ElseBlock.
731/// Before:
732/// Head
733/// SplitBefore
734/// Tail
735/// After:
736/// Head
737/// if (Cond)
738/// ThenBlock
739/// else
740/// ElseBlock
741/// SplitBefore
742/// Tail
743void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
744 TerminatorInst **ThenTerm,
745 TerminatorInst **ElseTerm,
746 MDNode *BranchWeights) {
747 BasicBlock *Head = SplitBefore->getParent();
748 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
749 TerminatorInst *HeadOldTerm = Head->getTerminator();
750 LLVMContext &C = Head->getContext();
751 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
752 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
753 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000754 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000755 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000756 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000757 BranchInst *HeadNewTerm =
758 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
Evgeniy Stepanov2275a012014-03-19 12:56:38 +0000759 HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
Kostya Serebryany530e2072013-12-23 14:15:08 +0000760 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
761 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
762}
763
764
Tom Stellardaa664d92013-08-06 02:43:45 +0000765/// GetIfCondition - Given a basic block (BB) with two predecessors,
766/// check to see if the merge at this block is due
767/// to an "if condition". If so, return the boolean condition that determines
768/// which entry into BB will be taken. Also, return by references the block
769/// that will be entered from if the condition is true, and the block that will
770/// be entered if the condition is false.
771///
772/// This does no checking to see if the true/false blocks have large or unsavory
773/// instructions in them.
774Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
775 BasicBlock *&IfFalse) {
776 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
Craig Topperf40110f2014-04-25 05:29:35 +0000777 BasicBlock *Pred1 = nullptr;
778 BasicBlock *Pred2 = nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000779
780 if (SomePHI) {
781 if (SomePHI->getNumIncomingValues() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +0000782 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000783 Pred1 = SomePHI->getIncomingBlock(0);
784 Pred2 = SomePHI->getIncomingBlock(1);
785 } else {
786 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
787 if (PI == PE) // No predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000788 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000789 Pred1 = *PI++;
790 if (PI == PE) // Only one predecessor
Craig Topperf40110f2014-04-25 05:29:35 +0000791 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000792 Pred2 = *PI++;
793 if (PI != PE) // More than two predecessors
Craig Topperf40110f2014-04-25 05:29:35 +0000794 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000795 }
796
797 // We can only handle branches. Other control flow will be lowered to
798 // branches if possible anyway.
799 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
800 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000801 if (!Pred1Br || !Pred2Br)
802 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000803
804 // Eliminate code duplication by ensuring that Pred1Br is conditional if
805 // either are.
806 if (Pred2Br->isConditional()) {
807 // If both branches are conditional, we don't have an "if statement". In
808 // reality, we could transform this case, but since the condition will be
809 // required anyway, we stand no chance of eliminating it, so the xform is
810 // probably not profitable.
811 if (Pred1Br->isConditional())
Craig Topperf40110f2014-04-25 05:29:35 +0000812 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000813
814 std::swap(Pred1, Pred2);
815 std::swap(Pred1Br, Pred2Br);
816 }
817
818 if (Pred1Br->isConditional()) {
819 // The only thing we have to watch out for here is to make sure that Pred2
820 // doesn't have incoming edges from other blocks. If it does, the condition
821 // doesn't dominate BB.
Craig Topperf40110f2014-04-25 05:29:35 +0000822 if (!Pred2->getSinglePredecessor())
823 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000824
825 // If we found a conditional branch predecessor, make sure that it branches
826 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
827 if (Pred1Br->getSuccessor(0) == BB &&
828 Pred1Br->getSuccessor(1) == Pred2) {
829 IfTrue = Pred1;
830 IfFalse = Pred2;
831 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
832 Pred1Br->getSuccessor(1) == BB) {
833 IfTrue = Pred2;
834 IfFalse = Pred1;
835 } else {
836 // We know that one arm of the conditional goes to BB, so the other must
837 // go somewhere unrelated, and this must not be an "if statement".
Craig Topperf40110f2014-04-25 05:29:35 +0000838 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000839 }
840
841 return Pred1Br->getCondition();
842 }
843
844 // Ok, if we got here, both predecessors end with an unconditional branch to
845 // BB. Don't panic! If both blocks only have a single (identical)
846 // predecessor, and THAT is a conditional branch, then we're all ok!
847 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
Craig Topperf40110f2014-04-25 05:29:35 +0000848 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
849 return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000850
851 // Otherwise, if this is a conditional branch, then we can use it!
852 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000853 if (!BI) return nullptr;
Tom Stellardaa664d92013-08-06 02:43:45 +0000854
855 assert(BI->isConditional() && "Two successors but not conditional?");
856 if (BI->getSuccessor(0) == Pred1) {
857 IfTrue = Pred1;
858 IfFalse = Pred2;
859 } else {
860 IfTrue = Pred2;
861 IfFalse = Pred1;
862 }
863 return BI->getCondition();
864}