1 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform manipulations on basic blocks, and
11 // instructions contained within basic blocks.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
16 #include "llvm/Function.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/IntrinsicInst.h"
19 #include "llvm/Constant.h"
20 #include "llvm/Type.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/DominanceFrontier.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ValueHandle.h"
33 /// DeleteDeadBlock - Delete the specified block, which must have no
35 void llvm::DeleteDeadBlock(BasicBlock *BB) {
36 assert((pred_begin(BB) == pred_end(BB) ||
37 // Can delete self loop.
38 BB->getSinglePredecessor() == BB) && "Block is not dead!");
39 TerminatorInst *BBTerm = BB->getTerminator();
41 // Loop through all of our successors and make sure they know that one
42 // of their predecessors is going away.
43 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
44 BBTerm->getSuccessor(i)->removePredecessor(BB);
46 // Zap all the instructions in the block.
47 while (!BB->empty()) {
48 Instruction &I = BB->back();
49 // If this instruction is used, replace uses with an arbitrary value.
50 // Because control flow can't get here, we don't care what we replace the
51 // value with. Note that since this block is unreachable, and all values
52 // contained within it must dominate their uses, that all uses will
53 // eventually be removed (they are themselves dead).
55 I.replaceAllUsesWith(UndefValue::get(I.getType()));
56 BB->getInstList().pop_back();
60 BB->eraseFromParent();
63 /// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
64 /// any single-entry PHI nodes in it, fold them away. This handles the case
65 /// when all entries to the PHI nodes in a block are guaranteed equal, such as
66 /// when the block has exactly one predecessor.
67 void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P) {
68 if (!isa<PHINode>(BB->begin())) return;
70 AliasAnalysis *AA = 0;
71 MemoryDependenceAnalysis *MemDep = 0;
73 AA = P->getAnalysisIfAvailable<AliasAnalysis>();
74 MemDep = P->getAnalysisIfAvailable<MemoryDependenceAnalysis>();
77 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
78 if (PN->getIncomingValue(0) != PN)
79 PN->replaceAllUsesWith(PN->getIncomingValue(0));
81 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
84 MemDep->removeInstruction(PN); // Memdep updates AA itself.
85 else if (AA && isa<PointerType>(PN->getType()))
88 PN->eraseFromParent();
93 /// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
94 /// is dead. Also recursively delete any operands that become dead as
95 /// a result. This includes tracing the def-use list from the PHI to see if
96 /// it is ultimately unused or if it reaches an unused cycle.
97 bool llvm::DeleteDeadPHIs(BasicBlock *BB) {
98 // Recursively deleting a PHI may cause multiple PHIs to be deleted
99 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
100 SmallVector<WeakVH, 8> PHIs;
101 for (BasicBlock::iterator I = BB->begin();
102 PHINode *PN = dyn_cast<PHINode>(I); ++I)
105 bool Changed = false;
106 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
107 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
108 Changed |= RecursivelyDeleteDeadPHINode(PN);
113 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
114 /// if possible. The return value indicates success or failure.
115 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
116 // Don't merge away blocks who have their address taken.
117 if (BB->hasAddressTaken()) return false;
119 // Can't merge if there are multiple predecessors, or no predecessors.
120 BasicBlock *PredBB = BB->getUniquePredecessor();
121 if (!PredBB) return false;
123 // Don't break self-loops.
124 if (PredBB == BB) return false;
125 // Don't break invokes.
126 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
128 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
129 BasicBlock *OnlySucc = BB;
130 for (; SI != SE; ++SI)
131 if (*SI != OnlySucc) {
132 OnlySucc = 0; // There are multiple distinct successors!
136 // Can't merge if there are multiple successors.
137 if (!OnlySucc) return false;
139 // Can't merge if there is PHI loop.
140 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
141 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
142 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
143 if (PN->getIncomingValue(i) == PN)
149 // Begin by getting rid of unneeded PHIs.
150 if (isa<PHINode>(BB->front()))
151 FoldSingleEntryPHINodes(BB, P);
153 // Delete the unconditional branch from the predecessor...
154 PredBB->getInstList().pop_back();
156 // Move all definitions in the successor to the predecessor...
157 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
159 // Make all PHI nodes that referred to BB now refer to Pred as their
161 BB->replaceAllUsesWith(PredBB);
163 // Inherit predecessors name if it exists.
164 if (!PredBB->hasName())
165 PredBB->takeName(BB);
167 // Finally, erase the old block and update dominator info.
169 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) {
170 if (DomTreeNode *DTN = DT->getNode(BB)) {
171 DomTreeNode *PredDTN = DT->getNode(PredBB);
172 SmallVector<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
173 for (SmallVector<DomTreeNode*, 8>::iterator DI = Children.begin(),
174 DE = Children.end(); DI != DE; ++DI)
175 DT->changeImmediateDominator(*DI, PredDTN);
180 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
183 if (MemoryDependenceAnalysis *MD =
184 P->getAnalysisIfAvailable<MemoryDependenceAnalysis>())
185 MD->invalidateCachedPredecessors();
189 BB->eraseFromParent();
193 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
194 /// with a value, then remove and delete the original instruction.
196 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
197 BasicBlock::iterator &BI, Value *V) {
198 Instruction &I = *BI;
199 // Replaces all of the uses of the instruction with uses of the value
200 I.replaceAllUsesWith(V);
202 // Make sure to propagate a name if there is one already.
203 if (I.hasName() && !V->hasName())
206 // Delete the unnecessary instruction now...
211 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
212 /// instruction specified by I. The original instruction is deleted and BI is
213 /// updated to point to the new instruction.
215 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
216 BasicBlock::iterator &BI, Instruction *I) {
217 assert(I->getParent() == 0 &&
218 "ReplaceInstWithInst: Instruction already inserted into basic block!");
220 // Insert the new instruction into the basic block...
221 BasicBlock::iterator New = BIL.insert(BI, I);
223 // Replace all uses of the old instruction, and delete it.
224 ReplaceInstWithValue(BIL, BI, I);
226 // Move BI back to point to the newly inserted instruction
230 /// ReplaceInstWithInst - Replace the instruction specified by From with the
231 /// instruction specified by To.
233 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
234 BasicBlock::iterator BI(From);
235 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
238 /// GetSuccessorNumber - Search for the specified successor of basic block BB
239 /// and return its position in the terminator instruction's list of
240 /// successors. It is an error to call this with a block that is not a
242 unsigned llvm::GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ) {
243 TerminatorInst *Term = BB->getTerminator();
245 unsigned e = Term->getNumSuccessors();
247 for (unsigned i = 0; ; ++i) {
248 assert(i != e && "Didn't find edge?");
249 if (Term->getSuccessor(i) == Succ)
255 /// SplitEdge - Split the edge connecting specified block. Pass P must
257 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
258 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
260 // If this is a critical edge, let SplitCriticalEdge do it.
261 TerminatorInst *LatchTerm = BB->getTerminator();
262 if (SplitCriticalEdge(LatchTerm, SuccNum, P))
263 return LatchTerm->getSuccessor(SuccNum);
265 // If the edge isn't critical, then BB has a single successor or Succ has a
266 // single pred. Split the block.
267 BasicBlock::iterator SplitPoint;
268 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
269 // If the successor only has a single pred, split the top of the successor
271 assert(SP == BB && "CFG broken");
273 return SplitBlock(Succ, Succ->begin(), P);
276 // Otherwise, if BB has a single successor, split it at the bottom of the
278 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
279 "Should have a single succ!");
280 return SplitBlock(BB, BB->getTerminator(), P);
283 /// 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.
288 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
289 BasicBlock::iterator SplitIt = SplitPt;
290 while (isa<PHINode>(SplitIt))
292 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
294 // The new block lives in whichever loop the old one did. This preserves
295 // LCSSA as well, because we force the split point to be after any PHI nodes.
296 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
297 if (Loop *L = LI->getLoopFor(Old))
298 L->addBasicBlockToLoop(New, LI->getBase());
300 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>()) {
301 // Old dominates New. New node dominates all other nodes dominated by Old.
302 DomTreeNode *OldNode = DT->getNode(Old);
303 std::vector<DomTreeNode *> Children;
304 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
306 Children.push_back(*I);
308 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
309 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
310 E = Children.end(); I != E; ++I)
311 DT->changeImmediateDominator(*I, NewNode);
314 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
321 /// SplitBlockPredecessors - This method transforms BB by introducing a new
322 /// basic block into the function, and moving some of the predecessors of BB to
323 /// be predecessors of the new block. The new predecessors are indicated by the
324 /// Preds array, which has NumPreds elements in it. The new block is given a
325 /// suffix of 'Suffix'.
327 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
328 /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
329 /// In particular, it does not preserve LoopSimplify (because it's
330 /// complicated to handle the case where one of the edges being split
331 /// is an exit of a loop with other exits).
333 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
334 BasicBlock *const *Preds,
335 unsigned NumPreds, const char *Suffix,
337 // Create new basic block, insert right before the original block.
338 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
339 BB->getParent(), BB);
341 // The new block unconditionally branches to the old block.
342 BranchInst *BI = BranchInst::Create(BB, NewBB);
344 LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0;
345 Loop *L = LI ? LI->getLoopFor(BB) : 0;
346 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
348 // Move the edges from Preds to point to NewBB instead of BB.
349 // While here, if we need to preserve loop analyses, collect
350 // some information about how this split will affect loops.
351 bool HasLoopExit = false;
352 bool IsLoopEntry = !!L;
353 bool SplitMakesNewLoopHeader = false;
354 for (unsigned i = 0; i != NumPreds; ++i) {
355 // This is slightly more strict than necessary; the minimum requirement
356 // is that there be no more than one indirectbr branching to BB. And
357 // all BlockAddress uses would need to be updated.
358 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
359 "Cannot split an edge from an IndirectBrInst");
361 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
364 // If we need to preserve LCSSA, determine if any of
365 // the preds is a loop exit.
367 if (Loop *PL = LI->getLoopFor(Preds[i]))
368 if (!PL->contains(BB))
370 // If we need to preserve LoopInfo, note whether any of the
371 // preds crosses an interesting loop boundary.
373 if (L->contains(Preds[i]))
376 SplitMakesNewLoopHeader = true;
381 // Update dominator tree and dominator frontier if available.
382 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
384 DT->splitBlock(NewBB);
385 if (DominanceFrontier *DF =
386 P ? P->getAnalysisIfAvailable<DominanceFrontier>() : 0)
387 DF->splitBlock(NewBB);
389 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
390 // node becomes an incoming value for BB's phi node. However, if the Preds
391 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
392 // account for the newly created predecessor.
394 // Insert dummy values as the incoming value.
395 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
396 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
400 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
404 // Add the new block to the nearest enclosing loop (and not an
405 // adjacent loop). To find this, examine each of the predecessors and
406 // determine which loops enclose them, and select the most-nested loop
407 // which contains the loop containing the block being split.
408 Loop *InnermostPredLoop = 0;
409 for (unsigned i = 0; i != NumPreds; ++i)
410 if (Loop *PredLoop = LI->getLoopFor(Preds[i])) {
411 // Seek a loop which actually contains the block being split (to
412 // avoid adjacent loops).
413 while (PredLoop && !PredLoop->contains(BB))
414 PredLoop = PredLoop->getParentLoop();
415 // Select the most-nested of these loops which contains the block.
417 PredLoop->contains(BB) &&
418 (!InnermostPredLoop ||
419 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
420 InnermostPredLoop = PredLoop;
422 if (InnermostPredLoop)
423 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
425 L->addBasicBlockToLoop(NewBB, LI->getBase());
426 if (SplitMakesNewLoopHeader)
427 L->moveToHeader(NewBB);
431 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
432 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
433 PHINode *PN = cast<PHINode>(I++);
435 // Check to see if all of the values coming in are the same. If so, we
436 // don't need to create a new PHI node, unless it's needed for LCSSA.
439 InVal = PN->getIncomingValueForBlock(Preds[0]);
440 for (unsigned i = 1; i != NumPreds; ++i)
441 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
448 // If all incoming values for the new PHI would be the same, just don't
449 // make a new PHI. Instead, just remove the incoming values from the old
451 for (unsigned i = 0; i != NumPreds; ++i)
452 PN->removeIncomingValue(Preds[i], false);
454 // If the values coming into the block are not the same, we need a PHI.
455 // Create the new PHI node, insert it into NewBB at the end of the block
457 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
458 if (AA) AA->copyValue(PN, NewPHI);
460 // Move all of the PHI values for 'Preds' to the new PHI.
461 for (unsigned i = 0; i != NumPreds; ++i) {
462 Value *V = PN->removeIncomingValue(Preds[i], false);
463 NewPHI->addIncoming(V, Preds[i]);
468 // Add an incoming value to the PHI node in the loop for the preheader
470 PN->addIncoming(InVal, NewBB);
476 /// FindFunctionBackedges - Analyze the specified function to find all of the
477 /// loop backedges in the function and return them. This is a relatively cheap
478 /// (compared to computing dominators and loop info) analysis.
480 /// The output is added to Result, as pairs of <from,to> edge info.
481 void llvm::FindFunctionBackedges(const Function &F,
482 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
483 const BasicBlock *BB = &F.getEntryBlock();
484 if (succ_begin(BB) == succ_end(BB))
487 SmallPtrSet<const BasicBlock*, 8> Visited;
488 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
489 SmallPtrSet<const BasicBlock*, 8> InStack;
492 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
495 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
496 const BasicBlock *ParentBB = Top.first;
497 succ_const_iterator &I = Top.second;
499 bool FoundNew = false;
500 while (I != succ_end(ParentBB)) {
502 if (Visited.insert(BB)) {
506 // Successor is in VisitStack, it's a back edge.
507 if (InStack.count(BB))
508 Result.push_back(std::make_pair(ParentBB, BB));
512 // Go down one level if there is a unvisited successor.
514 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
517 InStack.erase(VisitStack.pop_back_val().first);
519 } while (!VisitStack.empty());