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/Constant.h"
19 #include "llvm/Type.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Target/TargetData.h"
27 /// DeleteDeadBlock - Delete the specified block, which must have no
29 void llvm::DeleteDeadBlock(BasicBlock *BB) {
30 assert((pred_begin(BB) == pred_end(BB) ||
31 // Can delete self loop.
32 BB->getSinglePredecessor() == BB) && "Block is not dead!");
33 TerminatorInst *BBTerm = BB->getTerminator();
35 // Loop through all of our successors and make sure they know that one
36 // of their predecessors is going away.
37 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
38 BBTerm->getSuccessor(i)->removePredecessor(BB);
40 // Zap all the instructions in the block.
41 while (!BB->empty()) {
42 Instruction &I = BB->back();
43 // If this instruction is used, replace uses with an arbitrary value.
44 // Because control flow can't get here, we don't care what we replace the
45 // value with. Note that since this block is unreachable, and all values
46 // contained within it must dominate their uses, that all uses will
47 // eventually be removed (they are themselves dead).
49 I.replaceAllUsesWith(UndefValue::get(I.getType()));
50 BB->getInstList().pop_back();
54 BB->eraseFromParent();
57 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
58 /// if possible. The return value indicates success or failure.
59 bool llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
60 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
61 // Can't merge the entry block.
62 if (pred_begin(BB) == pred_end(BB)) return false;
64 BasicBlock *PredBB = *PI++;
65 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
67 PredBB = 0; // There are multiple different predecessors...
71 // Can't merge if there are multiple predecessors.
72 if (!PredBB) return false;
73 // Don't break self-loops.
74 if (PredBB == BB) return false;
75 // Don't break invokes.
76 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
78 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
79 BasicBlock* OnlySucc = BB;
80 for (; SI != SE; ++SI)
81 if (*SI != OnlySucc) {
82 OnlySucc = 0; // There are multiple distinct successors!
86 // Can't merge if there are multiple successors.
87 if (!OnlySucc) return false;
89 // Can't merge if there is PHI loop.
90 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
91 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
92 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
93 if (PN->getIncomingValue(i) == PN)
99 // Begin by getting rid of unneeded PHIs.
100 while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
101 PN->replaceAllUsesWith(PN->getIncomingValue(0));
102 BB->getInstList().pop_front(); // Delete the phi node...
105 // Delete the unconditional branch from the predecessor...
106 PredBB->getInstList().pop_back();
108 // Move all definitions in the successor to the predecessor...
109 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
111 // Make all PHI nodes that referred to BB now refer to Pred as their
113 BB->replaceAllUsesWith(PredBB);
115 // Inherit predecessors name if it exists.
116 if (!PredBB->hasName())
117 PredBB->takeName(BB);
119 // Finally, erase the old block and update dominator info.
121 if (DominatorTree* DT = P->getAnalysisToUpdate<DominatorTree>()) {
122 DomTreeNode* DTN = DT->getNode(BB);
123 DomTreeNode* PredDTN = DT->getNode(PredBB);
126 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
127 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
128 DE = Children.end(); DI != DE; ++DI)
129 DT->changeImmediateDominator(*DI, PredDTN);
136 BB->eraseFromParent();
142 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
143 /// with a value, then remove and delete the original instruction.
145 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
146 BasicBlock::iterator &BI, Value *V) {
147 Instruction &I = *BI;
148 // Replaces all of the uses of the instruction with uses of the value
149 I.replaceAllUsesWith(V);
151 // Make sure to propagate a name if there is one already.
152 if (I.hasName() && !V->hasName())
155 // Delete the unnecessary instruction now...
160 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
161 /// instruction specified by I. The original instruction is deleted and BI is
162 /// updated to point to the new instruction.
164 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
165 BasicBlock::iterator &BI, Instruction *I) {
166 assert(I->getParent() == 0 &&
167 "ReplaceInstWithInst: Instruction already inserted into basic block!");
169 // Insert the new instruction into the basic block...
170 BasicBlock::iterator New = BIL.insert(BI, I);
172 // Replace all uses of the old instruction, and delete it.
173 ReplaceInstWithValue(BIL, BI, I);
175 // Move BI back to point to the newly inserted instruction
179 /// ReplaceInstWithInst - Replace the instruction specified by From with the
180 /// instruction specified by To.
182 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
183 BasicBlock::iterator BI(From);
184 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
187 /// RemoveSuccessor - Change the specified terminator instruction such that its
188 /// successor SuccNum no longer exists. Because this reduces the outgoing
189 /// degree of the current basic block, the actual terminator instruction itself
190 /// may have to be changed. In the case where the last successor of the block
191 /// is deleted, a return instruction is inserted in its place which can cause a
192 /// surprising change in program behavior if it is not expected.
194 void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
195 assert(SuccNum < TI->getNumSuccessors() &&
196 "Trying to remove a nonexistant successor!");
198 // If our old successor block contains any PHI nodes, remove the entry in the
199 // PHI nodes that comes from this branch...
201 BasicBlock *BB = TI->getParent();
202 TI->getSuccessor(SuccNum)->removePredecessor(BB);
204 TerminatorInst *NewTI = 0;
205 switch (TI->getOpcode()) {
206 case Instruction::Br:
207 // If this is a conditional branch... convert to unconditional branch.
208 if (TI->getNumSuccessors() == 2) {
209 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
210 } else { // Otherwise convert to a return instruction...
213 // Create a value to return... if the function doesn't return null...
214 if (BB->getParent()->getReturnType() != Type::VoidTy)
215 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
217 // Create the return...
218 NewTI = ReturnInst::Create(RetVal);
222 case Instruction::Invoke: // Should convert to call
223 case Instruction::Switch: // Should remove entry
225 case Instruction::Ret: // Cannot happen, has no successors!
226 assert(0 && "Unhandled terminator instruction type in RemoveSuccessor!");
230 if (NewTI) // If it's a different instruction, replace.
231 ReplaceInstWithInst(TI, NewTI);
234 /// SplitEdge - Split the edge connecting specified block. Pass P must
236 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
237 TerminatorInst *LatchTerm = BB->getTerminator();
238 unsigned SuccNum = 0;
240 unsigned e = LatchTerm->getNumSuccessors();
242 for (unsigned i = 0; ; ++i) {
243 assert(i != e && "Didn't find edge?");
244 if (LatchTerm->getSuccessor(i) == Succ) {
250 // If this is a critical edge, let SplitCriticalEdge do it.
251 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
252 return LatchTerm->getSuccessor(SuccNum);
254 // If the edge isn't critical, then BB has a single successor or Succ has a
255 // single pred. Split the block.
256 BasicBlock::iterator SplitPoint;
257 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
258 // If the successor only has a single pred, split the top of the successor
260 assert(SP == BB && "CFG broken");
262 return SplitBlock(Succ, Succ->begin(), P);
264 // Otherwise, if BB has a single successor, split it at the bottom of the
266 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
267 "Should have a single succ!");
268 return SplitBlock(BB, BB->getTerminator(), P);
272 /// SplitBlock - Split the specified block at the specified instruction - every
273 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
274 /// to a new block. The two blocks are joined by an unconditional branch and
275 /// the loop info is updated.
277 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
278 BasicBlock::iterator SplitIt = SplitPt;
279 while (isa<PHINode>(SplitIt))
281 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
283 // The new block lives in whichever loop the old one did.
284 if (LoopInfo* LI = P->getAnalysisToUpdate<LoopInfo>())
285 if (Loop *L = LI->getLoopFor(Old))
286 L->addBasicBlockToLoop(New, LI->getBase());
288 if (DominatorTree *DT = P->getAnalysisToUpdate<DominatorTree>())
290 // Old dominates New. New node domiantes all other nodes dominated by Old.
291 DomTreeNode *OldNode = DT->getNode(Old);
292 std::vector<DomTreeNode *> Children;
293 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
295 Children.push_back(*I);
297 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
299 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
300 E = Children.end(); I != E; ++I)
301 DT->changeImmediateDominator(*I, NewNode);
304 if (DominanceFrontier *DF = P->getAnalysisToUpdate<DominanceFrontier>())
311 /// SplitBlockPredecessors - This method transforms BB by introducing a new
312 /// basic block into the function, and moving some of the predecessors of BB to
313 /// be predecessors of the new block. The new predecessors are indicated by the
314 /// Preds array, which has NumPreds elements in it. The new block is given a
315 /// suffix of 'Suffix'.
317 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree and
318 /// DominanceFrontier, but no other analyses.
319 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
320 BasicBlock *const *Preds,
321 unsigned NumPreds, const char *Suffix,
323 // Create new basic block, insert right before the original block.
325 BasicBlock::Create(BB->getName()+Suffix, BB->getParent(), BB);
327 // The new block unconditionally branches to the old block.
328 BranchInst *BI = BranchInst::Create(BB, NewBB);
330 // Move the edges from Preds to point to NewBB instead of BB.
331 for (unsigned i = 0; i != NumPreds; ++i)
332 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
334 // Update dominator tree and dominator frontier if available.
335 DominatorTree *DT = P ? P->getAnalysisToUpdate<DominatorTree>() : 0;
337 DT->splitBlock(NewBB);
338 if (DominanceFrontier *DF = P ? P->getAnalysisToUpdate<DominanceFrontier>():0)
339 DF->splitBlock(NewBB);
340 AliasAnalysis *AA = P ? P->getAnalysisToUpdate<AliasAnalysis>() : 0;
343 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
344 // node becomes an incoming value for BB's phi node. However, if the Preds
345 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
346 // account for the newly created predecessor.
348 // Insert dummy values as the incoming value.
349 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
350 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
354 // Otherwise, create a new PHI node in NewBB for each PHI node in BB.
355 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
356 PHINode *PN = cast<PHINode>(I++);
358 // Check to see if all of the values coming in are the same. If so, we
359 // don't need to create a new PHI node.
360 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
361 for (unsigned i = 1; i != NumPreds; ++i)
362 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
368 // If all incoming values for the new PHI would be the same, just don't
369 // make a new PHI. Instead, just remove the incoming values from the old
371 for (unsigned i = 0; i != NumPreds; ++i)
372 PN->removeIncomingValue(Preds[i], false);
374 // If the values coming into the block are not the same, we need a PHI.
375 // Create the new PHI node, insert it into NewBB at the end of the block
377 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
378 if (AA) AA->copyValue(PN, NewPHI);
380 // Move all of the PHI values for 'Preds' to the new PHI.
381 for (unsigned i = 0; i != NumPreds; ++i) {
382 Value *V = PN->removeIncomingValue(Preds[i], false);
383 NewPHI->addIncoming(V, Preds[i]);
388 // Add an incoming value to the PHI node in the loop for the preheader
390 PN->addIncoming(InVal, NewBB);
392 // Check to see if we can eliminate this phi node.
393 if (Value *V = PN->hasConstantValue(DT != 0)) {
394 Instruction *I = dyn_cast<Instruction>(V);
395 if (!I || DT == 0 || DT->dominates(I, PN)) {
396 PN->replaceAllUsesWith(V);
397 if (AA) AA->deleteValue(PN);
398 PN->eraseFromParent();
406 /// AreEquivalentAddressValues - Test if A and B will obviously have the same
407 /// value. This includes recognizing that %t0 and %t1 will have the same
408 /// value in code like this:
409 /// %t0 = getelementptr @a, 0, 3
410 /// store i32 0, i32* %t0
411 /// %t1 = getelementptr @a, 0, 3
412 /// %t2 = load i32* %t1
414 static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
415 // Test if the values are trivially equivalent.
416 if (A == B) return true;
418 // Test if the values come form identical arithmetic instructions.
419 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
420 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
421 if (const Instruction *BI = dyn_cast<Instruction>(B))
422 if (cast<Instruction>(A)->isIdenticalTo(BI))
425 // Otherwise they may not be equivalent.
429 /// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
430 /// instruction before ScanFrom) checking to see if we have the value at the
431 /// memory address *Ptr locally available within a small number of instructions.
432 /// If the value is available, return it.
434 /// If not, return the iterator for the last validated instruction that the
435 /// value would be live through. If we scanned the entire block and didn't find
436 /// something that invalidates *Ptr or provides it, ScanFrom would be left at
437 /// begin() and this returns null. ScanFrom could also be left
439 /// MaxInstsToScan specifies the maximum instructions to scan in the block. If
440 /// it is set to 0, it will scan the whole block. You can also optionally
441 /// specify an alias analysis implementation, which makes this more precise.
442 Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
443 BasicBlock::iterator &ScanFrom,
444 unsigned MaxInstsToScan,
446 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
448 // If we're using alias analysis to disambiguate get the size of *Ptr.
449 unsigned AccessSize = 0;
451 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
452 AccessSize = AA->getTargetData().getTypeStoreSizeInBits(AccessTy);
455 while (ScanFrom != ScanBB->begin()) {
456 // Don't scan huge blocks.
457 if (MaxInstsToScan-- == 0) return 0;
459 Instruction *Inst = --ScanFrom;
461 // If this is a load of Ptr, the loaded value is available.
462 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
463 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
466 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
467 // If this is a store through Ptr, the value is available!
468 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
469 return SI->getOperand(0);
471 // If Ptr is an alloca and this is a store to a different alloca, ignore
472 // the store. This is a trivial form of alias analysis that is important
473 // for reg2mem'd code.
474 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
475 (isa<AllocaInst>(SI->getOperand(1)) ||
476 isa<GlobalVariable>(SI->getOperand(1))))
479 // If we have alias analysis and it says the store won't modify the loaded
480 // value, ignore the store.
482 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
485 // Otherwise the store that may or may not alias the pointer, bail out.
490 // If this is some other instruction that may clobber Ptr, bail out.
491 if (Inst->mayWriteToMemory()) {
492 // If alias analysis claims that it really won't modify the load,
495 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
498 // May modify the pointer, bail out.
504 // Got to the start of the block, we didn't find it, but are done for this