blob: 9507941f6c8dc0f9a28bb18c49714b7fee516ec3 [file] [log] [blame]
Chris Lattner38acf9e2002-09-26 16:17:31 +00001//===- LoopPreheaders.cpp - Loop Preheader Insertion Pass -----------------===//
2//
Chris Lattnerdbf3cd72003-02-27 20:27:08 +00003// Insert Loop pre-headers and exit blocks into the CFG for each function in the
4// module. This pass updates loop information and dominator information.
5//
6// Loop pre-header insertion guarantees that there is a single, non-critical
7// entry edge from outside of the loop to the loop header. This simplifies a
8// number of analyses and transformations, such as LICM.
9//
10// Loop exit-block insertion guarantees that all exit blocks from the loop
11// (blocks which are outside of the loop that have predecessors inside of the
12// loop) are dominated by the loop header. This simplifies transformations such
13// as store-sinking that is built into LICM.
14//
15// Note that the simplifycfg pass will clean up blocks which are split out but
Misha Brukman5560c9d2003-08-18 14:43:39 +000016// end up being unnecessary, so usage of this pass does not neccesarily
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000017// pessimize generated code.
Chris Lattner38acf9e2002-09-26 16:17:31 +000018//
19//===----------------------------------------------------------------------===//
20
21#include "llvm/Transforms/Scalar.h"
22#include "llvm/Analysis/Dominators.h"
23#include "llvm/Analysis/LoopInfo.h"
24#include "llvm/Function.h"
25#include "llvm/iTerminators.h"
26#include "llvm/iPHINode.h"
27#include "llvm/Constant.h"
28#include "llvm/Support/CFG.h"
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000029#include "Support/SetOperations.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000030#include "Support/Statistic.h"
Chris Lattner74cd04e2003-02-28 03:07:54 +000031#include "Support/DepthFirstIterator.h"
Chris Lattner38acf9e2002-09-26 16:17:31 +000032
33namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000034 Statistic<> NumInserted("preheaders", "Number of pre-header nodes inserted");
Chris Lattner38acf9e2002-09-26 16:17:31 +000035
36 struct Preheaders : public FunctionPass {
37 virtual bool runOnFunction(Function &F);
38
39 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40 // We need loop information to identify the loops...
41 AU.addRequired<LoopInfo>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000042 AU.addRequired<DominatorSet>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000043
44 AU.addPreserved<LoopInfo>();
45 AU.addPreserved<DominatorSet>();
46 AU.addPreserved<ImmediateDominators>();
47 AU.addPreserved<DominatorTree>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000048 AU.addPreserved<DominanceFrontier>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000049 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
50 }
51 private:
52 bool ProcessLoop(Loop *L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000053 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
54 const std::vector<BasicBlock*> &Preds);
55 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner38acf9e2002-09-26 16:17:31 +000056 void InsertPreheaderForLoop(Loop *L);
57 };
58
Chris Lattner0bd36162002-09-26 16:37:37 +000059 RegisterOpt<Preheaders> X("preheaders", "Natural loop pre-header insertion");
Chris Lattner38acf9e2002-09-26 16:17:31 +000060}
61
62// Publically exposed interface to pass...
63const PassInfo *LoopPreheadersID = X.getPassInfo();
64Pass *createLoopPreheaderInsertionPass() { return new Preheaders(); }
65
66
67/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
68/// it in any convenient order) inserting preheaders...
69///
70bool Preheaders::runOnFunction(Function &F) {
71 bool Changed = false;
72 LoopInfo &LI = getAnalysis<LoopInfo>();
73
74 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i)
75 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]);
76
77 return Changed;
78}
79
80
81/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
82/// all loops have preheaders.
83///
84bool Preheaders::ProcessLoop(Loop *L) {
85 bool Changed = false;
86
87 // Does the loop already have a preheader? If so, don't modify the loop...
88 if (L->getLoopPreheader() == 0) {
89 InsertPreheaderForLoop(L);
90 NumInserted++;
91 Changed = true;
92 }
93
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000094 DominatorSet &DS = getAnalysis<DominatorSet>();
95 BasicBlock *Header = L->getHeader();
96 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i)
97 if (!DS.dominates(Header, L->getExitBlocks()[i])) {
98 RewriteLoopExitBlock(L, L->getExitBlocks()[i]);
Chris Lattner7e7ad492003-02-27 22:31:07 +000099 assert(DS.dominates(Header, L->getExitBlocks()[i]) &&
100 "RewriteLoopExitBlock failed?");
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000101 NumInserted++;
102 Changed = true;
103 }
104
Chris Lattner38acf9e2002-09-26 16:17:31 +0000105 const std::vector<Loop*> &SubLoops = L->getSubLoops();
106 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
107 Changed |= ProcessLoop(SubLoops[i]);
108 return Changed;
109}
110
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000111/// SplitBlockPredecessors - Split the specified block into two blocks. We want
112/// to move the predecessors specified in the Preds list to point to the new
113/// block, leaving the remaining predecessors pointing to BB. This method
114/// updates the SSA PHINode's, but no other analyses.
115///
116BasicBlock *Preheaders::SplitBlockPredecessors(BasicBlock *BB,
117 const char *Suffix,
118 const std::vector<BasicBlock*> &Preds) {
119
120 // Create new basic block, insert right before the original block...
121 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB);
122
123 // The preheader first gets an unconditional branch to the loop header...
124 BranchInst *BI = new BranchInst(BB);
125 NewBB->getInstList().push_back(BI);
126
127 // For every PHI node in the block, insert a PHI node into NewBB where the
128 // incoming values from the out of loop edges are moved to NewBB. We have two
129 // possible cases here. If the loop is dead, we just insert dummy entries
130 // into the PHI nodes for the new edge. If the loop is not dead, we move the
131 // incoming edges in BB into new PHI nodes in NewBB.
132 //
133 if (!Preds.empty()) { // Is the loop not obviously dead?
134 for (BasicBlock::iterator I = BB->begin();
Chris Lattnere408e252003-04-23 16:37:45 +0000135 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000136
137 // Create the new PHI node, insert it into NewBB at the end of the block
138 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
139
140 // Move all of the edges from blocks outside the loop to the new PHI
141 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
142 Value *V = PN->removeIncomingValue(Preds[i]);
143 NewPHI->addIncoming(V, Preds[i]);
144 }
145
146 // Add an incoming value to the PHI node in the loop for the preheader
147 // edge
148 PN->addIncoming(NewPHI, NewBB);
149 }
150
151 // Now that the PHI nodes are updated, actually move the edges from
152 // Preds to point to NewBB instead of BB.
153 //
154 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
155 TerminatorInst *TI = Preds[i]->getTerminator();
156 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
157 if (TI->getSuccessor(s) == BB)
158 TI->setSuccessor(s, NewBB);
159 }
160
161 } else { // Otherwise the loop is dead...
162 for (BasicBlock::iterator I = BB->begin();
Chris Lattnere408e252003-04-23 16:37:45 +0000163 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000164 // Insert dummy values as the incoming value...
165 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
166 }
167 return NewBB;
168}
169
Chris Lattner8f6396e2003-05-12 22:04:34 +0000170// ChangeExitBlock - This recursive function is used to change any exit blocks
171// that use OldExit to use NewExit instead. This is recursive because children
172// may need to be processed as well.
173//
174static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) {
175 if (L->hasExitBlock(OldExit)) {
176 L->changeExitBlock(OldExit, NewExit);
177 const std::vector<Loop*> &SubLoops = L->getSubLoops();
178 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
179 ChangeExitBlock(SubLoops[i], OldExit, NewExit);
180 }
181}
182
Chris Lattner38acf9e2002-09-26 16:17:31 +0000183
184/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
185/// preheader, this method is called to insert one. This method has two phases:
186/// preheader insertion and analysis updating.
187///
188void Preheaders::InsertPreheaderForLoop(Loop *L) {
189 BasicBlock *Header = L->getHeader();
190
191 // Compute the set of predecessors of the loop that are not in the loop.
192 std::vector<BasicBlock*> OutsideBlocks;
193 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
194 PI != PE; ++PI)
195 if (!L->contains(*PI)) // Coming in from outside the loop?
196 OutsideBlocks.push_back(*PI); // Keep track of it...
197
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000198 // Split out the loop pre-header
199 BasicBlock *NewBB =
200 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000201
Chris Lattner38acf9e2002-09-26 16:17:31 +0000202 //===--------------------------------------------------------------------===//
203 // Update analysis results now that we have preformed the transformation
204 //
205
206 // We know that we have loop information to update... update it now.
207 if (Loop *Parent = L->getParentLoop())
208 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner9f879cf2003-02-27 22:48:57 +0000209
210 // If the header for the loop used to be an exit node for another loop, then
211 // we need to update this to know that the loop-preheader is now the exit
212 // node. Note that the only loop that could have our header as an exit node
Chris Lattner8f6396e2003-05-12 22:04:34 +0000213 // is a sibling loop, ie, one with the same parent loop, or one if it's
214 // children.
215 //
Chris Lattner9f879cf2003-02-27 22:48:57 +0000216 const std::vector<Loop*> *ParentSubLoops;
217 if (Loop *Parent = L->getParentLoop())
218 ParentSubLoops = &Parent->getSubLoops();
219 else // Must check top-level loops...
220 ParentSubLoops = &getAnalysis<LoopInfo>().getTopLevelLoops();
221
Chris Lattner8f6396e2003-05-12 22:04:34 +0000222 // Loop over all sibling loops, performing the substitution (recursively to
223 // include child loops)...
Chris Lattner9f879cf2003-02-27 22:48:57 +0000224 for (unsigned i = 0, e = ParentSubLoops->size(); i != e; ++i)
Chris Lattner8f6396e2003-05-12 22:04:34 +0000225 ChangeExitBlock((*ParentSubLoops)[i], Header, NewBB);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000226
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000227 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
228 {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000229 // The blocks that dominate NewBB are the blocks that dominate Header,
230 // minus Header, plus NewBB.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000231 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner4d018922002-09-29 21:41:38 +0000232 DomSet.insert(NewBB); // We dominate ourself
Chris Lattner38acf9e2002-09-26 16:17:31 +0000233 DomSet.erase(Header); // Header does not dominate us...
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000234 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner4d018922002-09-29 21:41:38 +0000235
236 // The newly created basic block dominates all nodes dominated by Header.
237 for (Function::iterator I = Header->getParent()->begin(),
238 E = Header->getParent()->end(); I != E; ++I)
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000239 if (DS.dominates(Header, I))
240 DS.addDominator(I, NewBB);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000241 }
242
243 // Update immediate dominator information if we have it...
244 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
245 // Whatever i-dominated the header node now immediately dominates NewBB
246 ID->addNewBlock(NewBB, ID->get(Header));
247
248 // The preheader now is the immediate dominator for the header node...
249 ID->setImmediateDominator(Header, NewBB);
250 }
251
252 // Update DominatorTree information if it is active.
253 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
254 // The immediate dominator of the preheader is the immediate dominator of
255 // the old header.
256 //
257 DominatorTree::Node *HeaderNode = DT->getNode(Header);
Chris Lattner4d018922002-09-29 21:41:38 +0000258 DominatorTree::Node *PHNode = DT->createNewNode(NewBB,
259 HeaderNode->getIDom());
Chris Lattner38acf9e2002-09-26 16:17:31 +0000260
261 // Change the header node so that PNHode is the new immediate dominator
262 DT->changeImmediateDominator(HeaderNode, PHNode);
263 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000264
265 // Update dominance frontier information...
266 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
267 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
268 // everything that Header does, and it strictly dominates Header in
269 // addition.
270 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
271 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
272 NewDFSet.erase(Header);
273 DF->addBasicBlock(NewBB, NewDFSet);
274
275 // Now we must loop over all of the dominance frontiers in the function,
276 // replacing occurances of Header with NewBB in some cases. If a block
277 // dominates a (now) predecessor of NewBB, but did not strictly dominate
278 // Header, it will have Header in it's DF set, but should now have NewBB in
279 // its set.
280 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
281 // Get all of the dominators of the predecessor...
282 const DominatorSet::DomSetType &PredDoms =
283 DS.getDominators(OutsideBlocks[i]);
284 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
285 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
286 BasicBlock *PredDom = *PDI;
287 // If the loop header is in DF(PredDom), then PredDom didn't dominate
288 // the header but did dominate a predecessor outside of the loop. Now
289 // we change this entry to include the preheader in the DF instead of
290 // the header.
291 DominanceFrontier::iterator DFI = DF->find(PredDom);
292 assert(DFI != DF->end() && "No dominance frontier for node?");
293 if (DFI->second.count(Header)) {
294 DF->removeFromFrontier(DFI, Header);
295 DF->addToFrontier(DFI, NewBB);
296 }
297 }
298 }
299 }
300}
301
302void Preheaders::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
303 DominatorSet &DS = getAnalysis<DominatorSet>();
304 assert(!DS.dominates(L->getHeader(), Exit) &&
305 "Loop already dominates exit block??");
Chris Lattner7e7ad492003-02-27 22:31:07 +0000306 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
307 != L->getExitBlocks().end() && "Not a current exit block!");
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000308
309 std::vector<BasicBlock*> LoopBlocks;
310 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
311 if (L->contains(*I))
312 LoopBlocks.push_back(*I);
313
Chris Lattner7e7ad492003-02-27 22:31:07 +0000314 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
315 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
316
Chris Lattner69269ac2003-02-27 21:50:19 +0000317 // Update Loop Information - we know that the new block will be in the parent
318 // loop of L.
319 if (Loop *Parent = L->getParentLoop())
320 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner74cd04e2003-02-28 03:07:54 +0000321
322 // Replace any instances of Exit with NewBB in this and any nested loops...
323 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
Chris Lattner63159382003-02-28 16:54:17 +0000324 if (I->hasExitBlock(Exit))
325 I->changeExitBlock(Exit, NewBB); // Update exit block information
Chris Lattner69269ac2003-02-27 21:50:19 +0000326
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000327 // Update dominator information... The blocks that dominate NewBB are the
328 // intersection of the dominators of predecessors, plus the block itself.
329 // The newly created basic block does not dominate anything except itself.
330 //
331 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(LoopBlocks[0]);
332 for (unsigned i = 1, e = LoopBlocks.size(); i != e; ++i)
333 set_intersect(NewBBDomSet, DS.getDominators(LoopBlocks[i]));
334 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
335 DS.addBasicBlock(NewBB, NewBBDomSet);
336
337 // Update immediate dominator information if we have it...
338 BasicBlock *NewBBIDom = 0;
339 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
340 // This block does not strictly dominate anything, so it is not an immediate
341 // dominator. To find the immediate dominator of the new exit node, we
342 // trace up the immediate dominators of a predecessor until we find a basic
343 // block that dominates the exit block.
344 //
345 BasicBlock *Dom = LoopBlocks[0]; // Some random predecessor...
346 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
347 assert(Dom != 0 && "No shared dominator found???");
348 Dom = ID->get(Dom);
349 }
350
351 // Set the immediate dominator now...
352 ID->addNewBlock(NewBB, Dom);
353 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
354 }
355
356 // Update DominatorTree information if it is active.
357 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
358 // NewBB doesn't dominate anything, so just create a node and link it into
359 // its immediate dominator. If we don't have ImmediateDominator info
360 // around, calculate the idom as above.
361 DominatorTree::Node *NewBBIDomNode;
362 if (NewBBIDom) {
363 NewBBIDomNode = DT->getNode(NewBBIDom);
364 } else {
365 NewBBIDomNode = DT->getNode(LoopBlocks[0]); // Random pred
366 while (!NewBBDomSet.count(NewBBIDomNode->getNode())) {
367 NewBBIDomNode = NewBBIDomNode->getIDom();
368 assert(NewBBIDomNode && "No shared dominator found??");
369 }
370 }
371
372 // Create the new dominator tree node...
373 DT->createNewNode(NewBB, NewBBIDomNode);
374 }
375
376 // Update dominance frontier information...
377 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
378 // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it
379 // does dominate itself (and there is an edge (NewBB -> Exit)).
380 DominanceFrontier::DomSetType NewDFSet;
381 NewDFSet.insert(Exit);
382 DF->addBasicBlock(NewBB, NewDFSet);
383
384 // Now we must loop over all of the dominance frontiers in the function,
385 // replacing occurances of Exit with NewBB in some cases. If a block
386 // dominates a (now) predecessor of NewBB, but did not strictly dominate
387 // Exit, it will have Exit in it's DF set, but should now have NewBB in its
388 // set.
389 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
390 // Get all of the dominators of the predecessor...
391 const DominatorSet::DomSetType &PredDoms =DS.getDominators(LoopBlocks[i]);
392 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
393 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
394 BasicBlock *PredDom = *PDI;
395 // Make sure to only rewrite blocks that are part of the loop...
396 if (L->contains(PredDom)) {
397 // If the exit node is in DF(PredDom), then PredDom didn't dominate
398 // Exit but did dominate a predecessor inside of the loop. Now we
399 // change this entry to include NewBB in the DF instead of Exit.
400 DominanceFrontier::iterator DFI = DF->find(PredDom);
401 assert(DFI != DF->end() && "No dominance frontier for node?");
402 if (DFI->second.count(Exit)) {
403 DF->removeFromFrontier(DFI, Exit);
404 DF->addToFrontier(DFI, NewBB);
405 }
406 }
407 }
408 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000409 }
Chris Lattner38acf9e2002-09-26 16:17:31 +0000410}