blob: b6f00e24c73f07aeadb1978bf0d28b32c7cb56a0 [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4d1e46e2002-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"
16#include "llvm/Function.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000017#include "llvm/Instructions.h"
Dale Johannesenbd8e6502009-03-03 01:09:07 +000018#include "llvm/IntrinsicInst.h"
Owen Anderson0a205a42009-07-05 22:41:43 +000019#include "llvm/LLVMContext.h"
Chris Lattnerb0f0ef82002-07-29 22:32:08 +000020#include "llvm/Constant.h"
21#include "llvm/Type.h"
Chris Lattner54b9c3b2008-04-21 01:28:02 +000022#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel80198932007-07-06 21:39:20 +000023#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/Analysis/Dominators.h"
Chris Lattneree6e10b2008-11-27 08:18:12 +000025#include "llvm/Target/TargetData.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000026#include "llvm/Transforms/Utils/Local.h"
Dan Gohman5c89b522009-09-08 15:45:00 +000027#include "llvm/Transforms/Scalar.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000028#include "llvm/Support/ErrorHandling.h"
Dan Gohmanafc36a92009-05-02 18:29:22 +000029#include "llvm/Support/ValueHandle.h"
Chris Lattner4d1e46e2002-05-07 18:07:59 +000030#include <algorithm>
Chris Lattnerf7703df2004-01-09 06:12:26 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Chris Lattner71af9b02008-12-03 06:40:52 +000033/// DeleteDeadBlock - Delete the specified block, which must have no
34/// predecessors.
35void llvm::DeleteDeadBlock(BasicBlock *BB) {
Chris Lattner2973a252008-12-03 07:45:15 +000036 assert((pred_begin(BB) == pred_end(BB) ||
37 // Can delete self loop.
38 BB->getSinglePredecessor() == BB) && "Block is not dead!");
Chris Lattner2b1ba242008-12-03 06:37:44 +000039 TerminatorInst *BBTerm = BB->getTerminator();
Devang Patel5622f072009-02-24 00:05:16 +000040
Chris Lattner2b1ba242008-12-03 06:37:44 +000041 // 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);
45
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).
54 if (!I.use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000055 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner2b1ba242008-12-03 06:37:44 +000056 BB->getInstList().pop_back();
57 }
Devang Patel5622f072009-02-24 00:05:16 +000058
Chris Lattner2b1ba242008-12-03 06:37:44 +000059 // Zap the block!
60 BB->eraseFromParent();
Chris Lattner2b1ba242008-12-03 06:37:44 +000061}
62
Chris Lattner29874e02008-12-03 19:44:02 +000063/// 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.
67void llvm::FoldSingleEntryPHINodes(BasicBlock *BB) {
68 if (!isa<PHINode>(BB->begin()))
69 return;
70
71 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
72 if (PN->getIncomingValue(0) != PN)
73 PN->replaceAllUsesWith(PN->getIncomingValue(0));
74 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000075 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
Chris Lattner29874e02008-12-03 19:44:02 +000076 PN->eraseFromParent();
77 }
78}
79
80
Dan Gohmanafc36a92009-05-02 18:29:22 +000081/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
82/// is dead. Also recursively delete any operands that become dead as
83/// a result. This includes tracing the def-use list from the PHI to see if
Dan Gohman35738ac2009-05-04 22:30:44 +000084/// it is ultimately unused or if it reaches an unused cycle.
85void llvm::DeleteDeadPHIs(BasicBlock *BB) {
Dan Gohmanafc36a92009-05-02 18:29:22 +000086 // Recursively deleting a PHI may cause multiple PHIs to be deleted
87 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
88 SmallVector<WeakVH, 8> PHIs;
89 for (BasicBlock::iterator I = BB->begin();
90 PHINode *PN = dyn_cast<PHINode>(I); ++I)
91 PHIs.push_back(PN);
92
93 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
94 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
Dan Gohman35738ac2009-05-04 22:30:44 +000095 RecursivelyDeleteDeadPHINode(PN);
Dan Gohmanafc36a92009-05-02 18:29:22 +000096}
97
Dan Gohmanf230d8a2009-10-31 16:08:00 +000098/// MergeBlockIntoPredecessor - Folds a basic block into its predecessor if it
99/// only has one predecessor, and that predecessor only has one successor.
100/// If a Pass is given, the LoopInfo and DominatorTree analyses will be kept
101/// current. Returns the combined block, or null if no merging was performed.
102BasicBlock *llvm::MergeBlockIntoPredecessor(BasicBlock* BB, Pass* P) {
103 // Don't merge if the block has multiple predecessors.
104 BasicBlock *PredBB = BB->getSinglePredecessor();
105 if (!PredBB) return 0;
106 // Don't merge if the predecessor has multiple successors.
107 if (PredBB->getTerminator()->getNumSuccessors() != 1) return 0;
Owen Anderson3ecaf1b2008-07-18 17:46:41 +0000108 // Don't break self-loops.
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000109 if (PredBB == BB) return 0;
Owen Anderson3ecaf1b2008-07-18 17:46:41 +0000110 // Don't break invokes.
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000111 if (isa<InvokeInst>(PredBB->getTerminator())) return 0;
Owen Anderson11f2ec82008-07-17 19:42:29 +0000112
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000113 // Resolve any PHI nodes at the start of the block. They are all
114 // guaranteed to have exactly one entry if they exist, unless there are
115 // multiple duplicate (but guaranteed to be equal) entries for the
116 // incoming edges. This occurs when there are multiple edges from
117 // PredBB to BB.
118 FoldSingleEntryPHINodes(BB);
Devang Patele435a5d2008-09-09 01:06:56 +0000119
Owen Andersonb31b06d2008-07-17 00:01:40 +0000120 // Delete the unconditional branch from the predecessor...
121 PredBB->getInstList().pop_back();
122
123 // Move all definitions in the successor to the predecessor...
124 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
125
126 // Make all PHI nodes that referred to BB now refer to Pred as their
127 // source...
128 BB->replaceAllUsesWith(PredBB);
129
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000130 // If the predecessor doesn't have a name, take the successor's name.
Owen Anderson11f2ec82008-07-17 19:42:29 +0000131 if (!PredBB->hasName())
132 PredBB->takeName(BB);
133
Owen Andersonb31b06d2008-07-17 00:01:40 +0000134 // Finally, erase the old block and update dominator info.
135 if (P) {
Duncan Sands1465d612009-01-28 13:14:17 +0000136 if (DominatorTree* DT = P->getAnalysisIfAvailable<DominatorTree>()) {
Owen Andersonb31b06d2008-07-17 00:01:40 +0000137 DomTreeNode* DTN = DT->getNode(BB);
138 DomTreeNode* PredDTN = DT->getNode(PredBB);
139
140 if (DTN) {
141 SmallPtrSet<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
142 for (SmallPtrSet<DomTreeNode*, 8>::iterator DI = Children.begin(),
143 DE = Children.end(); DI != DE; ++DI)
144 DT->changeImmediateDominator(*DI, PredDTN);
145
146 DT->eraseNode(BB);
147 }
148 }
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000149 // Notify LoopInfo that the block is removed.
150 if (LoopInfo *LI = P->getAnalysisIfAvailable<LoopInfo>())
151 LI->removeBlock(BB);
Owen Andersonb31b06d2008-07-17 00:01:40 +0000152 }
153
154 BB->eraseFromParent();
155
Dan Gohmanf230d8a2009-10-31 16:08:00 +0000156 return PredBB;
Owen Andersonb31b06d2008-07-17 00:01:40 +0000157}
158
Chris Lattner0f67dd62005-04-21 16:04:49 +0000159/// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
160/// with a value, then remove and delete the original instruction.
161///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000162void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
163 BasicBlock::iterator &BI, Value *V) {
Chris Lattner18961502002-06-25 16:12:52 +0000164 Instruction &I = *BI;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000165 // Replaces all of the uses of the instruction with uses of the value
Chris Lattner18961502002-06-25 16:12:52 +0000166 I.replaceAllUsesWith(V);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000167
Chris Lattner86cc4232007-02-11 01:37:51 +0000168 // Make sure to propagate a name if there is one already.
169 if (I.hasName() && !V->hasName())
170 V->takeName(&I);
Misha Brukmanfd939082005-04-21 23:48:37 +0000171
Misha Brukman5560c9d2003-08-18 14:43:39 +0000172 // Delete the unnecessary instruction now...
Chris Lattner18961502002-06-25 16:12:52 +0000173 BI = BIL.erase(BI);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000174}
175
176
Chris Lattner0f67dd62005-04-21 16:04:49 +0000177/// ReplaceInstWithInst - Replace the instruction specified by BI with the
178/// instruction specified by I. The original instruction is deleted and BI is
179/// updated to point to the new instruction.
180///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000181void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
182 BasicBlock::iterator &BI, Instruction *I) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000183 assert(I->getParent() == 0 &&
184 "ReplaceInstWithInst: Instruction already inserted into basic block!");
185
186 // Insert the new instruction into the basic block...
Chris Lattner18961502002-06-25 16:12:52 +0000187 BasicBlock::iterator New = BIL.insert(BI, I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000188
189 // Replace all uses of the old instruction, and delete it.
190 ReplaceInstWithValue(BIL, BI, I);
191
192 // Move BI back to point to the newly inserted instruction
Chris Lattner18961502002-06-25 16:12:52 +0000193 BI = New;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000194}
195
Chris Lattner0f67dd62005-04-21 16:04:49 +0000196/// ReplaceInstWithInst - Replace the instruction specified by From with the
197/// instruction specified by To.
198///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000199void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
Chris Lattner18961502002-06-25 16:12:52 +0000200 BasicBlock::iterator BI(From);
201 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000202}
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000203
Chris Lattner0f67dd62005-04-21 16:04:49 +0000204/// RemoveSuccessor - Change the specified terminator instruction such that its
Reid Spencerbc2eba12006-05-19 19:09:46 +0000205/// successor SuccNum no longer exists. Because this reduces the outgoing
Chris Lattner0f67dd62005-04-21 16:04:49 +0000206/// degree of the current basic block, the actual terminator instruction itself
Reid Spencerbc2eba12006-05-19 19:09:46 +0000207/// may have to be changed. In the case where the last successor of the block
208/// is deleted, a return instruction is inserted in its place which can cause a
Chris Lattner0f67dd62005-04-21 16:04:49 +0000209/// surprising change in program behavior if it is not expected.
210///
Chris Lattnerf7703df2004-01-09 06:12:26 +0000211void llvm::RemoveSuccessor(TerminatorInst *TI, unsigned SuccNum) {
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000212 assert(SuccNum < TI->getNumSuccessors() &&
213 "Trying to remove a nonexistant successor!");
214
215 // If our old successor block contains any PHI nodes, remove the entry in the
216 // PHI nodes that comes from this branch...
217 //
218 BasicBlock *BB = TI->getParent();
219 TI->getSuccessor(SuccNum)->removePredecessor(BB);
220
221 TerminatorInst *NewTI = 0;
222 switch (TI->getOpcode()) {
223 case Instruction::Br:
224 // If this is a conditional branch... convert to unconditional branch.
225 if (TI->getNumSuccessors() == 2) {
226 cast<BranchInst>(TI)->setUnconditionalDest(TI->getSuccessor(1-SuccNum));
227 } else { // Otherwise convert to a return instruction...
228 Value *RetVal = 0;
Misha Brukmanfd939082005-04-21 23:48:37 +0000229
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000230 // Create a value to return... if the function doesn't return null...
Owen Anderson1d0be152009-08-13 21:58:54 +0000231 if (BB->getParent()->getReturnType() != Type::getVoidTy(TI->getContext()))
Owen Andersona7235ea2009-07-31 20:28:14 +0000232 RetVal = Constant::getNullValue(BB->getParent()->getReturnType());
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000233
234 // Create the return...
Owen Anderson1d0be152009-08-13 21:58:54 +0000235 NewTI = ReturnInst::Create(TI->getContext(), RetVal);
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000236 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000237 break;
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000238
239 case Instruction::Invoke: // Should convert to call
240 case Instruction::Switch: // Should remove entry
241 default:
242 case Instruction::Ret: // Cannot happen, has no successors!
Torok Edwinc23197a2009-07-14 16:55:14 +0000243 llvm_unreachable("Unhandled terminator instruction type in RemoveSuccessor!");
Chris Lattnerb0f0ef82002-07-29 22:32:08 +0000244 }
245
246 if (NewTI) // If it's a different instruction, replace.
247 ReplaceInstWithInst(TI, NewTI);
248}
Brian Gaeked0fde302003-11-11 22:41:34 +0000249
Devang Patel80198932007-07-06 21:39:20 +0000250/// SplitEdge - Split the edge connecting specified block. Pass P must
251/// not be NULL.
252BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
253 TerminatorInst *LatchTerm = BB->getTerminator();
254 unsigned SuccNum = 0;
Devang Patel8a88a142008-11-03 23:14:09 +0000255#ifndef NDEBUG
256 unsigned e = LatchTerm->getNumSuccessors();
257#endif
258 for (unsigned i = 0; ; ++i) {
Devang Patel80198932007-07-06 21:39:20 +0000259 assert(i != e && "Didn't find edge?");
260 if (LatchTerm->getSuccessor(i) == Succ) {
261 SuccNum = i;
262 break;
263 }
264 }
265
266 // If this is a critical edge, let SplitCriticalEdge do it.
267 if (SplitCriticalEdge(BB->getTerminator(), SuccNum, P))
268 return LatchTerm->getSuccessor(SuccNum);
269
270 // If the edge isn't critical, then BB has a single successor or Succ has a
271 // single pred. Split the block.
272 BasicBlock::iterator SplitPoint;
273 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
274 // If the successor only has a single pred, split the top of the successor
275 // block.
276 assert(SP == BB && "CFG broken");
Devang Patel8a88a142008-11-03 23:14:09 +0000277 SP = NULL;
Devang Patel80198932007-07-06 21:39:20 +0000278 return SplitBlock(Succ, Succ->begin(), P);
279 } else {
280 // Otherwise, if BB has a single successor, split it at the bottom of the
281 // block.
282 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
283 "Should have a single succ!");
284 return SplitBlock(BB, BB->getTerminator(), P);
285 }
286}
287
288/// SplitBlock - Split the specified block at the specified instruction - every
289/// thing before SplitPt stays in Old and everything starting with SplitPt moves
290/// to a new block. The two blocks are joined by an unconditional branch and
291/// the loop info is updated.
292///
293BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
Devang Patel80198932007-07-06 21:39:20 +0000294 BasicBlock::iterator SplitIt = SplitPt;
295 while (isa<PHINode>(SplitIt))
296 ++SplitIt;
297 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
298
Dan Gohman5c89b522009-09-08 15:45:00 +0000299 // The new block lives in whichever loop the old one did. This preserves
300 // LCSSA as well, because we force the split point to be after any PHI nodes.
Duncan Sands1465d612009-01-28 13:14:17 +0000301 if (LoopInfo* LI = P->getAnalysisIfAvailable<LoopInfo>())
Owen Andersona90793b2008-10-03 06:55:35 +0000302 if (Loop *L = LI->getLoopFor(Old))
303 L->addBasicBlockToLoop(New, LI->getBase());
Devang Patel80198932007-07-06 21:39:20 +0000304
Duncan Sands1465d612009-01-28 13:14:17 +0000305 if (DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>())
Devang Patela8a8a362007-07-19 02:29:24 +0000306 {
307 // Old dominates New. New node domiantes all other nodes dominated by Old.
308 DomTreeNode *OldNode = DT->getNode(Old);
309 std::vector<DomTreeNode *> Children;
310 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
311 I != E; ++I)
312 Children.push_back(*I);
313
314 DomTreeNode *NewNode = DT->addNewBlock(New,Old);
315
316 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
317 E = Children.end(); I != E; ++I)
318 DT->changeImmediateDominator(*I, NewNode);
319 }
Devang Patel80198932007-07-06 21:39:20 +0000320
Duncan Sands1465d612009-01-28 13:14:17 +0000321 if (DominanceFrontier *DF = P->getAnalysisIfAvailable<DominanceFrontier>())
Devang Patel80198932007-07-06 21:39:20 +0000322 DF->splitBlock(Old);
323
324 return New;
325}
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000326
327
328/// SplitBlockPredecessors - This method transforms BB by introducing a new
329/// basic block into the function, and moving some of the predecessors of BB to
330/// be predecessors of the new block. The new predecessors are indicated by the
331/// Preds array, which has NumPreds elements in it. The new block is given a
332/// suffix of 'Suffix'.
333///
Dan Gohman5c89b522009-09-08 15:45:00 +0000334/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
335/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
336/// In particular, it does not preserve LoopSimplify (because it's
337/// complicated to handle the case where one of the edges being split
338/// is an exit of a loop with other exits).
339///
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000340BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
341 BasicBlock *const *Preds,
342 unsigned NumPreds, const char *Suffix,
343 Pass *P) {
344 // Create new basic block, insert right before the original block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000345 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
346 BB->getParent(), BB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000347
348 // The new block unconditionally branches to the old block.
349 BranchInst *BI = BranchInst::Create(BB, NewBB);
350
Dan Gohman5c89b522009-09-08 15:45:00 +0000351 LoopInfo *LI = P ? P->getAnalysisIfAvailable<LoopInfo>() : 0;
352 Loop *L = LI ? LI->getLoopFor(BB) : 0;
353 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
354
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000355 // Move the edges from Preds to point to NewBB instead of BB.
Dan Gohman5c89b522009-09-08 15:45:00 +0000356 // While here, if we need to preserve loop analyses, collect
357 // some information about how this split will affect loops.
358 bool HasLoopExit = false;
359 bool IsLoopEntry = !!L;
360 bool SplitMakesNewLoopHeader = false;
361 for (unsigned i = 0; i != NumPreds; ++i) {
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000362 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000363
364 if (LI) {
365 // If we need to preserve LCSSA, determine if any of
366 // the preds is a loop exit.
367 if (PreserveLCSSA)
368 if (Loop *PL = LI->getLoopFor(Preds[i]))
369 if (!PL->contains(BB))
370 HasLoopExit = true;
371 // If we need to preserve LoopInfo, note whether any of the
372 // preds crosses an interesting loop boundary.
373 if (L) {
374 if (L->contains(Preds[i]))
375 IsLoopEntry = false;
376 else
377 SplitMakesNewLoopHeader = true;
378 }
379 }
380 }
381
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000382 // Update dominator tree and dominator frontier if available.
Duncan Sands1465d612009-01-28 13:14:17 +0000383 DominatorTree *DT = P ? P->getAnalysisIfAvailable<DominatorTree>() : 0;
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000384 if (DT)
385 DT->splitBlock(NewBB);
Duncan Sands1465d612009-01-28 13:14:17 +0000386 if (DominanceFrontier *DF = P ? P->getAnalysisIfAvailable<DominanceFrontier>():0)
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000387 DF->splitBlock(NewBB);
Dan Gohman5c89b522009-09-08 15:45:00 +0000388
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000389 // 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.
393 if (NumPreds == 0) {
394 // Insert dummy values as the incoming value.
395 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000396 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000397 return NewBB;
398 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000399
400 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : 0;
401
402 if (L) {
403 if (IsLoopEntry) {
Dan Gohman841a1472009-10-19 16:04:50 +0000404 // 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.
416 if (PredLoop &&
417 PredLoop->contains(BB) &&
418 (!InnermostPredLoop ||
419 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
420 InnermostPredLoop = PredLoop;
421 }
422 if (InnermostPredLoop)
423 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
Dan Gohman5c89b522009-09-08 15:45:00 +0000424 } else {
425 L->addBasicBlockToLoop(NewBB, LI->getBase());
426 if (SplitMakesNewLoopHeader)
427 L->moveToHeader(NewBB);
428 }
429 }
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000430
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++);
434
435 // Check to see if all of the values coming in are the same. If so, we
Dan Gohman5c89b522009-09-08 15:45:00 +0000436 // don't need to create a new PHI node, unless it's needed for LCSSA.
437 Value *InVal = 0;
438 if (!HasLoopExit) {
439 InVal = PN->getIncomingValueForBlock(Preds[0]);
440 for (unsigned i = 1; i != NumPreds; ++i)
441 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
442 InVal = 0;
443 break;
444 }
445 }
446
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000447 if (InVal) {
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
450 // PHI.
451 for (unsigned i = 0; i != NumPreds; ++i)
452 PN->removeIncomingValue(Preds[i], false);
453 } else {
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
456 PHINode *NewPHI =
457 PHINode::Create(PN->getType(), PN->getName()+".ph", BI);
458 if (AA) AA->copyValue(PN, NewPHI);
459
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]);
464 }
465 InVal = NewPHI;
466 }
467
468 // Add an incoming value to the PHI node in the loop for the preheader
469 // edge.
470 PN->addIncoming(InVal, NewBB);
Chris Lattner54b9c3b2008-04-21 01:28:02 +0000471 }
472
473 return NewBB;
474}
Chris Lattner52c95852008-11-27 08:10:05 +0000475
Mike Stumpfe095f32009-05-04 18:40:41 +0000476/// 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.
479///
480/// The output is added to Result, as pairs of <from,to> edge info.
481void 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))
485 return;
486
487 SmallPtrSet<const BasicBlock*, 8> Visited;
488 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
489 SmallPtrSet<const BasicBlock*, 8> InStack;
490
491 Visited.insert(BB);
492 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
493 InStack.insert(BB);
494 do {
495 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
496 const BasicBlock *ParentBB = Top.first;
497 succ_const_iterator &I = Top.second;
498
499 bool FoundNew = false;
500 while (I != succ_end(ParentBB)) {
501 BB = *I++;
502 if (Visited.insert(BB)) {
503 FoundNew = true;
504 break;
505 }
506 // Successor is in VisitStack, it's a back edge.
507 if (InStack.count(BB))
508 Result.push_back(std::make_pair(ParentBB, BB));
509 }
510
511 if (FoundNew) {
512 // Go down one level if there is a unvisited successor.
513 InStack.insert(BB);
514 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
515 } else {
516 // Go up one level.
517 InStack.erase(VisitStack.pop_back_val().first);
518 }
519 } while (!VisitStack.empty());
520
521
522}
523
524
525
Chris Lattner4aebaee2008-11-27 08:56:30 +0000526/// AreEquivalentAddressValues - Test if A and B will obviously have the same
527/// value. This includes recognizing that %t0 and %t1 will have the same
528/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000529/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000530/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +0000531/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +0000532/// %t2 = load i32* %t1
533///
534static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
535 // Test if the values are trivially equivalent.
536 if (A == B) return true;
537
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000538 // Test if the values come from identical arithmetic instructions.
539 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
540 // this function is only used when one address use dominates the
541 // other, which means that they'll always either have the same
542 // value or one of them will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +0000543 if (isa<BinaryOperator>(A) || isa<CastInst>(A) ||
544 isa<PHINode>(A) || isa<GetElementPtrInst>(A))
545 if (const Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +0000546 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000547 return true;
548
549 // Otherwise they may not be equivalent.
550 return false;
551}
552
Chris Lattner52c95852008-11-27 08:10:05 +0000553/// FindAvailableLoadedValue - Scan the ScanBB block backwards (starting at the
554/// instruction before ScanFrom) checking to see if we have the value at the
555/// memory address *Ptr locally available within a small number of instructions.
556/// If the value is available, return it.
557///
558/// If not, return the iterator for the last validated instruction that the
559/// value would be live through. If we scanned the entire block and didn't find
560/// something that invalidates *Ptr or provides it, ScanFrom would be left at
561/// begin() and this returns null. ScanFrom could also be left
562///
563/// MaxInstsToScan specifies the maximum instructions to scan in the block. If
564/// it is set to 0, it will scan the whole block. You can also optionally
565/// specify an alias analysis implementation, which makes this more precise.
566Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
567 BasicBlock::iterator &ScanFrom,
568 unsigned MaxInstsToScan,
569 AliasAnalysis *AA) {
570 if (MaxInstsToScan == 0) MaxInstsToScan = ~0U;
Chris Lattneree6e10b2008-11-27 08:18:12 +0000571
572 // If we're using alias analysis to disambiguate get the size of *Ptr.
573 unsigned AccessSize = 0;
574 if (AA) {
575 const Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
Dan Gohmanfc2a3ed2009-07-25 00:48:42 +0000576 AccessSize = AA->getTypeStoreSize(AccessTy);
Chris Lattneree6e10b2008-11-27 08:18:12 +0000577 }
Chris Lattner52c95852008-11-27 08:10:05 +0000578
579 while (ScanFrom != ScanBB->begin()) {
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000580 // We must ignore debug info directives when counting (otherwise they
581 // would affect codegen).
582 Instruction *Inst = --ScanFrom;
583 if (isa<DbgInfoIntrinsic>(Inst))
584 continue;
Dale Johannesend9c05d72009-03-04 02:06:53 +0000585 // We skip pointer-to-pointer bitcasts, which are NOPs.
586 // It is necessary for correctness to skip those that feed into a
587 // llvm.dbg.declare, as these are not present when debugging is off.
588 if (isa<BitCastInst>(Inst) && isa<PointerType>(Inst->getType()))
Dale Johannesen4ded40a2009-03-03 22:36:47 +0000589 continue;
590
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000591 // Restore ScanFrom to expected value in case next test succeeds
592 ScanFrom++;
593
Chris Lattner52c95852008-11-27 08:10:05 +0000594 // Don't scan huge blocks.
595 if (MaxInstsToScan-- == 0) return 0;
596
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000597 --ScanFrom;
Chris Lattner52c95852008-11-27 08:10:05 +0000598 // If this is a load of Ptr, the loaded value is available.
599 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chris Lattner4aebaee2008-11-27 08:56:30 +0000600 if (AreEquivalentAddressValues(LI->getOperand(0), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000601 return LI;
602
603 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
604 // If this is a store through Ptr, the value is available!
Chris Lattner4aebaee2008-11-27 08:56:30 +0000605 if (AreEquivalentAddressValues(SI->getOperand(1), Ptr))
Chris Lattner52c95852008-11-27 08:10:05 +0000606 return SI->getOperand(0);
607
608 // If Ptr is an alloca and this is a store to a different alloca, ignore
609 // the store. This is a trivial form of alias analysis that is important
610 // for reg2mem'd code.
611 if ((isa<AllocaInst>(Ptr) || isa<GlobalVariable>(Ptr)) &&
612 (isa<AllocaInst>(SI->getOperand(1)) ||
613 isa<GlobalVariable>(SI->getOperand(1))))
614 continue;
615
Chris Lattneree6e10b2008-11-27 08:18:12 +0000616 // If we have alias analysis and it says the store won't modify the loaded
617 // value, ignore the store.
618 if (AA &&
619 (AA->getModRefInfo(SI, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
620 continue;
621
Chris Lattner52c95852008-11-27 08:10:05 +0000622 // Otherwise the store that may or may not alias the pointer, bail out.
623 ++ScanFrom;
624 return 0;
625 }
626
Chris Lattner52c95852008-11-27 08:10:05 +0000627 // If this is some other instruction that may clobber Ptr, bail out.
628 if (Inst->mayWriteToMemory()) {
Chris Lattneree6e10b2008-11-27 08:18:12 +0000629 // If alias analysis claims that it really won't modify the load,
630 // ignore it.
631 if (AA &&
632 (AA->getModRefInfo(Inst, Ptr, AccessSize) & AliasAnalysis::Mod) == 0)
633 continue;
634
Chris Lattner52c95852008-11-27 08:10:05 +0000635 // May modify the pointer, bail out.
636 ++ScanFrom;
637 return 0;
638 }
639 }
640
641 // Got to the start of the block, we didn't find it, but are done for this
642 // block.
643 return 0;
644}
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000645
646/// CopyPrecedingStopPoint - If I is immediately preceded by a StopPoint,
647/// make a copy of the stoppoint before InsertPos (presumably before copying
648/// or moving I).
649void llvm::CopyPrecedingStopPoint(Instruction *I,
650 BasicBlock::iterator InsertPos) {
651 if (I != I->getParent()->begin()) {
652 BasicBlock::iterator BBI = I; --BBI;
653 if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BBI)) {
Devang Patel50b6e332009-10-27 22:16:29 +0000654 CallInst *newDSPI = cast<CallInst>(DSPI->clone());
Dale Johannesenbd8e6502009-03-03 01:09:07 +0000655 newDSPI->insertBefore(InsertPos);
656 }
657 }
658}