blob: 5acece85c34bf6ac41c05c79442930e2b274c860 [file] [log] [blame]
Chris Lattner55d47882003-10-12 21:44:18 +00001//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner61992f62002-09-26 16:17:31 +00009//
Chris Lattner154e4d52003-10-12 21:43:28 +000010// This pass performs several transformations to transform natural loops into a
11// simpler form, which makes subsequent analyses and transformations simpler and
12// more effective.
Chris Lattner650096a2003-02-27 20:27:08 +000013//
14// Loop pre-header insertion guarantees that there is a single, non-critical
15// entry edge from outside of the loop to the loop header. This simplifies a
16// number of analyses and transformations, such as LICM.
17//
18// Loop exit-block insertion guarantees that all exit blocks from the loop
19// (blocks which are outside of the loop that have predecessors inside of the
Chris Lattner7710f2f2003-12-10 17:20:35 +000020// loop) only have predecessors from inside of the loop (and are thus dominated
21// by the loop header). This simplifies transformations such as store-sinking
22// that are built into LICM.
Chris Lattner650096a2003-02-27 20:27:08 +000023//
Chris Lattnerc4622a62003-10-13 00:37:13 +000024// This pass also guarantees that loops will have exactly one backedge.
25//
Chris Lattner650096a2003-02-27 20:27:08 +000026// Note that the simplifycfg pass will clean up blocks which are split out but
Chris Lattner154e4d52003-10-12 21:43:28 +000027// end up being unnecessary, so usage of this pass should not pessimize
28// generated code.
29//
30// This pass obviously modifies the CFG, but updates loop information and
31// dominator information.
Chris Lattner61992f62002-09-26 16:17:31 +000032//
33//===----------------------------------------------------------------------===//
34
35#include "llvm/Transforms/Scalar.h"
Chris Lattnerd0788122004-03-14 03:59:22 +000036#include "llvm/Constant.h"
Chris Lattner61992f62002-09-26 16:17:31 +000037#include "llvm/iTerminators.h"
38#include "llvm/iPHINode.h"
Chris Lattnerd0788122004-03-14 03:59:22 +000039#include "llvm/Function.h"
40#include "llvm/Type.h"
Chris Lattner031a3f82003-12-19 06:27:08 +000041#include "llvm/Analysis/Dominators.h"
42#include "llvm/Analysis/LoopInfo.h"
Chris Lattner61992f62002-09-26 16:17:31 +000043#include "llvm/Support/CFG.h"
Chris Lattner84170522004-04-13 05:05:33 +000044#include "llvm/Transforms/Utils/Local.h"
Chris Lattner650096a2003-02-27 20:27:08 +000045#include "Support/SetOperations.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000046#include "Support/Statistic.h"
Chris Lattner32a39c22003-02-28 03:07:54 +000047#include "Support/DepthFirstIterator.h"
Chris Lattner7710f2f2003-12-10 17:20:35 +000048using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000049
Chris Lattner61992f62002-09-26 16:17:31 +000050namespace {
Chris Lattner154e4d52003-10-12 21:43:28 +000051 Statistic<>
Chris Lattner7710f2f2003-12-10 17:20:35 +000052 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
Chris Lattner84170522004-04-13 05:05:33 +000053 Statistic<>
54 NumNested("loopsimplify", "Number of nested loops split out");
Chris Lattner61992f62002-09-26 16:17:31 +000055
Chris Lattner154e4d52003-10-12 21:43:28 +000056 struct LoopSimplify : public FunctionPass {
Chris Lattner61992f62002-09-26 16:17:31 +000057 virtual bool runOnFunction(Function &F);
58
59 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60 // We need loop information to identify the loops...
61 AU.addRequired<LoopInfo>();
Chris Lattner650096a2003-02-27 20:27:08 +000062 AU.addRequired<DominatorSet>();
Chris Lattner797cb2f2004-03-13 22:01:26 +000063 AU.addRequired<DominatorTree>();
Chris Lattner61992f62002-09-26 16:17:31 +000064
65 AU.addPreserved<LoopInfo>();
66 AU.addPreserved<DominatorSet>();
67 AU.addPreserved<ImmediateDominators>();
68 AU.addPreserved<DominatorTree>();
Chris Lattner650096a2003-02-27 20:27:08 +000069 AU.addPreserved<DominanceFrontier>();
Chris Lattner61992f62002-09-26 16:17:31 +000070 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
71 }
72 private:
73 bool ProcessLoop(Loop *L);
Chris Lattner650096a2003-02-27 20:27:08 +000074 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
75 const std::vector<BasicBlock*> &Preds);
76 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner61992f62002-09-26 16:17:31 +000077 void InsertPreheaderForLoop(Loop *L);
Chris Lattner84170522004-04-13 05:05:33 +000078 Loop *SeparateNestedLoop(Loop *L);
Chris Lattnerc4622a62003-10-13 00:37:13 +000079 void InsertUniqueBackedgeBlock(Loop *L);
80
81 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
82 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner61992f62002-09-26 16:17:31 +000083 };
84
Chris Lattner154e4d52003-10-12 21:43:28 +000085 RegisterOpt<LoopSimplify>
86 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner61992f62002-09-26 16:17:31 +000087}
88
89// Publically exposed interface to pass...
Chris Lattner7710f2f2003-12-10 17:20:35 +000090const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
91Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner61992f62002-09-26 16:17:31 +000092
Chris Lattner61992f62002-09-26 16:17:31 +000093/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
94/// it in any convenient order) inserting preheaders...
95///
Chris Lattner154e4d52003-10-12 21:43:28 +000096bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner61992f62002-09-26 16:17:31 +000097 bool Changed = false;
98 LoopInfo &LI = getAnalysis<LoopInfo>();
99
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000100 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
101 Changed |= ProcessLoop(*I);
Chris Lattner61992f62002-09-26 16:17:31 +0000102
103 return Changed;
104}
105
106
107/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
108/// all loops have preheaders.
109///
Chris Lattner154e4d52003-10-12 21:43:28 +0000110bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000111 bool Changed = false;
112
Chris Lattnerd0788122004-03-14 03:59:22 +0000113 // Check to see that no blocks (other than the header) in the loop have
114 // predecessors that are not in the loop. This is not valid for natural
115 // loops, but can occur if the blocks are unreachable. Since they are
116 // unreachable we can just shamelessly destroy their terminators to make them
117 // not branch into the loop!
118 assert(L->getBlocks()[0] == L->getHeader() &&
119 "Header isn't first block in loop?");
120 for (unsigned i = 1, e = L->getBlocks().size(); i != e; ++i) {
121 BasicBlock *LoopBB = L->getBlocks()[i];
122 Retry:
123 for (pred_iterator PI = pred_begin(LoopBB), E = pred_end(LoopBB);
124 PI != E; ++PI)
125 if (!L->contains(*PI)) {
126 // This predecessor is not in the loop. Kill its terminator!
127 BasicBlock *DeadBlock = *PI;
128 for (succ_iterator SI = succ_begin(DeadBlock), E = succ_end(DeadBlock);
129 SI != E; ++SI)
130 (*SI)->removePredecessor(DeadBlock); // Remove PHI node entries
131
132 // Delete the dead terminator.
133 DeadBlock->getInstList().pop_back();
134
135 Value *RetVal = 0;
136 if (LoopBB->getParent()->getReturnType() != Type::VoidTy)
137 RetVal = Constant::getNullValue(LoopBB->getParent()->getReturnType());
138 new ReturnInst(RetVal, DeadBlock);
139 goto Retry; // We just invalidated the pred_iterator. Retry.
140 }
141 }
142
Chris Lattner61992f62002-09-26 16:17:31 +0000143 // Does the loop already have a preheader? If so, don't modify the loop...
144 if (L->getLoopPreheader() == 0) {
145 InsertPreheaderForLoop(L);
146 NumInserted++;
147 Changed = true;
148 }
149
Chris Lattner7710f2f2003-12-10 17:20:35 +0000150 // Next, check to make sure that all exit nodes of the loop only have
151 // predecessors that are inside of the loop. This check guarantees that the
152 // loop preheader/header will dominate the exit blocks. If the exit block has
153 // predecessors from outside of the loop, split the edge now.
154 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i) {
155 BasicBlock *ExitBlock = L->getExitBlocks()[i];
156 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
157 PI != PE; ++PI)
158 if (!L->contains(*PI)) {
159 RewriteLoopExitBlock(L, ExitBlock);
160 NumInserted++;
161 Changed = true;
162 break;
163 }
Chris Lattner650096a2003-02-27 20:27:08 +0000164 }
165
Chris Lattner84170522004-04-13 05:05:33 +0000166 // If the header has more than two predecessors at this point (from the
167 // preheader and from multiple backedges), we must adjust the loop.
Chris Lattnerc4622a62003-10-13 00:37:13 +0000168 if (L->getNumBackEdges() != 1) {
Chris Lattner84170522004-04-13 05:05:33 +0000169 // If this is really a nested loop, rip it out into a child loop.
170 if (Loop *NL = SeparateNestedLoop(L)) {
171 ++NumNested;
172 // This is a big restructuring change, reprocess the whole loop.
173 ProcessLoop(NL);
174 return true;
175 }
176
Chris Lattnerc4622a62003-10-13 00:37:13 +0000177 InsertUniqueBackedgeBlock(L);
178 NumInserted++;
179 Changed = true;
180 }
181
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000182 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
183 Changed |= ProcessLoop(*I);
Chris Lattner61992f62002-09-26 16:17:31 +0000184 return Changed;
185}
186
Chris Lattner650096a2003-02-27 20:27:08 +0000187/// SplitBlockPredecessors - Split the specified block into two blocks. We want
188/// to move the predecessors specified in the Preds list to point to the new
189/// block, leaving the remaining predecessors pointing to BB. This method
190/// updates the SSA PHINode's, but no other analyses.
191///
Chris Lattner154e4d52003-10-12 21:43:28 +0000192BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
193 const char *Suffix,
Chris Lattner650096a2003-02-27 20:27:08 +0000194 const std::vector<BasicBlock*> &Preds) {
195
196 // Create new basic block, insert right before the original block...
Chris Lattner8d414ad2004-02-04 03:58:28 +0000197 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattner650096a2003-02-27 20:27:08 +0000198
199 // The preheader first gets an unconditional branch to the loop header...
Chris Lattnera2960002003-11-21 16:52:05 +0000200 BranchInst *BI = new BranchInst(BB, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000201
202 // For every PHI node in the block, insert a PHI node into NewBB where the
203 // incoming values from the out of loop edges are moved to NewBB. We have two
204 // possible cases here. If the loop is dead, we just insert dummy entries
205 // into the PHI nodes for the new edge. If the loop is not dead, we move the
206 // incoming edges in BB into new PHI nodes in NewBB.
207 //
208 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner031a3f82003-12-19 06:27:08 +0000209 // Check to see if the values being merged into the new block need PHI
210 // nodes. If so, insert them.
211 for (BasicBlock::iterator I = BB->begin();
Chris Lattner84170522004-04-13 05:05:33 +0000212 PHINode *PN = dyn_cast<PHINode>(I); ) {
213 ++I;
214
Chris Lattner031a3f82003-12-19 06:27:08 +0000215 // Check to see if all of the values coming in are the same. If so, we
216 // don't need to create a new PHI node.
217 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
218 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
219 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
220 InVal = 0;
221 break;
222 }
223
224 // If the values coming into the block are not the same, we need a PHI.
225 if (InVal == 0) {
Chris Lattner6c237bc2003-12-09 23:12:55 +0000226 // Create the new PHI node, insert it into NewBB at the end of the block
227 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
228
229 // Move all of the edges from blocks outside the loop to the new PHI
230 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Chris Lattner84170522004-04-13 05:05:33 +0000231 Value *V = PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000232 NewPHI->addIncoming(V, Preds[i]);
233 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000234 InVal = NewPHI;
235 } else {
236 // Remove all of the edges coming into the PHI nodes from outside of the
237 // block.
238 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
239 PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000240 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000241
242 // Add an incoming value to the PHI node in the loop for the preheader
243 // edge.
244 PN->addIncoming(InVal, NewBB);
Chris Lattner84170522004-04-13 05:05:33 +0000245
246 // Can we eliminate this phi node now?
247 if (Value *V = hasConstantValue(PN)) {
248 PN->replaceAllUsesWith(V);
249 BB->getInstList().erase(PN);
250 }
Chris Lattner650096a2003-02-27 20:27:08 +0000251 }
252
253 // Now that the PHI nodes are updated, actually move the edges from
254 // Preds to point to NewBB instead of BB.
255 //
256 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
257 TerminatorInst *TI = Preds[i]->getTerminator();
258 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
259 if (TI->getSuccessor(s) == BB)
260 TI->setSuccessor(s, NewBB);
261 }
262
263 } else { // Otherwise the loop is dead...
264 for (BasicBlock::iterator I = BB->begin();
Chris Lattner889f6202003-04-23 16:37:45 +0000265 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattner650096a2003-02-27 20:27:08 +0000266 // Insert dummy values as the incoming value...
267 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
268 }
269 return NewBB;
270}
271
Chris Lattner08950252003-05-12 22:04:34 +0000272// ChangeExitBlock - This recursive function is used to change any exit blocks
273// that use OldExit to use NewExit instead. This is recursive because children
274// may need to be processed as well.
275//
276static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) {
277 if (L->hasExitBlock(OldExit)) {
278 L->changeExitBlock(OldExit, NewExit);
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000279 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
280 ChangeExitBlock(*I, OldExit, NewExit);
Chris Lattner08950252003-05-12 22:04:34 +0000281 }
282}
283
Chris Lattner61992f62002-09-26 16:17:31 +0000284
285/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
286/// preheader, this method is called to insert one. This method has two phases:
287/// preheader insertion and analysis updating.
288///
Chris Lattner154e4d52003-10-12 21:43:28 +0000289void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000290 BasicBlock *Header = L->getHeader();
291
292 // Compute the set of predecessors of the loop that are not in the loop.
293 std::vector<BasicBlock*> OutsideBlocks;
294 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
295 PI != PE; ++PI)
296 if (!L->contains(*PI)) // Coming in from outside the loop?
297 OutsideBlocks.push_back(*PI); // Keep track of it...
298
Chris Lattner650096a2003-02-27 20:27:08 +0000299 // Split out the loop pre-header
300 BasicBlock *NewBB =
301 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner61992f62002-09-26 16:17:31 +0000302
Chris Lattner61992f62002-09-26 16:17:31 +0000303 //===--------------------------------------------------------------------===//
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000304 // Update analysis results now that we have performed the transformation
Chris Lattner61992f62002-09-26 16:17:31 +0000305 //
306
307 // We know that we have loop information to update... update it now.
308 if (Loop *Parent = L->getParentLoop())
309 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000310
311 // If the header for the loop used to be an exit node for another loop, then
312 // we need to update this to know that the loop-preheader is now the exit
313 // node. Note that the only loop that could have our header as an exit node
Chris Lattner08950252003-05-12 22:04:34 +0000314 // is a sibling loop, ie, one with the same parent loop, or one if it's
315 // children.
316 //
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000317 LoopInfo::iterator ParentLoops, ParentLoopsE;
318 if (Loop *Parent = L->getParentLoop()) {
319 ParentLoops = Parent->begin();
320 ParentLoopsE = Parent->end();
321 } else { // Must check top-level loops...
322 ParentLoops = getAnalysis<LoopInfo>().begin();
323 ParentLoopsE = getAnalysis<LoopInfo>().end();
324 }
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000325
Chris Lattner08950252003-05-12 22:04:34 +0000326 // Loop over all sibling loops, performing the substitution (recursively to
327 // include child loops)...
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000328 for (; ParentLoops != ParentLoopsE; ++ParentLoops)
329 ChangeExitBlock(*ParentLoops, Header, NewBB);
Chris Lattner61992f62002-09-26 16:17:31 +0000330
Chris Lattner650096a2003-02-27 20:27:08 +0000331 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
Chris Lattner797cb2f2004-03-13 22:01:26 +0000332 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattnerdb5b8f42004-03-16 06:00:15 +0000333
334
335 // Update the dominator tree information.
336 // The immediate dominator of the preheader is the immediate dominator of
337 // the old header.
338 DominatorTree::Node *PHDomTreeNode =
339 DT.createNewNode(NewBB, DT.getNode(Header)->getIDom());
340
341 // Change the header node so that PNHode is the new immediate dominator
342 DT.changeImmediateDominator(DT.getNode(Header), PHDomTreeNode);
Chris Lattner797cb2f2004-03-13 22:01:26 +0000343
Chris Lattner650096a2003-02-27 20:27:08 +0000344 {
Chris Lattner61992f62002-09-26 16:17:31 +0000345 // The blocks that dominate NewBB are the blocks that dominate Header,
346 // minus Header, plus NewBB.
Chris Lattner650096a2003-02-27 20:27:08 +0000347 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner61992f62002-09-26 16:17:31 +0000348 DomSet.erase(Header); // Header does not dominate us...
Chris Lattner650096a2003-02-27 20:27:08 +0000349 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner03a9e152002-09-29 21:41:38 +0000350
351 // The newly created basic block dominates all nodes dominated by Header.
Chris Lattnerdb5b8f42004-03-16 06:00:15 +0000352 for (df_iterator<DominatorTree::Node*> DFI = df_begin(PHDomTreeNode),
353 E = df_end(PHDomTreeNode); DFI != E; ++DFI)
354 DS.addDominator((*DFI)->getBlock(), NewBB);
Chris Lattner61992f62002-09-26 16:17:31 +0000355 }
356
357 // Update immediate dominator information if we have it...
358 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
359 // Whatever i-dominated the header node now immediately dominates NewBB
360 ID->addNewBlock(NewBB, ID->get(Header));
361
362 // The preheader now is the immediate dominator for the header node...
363 ID->setImmediateDominator(Header, NewBB);
364 }
365
Chris Lattner650096a2003-02-27 20:27:08 +0000366 // Update dominance frontier information...
367 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
368 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
369 // everything that Header does, and it strictly dominates Header in
370 // addition.
371 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
372 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
373 NewDFSet.erase(Header);
374 DF->addBasicBlock(NewBB, NewDFSet);
375
376 // Now we must loop over all of the dominance frontiers in the function,
Misha Brukman4ace48e2003-09-09 21:54:45 +0000377 // replacing occurrences of Header with NewBB in some cases. If a block
Chris Lattner650096a2003-02-27 20:27:08 +0000378 // dominates a (now) predecessor of NewBB, but did not strictly dominate
379 // Header, it will have Header in it's DF set, but should now have NewBB in
380 // its set.
381 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
382 // Get all of the dominators of the predecessor...
383 const DominatorSet::DomSetType &PredDoms =
384 DS.getDominators(OutsideBlocks[i]);
385 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
386 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
387 BasicBlock *PredDom = *PDI;
388 // If the loop header is in DF(PredDom), then PredDom didn't dominate
389 // the header but did dominate a predecessor outside of the loop. Now
390 // we change this entry to include the preheader in the DF instead of
391 // the header.
392 DominanceFrontier::iterator DFI = DF->find(PredDom);
393 assert(DFI != DF->end() && "No dominance frontier for node?");
394 if (DFI->second.count(Header)) {
395 DF->removeFromFrontier(DFI, Header);
396 DF->addToFrontier(DFI, NewBB);
397 }
398 }
399 }
400 }
401}
402
Chris Lattner84170522004-04-13 05:05:33 +0000403/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
404/// blocks. This method is used to split exit blocks that have predecessors
405/// outside of the loop.
Chris Lattner154e4d52003-10-12 21:43:28 +0000406void LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattner650096a2003-02-27 20:27:08 +0000407 DominatorSet &DS = getAnalysis<DominatorSet>();
Chris Lattner10b2b052003-02-27 22:31:07 +0000408 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
409 != L->getExitBlocks().end() && "Not a current exit block!");
Chris Lattner650096a2003-02-27 20:27:08 +0000410
411 std::vector<BasicBlock*> LoopBlocks;
412 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
413 if (L->contains(*I))
414 LoopBlocks.push_back(*I);
415
Chris Lattner10b2b052003-02-27 22:31:07 +0000416 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
417 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
418
Chris Lattner4e2fbfb2003-02-27 21:50:19 +0000419 // Update Loop Information - we know that the new block will be in the parent
420 // loop of L.
421 if (Loop *Parent = L->getParentLoop())
422 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner32a39c22003-02-28 03:07:54 +0000423
424 // Replace any instances of Exit with NewBB in this and any nested loops...
425 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
Chris Lattner49eb0e32003-02-28 16:54:17 +0000426 if (I->hasExitBlock(Exit))
427 I->changeExitBlock(Exit, NewBB); // Update exit block information
Chris Lattner4e2fbfb2003-02-27 21:50:19 +0000428
Chris Lattnerc4622a62003-10-13 00:37:13 +0000429 // Update dominator information (set, immdom, domtree, and domfrontier)
430 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
431}
432
Chris Lattner84170522004-04-13 05:05:33 +0000433/// AddBlockAndPredsToSet - Add the specified block, and all of its
434/// predecessors, to the specified set, if it's not already in there. Stop
435/// predecessor traversal when we reach StopBlock.
436static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
437 std::set<BasicBlock*> &Blocks) {
438 if (!Blocks.insert(BB).second) return; // already processed.
439 if (BB == StopBlock) return; // Stop here!
440
441 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
442 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
443}
444
445static void ReplaceExitBlocksOfLoopAndParents(Loop *L, BasicBlock *Old,
446 BasicBlock *New) {
447 if (!L->hasExitBlock(Old)) return;
448 L->changeExitBlock(Old, New);
449 ReplaceExitBlocksOfLoopAndParents(L->getParentLoop(), Old, New);
450}
451
452/// VerifyExitBlocks - This is a function which can be useful for hacking on the
453/// LoopSimplify Code.
454static void VerifyExitBlocks(Loop *L) {
455 std::vector<BasicBlock*> ExitBlocks;
456 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
457 BasicBlock *BB = L->getBlocks()[i];
458 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
459 if (!L->contains(*SI))
460 ExitBlocks.push_back(*SI);
461 }
462
463 std::vector<BasicBlock*> EB = L->getExitBlocks();
464 std::sort(EB.begin(), EB.end());
465 std::sort(ExitBlocks.begin(), ExitBlocks.end());
466 assert(EB == ExitBlocks && "Exit blocks were incorrectly updated!");
467
468 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
469 VerifyExitBlocks(*I);
470}
471
472/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
473/// them out into a nested loop. This is important for code that looks like
474/// this:
475///
476/// Loop:
477/// ...
478/// br cond, Loop, Next
479/// ...
480/// br cond2, Loop, Out
481///
482/// To identify this common case, we look at the PHI nodes in the header of the
483/// loop. PHI nodes with unchanging values on one backedge correspond to values
484/// that change in the "outer" loop, but not in the "inner" loop.
485///
486/// If we are able to separate out a loop, return the new outer loop that was
487/// created.
488///
489Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
490 BasicBlock *Header = L->getHeader();
491
492 std::vector<BasicBlock*> OuterLoopPreds;
493 for (BasicBlock::iterator I = Header->begin();
494 PHINode *PN = dyn_cast<PHINode>(I); ) {
495 ++I;
496 if (Value *V = hasConstantValue(PN)) {
497 // This is a degenerate PHI already, don't modify it!
498 PN->replaceAllUsesWith(V);
499 Header->getInstList().erase(PN);
500 continue;
501 }
502
503 // Scan this PHI node looking for a use of the PHI node by itself.
504 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
505 if (PN->getIncomingValue(i) == PN &&
506 L->contains(PN->getIncomingBlock(i))) {
507 // Wow, we found something tasty to remove. Pull out all predecessors
508 // that have varying values in the loop. This handles the case when a
509 // PHI node has multiple instances of itself as arguments.
510 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
511 if (PN->getIncomingValue(i) != PN ||
512 !L->contains(PN->getIncomingBlock(i)))
513 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
514 goto FoundExtraction;
515 }
516 }
517
518 return 0; // Nothing looks appetizing to separate out
519
520FoundExtraction:
521 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
522
523 // Update dominator information (set, immdom, domtree, and domfrontier)
524 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
525
526 // Create the new outer loop.
527 Loop *NewOuter = new Loop();
528
529 LoopInfo &LI = getAnalysis<LoopInfo>();
530
531 // Change the parent loop to use the outer loop as its child now.
532 if (Loop *Parent = L->getParentLoop())
533 Parent->replaceChildLoopWith(L, NewOuter);
534 else
535 LI.changeTopLevelLoop(L, NewOuter);
536
537 // This block is going to be our new header block: add it to this loop and all
538 // parent loops.
539 NewOuter->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
540
541 // L is now a subloop of our outer loop.
542 NewOuter->addChildLoop(L);
543
544 // Add all of L's exit blocks to the outer loop.
545 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i)
546 NewOuter->addExitBlock(L->getExitBlocks()[i]);
547
548 // Add temporary exit block entries for NewBB. Add one for each edge in L
549 // that goes to NewBB.
550 for (pred_iterator PI = pred_begin(NewBB), E = pred_end(NewBB); PI != E; ++PI)
551 if (L->contains(*PI))
552 L->addExitBlock(NewBB);
553
554 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
555 NewOuter->addBlockEntry(L->getBlocks()[i]);
556
557 // Determine which blocks should stay in L and which should be moved out to
558 // the Outer loop now.
559 DominatorSet &DS = getAnalysis<DominatorSet>();
560 std::set<BasicBlock*> BlocksInL;
561 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
562 if (DS.dominates(Header, *PI))
563 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
564
565
566 // Scan all of the loop children of L, moving them to OuterLoop if they are
567 // not part of the inner loop.
568 for (Loop::iterator I = L->begin(); I != L->end(); )
569 if (BlocksInL.count((*I)->getHeader()))
570 ++I; // Loop remains in L
571 else
572 NewOuter->addChildLoop(L->removeChildLoop(I));
573
574 // Now that we know which blocks are in L and which need to be moved to
575 // OuterLoop, move any blocks that need it.
576 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
577 BasicBlock *BB = L->getBlocks()[i];
578 if (!BlocksInL.count(BB)) {
579 // Move this block to the parent, updating the exit blocks sets
580 L->removeBlockFromLoop(BB);
581 if (LI[BB] == L)
582 LI.changeLoopFor(BB, NewOuter);
583 --i;
584 }
585 }
586
587 // Check all subloops of this loop, replacing any exit blocks that got
588 // revectored with the new basic block.
589 for (pred_iterator I = pred_begin(NewBB), E = pred_end(NewBB); I != E; ++I)
590 if (NewOuter->contains(*I)) {
591 // Change any exit blocks that used to go to Header to go to NewBB
592 // instead.
593 ReplaceExitBlocksOfLoopAndParents((Loop*)LI[*I], Header, NewBB);
594 }
595
596 //VerifyExitBlocks(NewOuter);
597 return NewOuter;
598}
599
600
601
Chris Lattnerc4622a62003-10-13 00:37:13 +0000602/// InsertUniqueBackedgeBlock - This method is called when the specified loop
603/// has more than one backedge in it. If this occurs, revector all of these
604/// backedges to target a new basic block and have that block branch to the loop
605/// header. This ensures that loops have exactly one backedge.
606///
607void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
608 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
609
610 // Get information about the loop
611 BasicBlock *Preheader = L->getLoopPreheader();
612 BasicBlock *Header = L->getHeader();
613 Function *F = Header->getParent();
614
615 // Figure out which basic blocks contain back-edges to the loop header.
616 std::vector<BasicBlock*> BackedgeBlocks;
617 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
618 if (*I != Preheader) BackedgeBlocks.push_back(*I);
619
620 // Create and insert the new backedge block...
621 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattnera2960002003-11-21 16:52:05 +0000622 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000623
624 // Move the new backedge block to right after the last backedge block.
625 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
626 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
627
628 // Now that the block has been inserted into the function, create PHI nodes in
629 // the backedge block which correspond to any PHI nodes in the header block.
630 for (BasicBlock::iterator I = Header->begin();
631 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
632 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
633 BETerminator);
634 NewPN->op_reserve(2*BackedgeBlocks.size());
635
636 // Loop over the PHI node, moving all entries except the one for the
637 // preheader over to the new PHI node.
638 unsigned PreheaderIdx = ~0U;
639 bool HasUniqueIncomingValue = true;
640 Value *UniqueValue = 0;
641 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
642 BasicBlock *IBB = PN->getIncomingBlock(i);
643 Value *IV = PN->getIncomingValue(i);
644 if (IBB == Preheader) {
645 PreheaderIdx = i;
646 } else {
647 NewPN->addIncoming(IV, IBB);
648 if (HasUniqueIncomingValue) {
649 if (UniqueValue == 0)
650 UniqueValue = IV;
651 else if (UniqueValue != IV)
652 HasUniqueIncomingValue = false;
653 }
654 }
655 }
656
657 // Delete all of the incoming values from the old PN except the preheader's
658 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
659 if (PreheaderIdx != 0) {
660 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
661 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
662 }
663 PN->op_erase(PN->op_begin()+2, PN->op_end());
664
665 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
666 PN->addIncoming(NewPN, BEBlock);
667
668 // As an optimization, if all incoming values in the new PhiNode (which is a
669 // subset of the incoming values of the old PHI node) have the same value,
670 // eliminate the PHI Node.
671 if (HasUniqueIncomingValue) {
672 NewPN->replaceAllUsesWith(UniqueValue);
673 BEBlock->getInstList().erase(NewPN);
674 }
675 }
676
677 // Now that all of the PHI nodes have been inserted and adjusted, modify the
678 // backedge blocks to just to the BEBlock instead of the header.
679 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
680 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
681 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
682 if (TI->getSuccessor(Op) == Header)
683 TI->setSuccessor(Op, BEBlock);
684 }
685
686 //===--- Update all analyses which we must preserve now -----------------===//
687
688 // Update Loop Information - we know that this block is now in the current
689 // loop and all parent loops.
690 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
691
692 // Replace any instances of Exit with NewBB in this and any nested loops...
693 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
694 if (I->hasExitBlock(Header))
695 I->changeExitBlock(Header, BEBlock); // Update exit block information
696
697 // Update dominator information (set, immdom, domtree, and domfrontier)
698 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
699}
700
701/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
702/// different kinds of dominator information (dominator sets, immediate
703/// dominators, dominator trees, and dominance frontiers) after a new block has
704/// been added to the CFG.
705///
Chris Lattner14ab84a2004-02-05 21:12:24 +0000706/// This only supports the case when an existing block (known as "NewBBSucc"),
707/// had some of its predecessors factored into a new basic block. This
Chris Lattnerc4622a62003-10-13 00:37:13 +0000708/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner14ab84a2004-02-05 21:12:24 +0000709/// unconditional branch to NewBBSucc, and moves some predecessors of
710/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
711/// PredBlocks, even though they are the same as
712/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattnerc4622a62003-10-13 00:37:13 +0000713///
714void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
715 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000716 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattnerc4622a62003-10-13 00:37:13 +0000717 assert(succ_begin(NewBB) != succ_end(NewBB) &&
718 ++succ_begin(NewBB) == succ_end(NewBB) &&
719 "NewBB should have a single successor!");
Chris Lattner14ab84a2004-02-05 21:12:24 +0000720 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000721 DominatorSet &DS = getAnalysis<DominatorSet>();
722
Chris Lattner146d0df2004-04-01 19:06:07 +0000723 // Update dominator information... The blocks that dominate NewBB are the
724 // intersection of the dominators of predecessors, plus the block itself.
725 //
726 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
727 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
728 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
729 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
730 DS.addBasicBlock(NewBB, NewBBDomSet);
731
Chris Lattner14ab84a2004-02-05 21:12:24 +0000732 // The newly inserted basic block will dominate existing basic blocks iff the
733 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
734 // the non-pred blocks, then they all must be the same block!
Chris Lattner146d0df2004-04-01 19:06:07 +0000735 //
Chris Lattner14ab84a2004-02-05 21:12:24 +0000736 bool NewBBDominatesNewBBSucc = true;
737 {
738 BasicBlock *OnePred = PredBlocks[0];
739 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
740 if (PredBlocks[i] != OnePred) {
741 NewBBDominatesNewBBSucc = false;
742 break;
743 }
744
745 if (NewBBDominatesNewBBSucc)
746 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
747 PI != E; ++PI)
Chris Lattner2dd1c8d2004-02-05 23:20:59 +0000748 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000749 NewBBDominatesNewBBSucc = false;
750 break;
751 }
752 }
753
Chris Lattner146d0df2004-04-01 19:06:07 +0000754 // The other scenario where the new block can dominate its successors are when
755 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
756 // already.
757 if (!NewBBDominatesNewBBSucc) {
758 NewBBDominatesNewBBSucc = true;
759 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
760 PI != E; ++PI)
761 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
762 NewBBDominatesNewBBSucc = false;
763 break;
764 }
765 }
Chris Lattner650096a2003-02-27 20:27:08 +0000766
Chris Lattner14ab84a2004-02-05 21:12:24 +0000767 // If NewBB dominates some blocks, then it will dominate all blocks that
Chris Lattnerc0c953f2004-02-05 22:33:26 +0000768 // NewBBSucc does.
Chris Lattner14ab84a2004-02-05 21:12:24 +0000769 if (NewBBDominatesNewBBSucc) {
770 BasicBlock *PredBlock = PredBlocks[0];
771 Function *F = NewBB->getParent();
772 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattnerc0c953f2004-02-05 22:33:26 +0000773 if (DS.dominates(NewBBSucc, I))
Chris Lattner14ab84a2004-02-05 21:12:24 +0000774 DS.addDominator(I, NewBB);
775 }
776
Chris Lattner650096a2003-02-27 20:27:08 +0000777 // Update immediate dominator information if we have it...
778 BasicBlock *NewBBIDom = 0;
779 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000780 // To find the immediate dominator of the new exit node, we trace up the
781 // immediate dominators of a predecessor until we find a basic block that
782 // dominates the exit block.
Chris Lattner650096a2003-02-27 20:27:08 +0000783 //
Chris Lattnerc4622a62003-10-13 00:37:13 +0000784 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
Chris Lattner650096a2003-02-27 20:27:08 +0000785 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
786 assert(Dom != 0 && "No shared dominator found???");
787 Dom = ID->get(Dom);
788 }
789
790 // Set the immediate dominator now...
791 ID->addNewBlock(NewBB, Dom);
792 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
Chris Lattner14ab84a2004-02-05 21:12:24 +0000793
794 // If NewBB strictly dominates other blocks, we need to update their idom's
795 // now. The only block that need adjustment is the NewBBSucc block, whose
796 // idom should currently be set to PredBlocks[0].
Chris Lattner59fdf742004-04-01 19:21:46 +0000797 if (NewBBDominatesNewBBSucc)
Chris Lattner14ab84a2004-02-05 21:12:24 +0000798 ID->setImmediateDominator(NewBBSucc, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000799 }
800
801 // Update DominatorTree information if it is active.
802 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000803 // If we don't have ImmediateDominator info around, calculate the idom as
804 // above.
Chris Lattner650096a2003-02-27 20:27:08 +0000805 DominatorTree::Node *NewBBIDomNode;
806 if (NewBBIDom) {
807 NewBBIDomNode = DT->getNode(NewBBIDom);
808 } else {
Chris Lattnerc4622a62003-10-13 00:37:13 +0000809 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
Chris Lattnerbb9d03b2003-09-11 16:26:13 +0000810 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
Chris Lattner650096a2003-02-27 20:27:08 +0000811 NewBBIDomNode = NewBBIDomNode->getIDom();
812 assert(NewBBIDomNode && "No shared dominator found??");
813 }
814 }
815
Chris Lattner14ab84a2004-02-05 21:12:24 +0000816 // Create the new dominator tree node... and set the idom of NewBB.
817 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
818
819 // If NewBB strictly dominates other blocks, then it is now the immediate
820 // dominator of NewBBSucc. Update the dominator tree as appropriate.
821 if (NewBBDominatesNewBBSucc) {
822 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
Chris Lattner14ab84a2004-02-05 21:12:24 +0000823 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
824 }
Chris Lattner650096a2003-02-27 20:27:08 +0000825 }
826
827 // Update dominance frontier information...
828 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000829 // If NewBB dominates NewBBSucc, then the global dominance frontiers are not
830 // changed. DF(NewBB) is now going to be the DF(PredBlocks[0]) without the
831 // stuff that the new block does not dominate a predecessor of.
832 if (NewBBDominatesNewBBSucc) {
833 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
834 if (DFI != DF->end()) {
835 DominanceFrontier::DomSetType Set = DFI->second;
836 // Filter out stuff in Set that we do not dominate a predecessor of.
837 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
838 E = Set.end(); SetI != E;) {
839 bool DominatesPred = false;
840 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
841 PI != E; ++PI)
842 if (DS.dominates(NewBB, *PI))
843 DominatesPred = true;
844 if (!DominatesPred)
845 Set.erase(SetI++);
846 else
847 ++SetI;
848 }
Chris Lattner650096a2003-02-27 20:27:08 +0000849
Chris Lattner14ab84a2004-02-05 21:12:24 +0000850 DF->addBasicBlock(NewBB, Set);
851 }
852
853 } else {
854 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
855 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
856 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
857 DominanceFrontier::DomSetType NewDFSet;
858 NewDFSet.insert(NewBBSucc);
859 DF->addBasicBlock(NewBB, NewDFSet);
860
861 // Now we must loop over all of the dominance frontiers in the function,
862 // replacing occurrences of NewBBSucc with NewBB in some cases. All
863 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
864 // their dominance frontier must be updated to contain NewBB instead.
865 //
Chris Lattnerc4622a62003-10-13 00:37:13 +0000866 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
867 BasicBlock *Pred = PredBlocks[i];
868 // Get all of the dominators of the predecessor...
869 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
870 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
871 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
872 BasicBlock *PredDom = *PDI;
873
Chris Lattner14ab84a2004-02-05 21:12:24 +0000874 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
875 // dominate NewBBSucc but did dominate a predecessor of it. Now we
876 // change this entry to include NewBB in the DF instead of NewBBSucc.
Chris Lattner650096a2003-02-27 20:27:08 +0000877 DominanceFrontier::iterator DFI = DF->find(PredDom);
878 assert(DFI != DF->end() && "No dominance frontier for node?");
Chris Lattner14ab84a2004-02-05 21:12:24 +0000879 if (DFI->second.count(NewBBSucc)) {
880 DF->removeFromFrontier(DFI, NewBBSucc);
Chris Lattner650096a2003-02-27 20:27:08 +0000881 DF->addToFrontier(DFI, NewBB);
882 }
883 }
884 }
885 }
Chris Lattner650096a2003-02-27 20:27:08 +0000886 }
Chris Lattner61992f62002-09-26 16:17:31 +0000887}
Brian Gaeke960707c2003-11-11 22:41:34 +0000888