1 //===- LoopPreheaders.cpp - Loop Preheader Insertion Pass -----------------===//
3 // 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.
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.
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 are built into LICM.
15 // Note that the simplifycfg pass will clean up blocks which are split out but
16 // end up being unnecessary, so usage of this pass does not necessarily
17 // pessimize generated code.
19 //===----------------------------------------------------------------------===//
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"
29 #include "Support/SetOperations.h"
30 #include "Support/Statistic.h"
31 #include "Support/DepthFirstIterator.h"
34 Statistic<> NumInserted("preheaders", "Number of pre-header nodes inserted");
36 struct Preheaders : public FunctionPass {
37 virtual bool runOnFunction(Function &F);
39 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40 // We need loop information to identify the loops...
41 AU.addRequired<LoopInfo>();
42 AU.addRequired<DominatorSet>();
44 AU.addPreserved<LoopInfo>();
45 AU.addPreserved<DominatorSet>();
46 AU.addPreserved<ImmediateDominators>();
47 AU.addPreserved<DominatorTree>();
48 AU.addPreserved<DominanceFrontier>();
49 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
52 bool ProcessLoop(Loop *L);
53 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
54 const std::vector<BasicBlock*> &Preds);
55 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
56 void InsertPreheaderForLoop(Loop *L);
59 RegisterOpt<Preheaders> X("preheaders", "Natural loop pre-header insertion",
63 // Publically exposed interface to pass...
64 const PassInfo *LoopPreheadersID = X.getPassInfo();
65 Pass *createLoopPreheaderInsertionPass() { return new Preheaders(); }
68 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
69 /// it in any convenient order) inserting preheaders...
71 bool Preheaders::runOnFunction(Function &F) {
73 LoopInfo &LI = getAnalysis<LoopInfo>();
75 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i)
76 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]);
82 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
83 /// all loops have preheaders.
85 bool Preheaders::ProcessLoop(Loop *L) {
88 // Does the loop already have a preheader? If so, don't modify the loop...
89 if (L->getLoopPreheader() == 0) {
90 InsertPreheaderForLoop(L);
95 // Regardless of whether or not we added a preheader to the loop we must
96 // guarantee that the preheader dominates all exit nodes. If there are any
97 // exit nodes not dominated, split them now.
98 DominatorSet &DS = getAnalysis<DominatorSet>();
99 BasicBlock *Header = L->getHeader();
100 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i)
101 if (!DS.dominates(Header, L->getExitBlocks()[i])) {
102 RewriteLoopExitBlock(L, L->getExitBlocks()[i]);
103 assert(DS.dominates(Header, L->getExitBlocks()[i]) &&
104 "RewriteLoopExitBlock failed?");
109 const std::vector<Loop*> &SubLoops = L->getSubLoops();
110 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
111 Changed |= ProcessLoop(SubLoops[i]);
115 /// SplitBlockPredecessors - Split the specified block into two blocks. We want
116 /// to move the predecessors specified in the Preds list to point to the new
117 /// block, leaving the remaining predecessors pointing to BB. This method
118 /// updates the SSA PHINode's, but no other analyses.
120 BasicBlock *Preheaders::SplitBlockPredecessors(BasicBlock *BB,
122 const std::vector<BasicBlock*> &Preds) {
124 // Create new basic block, insert right before the original block...
125 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB);
127 // The preheader first gets an unconditional branch to the loop header...
128 BranchInst *BI = new BranchInst(BB);
129 NewBB->getInstList().push_back(BI);
131 // For every PHI node in the block, insert a PHI node into NewBB where the
132 // incoming values from the out of loop edges are moved to NewBB. We have two
133 // possible cases here. If the loop is dead, we just insert dummy entries
134 // into the PHI nodes for the new edge. If the loop is not dead, we move the
135 // incoming edges in BB into new PHI nodes in NewBB.
137 if (!Preds.empty()) { // Is the loop not obviously dead?
138 for (BasicBlock::iterator I = BB->begin();
139 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
141 // Create the new PHI node, insert it into NewBB at the end of the block
142 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
144 // Move all of the edges from blocks outside the loop to the new PHI
145 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
146 Value *V = PN->removeIncomingValue(Preds[i]);
147 NewPHI->addIncoming(V, Preds[i]);
150 // Add an incoming value to the PHI node in the loop for the preheader
152 PN->addIncoming(NewPHI, NewBB);
155 // Now that the PHI nodes are updated, actually move the edges from
156 // Preds to point to NewBB instead of BB.
158 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
159 TerminatorInst *TI = Preds[i]->getTerminator();
160 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
161 if (TI->getSuccessor(s) == BB)
162 TI->setSuccessor(s, NewBB);
165 } else { // Otherwise the loop is dead...
166 for (BasicBlock::iterator I = BB->begin();
167 PHINode *PN = dyn_cast<PHINode>(I); ++I)
168 // Insert dummy values as the incoming value...
169 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
174 // ChangeExitBlock - This recursive function is used to change any exit blocks
175 // that use OldExit to use NewExit instead. This is recursive because children
176 // may need to be processed as well.
178 static void ChangeExitBlock(Loop *L, BasicBlock *OldExit, BasicBlock *NewExit) {
179 if (L->hasExitBlock(OldExit)) {
180 L->changeExitBlock(OldExit, NewExit);
181 const std::vector<Loop*> &SubLoops = L->getSubLoops();
182 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
183 ChangeExitBlock(SubLoops[i], OldExit, NewExit);
188 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
189 /// preheader, this method is called to insert one. This method has two phases:
190 /// preheader insertion and analysis updating.
192 void Preheaders::InsertPreheaderForLoop(Loop *L) {
193 BasicBlock *Header = L->getHeader();
195 // Compute the set of predecessors of the loop that are not in the loop.
196 std::vector<BasicBlock*> OutsideBlocks;
197 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
199 if (!L->contains(*PI)) // Coming in from outside the loop?
200 OutsideBlocks.push_back(*PI); // Keep track of it...
202 // Split out the loop pre-header
204 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
206 //===--------------------------------------------------------------------===//
207 // Update analysis results now that we have performed the transformation
210 // We know that we have loop information to update... update it now.
211 if (Loop *Parent = L->getParentLoop())
212 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
214 // If the header for the loop used to be an exit node for another loop, then
215 // we need to update this to know that the loop-preheader is now the exit
216 // node. Note that the only loop that could have our header as an exit node
217 // is a sibling loop, ie, one with the same parent loop, or one if it's
220 const std::vector<Loop*> *ParentSubLoops;
221 if (Loop *Parent = L->getParentLoop())
222 ParentSubLoops = &Parent->getSubLoops();
223 else // Must check top-level loops...
224 ParentSubLoops = &getAnalysis<LoopInfo>().getTopLevelLoops();
226 // Loop over all sibling loops, performing the substitution (recursively to
227 // include child loops)...
228 for (unsigned i = 0, e = ParentSubLoops->size(); i != e; ++i)
229 ChangeExitBlock((*ParentSubLoops)[i], Header, NewBB);
231 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
233 // The blocks that dominate NewBB are the blocks that dominate Header,
234 // minus Header, plus NewBB.
235 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
236 DomSet.insert(NewBB); // We dominate ourself
237 DomSet.erase(Header); // Header does not dominate us...
238 DS.addBasicBlock(NewBB, DomSet);
240 // The newly created basic block dominates all nodes dominated by Header.
241 for (Function::iterator I = Header->getParent()->begin(),
242 E = Header->getParent()->end(); I != E; ++I)
243 if (DS.dominates(Header, I))
244 DS.addDominator(I, NewBB);
247 // Update immediate dominator information if we have it...
248 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
249 // Whatever i-dominated the header node now immediately dominates NewBB
250 ID->addNewBlock(NewBB, ID->get(Header));
252 // The preheader now is the immediate dominator for the header node...
253 ID->setImmediateDominator(Header, NewBB);
256 // Update DominatorTree information if it is active.
257 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
258 // The immediate dominator of the preheader is the immediate dominator of
261 DominatorTree::Node *HeaderNode = DT->getNode(Header);
262 DominatorTree::Node *PHNode = DT->createNewNode(NewBB,
263 HeaderNode->getIDom());
265 // Change the header node so that PNHode is the new immediate dominator
266 DT->changeImmediateDominator(HeaderNode, PHNode);
269 // Update dominance frontier information...
270 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
271 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
272 // everything that Header does, and it strictly dominates Header in
274 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
275 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
276 NewDFSet.erase(Header);
277 DF->addBasicBlock(NewBB, NewDFSet);
279 // Now we must loop over all of the dominance frontiers in the function,
280 // replacing occurrences of Header with NewBB in some cases. If a block
281 // dominates a (now) predecessor of NewBB, but did not strictly dominate
282 // Header, it will have Header in it's DF set, but should now have NewBB in
284 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
285 // Get all of the dominators of the predecessor...
286 const DominatorSet::DomSetType &PredDoms =
287 DS.getDominators(OutsideBlocks[i]);
288 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
289 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
290 BasicBlock *PredDom = *PDI;
291 // If the loop header is in DF(PredDom), then PredDom didn't dominate
292 // the header but did dominate a predecessor outside of the loop. Now
293 // we change this entry to include the preheader in the DF instead of
295 DominanceFrontier::iterator DFI = DF->find(PredDom);
296 assert(DFI != DF->end() && "No dominance frontier for node?");
297 if (DFI->second.count(Header)) {
298 DF->removeFromFrontier(DFI, Header);
299 DF->addToFrontier(DFI, NewBB);
306 void Preheaders::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
307 DominatorSet &DS = getAnalysis<DominatorSet>();
308 assert(!DS.dominates(L->getHeader(), Exit) &&
309 "Loop already dominates exit block??");
310 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
311 != L->getExitBlocks().end() && "Not a current exit block!");
313 std::vector<BasicBlock*> LoopBlocks;
314 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
316 LoopBlocks.push_back(*I);
318 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
319 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
321 // Update Loop Information - we know that the new block will be in the parent
323 if (Loop *Parent = L->getParentLoop())
324 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
326 // Replace any instances of Exit with NewBB in this and any nested loops...
327 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
328 if (I->hasExitBlock(Exit))
329 I->changeExitBlock(Exit, NewBB); // Update exit block information
331 // Update dominator information... The blocks that dominate NewBB are the
332 // intersection of the dominators of predecessors, plus the block itself.
333 // The newly created basic block does not dominate anything except itself.
335 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(LoopBlocks[0]);
336 for (unsigned i = 1, e = LoopBlocks.size(); i != e; ++i)
337 set_intersect(NewBBDomSet, DS.getDominators(LoopBlocks[i]));
338 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
339 DS.addBasicBlock(NewBB, NewBBDomSet);
341 // Update immediate dominator information if we have it...
342 BasicBlock *NewBBIDom = 0;
343 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
344 // This block does not strictly dominate anything, so it is not an immediate
345 // dominator. To find the immediate dominator of the new exit node, we
346 // trace up the immediate dominators of a predecessor until we find a basic
347 // block that dominates the exit block.
349 BasicBlock *Dom = LoopBlocks[0]; // Some random predecessor...
350 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
351 assert(Dom != 0 && "No shared dominator found???");
355 // Set the immediate dominator now...
356 ID->addNewBlock(NewBB, Dom);
357 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
360 // Update DominatorTree information if it is active.
361 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
362 // NewBB doesn't dominate anything, so just create a node and link it into
363 // its immediate dominator. If we don't have ImmediateDominator info
364 // around, calculate the idom as above.
365 DominatorTree::Node *NewBBIDomNode;
367 NewBBIDomNode = DT->getNode(NewBBIDom);
369 NewBBIDomNode = DT->getNode(LoopBlocks[0]); // Random pred
370 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
371 NewBBIDomNode = NewBBIDomNode->getIDom();
372 assert(NewBBIDomNode && "No shared dominator found??");
376 // Create the new dominator tree node...
377 DT->createNewNode(NewBB, NewBBIDomNode);
380 // Update dominance frontier information...
381 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
382 // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it
383 // does dominate itself (and there is an edge (NewBB -> Exit)).
384 DominanceFrontier::DomSetType NewDFSet;
385 NewDFSet.insert(Exit);
386 DF->addBasicBlock(NewBB, NewDFSet);
388 // Now we must loop over all of the dominance frontiers in the function,
389 // replacing occurrences of Exit with NewBB in some cases. If a block
390 // dominates a (now) predecessor of NewBB, but did not strictly dominate
391 // Exit, it will have Exit in it's DF set, but should now have NewBB in its
393 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
394 // Get all of the dominators of the predecessor...
395 const DominatorSet::DomSetType &PredDoms =DS.getDominators(LoopBlocks[i]);
396 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
397 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
398 BasicBlock *PredDom = *PDI;
399 // Make sure to only rewrite blocks that are part of the loop...
400 if (L->contains(PredDom)) {
401 // If the exit node is in DF(PredDom), then PredDom didn't dominate
402 // Exit but did dominate a predecessor inside of the loop. Now we
403 // change this entry to include NewBB in the DF instead of Exit.
404 DominanceFrontier::iterator DFI = DF->find(PredDom);
405 assert(DFI != DF->end() && "No dominance frontier for node?");
406 if (DFI->second.count(Exit)) {
407 DF->removeFromFrontier(DFI, Exit);
408 DF->addToFrontier(DFI, NewBB);