blob: e40f1457ae4d8e3a5f32dfa0d9f6563ed0dff56a [file] [log] [blame]
Chris Lattner61992f62002-09-26 16:17:31 +00001//===- LoopPreheaders.cpp - Loop Preheader Insertion Pass -----------------===//
2//
Chris Lattner650096a2003-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
16// end up being unneccesary, so usage of this pass does not neccesarily
17// pessimize generated code.
Chris Lattner61992f62002-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 Lattner650096a2003-02-27 20:27:08 +000029#include "Support/SetOperations.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000030#include "Support/Statistic.h"
Chris Lattner61992f62002-09-26 16:17:31 +000031
32namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000033 Statistic<> NumInserted("preheaders", "Number of pre-header nodes inserted");
Chris Lattner61992f62002-09-26 16:17:31 +000034
35 struct Preheaders : public FunctionPass {
36 virtual bool runOnFunction(Function &F);
37
38 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
39 // We need loop information to identify the loops...
40 AU.addRequired<LoopInfo>();
Chris Lattner650096a2003-02-27 20:27:08 +000041 AU.addRequired<DominatorSet>();
Chris Lattner61992f62002-09-26 16:17:31 +000042
43 AU.addPreserved<LoopInfo>();
44 AU.addPreserved<DominatorSet>();
45 AU.addPreserved<ImmediateDominators>();
46 AU.addPreserved<DominatorTree>();
Chris Lattner650096a2003-02-27 20:27:08 +000047 AU.addPreserved<DominanceFrontier>();
Chris Lattner61992f62002-09-26 16:17:31 +000048 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
49 }
50 private:
51 bool ProcessLoop(Loop *L);
Chris Lattner650096a2003-02-27 20:27:08 +000052 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
53 const std::vector<BasicBlock*> &Preds);
54 void RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner61992f62002-09-26 16:17:31 +000055 void InsertPreheaderForLoop(Loop *L);
56 };
57
Chris Lattnerca056912002-09-26 16:37:37 +000058 RegisterOpt<Preheaders> X("preheaders", "Natural loop pre-header insertion");
Chris Lattner61992f62002-09-26 16:17:31 +000059}
60
61// Publically exposed interface to pass...
62const PassInfo *LoopPreheadersID = X.getPassInfo();
63Pass *createLoopPreheaderInsertionPass() { return new Preheaders(); }
64
65
66/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
67/// it in any convenient order) inserting preheaders...
68///
69bool Preheaders::runOnFunction(Function &F) {
70 bool Changed = false;
71 LoopInfo &LI = getAnalysis<LoopInfo>();
72
73 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i)
74 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]);
75
76 return Changed;
77}
78
79
80/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
81/// all loops have preheaders.
82///
83bool Preheaders::ProcessLoop(Loop *L) {
84 bool Changed = false;
85
86 // Does the loop already have a preheader? If so, don't modify the loop...
87 if (L->getLoopPreheader() == 0) {
88 InsertPreheaderForLoop(L);
89 NumInserted++;
90 Changed = true;
91 }
92
Chris Lattner650096a2003-02-27 20:27:08 +000093 DominatorSet &DS = getAnalysis<DominatorSet>();
94 BasicBlock *Header = L->getHeader();
95 for (unsigned i = 0, e = L->getExitBlocks().size(); i != e; ++i)
96 if (!DS.dominates(Header, L->getExitBlocks()[i])) {
97 RewriteLoopExitBlock(L, L->getExitBlocks()[i]);
Chris Lattner10b2b052003-02-27 22:31:07 +000098 assert(DS.dominates(Header, L->getExitBlocks()[i]) &&
99 "RewriteLoopExitBlock failed?");
Chris Lattner650096a2003-02-27 20:27:08 +0000100 NumInserted++;
101 Changed = true;
102 }
103
Chris Lattner61992f62002-09-26 16:17:31 +0000104 const std::vector<Loop*> &SubLoops = L->getSubLoops();
105 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
106 Changed |= ProcessLoop(SubLoops[i]);
107 return Changed;
108}
109
Chris Lattner650096a2003-02-27 20:27:08 +0000110/// SplitBlockPredecessors - Split the specified block into two blocks. We want
111/// to move the predecessors specified in the Preds list to point to the new
112/// block, leaving the remaining predecessors pointing to BB. This method
113/// updates the SSA PHINode's, but no other analyses.
114///
115BasicBlock *Preheaders::SplitBlockPredecessors(BasicBlock *BB,
116 const char *Suffix,
117 const std::vector<BasicBlock*> &Preds) {
118
119 // Create new basic block, insert right before the original block...
120 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB);
121
122 // The preheader first gets an unconditional branch to the loop header...
123 BranchInst *BI = new BranchInst(BB);
124 NewBB->getInstList().push_back(BI);
125
126 // For every PHI node in the block, insert a PHI node into NewBB where the
127 // incoming values from the out of loop edges are moved to NewBB. We have two
128 // possible cases here. If the loop is dead, we just insert dummy entries
129 // into the PHI nodes for the new edge. If the loop is not dead, we move the
130 // incoming edges in BB into new PHI nodes in NewBB.
131 //
132 if (!Preds.empty()) { // Is the loop not obviously dead?
133 for (BasicBlock::iterator I = BB->begin();
134 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
135
136 // Create the new PHI node, insert it into NewBB at the end of the block
137 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
138
139 // Move all of the edges from blocks outside the loop to the new PHI
140 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
141 Value *V = PN->removeIncomingValue(Preds[i]);
142 NewPHI->addIncoming(V, Preds[i]);
143 }
144
145 // Add an incoming value to the PHI node in the loop for the preheader
146 // edge
147 PN->addIncoming(NewPHI, NewBB);
148 }
149
150 // Now that the PHI nodes are updated, actually move the edges from
151 // Preds to point to NewBB instead of BB.
152 //
153 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
154 TerminatorInst *TI = Preds[i]->getTerminator();
155 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
156 if (TI->getSuccessor(s) == BB)
157 TI->setSuccessor(s, NewBB);
158 }
159
160 } else { // Otherwise the loop is dead...
161 for (BasicBlock::iterator I = BB->begin();
162 PHINode *PN = dyn_cast<PHINode>(&*I); ++I)
163 // Insert dummy values as the incoming value...
164 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
165 }
166 return NewBB;
167}
168
Chris Lattner61992f62002-09-26 16:17:31 +0000169
170/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
171/// preheader, this method is called to insert one. This method has two phases:
172/// preheader insertion and analysis updating.
173///
174void Preheaders::InsertPreheaderForLoop(Loop *L) {
175 BasicBlock *Header = L->getHeader();
176
177 // Compute the set of predecessors of the loop that are not in the loop.
178 std::vector<BasicBlock*> OutsideBlocks;
179 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
180 PI != PE; ++PI)
181 if (!L->contains(*PI)) // Coming in from outside the loop?
182 OutsideBlocks.push_back(*PI); // Keep track of it...
183
Chris Lattner650096a2003-02-27 20:27:08 +0000184 // Split out the loop pre-header
185 BasicBlock *NewBB =
186 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner61992f62002-09-26 16:17:31 +0000187
Chris Lattner61992f62002-09-26 16:17:31 +0000188 //===--------------------------------------------------------------------===//
189 // Update analysis results now that we have preformed the transformation
190 //
191
192 // We know that we have loop information to update... update it now.
193 if (Loop *Parent = L->getParentLoop())
194 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
195
Chris Lattner650096a2003-02-27 20:27:08 +0000196 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
197 {
Chris Lattner61992f62002-09-26 16:17:31 +0000198 // The blocks that dominate NewBB are the blocks that dominate Header,
199 // minus Header, plus NewBB.
Chris Lattner650096a2003-02-27 20:27:08 +0000200 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner03a9e152002-09-29 21:41:38 +0000201 DomSet.insert(NewBB); // We dominate ourself
Chris Lattner61992f62002-09-26 16:17:31 +0000202 DomSet.erase(Header); // Header does not dominate us...
Chris Lattner650096a2003-02-27 20:27:08 +0000203 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner03a9e152002-09-29 21:41:38 +0000204
205 // The newly created basic block dominates all nodes dominated by Header.
206 for (Function::iterator I = Header->getParent()->begin(),
207 E = Header->getParent()->end(); I != E; ++I)
Chris Lattner650096a2003-02-27 20:27:08 +0000208 if (DS.dominates(Header, I))
209 DS.addDominator(I, NewBB);
Chris Lattner61992f62002-09-26 16:17:31 +0000210 }
211
212 // Update immediate dominator information if we have it...
213 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
214 // Whatever i-dominated the header node now immediately dominates NewBB
215 ID->addNewBlock(NewBB, ID->get(Header));
216
217 // The preheader now is the immediate dominator for the header node...
218 ID->setImmediateDominator(Header, NewBB);
219 }
220
221 // Update DominatorTree information if it is active.
222 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
223 // The immediate dominator of the preheader is the immediate dominator of
224 // the old header.
225 //
226 DominatorTree::Node *HeaderNode = DT->getNode(Header);
Chris Lattner03a9e152002-09-29 21:41:38 +0000227 DominatorTree::Node *PHNode = DT->createNewNode(NewBB,
228 HeaderNode->getIDom());
Chris Lattner61992f62002-09-26 16:17:31 +0000229
230 // Change the header node so that PNHode is the new immediate dominator
231 DT->changeImmediateDominator(HeaderNode, PHNode);
232 }
Chris Lattner650096a2003-02-27 20:27:08 +0000233
234 // Update dominance frontier information...
235 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
236 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
237 // everything that Header does, and it strictly dominates Header in
238 // addition.
239 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
240 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
241 NewDFSet.erase(Header);
242 DF->addBasicBlock(NewBB, NewDFSet);
243
244 // Now we must loop over all of the dominance frontiers in the function,
245 // replacing occurances of Header with NewBB in some cases. If a block
246 // dominates a (now) predecessor of NewBB, but did not strictly dominate
247 // Header, it will have Header in it's DF set, but should now have NewBB in
248 // its set.
249 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
250 // Get all of the dominators of the predecessor...
251 const DominatorSet::DomSetType &PredDoms =
252 DS.getDominators(OutsideBlocks[i]);
253 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
254 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
255 BasicBlock *PredDom = *PDI;
256 // If the loop header is in DF(PredDom), then PredDom didn't dominate
257 // the header but did dominate a predecessor outside of the loop. Now
258 // we change this entry to include the preheader in the DF instead of
259 // the header.
260 DominanceFrontier::iterator DFI = DF->find(PredDom);
261 assert(DFI != DF->end() && "No dominance frontier for node?");
262 if (DFI->second.count(Header)) {
263 DF->removeFromFrontier(DFI, Header);
264 DF->addToFrontier(DFI, NewBB);
265 }
266 }
267 }
268 }
269}
270
271void Preheaders::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
272 DominatorSet &DS = getAnalysis<DominatorSet>();
273 assert(!DS.dominates(L->getHeader(), Exit) &&
274 "Loop already dominates exit block??");
Chris Lattner10b2b052003-02-27 22:31:07 +0000275 assert(std::find(L->getExitBlocks().begin(), L->getExitBlocks().end(), Exit)
276 != L->getExitBlocks().end() && "Not a current exit block!");
Chris Lattner650096a2003-02-27 20:27:08 +0000277
278 std::vector<BasicBlock*> LoopBlocks;
279 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
280 if (L->contains(*I))
281 LoopBlocks.push_back(*I);
282
Chris Lattner10b2b052003-02-27 22:31:07 +0000283 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
284 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
285
Chris Lattner4e2fbfb2003-02-27 21:50:19 +0000286 // Update Loop Information - we know that the new block will be in the parent
287 // loop of L.
288 if (Loop *Parent = L->getParentLoop())
289 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner10b2b052003-02-27 22:31:07 +0000290 L->changeExitBlock(Exit, NewBB); // Update exit block information
Chris Lattner4e2fbfb2003-02-27 21:50:19 +0000291
Chris Lattner650096a2003-02-27 20:27:08 +0000292 // Update dominator information... The blocks that dominate NewBB are the
293 // intersection of the dominators of predecessors, plus the block itself.
294 // The newly created basic block does not dominate anything except itself.
295 //
296 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(LoopBlocks[0]);
297 for (unsigned i = 1, e = LoopBlocks.size(); i != e; ++i)
298 set_intersect(NewBBDomSet, DS.getDominators(LoopBlocks[i]));
299 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
300 DS.addBasicBlock(NewBB, NewBBDomSet);
301
302 // Update immediate dominator information if we have it...
303 BasicBlock *NewBBIDom = 0;
304 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
305 // This block does not strictly dominate anything, so it is not an immediate
306 // dominator. To find the immediate dominator of the new exit node, we
307 // trace up the immediate dominators of a predecessor until we find a basic
308 // block that dominates the exit block.
309 //
310 BasicBlock *Dom = LoopBlocks[0]; // Some random predecessor...
311 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
312 assert(Dom != 0 && "No shared dominator found???");
313 Dom = ID->get(Dom);
314 }
315
316 // Set the immediate dominator now...
317 ID->addNewBlock(NewBB, Dom);
318 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
319 }
320
321 // Update DominatorTree information if it is active.
322 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
323 // NewBB doesn't dominate anything, so just create a node and link it into
324 // its immediate dominator. If we don't have ImmediateDominator info
325 // around, calculate the idom as above.
326 DominatorTree::Node *NewBBIDomNode;
327 if (NewBBIDom) {
328 NewBBIDomNode = DT->getNode(NewBBIDom);
329 } else {
330 NewBBIDomNode = DT->getNode(LoopBlocks[0]); // Random pred
331 while (!NewBBDomSet.count(NewBBIDomNode->getNode())) {
332 NewBBIDomNode = NewBBIDomNode->getIDom();
333 assert(NewBBIDomNode && "No shared dominator found??");
334 }
335 }
336
337 // Create the new dominator tree node...
338 DT->createNewNode(NewBB, NewBBIDomNode);
339 }
340
341 // Update dominance frontier information...
342 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
343 // DF(NewBB) is {Exit} because NewBB does not strictly dominate Exit, but it
344 // does dominate itself (and there is an edge (NewBB -> Exit)).
345 DominanceFrontier::DomSetType NewDFSet;
346 NewDFSet.insert(Exit);
347 DF->addBasicBlock(NewBB, NewDFSet);
348
349 // Now we must loop over all of the dominance frontiers in the function,
350 // replacing occurances of Exit with NewBB in some cases. If a block
351 // dominates a (now) predecessor of NewBB, but did not strictly dominate
352 // Exit, it will have Exit in it's DF set, but should now have NewBB in its
353 // set.
354 for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
355 // Get all of the dominators of the predecessor...
356 const DominatorSet::DomSetType &PredDoms =DS.getDominators(LoopBlocks[i]);
357 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
358 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
359 BasicBlock *PredDom = *PDI;
360 // Make sure to only rewrite blocks that are part of the loop...
361 if (L->contains(PredDom)) {
362 // If the exit node is in DF(PredDom), then PredDom didn't dominate
363 // Exit but did dominate a predecessor inside of the loop. Now we
364 // change this entry to include NewBB in the DF instead of Exit.
365 DominanceFrontier::iterator DFI = DF->find(PredDom);
366 assert(DFI != DF->end() && "No dominance frontier for node?");
367 if (DFI->second.count(Exit)) {
368 DF->removeFromFrontier(DFI, Exit);
369 DF->addToFrontier(DFI, NewBB);
370 }
371 }
372 }
373 }
Chris Lattner650096a2003-02-27 20:27:08 +0000374 }
Chris Lattner61992f62002-09-26 16:17:31 +0000375}