blob: 120f0297643a7d1ff5132a35f03263fb71a3d9ec [file] [log] [blame]
Chris Lattner67a98012003-10-12 21:44:18 +00001//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
John Criswellb576c942003-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 Lattner38acf9e2002-09-26 16:17:31 +00009//
Chris Lattneree2c50c2003-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 Lattnerdbf3cd72003-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 Lattner66ea98e2003-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 Lattnerdbf3cd72003-02-27 20:27:08 +000023//
Chris Lattner2ab6a732003-10-13 00:37:13 +000024// This pass also guarantees that loops will have exactly one backedge.
25//
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000026// Note that the simplifycfg pass will clean up blocks which are split out but
Chris Lattneree2c50c2003-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 Lattner38acf9e2002-09-26 16:17:31 +000032//
33//===----------------------------------------------------------------------===//
34
35#include "llvm/Transforms/Scalar.h"
Chris Lattner2ef703e2004-03-14 03:59:22 +000036#include "llvm/Constant.h"
Chris Lattner38acf9e2002-09-26 16:17:31 +000037#include "llvm/iTerminators.h"
38#include "llvm/iPHINode.h"
Chris Lattner2ef703e2004-03-14 03:59:22 +000039#include "llvm/Function.h"
40#include "llvm/Type.h"
Chris Lattner0f98e752003-12-19 06:27:08 +000041#include "llvm/Analysis/Dominators.h"
42#include "llvm/Analysis/LoopInfo.h"
Chris Lattner38acf9e2002-09-26 16:17:31 +000043#include "llvm/Support/CFG.h"
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000044#include "Support/SetOperations.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000045#include "Support/Statistic.h"
Chris Lattner74cd04e2003-02-28 03:07:54 +000046#include "Support/DepthFirstIterator.h"
Chris Lattner66ea98e2003-12-10 17:20:35 +000047using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000048
Chris Lattner38acf9e2002-09-26 16:17:31 +000049namespace {
Chris Lattneree2c50c2003-10-12 21:43:28 +000050 Statistic<>
Chris Lattner66ea98e2003-12-10 17:20:35 +000051 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
Chris Lattner38acf9e2002-09-26 16:17:31 +000052
Chris Lattneree2c50c2003-10-12 21:43:28 +000053 struct LoopSimplify : public FunctionPass {
Chris Lattner38acf9e2002-09-26 16:17:31 +000054 virtual bool runOnFunction(Function &F);
55
56 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57 // We need loop information to identify the loops...
58 AU.addRequired<LoopInfo>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000059 AU.addRequired<DominatorSet>();
Chris Lattner786c5642004-03-13 22:01:26 +000060 AU.addRequired<DominatorTree>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000061
62 AU.addPreserved<LoopInfo>();
63 AU.addPreserved<DominatorSet>();
64 AU.addPreserved<ImmediateDominators>();
65 AU.addPreserved<DominatorTree>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000066 AU.addPreserved<DominanceFrontier>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000067 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
68 }
69 private:
70 bool ProcessLoop(Loop *L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000071 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
72 const std::vector<BasicBlock*> &Preds);
73 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner38acf9e2002-09-26 16:17:31 +000074 void InsertPreheaderForLoop(Loop *L);
Chris Lattner2ab6a732003-10-13 00:37:13 +000075 void InsertUniqueBackedgeBlock(Loop *L);
76
77 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
78 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner38acf9e2002-09-26 16:17:31 +000079 };
80
Chris Lattneree2c50c2003-10-12 21:43:28 +000081 RegisterOpt<LoopSimplify>
82 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner38acf9e2002-09-26 16:17:31 +000083}
84
85// Publically exposed interface to pass...
Chris Lattner66ea98e2003-12-10 17:20:35 +000086const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
87Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner38acf9e2002-09-26 16:17:31 +000088
Chris Lattner38acf9e2002-09-26 16:17:31 +000089/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
90/// it in any convenient order) inserting preheaders...
91///
Chris Lattneree2c50c2003-10-12 21:43:28 +000092bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner38acf9e2002-09-26 16:17:31 +000093 bool Changed = false;
94 LoopInfo &LI = getAnalysis<LoopInfo>();
95
Chris Lattner329c1c62004-01-08 00:09:44 +000096 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
97 Changed |= ProcessLoop(*I);
Chris Lattner38acf9e2002-09-26 16:17:31 +000098
99 return Changed;
100}
101
102
103/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
104/// all loops have preheaders.
105///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000106bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000107 bool Changed = false;
108
Chris Lattner2ef703e2004-03-14 03:59:22 +0000109 // Check to see that no blocks (other than the header) in the loop have
110 // predecessors that are not in the loop. This is not valid for natural
111 // loops, but can occur if the blocks are unreachable. Since they are
112 // unreachable we can just shamelessly destroy their terminators to make them
113 // not branch into the loop!
114 assert(L->getBlocks()[0] == L->getHeader() &&
115 "Header isn't first block in loop?");
116 for (unsigned i = 1, e = L->getBlocks().size(); i != e; ++i) {
117 BasicBlock *LoopBB = L->getBlocks()[i];
118 Retry:
119 for (pred_iterator PI = pred_begin(LoopBB), E = pred_end(LoopBB);
120 PI != E; ++PI)
121 if (!L->contains(*PI)) {
122 // This predecessor is not in the loop. Kill its terminator!
123 BasicBlock *DeadBlock = *PI;
124 for (succ_iterator SI = succ_begin(DeadBlock), E = succ_end(DeadBlock);
125 SI != E; ++SI)
126 (*SI)->removePredecessor(DeadBlock); // Remove PHI node entries
127
128 // Delete the dead terminator.
129 DeadBlock->getInstList().pop_back();
130
131 Value *RetVal = 0;
132 if (LoopBB->getParent()->getReturnType() != Type::VoidTy)
133 RetVal = Constant::getNullValue(LoopBB->getParent()->getReturnType());
134 new ReturnInst(RetVal, DeadBlock);
135 goto Retry; // We just invalidated the pred_iterator. Retry.
136 }
137 }
138
Chris Lattner38acf9e2002-09-26 16:17:31 +0000139 // Does the loop already have a preheader? If so, don't modify the loop...
140 if (L->getLoopPreheader() == 0) {
141 InsertPreheaderForLoop(L);
142 NumInserted++;
143 Changed = true;
144 }
145
Chris Lattner66ea98e2003-12-10 17:20:35 +0000146 // Next, check to make sure that all exit nodes of the loop only have
147 // predecessors that are inside of the loop. This check guarantees that the
148 // loop preheader/header will dominate the exit blocks. If the exit block has
149 // predecessors from outside of the loop, split the edge now.
150 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i) {
151 BasicBlock *ExitBlock = L->getExitBlocks()[i];
152 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
153 PI != PE; ++PI)
154 if (!L->contains(*PI)) {
155 RewriteLoopExitBlock(L, ExitBlock);
156 NumInserted++;
157 Changed = true;
158 break;
159 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000160 }
161
Chris Lattner2ab6a732003-10-13 00:37:13 +0000162 // The preheader may have more than two predecessors at this point (from the
163 // preheader and from the backedges). To simplify the loop more, insert an
164 // extra back-edge block in the loop so that there is exactly one backedge.
165 if (L->getNumBackEdges() != 1) {
166 InsertUniqueBackedgeBlock(L);
167 NumInserted++;
168 Changed = true;
169 }
170
Chris Lattner329c1c62004-01-08 00:09:44 +0000171 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
172 Changed |= ProcessLoop(*I);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000173 return Changed;
174}
175
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000176/// SplitBlockPredecessors - Split the specified block into two blocks. We want
177/// to move the predecessors specified in the Preds list to point to the new
178/// block, leaving the remaining predecessors pointing to BB. This method
179/// updates the SSA PHINode's, but no other analyses.
180///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000181BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
182 const char *Suffix,
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000183 const std::vector<BasicBlock*> &Preds) {
184
185 // Create new basic block, insert right before the original block...
Chris Lattnerc24a0762004-02-04 03:58:28 +0000186 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000187
188 // The preheader first gets an unconditional branch to the loop header...
Chris Lattner108e4ab2003-11-21 16:52:05 +0000189 BranchInst *BI = new BranchInst(BB, NewBB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000190
191 // For every PHI node in the block, insert a PHI node into NewBB where the
192 // incoming values from the out of loop edges are moved to NewBB. We have two
193 // possible cases here. If the loop is dead, we just insert dummy entries
194 // into the PHI nodes for the new edge. If the loop is not dead, we move the
195 // incoming edges in BB into new PHI nodes in NewBB.
196 //
197 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner0f98e752003-12-19 06:27:08 +0000198 // Check to see if the values being merged into the new block need PHI
199 // nodes. If so, insert them.
200 for (BasicBlock::iterator I = BB->begin();
201 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
202
203 // Check to see if all of the values coming in are the same. If so, we
204 // don't need to create a new PHI node.
205 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
206 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
207 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
208 InVal = 0;
209 break;
210 }
211
212 // If the values coming into the block are not the same, we need a PHI.
213 if (InVal == 0) {
Chris Lattner010ba102003-12-09 23:12:55 +0000214 // Create the new PHI node, insert it into NewBB at the end of the block
215 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
216
217 // Move all of the edges from blocks outside the loop to the new PHI
218 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
219 Value *V = PN->removeIncomingValue(Preds[i]);
220 NewPHI->addIncoming(V, Preds[i]);
221 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000222 InVal = NewPHI;
223 } else {
224 // Remove all of the edges coming into the PHI nodes from outside of the
225 // block.
226 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
227 PN->removeIncomingValue(Preds[i], false);
Chris Lattner010ba102003-12-09 23:12:55 +0000228 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000229
230 // Add an incoming value to the PHI node in the loop for the preheader
231 // edge.
232 PN->addIncoming(InVal, NewBB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000233 }
234
235 // Now that the PHI nodes are updated, actually move the edges from
236 // Preds to point to NewBB instead of BB.
237 //
238 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
239 TerminatorInst *TI = Preds[i]->getTerminator();
240 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
241 if (TI->getSuccessor(s) == BB)
242 TI->setSuccessor(s, NewBB);
243 }
244
245 } else { // Otherwise the loop is dead...
246 for (BasicBlock::iterator I = BB->begin();
Chris Lattnere408e252003-04-23 16:37:45 +0000247 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000248 // Insert dummy values as the incoming value...
249 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
250 }
251 return NewBB;
252}
253
Chris Lattner8f6396e2003-05-12 22:04:34 +0000254// ChangeExitBlock - This recursive function is used to change any exit blocks
255// that use OldExit to use NewExit instead. This is recursive because children
256// may need to be processed as well.
257//
258static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) {
259 if (L->hasExitBlock(OldExit)) {
260 L->changeExitBlock(OldExit, NewExit);
Chris Lattner329c1c62004-01-08 00:09:44 +0000261 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
262 ChangeExitBlock(*I, OldExit, NewExit);
Chris Lattner8f6396e2003-05-12 22:04:34 +0000263 }
264}
265
Chris Lattner38acf9e2002-09-26 16:17:31 +0000266
267/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
268/// preheader, this method is called to insert one. This method has two phases:
269/// preheader insertion and analysis updating.
270///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000271void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000272 BasicBlock *Header = L->getHeader();
273
274 // Compute the set of predecessors of the loop that are not in the loop.
275 std::vector<BasicBlock*> OutsideBlocks;
276 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
277 PI != PE; ++PI)
278 if (!L->contains(*PI)) // Coming in from outside the loop?
279 OutsideBlocks.push_back(*PI); // Keep track of it...
280
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000281 // Split out the loop pre-header
282 BasicBlock *NewBB =
283 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000284
Chris Lattner38acf9e2002-09-26 16:17:31 +0000285 //===--------------------------------------------------------------------===//
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000286 // Update analysis results now that we have performed the transformation
Chris Lattner38acf9e2002-09-26 16:17:31 +0000287 //
288
289 // We know that we have loop information to update... update it now.
290 if (Loop *Parent = L->getParentLoop())
291 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner9f879cf2003-02-27 22:48:57 +0000292
293 // If the header for the loop used to be an exit node for another loop, then
294 // we need to update this to know that the loop-preheader is now the exit
295 // node. Note that the only loop that could have our header as an exit node
Chris Lattner8f6396e2003-05-12 22:04:34 +0000296 // is a sibling loop, ie, one with the same parent loop, or one if it's
297 // children.
298 //
Chris Lattner329c1c62004-01-08 00:09:44 +0000299 LoopInfo::iterator ParentLoops, ParentLoopsE;
300 if (Loop *Parent = L->getParentLoop()) {
301 ParentLoops = Parent->begin();
302 ParentLoopsE = Parent->end();
303 } else { // Must check top-level loops...
304 ParentLoops = getAnalysis<LoopInfo>().begin();
305 ParentLoopsE = getAnalysis<LoopInfo>().end();
306 }
Chris Lattner9f879cf2003-02-27 22:48:57 +0000307
Chris Lattner8f6396e2003-05-12 22:04:34 +0000308 // Loop over all sibling loops, performing the substitution (recursively to
309 // include child loops)...
Chris Lattner329c1c62004-01-08 00:09:44 +0000310 for (; ParentLoops != ParentLoopsE; ++ParentLoops)
311 ChangeExitBlock(*ParentLoops, Header, NewBB);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000312
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000313 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
Chris Lattner786c5642004-03-13 22:01:26 +0000314 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner85ebd542004-03-16 06:00:15 +0000315
316
317 // Update the dominator tree information.
318 // The immediate dominator of the preheader is the immediate dominator of
319 // the old header.
320 DominatorTree::Node *PHDomTreeNode =
321 DT.createNewNode(NewBB, DT.getNode(Header)->getIDom());
322
323 // Change the header node so that PNHode is the new immediate dominator
324 DT.changeImmediateDominator(DT.getNode(Header), PHDomTreeNode);
Chris Lattner786c5642004-03-13 22:01:26 +0000325
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000326 {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000327 // The blocks that dominate NewBB are the blocks that dominate Header,
328 // minus Header, plus NewBB.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000329 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000330 DomSet.erase(Header); // Header does not dominate us...
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000331 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner4d018922002-09-29 21:41:38 +0000332
333 // The newly created basic block dominates all nodes dominated by Header.
Chris Lattner85ebd542004-03-16 06:00:15 +0000334 for (df_iterator<DominatorTree::Node*> DFI = df_begin(PHDomTreeNode),
335 E = df_end(PHDomTreeNode); DFI != E; ++DFI)
336 DS.addDominator((*DFI)->getBlock(), NewBB);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000337 }
338
339 // Update immediate dominator information if we have it...
340 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
341 // Whatever i-dominated the header node now immediately dominates NewBB
342 ID->addNewBlock(NewBB, ID->get(Header));
343
344 // The preheader now is the immediate dominator for the header node...
345 ID->setImmediateDominator(Header, NewBB);
346 }
347
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000348 // Update dominance frontier information...
349 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
350 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
351 // everything that Header does, and it strictly dominates Header in
352 // addition.
353 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
354 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
355 NewDFSet.erase(Header);
356 DF->addBasicBlock(NewBB, NewDFSet);
357
358 // Now we must loop over all of the dominance frontiers in the function,
Misha Brukmandfa5f832003-09-09 21:54:45 +0000359 // replacing occurrences of Header with NewBB in some cases. If a block
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000360 // dominates a (now) predecessor of NewBB, but did not strictly dominate
361 // Header, it will have Header in it's DF set, but should now have NewBB in
362 // its set.
363 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
364 // Get all of the dominators of the predecessor...
365 const DominatorSet::DomSetType &PredDoms =
366 DS.getDominators(OutsideBlocks[i]);
367 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
368 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
369 BasicBlock *PredDom = *PDI;
370 // If the loop header is in DF(PredDom), then PredDom didn't dominate
371 // the header but did dominate a predecessor outside of the loop. Now
372 // we change this entry to include the preheader in the DF instead of
373 // the header.
374 DominanceFrontier::iterator DFI = DF->find(PredDom);
375 assert(DFI != DF->end() && "No dominance frontier for node?");
376 if (DFI->second.count(Header)) {
377 DF->removeFromFrontier(DFI, Header);
378 DF->addToFrontier(DFI, NewBB);
379 }
380 }
381 }
382 }
383}
384
Chris Lattneree2c50c2003-10-12 21:43:28 +0000385void LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000386 DominatorSet &DS = getAnalysis<DominatorSet>();
Chris Lattner7e7ad492003-02-27 22:31:07 +0000387 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
388 != L->getExitBlocks().end() && "Not a current exit block!");
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000389
390 std::vector<BasicBlock*> LoopBlocks;
391 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
392 if (L->contains(*I))
393 LoopBlocks.push_back(*I);
394
Chris Lattner7e7ad492003-02-27 22:31:07 +0000395 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
396 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
397
Chris Lattner69269ac2003-02-27 21:50:19 +0000398 // Update Loop Information - we know that the new block will be in the parent
399 // loop of L.
400 if (Loop *Parent = L->getParentLoop())
401 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner74cd04e2003-02-28 03:07:54 +0000402
403 // Replace any instances of Exit with NewBB in this and any nested loops...
404 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
Chris Lattner63159382003-02-28 16:54:17 +0000405 if (I->hasExitBlock(Exit))
406 I->changeExitBlock(Exit, NewBB); // Update exit block information
Chris Lattner69269ac2003-02-27 21:50:19 +0000407
Chris Lattner2ab6a732003-10-13 00:37:13 +0000408 // Update dominator information (set, immdom, domtree, and domfrontier)
409 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
410}
411
412/// InsertUniqueBackedgeBlock - This method is called when the specified loop
413/// has more than one backedge in it. If this occurs, revector all of these
414/// backedges to target a new basic block and have that block branch to the loop
415/// header. This ensures that loops have exactly one backedge.
416///
417void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
418 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
419
420 // Get information about the loop
421 BasicBlock *Preheader = L->getLoopPreheader();
422 BasicBlock *Header = L->getHeader();
423 Function *F = Header->getParent();
424
425 // Figure out which basic blocks contain back-edges to the loop header.
426 std::vector<BasicBlock*> BackedgeBlocks;
427 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
428 if (*I != Preheader) BackedgeBlocks.push_back(*I);
429
430 // Create and insert the new backedge block...
431 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattner108e4ab2003-11-21 16:52:05 +0000432 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000433
434 // Move the new backedge block to right after the last backedge block.
435 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
436 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
437
438 // Now that the block has been inserted into the function, create PHI nodes in
439 // the backedge block which correspond to any PHI nodes in the header block.
440 for (BasicBlock::iterator I = Header->begin();
441 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
442 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
443 BETerminator);
444 NewPN->op_reserve(2*BackedgeBlocks.size());
445
446 // Loop over the PHI node, moving all entries except the one for the
447 // preheader over to the new PHI node.
448 unsigned PreheaderIdx = ~0U;
449 bool HasUniqueIncomingValue = true;
450 Value *UniqueValue = 0;
451 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
452 BasicBlock *IBB = PN->getIncomingBlock(i);
453 Value *IV = PN->getIncomingValue(i);
454 if (IBB == Preheader) {
455 PreheaderIdx = i;
456 } else {
457 NewPN->addIncoming(IV, IBB);
458 if (HasUniqueIncomingValue) {
459 if (UniqueValue == 0)
460 UniqueValue = IV;
461 else if (UniqueValue != IV)
462 HasUniqueIncomingValue = false;
463 }
464 }
465 }
466
467 // Delete all of the incoming values from the old PN except the preheader's
468 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
469 if (PreheaderIdx != 0) {
470 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
471 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
472 }
473 PN->op_erase(PN->op_begin()+2, PN->op_end());
474
475 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
476 PN->addIncoming(NewPN, BEBlock);
477
478 // As an optimization, if all incoming values in the new PhiNode (which is a
479 // subset of the incoming values of the old PHI node) have the same value,
480 // eliminate the PHI Node.
481 if (HasUniqueIncomingValue) {
482 NewPN->replaceAllUsesWith(UniqueValue);
483 BEBlock->getInstList().erase(NewPN);
484 }
485 }
486
487 // Now that all of the PHI nodes have been inserted and adjusted, modify the
488 // backedge blocks to just to the BEBlock instead of the header.
489 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
490 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
491 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
492 if (TI->getSuccessor(Op) == Header)
493 TI->setSuccessor(Op, BEBlock);
494 }
495
496 //===--- Update all analyses which we must preserve now -----------------===//
497
498 // Update Loop Information - we know that this block is now in the current
499 // loop and all parent loops.
500 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
501
502 // Replace any instances of Exit with NewBB in this and any nested loops...
503 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
504 if (I->hasExitBlock(Header))
505 I->changeExitBlock(Header, BEBlock); // Update exit block information
506
507 // Update dominator information (set, immdom, domtree, and domfrontier)
508 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
509}
510
511/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
512/// different kinds of dominator information (dominator sets, immediate
513/// dominators, dominator trees, and dominance frontiers) after a new block has
514/// been added to the CFG.
515///
Chris Lattner4f02fc22004-02-05 21:12:24 +0000516/// This only supports the case when an existing block (known as "NewBBSucc"),
517/// had some of its predecessors factored into a new basic block. This
Chris Lattner2ab6a732003-10-13 00:37:13 +0000518/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner4f02fc22004-02-05 21:12:24 +0000519/// unconditional branch to NewBBSucc, and moves some predecessors of
520/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
521/// PredBlocks, even though they are the same as
522/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattner2ab6a732003-10-13 00:37:13 +0000523///
524void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
525 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000526 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattner2ab6a732003-10-13 00:37:13 +0000527 assert(succ_begin(NewBB) != succ_end(NewBB) &&
528 ++succ_begin(NewBB) == succ_end(NewBB) &&
529 "NewBB should have a single successor!");
Chris Lattner4f02fc22004-02-05 21:12:24 +0000530 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000531 DominatorSet &DS = getAnalysis<DominatorSet>();
532
Chris Lattner4f02fc22004-02-05 21:12:24 +0000533 // The newly inserted basic block will dominate existing basic blocks iff the
534 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
535 // the non-pred blocks, then they all must be the same block!
536 bool NewBBDominatesNewBBSucc = true;
537 {
538 BasicBlock *OnePred = PredBlocks[0];
539 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
540 if (PredBlocks[i] != OnePred) {
541 NewBBDominatesNewBBSucc = false;
542 break;
543 }
544
545 if (NewBBDominatesNewBBSucc)
546 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
547 PI != E; ++PI)
Chris Lattner99dcc1d2004-02-05 23:20:59 +0000548 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000549 NewBBDominatesNewBBSucc = false;
550 break;
551 }
552 }
553
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000554 // Update dominator information... The blocks that dominate NewBB are the
555 // intersection of the dominators of predecessors, plus the block itself.
556 // The newly created basic block does not dominate anything except itself.
557 //
Chris Lattner2ab6a732003-10-13 00:37:13 +0000558 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
559 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
560 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000561 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
562 DS.addBasicBlock(NewBB, NewBBDomSet);
563
Chris Lattner4f02fc22004-02-05 21:12:24 +0000564 // If NewBB dominates some blocks, then it will dominate all blocks that
Chris Lattner3e0b8702004-02-05 22:33:26 +0000565 // NewBBSucc does.
Chris Lattner4f02fc22004-02-05 21:12:24 +0000566 if (NewBBDominatesNewBBSucc) {
567 BasicBlock *PredBlock = PredBlocks[0];
568 Function *F = NewBB->getParent();
569 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner3e0b8702004-02-05 22:33:26 +0000570 if (DS.dominates(NewBBSucc, I))
Chris Lattner4f02fc22004-02-05 21:12:24 +0000571 DS.addDominator(I, NewBB);
572 }
573
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000574 // Update immediate dominator information if we have it...
575 BasicBlock *NewBBIDom = 0;
576 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000577 // To find the immediate dominator of the new exit node, we trace up the
578 // immediate dominators of a predecessor until we find a basic block that
579 // dominates the exit block.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000580 //
Chris Lattner2ab6a732003-10-13 00:37:13 +0000581 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000582 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
583 assert(Dom != 0 && "No shared dominator found???");
584 Dom = ID->get(Dom);
585 }
586
587 // Set the immediate dominator now...
588 ID->addNewBlock(NewBB, Dom);
589 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
Chris Lattner4f02fc22004-02-05 21:12:24 +0000590
591 // If NewBB strictly dominates other blocks, we need to update their idom's
592 // now. The only block that need adjustment is the NewBBSucc block, whose
593 // idom should currently be set to PredBlocks[0].
594 if (NewBBDominatesNewBBSucc) {
595 assert(ID->get(NewBBSucc) == PredBlocks[0] &&
596 "Immediate dominator update code broken!");
597 ID->setImmediateDominator(NewBBSucc, NewBB);
598 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000599 }
600
601 // Update DominatorTree information if it is active.
602 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000603 // If we don't have ImmediateDominator info around, calculate the idom as
604 // above.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000605 DominatorTree::Node *NewBBIDomNode;
606 if (NewBBIDom) {
607 NewBBIDomNode = DT->getNode(NewBBIDom);
608 } else {
Chris Lattner2ab6a732003-10-13 00:37:13 +0000609 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
Chris Lattnerc444a422003-09-11 16:26:13 +0000610 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000611 NewBBIDomNode = NewBBIDomNode->getIDom();
612 assert(NewBBIDomNode && "No shared dominator found??");
613 }
614 }
615
Chris Lattner4f02fc22004-02-05 21:12:24 +0000616 // Create the new dominator tree node... and set the idom of NewBB.
617 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
618
619 // If NewBB strictly dominates other blocks, then it is now the immediate
620 // dominator of NewBBSucc. Update the dominator tree as appropriate.
621 if (NewBBDominatesNewBBSucc) {
622 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
623 assert(NewBBSuccNode->getIDom()->getBlock() == PredBlocks[0] &&
624 "Immediate tree update code broken!");
625 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
626 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000627 }
628
629 // Update dominance frontier information...
630 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000631 // If NewBB dominates NewBBSucc, then the global dominance frontiers are not
632 // changed. DF(NewBB) is now going to be the DF(PredBlocks[0]) without the
633 // stuff that the new block does not dominate a predecessor of.
634 if (NewBBDominatesNewBBSucc) {
635 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
636 if (DFI != DF->end()) {
637 DominanceFrontier::DomSetType Set = DFI->second;
638 // Filter out stuff in Set that we do not dominate a predecessor of.
639 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
640 E = Set.end(); SetI != E;) {
641 bool DominatesPred = false;
642 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
643 PI != E; ++PI)
644 if (DS.dominates(NewBB, *PI))
645 DominatesPred = true;
646 if (!DominatesPred)
647 Set.erase(SetI++);
648 else
649 ++SetI;
650 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000651
Chris Lattner4f02fc22004-02-05 21:12:24 +0000652 DF->addBasicBlock(NewBB, Set);
653 }
654
655 } else {
656 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
657 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
658 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
659 DominanceFrontier::DomSetType NewDFSet;
660 NewDFSet.insert(NewBBSucc);
661 DF->addBasicBlock(NewBB, NewDFSet);
662
663 // Now we must loop over all of the dominance frontiers in the function,
664 // replacing occurrences of NewBBSucc with NewBB in some cases. All
665 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
666 // their dominance frontier must be updated to contain NewBB instead.
667 //
Chris Lattner2ab6a732003-10-13 00:37:13 +0000668 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
669 BasicBlock *Pred = PredBlocks[i];
670 // Get all of the dominators of the predecessor...
671 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
672 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
673 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
674 BasicBlock *PredDom = *PDI;
675
Chris Lattner4f02fc22004-02-05 21:12:24 +0000676 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
677 // dominate NewBBSucc but did dominate a predecessor of it. Now we
678 // change this entry to include NewBB in the DF instead of NewBBSucc.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000679 DominanceFrontier::iterator DFI = DF->find(PredDom);
680 assert(DFI != DF->end() && "No dominance frontier for node?");
Chris Lattner4f02fc22004-02-05 21:12:24 +0000681 if (DFI->second.count(NewBBSucc)) {
682 DF->removeFromFrontier(DFI, NewBBSucc);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000683 DF->addToFrontier(DFI, NewBB);
684 }
685 }
686 }
687 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000688 }
Chris Lattner38acf9e2002-09-26 16:17:31 +0000689}
Brian Gaeked0fde302003-11-11 22:41:34 +0000690