1 //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
3 // This pass performs several transformations to transform natural loops into a
4 // simpler form, which makes subsequent analyses and transformations simpler and
7 // Loop pre-header insertion guarantees that there is a single, non-critical
8 // entry edge from outside of the loop to the loop header. This simplifies a
9 // number of analyses and transformations, such as LICM.
11 // Loop exit-block insertion guarantees that all exit blocks from the loop
12 // (blocks which are outside of the loop that have predecessors inside of the
13 // loop) are dominated by the loop header. This simplifies transformations such
14 // as store-sinking that are built into LICM.
16 // This pass also guarantees that loops will have exactly one backedge.
18 // Note that the simplifycfg pass will clean up blocks which are split out but
19 // end up being unnecessary, so usage of this pass should not pessimize
22 // This pass obviously modifies the CFG, but updates loop information and
23 // dominator information.
25 //===----------------------------------------------------------------------===//
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Analysis/LoopInfo.h"
30 #include "llvm/Function.h"
31 #include "llvm/iTerminators.h"
32 #include "llvm/iPHINode.h"
33 #include "llvm/Constant.h"
34 #include "llvm/Support/CFG.h"
35 #include "Support/SetOperations.h"
36 #include "Support/Statistic.h"
37 #include "Support/DepthFirstIterator.h"
41 NumInserted("loopsimplify", "Number of pre-header blocks inserted");
43 struct LoopSimplify : public FunctionPass {
44 virtual bool runOnFunction(Function &F);
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47 // We need loop information to identify the loops...
48 AU.addRequired<LoopInfo>();
49 AU.addRequired<DominatorSet>();
51 AU.addPreserved<LoopInfo>();
52 AU.addPreserved<DominatorSet>();
53 AU.addPreserved<ImmediateDominators>();
54 AU.addPreserved<DominatorTree>();
55 AU.addPreserved<DominanceFrontier>();
56 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
59 bool ProcessLoop(Loop *L);
60 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
61 const std::vector<BasicBlock*> &Preds);
62 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
63 void InsertPreheaderForLoop(Loop *L);
64 void InsertUniqueBackedgeBlock(Loop *L);
66 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
67 std::vector<BasicBlock*> &PredBlocks);
70 RegisterOpt<LoopSimplify>
71 X("loopsimplify", "Canonicalize natural loops", true);
74 // Publically exposed interface to pass...
75 const PassInfo *LoopSimplifyID = X.getPassInfo();
76 Pass *createLoopSimplifyPass() { return new LoopSimplify(); }
79 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
80 /// it in any convenient order) inserting preheaders...
82 bool LoopSimplify::runOnFunction(Function &F) {
84 LoopInfo &LI = getAnalysis<LoopInfo>();
86 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i)
87 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]);
93 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
94 /// all loops have preheaders.
96 bool LoopSimplify::ProcessLoop(Loop *L) {
99 // Does the loop already have a preheader? If so, don't modify the loop...
100 if (L->getLoopPreheader() == 0) {
101 InsertPreheaderForLoop(L);
106 // Regardless of whether or not we added a preheader to the loop we must
107 // guarantee that the preheader dominates all exit nodes. If there are any
108 // exit nodes not dominated, split them now.
109 DominatorSet &DS = getAnalysis<DominatorSet>();
110 BasicBlock *Header = L->getHeader();
111 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i)
112 if (!DS.dominates(Header, L->getExitBlocks()[i])) {
113 RewriteLoopExitBlock(L, L->getExitBlocks()[i]);
114 assert(DS.dominates(Header, L->getExitBlocks()[i]) &&
115 "RewriteLoopExitBlock failed?");
120 // The preheader may have more than two predecessors at this point (from the
121 // preheader and from the backedges). To simplify the loop more, insert an
122 // extra back-edge block in the loop so that there is exactly one backedge.
123 if (L->getNumBackEdges() != 1) {
124 InsertUniqueBackedgeBlock(L);
129 const std::vector<Loop*> &SubLoops = L->getSubLoops();
130 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
131 Changed |= ProcessLoop(SubLoops[i]);
135 /// SplitBlockPredecessors - Split the specified block into two blocks. We want
136 /// to move the predecessors specified in the Preds list to point to the new
137 /// block, leaving the remaining predecessors pointing to BB. This method
138 /// updates the SSA PHINode's, but no other analyses.
140 BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
142 const std::vector<BasicBlock*> &Preds) {
144 // Create new basic block, insert right before the original block...
145 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB);
147 // The preheader first gets an unconditional branch to the loop header...
148 BranchInst *BI = new BranchInst(BB);
149 NewBB->getInstList().push_back(BI);
151 // For every PHI node in the block, insert a PHI node into NewBB where the
152 // incoming values from the out of loop edges are moved to NewBB. We have two
153 // possible cases here. If the loop is dead, we just insert dummy entries
154 // into the PHI nodes for the new edge. If the loop is not dead, we move the
155 // incoming edges in BB into new PHI nodes in NewBB.
157 if (!Preds.empty()) { // Is the loop not obviously dead?
158 for (BasicBlock::iterator I = BB->begin();
159 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
161 // Create the new PHI node, insert it into NewBB at the end of the block
162 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
164 // Move all of the edges from blocks outside the loop to the new PHI
165 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
166 Value *V = PN->removeIncomingValue(Preds[i]);
167 NewPHI->addIncoming(V, Preds[i]);
170 // Add an incoming value to the PHI node in the loop for the preheader
172 PN->addIncoming(NewPHI, NewBB);
175 // Now that the PHI nodes are updated, actually move the edges from
176 // Preds to point to NewBB instead of BB.
178 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
179 TerminatorInst *TI = Preds[i]->getTerminator();
180 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
181 if (TI->getSuccessor(s) == BB)
182 TI->setSuccessor(s, NewBB);
185 } else { // Otherwise the loop is dead...
186 for (BasicBlock::iterator I = BB->begin();
187 PHINode *PN = dyn_cast<PHINode>(I); ++I)
188 // Insert dummy values as the incoming value...
189 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
194 // ChangeExitBlock - This recursive function is used to change any exit blocks
195 // that use OldExit to use NewExit instead. This is recursive because children
196 // may need to be processed as well.
198 static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) {
199 if (L->hasExitBlock(OldExit)) {
200 L->changeExitBlock(OldExit, NewExit);
201 const std::vector<Loop*> &SubLoops = L->getSubLoops();
202 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
203 ChangeExitBlock(SubLoops[i], OldExit, NewExit);
208 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
209 /// preheader, this method is called to insert one. This method has two phases:
210 /// preheader insertion and analysis updating.
212 void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
213 BasicBlock *Header = L->getHeader();
215 // Compute the set of predecessors of the loop that are not in the loop.
216 std::vector<BasicBlock*> OutsideBlocks;
217 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
219 if (!L->contains(*PI)) // Coming in from outside the loop?
220 OutsideBlocks.push_back(*PI); // Keep track of it...
222 // Split out the loop pre-header
224 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
226 //===--------------------------------------------------------------------===//
227 // Update analysis results now that we have performed the transformation
230 // We know that we have loop information to update... update it now.
231 if (Loop *Parent = L->getParentLoop())
232 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
234 // If the header for the loop used to be an exit node for another loop, then
235 // we need to update this to know that the loop-preheader is now the exit
236 // node. Note that the only loop that could have our header as an exit node
237 // is a sibling loop, ie, one with the same parent loop, or one if it's
240 const std::vector<Loop*> *ParentSubLoops;
241 if (Loop *Parent = L->getParentLoop())
242 ParentSubLoops = &Parent->getSubLoops();
243 else // Must check top-level loops...
244 ParentSubLoops = &getAnalysis<LoopInfo>().getTopLevelLoops();
246 // Loop over all sibling loops, performing the substitution (recursively to
247 // include child loops)...
248 for (unsigned i = 0, e = ParentSubLoops->size(); i != e; ++i)
249 ChangeExitBlock((*ParentSubLoops)[i], Header, NewBB);
251 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
253 // The blocks that dominate NewBB are the blocks that dominate Header,
254 // minus Header, plus NewBB.
255 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
256 DomSet.insert(NewBB); // We dominate ourself
257 DomSet.erase(Header); // Header does not dominate us...
258 DS.addBasicBlock(NewBB, DomSet);
260 // The newly created basic block dominates all nodes dominated by Header.
261 for (Function::iterator I = Header->getParent()->begin(),
262 E = Header->getParent()->end(); I != E; ++I)
263 if (DS.dominates(Header, I))
264 DS.addDominator(I, NewBB);
267 // Update immediate dominator information if we have it...
268 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
269 // Whatever i-dominated the header node now immediately dominates NewBB
270 ID->addNewBlock(NewBB, ID->get(Header));
272 // The preheader now is the immediate dominator for the header node...
273 ID->setImmediateDominator(Header, NewBB);
276 // Update DominatorTree information if it is active.
277 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
278 // The immediate dominator of the preheader is the immediate dominator of
281 DominatorTree::Node *HeaderNode = DT->getNode(Header);
282 DominatorTree::Node *PHNode = DT->createNewNode(NewBB,
283 HeaderNode->getIDom());
285 // Change the header node so that PNHode is the new immediate dominator
286 DT->changeImmediateDominator(HeaderNode, PHNode);
289 // Update dominance frontier information...
290 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
291 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
292 // everything that Header does, and it strictly dominates Header in
294 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
295 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
296 NewDFSet.erase(Header);
297 DF->addBasicBlock(NewBB, NewDFSet);
299 // Now we must loop over all of the dominance frontiers in the function,
300 // replacing occurrences of Header with NewBB in some cases. If a block
301 // dominates a (now) predecessor of NewBB, but did not strictly dominate
302 // Header, it will have Header in it's DF set, but should now have NewBB in
304 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
305 // Get all of the dominators of the predecessor...
306 const DominatorSet::DomSetType &PredDoms =
307 DS.getDominators(OutsideBlocks[i]);
308 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
309 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
310 BasicBlock *PredDom = *PDI;
311 // If the loop header is in DF(PredDom), then PredDom didn't dominate
312 // the header but did dominate a predecessor outside of the loop. Now
313 // we change this entry to include the preheader in the DF instead of
315 DominanceFrontier::iterator DFI = DF->find(PredDom);
316 assert(DFI != DF->end() && "No dominance frontier for node?");
317 if (DFI->second.count(Header)) {
318 DF->removeFromFrontier(DFI, Header);
319 DF->addToFrontier(DFI, NewBB);
326 void LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
327 DominatorSet &DS = getAnalysis<DominatorSet>();
328 assert(!DS.dominates(L->getHeader(), Exit) &&
329 "Loop already dominates exit block??");
330 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
331 != L->getExitBlocks().end() && "Not a current exit block!");
333 std::vector<BasicBlock*> LoopBlocks;
334 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
336 LoopBlocks.push_back(*I);
338 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
339 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
341 // Update Loop Information - we know that the new block will be in the parent
343 if (Loop *Parent = L->getParentLoop())
344 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
346 // Replace any instances of Exit with NewBB in this and any nested loops...
347 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
348 if (I->hasExitBlock(Exit))
349 I->changeExitBlock(Exit, NewBB); // Update exit block information
351 // Update dominator information (set, immdom, domtree, and domfrontier)
352 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
355 /// InsertUniqueBackedgeBlock - This method is called when the specified loop
356 /// has more than one backedge in it. If this occurs, revector all of these
357 /// backedges to target a new basic block and have that block branch to the loop
358 /// header. This ensures that loops have exactly one backedge.
360 void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
361 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
363 // Get information about the loop
364 BasicBlock *Preheader = L->getLoopPreheader();
365 BasicBlock *Header = L->getHeader();
366 Function *F = Header->getParent();
368 // Figure out which basic blocks contain back-edges to the loop header.
369 std::vector<BasicBlock*> BackedgeBlocks;
370 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
371 if (*I != Preheader) BackedgeBlocks.push_back(*I);
373 // Create and insert the new backedge block...
374 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
375 Instruction *BETerminator = new BranchInst(Header);
376 BEBlock->getInstList().push_back(BETerminator);
378 // Move the new backedge block to right after the last backedge block.
379 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
380 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
382 // Now that the block has been inserted into the function, create PHI nodes in
383 // the backedge block which correspond to any PHI nodes in the header block.
384 for (BasicBlock::iterator I = Header->begin();
385 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
386 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
388 NewPN->op_reserve(2*BackedgeBlocks.size());
390 // Loop over the PHI node, moving all entries except the one for the
391 // preheader over to the new PHI node.
392 unsigned PreheaderIdx = ~0U;
393 bool HasUniqueIncomingValue = true;
394 Value *UniqueValue = 0;
395 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
396 BasicBlock *IBB = PN->getIncomingBlock(i);
397 Value *IV = PN->getIncomingValue(i);
398 if (IBB == Preheader) {
401 NewPN->addIncoming(IV, IBB);
402 if (HasUniqueIncomingValue) {
403 if (UniqueValue == 0)
405 else if (UniqueValue != IV)
406 HasUniqueIncomingValue = false;
411 // Delete all of the incoming values from the old PN except the preheader's
412 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
413 if (PreheaderIdx != 0) {
414 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
415 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
417 PN->op_erase(PN->op_begin()+2, PN->op_end());
419 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
420 PN->addIncoming(NewPN, BEBlock);
422 // As an optimization, if all incoming values in the new PhiNode (which is a
423 // subset of the incoming values of the old PHI node) have the same value,
424 // eliminate the PHI Node.
425 if (HasUniqueIncomingValue) {
426 NewPN->replaceAllUsesWith(UniqueValue);
427 BEBlock->getInstList().erase(NewPN);
431 // Now that all of the PHI nodes have been inserted and adjusted, modify the
432 // backedge blocks to just to the BEBlock instead of the header.
433 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
434 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
435 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
436 if (TI->getSuccessor(Op) == Header)
437 TI->setSuccessor(Op, BEBlock);
440 //===--- Update all analyses which we must preserve now -----------------===//
442 // Update Loop Information - we know that this block is now in the current
443 // loop and all parent loops.
444 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
446 // Replace any instances of Exit with NewBB in this and any nested loops...
447 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
448 if (I->hasExitBlock(Header))
449 I->changeExitBlock(Header, BEBlock); // Update exit block information
451 // Update dominator information (set, immdom, domtree, and domfrontier)
452 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
455 /// UpdateDomInfoForRevectoredPreds - This method is used to update the four
456 /// different kinds of dominator information (dominator sets, immediate
457 /// dominators, dominator trees, and dominance frontiers) after a new block has
458 /// been added to the CFG.
460 /// This only supports the case when an existing block (known as "Exit"), had
461 /// some of its predecessors factored into a new basic block. This
462 /// transformation inserts a new basic block ("NewBB"), with a single
463 /// unconditional branch to Exit, and moves some predecessors of "Exit" to now
464 /// branch to NewBB. These predecessors are listed in PredBlocks, even though
465 /// they are the same as pred_begin(NewBB)/pred_end(NewBB).
467 void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
468 std::vector<BasicBlock*> &PredBlocks) {
469 assert(succ_begin(NewBB) != succ_end(NewBB) &&
470 ++succ_begin(NewBB) == succ_end(NewBB) &&
471 "NewBB should have a single successor!");
472 DominatorSet &DS = getAnalysis<DominatorSet>();
474 // Update dominator information... The blocks that dominate NewBB are the
475 // intersection of the dominators of predecessors, plus the block itself.
476 // The newly created basic block does not dominate anything except itself.
478 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
479 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
480 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
481 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
482 DS.addBasicBlock(NewBB, NewBBDomSet);
484 // Update immediate dominator information if we have it...
485 BasicBlock *NewBBIDom = 0;
486 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
487 // This block does not strictly dominate anything, so it is not an immediate
488 // dominator. To find the immediate dominator of the new exit node, we
489 // trace up the immediate dominators of a predecessor until we find a basic
490 // block that dominates the exit block.
492 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
493 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
494 assert(Dom != 0 && "No shared dominator found???");
498 // Set the immediate dominator now...
499 ID->addNewBlock(NewBB, Dom);
500 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
503 // Update DominatorTree information if it is active.
504 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
505 // NewBB doesn't dominate anything, so just create a node and link it into
506 // its immediate dominator. If we don't have ImmediateDominator info
507 // around, calculate the idom as above.
508 DominatorTree::Node *NewBBIDomNode;
510 NewBBIDomNode = DT->getNode(NewBBIDom);
512 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
513 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
514 NewBBIDomNode = NewBBIDomNode->getIDom();
515 assert(NewBBIDomNode && "No shared dominator found??");
519 // Create the new dominator tree node...
520 DT->createNewNode(NewBB, NewBBIDomNode);
523 // Update dominance frontier information...
524 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
525 // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it
526 // does dominate itself (and there is an edge (NewBB -> Exit)). Exit is the
527 // single successor of NewBB.
528 DominanceFrontier::DomSetType NewDFSet;
529 BasicBlock *Exit = *succ_begin(NewBB);
530 NewDFSet.insert(Exit);
531 DF->addBasicBlock(NewBB, NewDFSet);
533 // Now we must loop over all of the dominance frontiers in the function,
534 // replacing occurrences of Exit with NewBB in some cases. All blocks that
535 // dominate a block in PredBlocks and contained Exit in their dominance
536 // frontier must be updated to contain NewBB instead. This only occurs if
537 // there is more than one block in PredBlocks.
539 if (PredBlocks.size() > 1) {
540 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
541 BasicBlock *Pred = PredBlocks[i];
542 // Get all of the dominators of the predecessor...
543 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
544 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
545 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
546 BasicBlock *PredDom = *PDI;
548 // If the Exit node is in DF(PredDom), then PredDom didn't dominate
549 // Exit but did dominate a predecessor of it. Now we change this
550 // entry to include NewBB in the DF instead of Exit.
551 DominanceFrontier::iterator DFI = DF->find(PredDom);
552 assert(DFI != DF->end() && "No dominance frontier for node?");
553 if (DFI->second.count(Exit)) {
554 DF->removeFromFrontier(DFI, Exit);
555 DF->addToFrontier(DFI, NewBB);