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 is built into LICM.
15 // Note that the simplifycfg pass will clean up blocks which are split out but
16 // end up being unneccesary, so usage of this pass does not neccesarily
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");
62 // Publically exposed interface to pass...
63 const PassInfo *LoopPreheadersID = X.getPassInfo();
64 Pass *createLoopPreheaderInsertionPass() { return new Preheaders(); }
67 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
68 /// it in any convenient order) inserting preheaders...
70 bool Preheaders::runOnFunction(Function &F) {
72 LoopInfo &LI = getAnalysis<LoopInfo>();
74 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i)
75 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]);
81 /// ProcessLoop - Walk the loop structure in depth first order, ensuring that
82 /// all loops have preheaders.
84 bool Preheaders::ProcessLoop(Loop *L) {
87 // Does the loop already have a preheader? If so, don't modify the loop...
88 if (L->getLoopPreheader() == 0) {
89 InsertPreheaderForLoop(L);
94 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]);
99 assert(DS.dominates(Header, L->getExitBlocks()[i]) &&
100 "RewriteLoopExitBlock failed?");
105 const std::vector<Loop*> &SubLoops = L->getSubLoops();
106 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
107 Changed |= ProcessLoop(SubLoops[i]);
111 /// 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.
116 BasicBlock *Preheaders::SplitBlockPredecessors(BasicBlock *BB,
118 const std::vector<BasicBlock*> &Preds) {
120 // Create new basic block, insert right before the original block...
121 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB);
123 // The preheader first gets an unconditional branch to the loop header...
124 BranchInst *BI = new BranchInst(BB);
125 NewBB->getInstList().push_back(BI);
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.
133 if (!Preds.empty()) { // Is the loop not obviously dead?
134 for (BasicBlock::iterator I = BB->begin();
135 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
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);
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]);
146 // Add an incoming value to the PHI node in the loop for the preheader
148 PN->addIncoming(NewPHI, NewBB);
151 // Now that the PHI nodes are updated, actually move the edges from
152 // Preds to point to NewBB instead of BB.
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);
161 } else { // Otherwise the loop is dead...
162 for (BasicBlock::iterator I = BB->begin();
163 PHINode *PN = dyn_cast<PHINode>(&*I); ++I)
164 // Insert dummy values as the incoming value...
165 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
171 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
172 /// preheader, this method is called to insert one. This method has two phases:
173 /// preheader insertion and analysis updating.
175 void Preheaders::InsertPreheaderForLoop(Loop *L) {
176 BasicBlock *Header = L->getHeader();
178 // Compute the set of predecessors of the loop that are not in the loop.
179 std::vector<BasicBlock*> OutsideBlocks;
180 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
182 if (!L->contains(*PI)) // Coming in from outside the loop?
183 OutsideBlocks.push_back(*PI); // Keep track of it...
185 // Split out the loop pre-header
187 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
189 //===--------------------------------------------------------------------===//
190 // Update analysis results now that we have preformed the transformation
193 // We know that we have loop information to update... update it now.
194 if (Loop *Parent = L->getParentLoop())
195 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
197 // If the header for the loop used to be an exit node for another loop, then
198 // we need to update this to know that the loop-preheader is now the exit
199 // node. Note that the only loop that could have our header as an exit node
200 // is a sibling loop, ie, one with the same parent loop.
201 const std::vector<Loop*> *ParentSubLoops;
202 if (Loop *Parent = L->getParentLoop())
203 ParentSubLoops = &Parent->getSubLoops();
204 else // Must check top-level loops...
205 ParentSubLoops = &getAnalysis<LoopInfo>().getTopLevelLoops();
207 // Loop over all sibling loops, performing the substitution...
208 for (unsigned i = 0, e = ParentSubLoops->size(); i != e; ++i)
209 if ((*ParentSubLoops)[i]->hasExitBlock(Header))
210 (*ParentSubLoops)[i]->changeExitBlock(Header, NewBB);
213 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
215 // The blocks that dominate NewBB are the blocks that dominate Header,
216 // minus Header, plus NewBB.
217 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
218 DomSet.insert(NewBB); // We dominate ourself
219 DomSet.erase(Header); // Header does not dominate us...
220 DS.addBasicBlock(NewBB, DomSet);
222 // The newly created basic block dominates all nodes dominated by Header.
223 for (Function::iterator I = Header->getParent()->begin(),
224 E = Header->getParent()->end(); I != E; ++I)
225 if (DS.dominates(Header, I))
226 DS.addDominator(I, NewBB);
229 // Update immediate dominator information if we have it...
230 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
231 // Whatever i-dominated the header node now immediately dominates NewBB
232 ID->addNewBlock(NewBB, ID->get(Header));
234 // The preheader now is the immediate dominator for the header node...
235 ID->setImmediateDominator(Header, NewBB);
238 // Update DominatorTree information if it is active.
239 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
240 // The immediate dominator of the preheader is the immediate dominator of
243 DominatorTree::Node *HeaderNode = DT->getNode(Header);
244 DominatorTree::Node *PHNode = DT->createNewNode(NewBB,
245 HeaderNode->getIDom());
247 // Change the header node so that PNHode is the new immediate dominator
248 DT->changeImmediateDominator(HeaderNode, PHNode);
251 // Update dominance frontier information...
252 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
253 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
254 // everything that Header does, and it strictly dominates Header in
256 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
257 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
258 NewDFSet.erase(Header);
259 DF->addBasicBlock(NewBB, NewDFSet);
261 // Now we must loop over all of the dominance frontiers in the function,
262 // replacing occurances of Header with NewBB in some cases. If a block
263 // dominates a (now) predecessor of NewBB, but did not strictly dominate
264 // Header, it will have Header in it's DF set, but should now have NewBB in
266 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
267 // Get all of the dominators of the predecessor...
268 const DominatorSet::DomSetType &PredDoms =
269 DS.getDominators(OutsideBlocks[i]);
270 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
271 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
272 BasicBlock *PredDom = *PDI;
273 // If the loop header is in DF(PredDom), then PredDom didn't dominate
274 // the header but did dominate a predecessor outside of the loop. Now
275 // we change this entry to include the preheader in the DF instead of
277 DominanceFrontier::iterator DFI = DF->find(PredDom);
278 assert(DFI != DF->end() && "No dominance frontier for node?");
279 if (DFI->second.count(Header)) {
280 DF->removeFromFrontier(DFI, Header);
281 DF->addToFrontier(DFI, NewBB);
288 void Preheaders::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
289 DominatorSet &DS = getAnalysis<DominatorSet>();
290 assert(!DS.dominates(L->getHeader(), Exit) &&
291 "Loop already dominates exit block??");
292 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
293 != L->getExitBlocks().end() && "Not a current exit block!");
295 std::vector<BasicBlock*> LoopBlocks;
296 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
298 LoopBlocks.push_back(*I);
300 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
301 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
303 // Update Loop Information - we know that the new block will be in the parent
305 if (Loop *Parent = L->getParentLoop())
306 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
308 // Replace any instances of Exit with NewBB in this and any nested loops...
309 for (df_iterator<Loop*> I = df_begin(L), E = df_end(L); I != E; ++I)
310 if (I->hasExitBlock(Exit))
311 I->changeExitBlock(Exit, NewBB); // Update exit block information
313 // Update dominator information... The blocks that dominate NewBB are the
314 // intersection of the dominators of predecessors, plus the block itself.
315 // The newly created basic block does not dominate anything except itself.
317 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(LoopBlocks[0]);
318 for (unsigned i = 1, e = LoopBlocks.size(); i != e; ++i)
319 set_intersect(NewBBDomSet, DS.getDominators(LoopBlocks[i]));
320 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
321 DS.addBasicBlock(NewBB, NewBBDomSet);
323 // Update immediate dominator information if we have it...
324 BasicBlock *NewBBIDom = 0;
325 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
326 // This block does not strictly dominate anything, so it is not an immediate
327 // dominator. To find the immediate dominator of the new exit node, we
328 // trace up the immediate dominators of a predecessor until we find a basic
329 // block that dominates the exit block.
331 BasicBlock *Dom = LoopBlocks[0]; // Some random predecessor...
332 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
333 assert(Dom != 0 && "No shared dominator found???");
337 // Set the immediate dominator now...
338 ID->addNewBlock(NewBB, Dom);
339 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
342 // Update DominatorTree information if it is active.
343 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
344 // NewBB doesn't dominate anything, so just create a node and link it into
345 // its immediate dominator. If we don't have ImmediateDominator info
346 // around, calculate the idom as above.
347 DominatorTree::Node *NewBBIDomNode;
349 NewBBIDomNode = DT->getNode(NewBBIDom);
351 NewBBIDomNode = DT->getNode(LoopBlocks[0]); // Random pred
352 while (!NewBBDomSet.count(NewBBIDomNode->getNode())) {
353 NewBBIDomNode = NewBBIDomNode->getIDom();
354 assert(NewBBIDomNode && "No shared dominator found??");
358 // Create the new dominator tree node...
359 DT->createNewNode(NewBB, NewBBIDomNode);
362 // Update dominance frontier information...
363 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
364 // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it
365 // does dominate itself (and there is an edge (NewBB -> Exit)).
366 DominanceFrontier::DomSetType NewDFSet;
367 NewDFSet.insert(Exit);
368 DF->addBasicBlock(NewBB, NewDFSet);
370 // Now we must loop over all of the dominance frontiers in the function,
371 // replacing occurances of Exit with NewBB in some cases. If a block
372 // dominates a (now) predecessor of NewBB, but did not strictly dominate
373 // Exit, it will have Exit in it's DF set, but should now have NewBB in its
375 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
376 // Get all of the dominators of the predecessor...
377 const DominatorSet::DomSetType &PredDoms =DS.getDominators(LoopBlocks[i]);
378 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
379 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
380 BasicBlock *PredDom = *PDI;
381 // Make sure to only rewrite blocks that are part of the loop...
382 if (L->contains(PredDom)) {
383 // If the exit node is in DF(PredDom), then PredDom didn't dominate
384 // Exit but did dominate a predecessor inside of the loop. Now we
385 // change this entry to include NewBB in the DF instead of Exit.
386 DominanceFrontier::iterator DFI = DF->find(PredDom);
387 assert(DFI != DF->end() && "No dominance frontier for node?");
388 if (DFI->second.count(Exit)) {
389 DF->removeFromFrontier(DFI, Exit);
390 DF->addToFrontier(DFI, NewBB);