blob: d27bc8c7ad217bacc75254230b0ce38a403d1d2b [file] [log] [blame]
Chris Lattner67a98012003-10-12 21:44:18 +00001//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner38acf9e2002-09-26 16:17:31 +00009//
Chris Lattneree2c50c2003-10-12 21:43:28 +000010// This pass performs several transformations to transform natural loops into a
11// simpler form, which makes subsequent analyses and transformations simpler and
12// more effective.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000013//
14// Loop pre-header insertion guarantees that there is a single, non-critical
15// entry edge from outside of the loop to the loop header. This simplifies a
16// number of analyses and transformations, such as LICM.
17//
18// Loop exit-block insertion guarantees that all exit blocks from the loop
19// (blocks which are outside of the loop that have predecessors inside of the
Chris Lattner66ea98e2003-12-10 17:20:35 +000020// loop) only have predecessors from inside of the loop (and are thus dominated
21// by the loop header). This simplifies transformations such as store-sinking
22// that are built into LICM.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000023//
Chris Lattner2ab6a732003-10-13 00:37:13 +000024// This pass also guarantees that loops will have exactly one backedge.
25//
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000026// Note that the simplifycfg pass will clean up blocks which are split out but
Chris Lattneree2c50c2003-10-12 21:43:28 +000027// end up being unnecessary, so usage of this pass should not pessimize
28// generated code.
29//
30// This pass obviously modifies the CFG, but updates loop information and
31// dominator information.
Chris Lattner38acf9e2002-09-26 16:17:31 +000032//
33//===----------------------------------------------------------------------===//
34
Chris Lattnerd216e8b2006-12-19 22:17:40 +000035#define DEBUG_TYPE "loopsimplify"
Chris Lattner38acf9e2002-09-26 16:17:31 +000036#include "llvm/Transforms/Scalar.h"
Chris Lattner2ef703e2004-03-14 03:59:22 +000037#include "llvm/Constant.h"
Misha Brukman47b14a42004-07-29 17:30:56 +000038#include "llvm/Instructions.h"
Chris Lattner2ef703e2004-03-14 03:59:22 +000039#include "llvm/Function.h"
40#include "llvm/Type.h"
Chris Lattnercec5b882005-03-25 06:37:22 +000041#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0f98e752003-12-19 06:27:08 +000042#include "llvm/Analysis/Dominators.h"
43#include "llvm/Analysis/LoopInfo.h"
Chris Lattner38acf9e2002-09-26 16:17:31 +000044#include "llvm/Support/CFG.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000045#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000046#include "llvm/ADT/SetOperations.h"
47#include "llvm/ADT/SetVector.h"
48#include "llvm/ADT/Statistic.h"
49#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattner66ea98e2003-12-10 17:20:35 +000050using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000051
Chris Lattnerd216e8b2006-12-19 22:17:40 +000052STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
53STATISTIC(NumNested , "Number of nested loops split out");
Chris Lattner38acf9e2002-09-26 16:17:31 +000054
Chris Lattnerd216e8b2006-12-19 22:17:40 +000055namespace {
Chris Lattner95255282006-06-28 23:17:24 +000056 struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass {
Chris Lattnercec5b882005-03-25 06:37:22 +000057 // AA - If we have an alias analysis object to update, this is it, otherwise
58 // this is null.
59 AliasAnalysis *AA;
Chris Lattnerc27e0562006-02-14 22:34:08 +000060 LoopInfo *LI;
Chris Lattnercec5b882005-03-25 06:37:22 +000061
Chris Lattner38acf9e2002-09-26 16:17:31 +000062 virtual bool runOnFunction(Function &F);
Misha Brukmanfd939082005-04-21 23:48:37 +000063
Chris Lattner38acf9e2002-09-26 16:17:31 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 // We need loop information to identify the loops...
66 AU.addRequired<LoopInfo>();
Chris Lattner786c5642004-03-13 22:01:26 +000067 AU.addRequired<DominatorTree>();
Devang Patel3b57b6f2007-03-20 20:18:12 +000068 AU.addRequired<ETForest>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000069
70 AU.addPreserved<LoopInfo>();
Chris Lattnerbaec98d2006-01-09 08:03:08 +000071 AU.addPreserved<ETForest>();
Chris Lattner38acf9e2002-09-26 16:17:31 +000072 AU.addPreserved<DominatorTree>();
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000073 AU.addPreserved<DominanceFrontier>();
Chris Lattner94f40322005-08-10 02:07:32 +000074 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
Chris Lattner38acf9e2002-09-26 16:17:31 +000075 }
76 private:
77 bool ProcessLoop(Loop *L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +000078 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
79 const std::vector<BasicBlock*> &Preds);
Chris Lattner59fb87d2004-04-18 22:27:10 +000080 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner38acf9e2002-09-26 16:17:31 +000081 void InsertPreheaderForLoop(Loop *L);
Chris Lattner529b28d2004-04-13 05:05:33 +000082 Loop *SeparateNestedLoop(Loop *L);
Chris Lattner2ab6a732003-10-13 00:37:13 +000083 void InsertUniqueBackedgeBlock(Loop *L);
Chris Lattner120fce52006-09-23 08:19:21 +000084 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
85 std::vector<BasicBlock*> &SplitPreds,
86 Loop *L);
87
Chris Lattner2ab6a732003-10-13 00:37:13 +000088 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
89 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner38acf9e2002-09-26 16:17:31 +000090 };
91
Chris Lattner7f8897f2006-08-27 22:42:52 +000092 RegisterPass<LoopSimplify>
Chris Lattneree2c50c2003-10-12 21:43:28 +000093 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner38acf9e2002-09-26 16:17:31 +000094}
95
96// Publically exposed interface to pass...
Chris Lattner66ea98e2003-12-10 17:20:35 +000097const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
Chris Lattner4b501562004-09-20 04:43:15 +000098FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner38acf9e2002-09-26 16:17:31 +000099
Chris Lattner38acf9e2002-09-26 16:17:31 +0000100/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
101/// it in any convenient order) inserting preheaders...
102///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000103bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000104 bool Changed = false;
Chris Lattnerc27e0562006-02-14 22:34:08 +0000105 LI = &getAnalysis<LoopInfo>();
Chris Lattnercec5b882005-03-25 06:37:22 +0000106 AA = getAnalysisToUpdate<AliasAnalysis>();
Chris Lattner38acf9e2002-09-26 16:17:31 +0000107
Chris Lattnerfa789462006-08-12 04:51:20 +0000108 // Check to see that no blocks (other than the header) in loops have
109 // predecessors that are not in loops. This is not valid for natural loops,
110 // but can occur if the blocks are unreachable. Since they are unreachable we
111 // can just shamelessly destroy their terminators to make them not branch into
112 // the loop!
113 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
114 // This case can only occur for unreachable blocks. Blocks that are
115 // unreachable can't be in loops, so filter those blocks out.
116 if (LI->getLoopFor(BB)) continue;
117
118 bool BlockUnreachable = false;
119 TerminatorInst *TI = BB->getTerminator();
120
121 // Check to see if any successors of this block are non-loop-header loops
122 // that are not the header.
123 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
124 // If this successor is not in a loop, BB is clearly ok.
125 Loop *L = LI->getLoopFor(TI->getSuccessor(i));
126 if (!L) continue;
127
128 // If the succ is the loop header, and if L is a top-level loop, then this
129 // is an entrance into a loop through the header, which is also ok.
130 if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
131 continue;
132
133 // Otherwise, this is an entrance into a loop from some place invalid.
134 // Either the loop structure is invalid and this is not a natural loop (in
135 // which case the compiler is buggy somewhere else) or BB is unreachable.
136 BlockUnreachable = true;
137 break;
138 }
139
140 // If this block is ok, check the next one.
141 if (!BlockUnreachable) continue;
142
143 // Otherwise, this block is dead. To clean up the CFG and to allow later
144 // loop transformations to ignore this case, we delete the edges into the
145 // loop by replacing the terminator.
146
147 // Remove PHI entries from the successors.
148 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
149 TI->getSuccessor(i)->removePredecessor(BB);
150
151 // Add a new unreachable instruction.
152 new UnreachableInst(TI);
153
154 // Delete the dead terminator.
155 if (AA) AA->deleteValue(&BB->back());
156 BB->getInstList().pop_back();
157 Changed |= true;
158 }
159
Chris Lattnerc27e0562006-02-14 22:34:08 +0000160 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner329c1c62004-01-08 00:09:44 +0000161 Changed |= ProcessLoop(*I);
Chris Lattner38acf9e2002-09-26 16:17:31 +0000162
163 return Changed;
164}
165
Chris Lattner38acf9e2002-09-26 16:17:31 +0000166/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
167/// all loops have preheaders.
168///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000169bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000170 bool Changed = false;
Chris Lattner3bb46572006-08-12 05:25:00 +0000171ReprocessLoop:
172
Chris Lattner0ab9f962006-02-14 23:06:02 +0000173 // Canonicalize inner loops before outer loops. Inner loop canonicalization
174 // can provide work for the outer loop to canonicalize.
175 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
176 Changed |= ProcessLoop(*I);
177
Chris Lattner2ef703e2004-03-14 03:59:22 +0000178 assert(L->getBlocks()[0] == L->getHeader() &&
179 "Header isn't first block in loop?");
Chris Lattner2ef703e2004-03-14 03:59:22 +0000180
Chris Lattnerfa789462006-08-12 04:51:20 +0000181 // Does the loop already have a preheader? If so, don't insert one.
Chris Lattner38acf9e2002-09-26 16:17:31 +0000182 if (L->getLoopPreheader() == 0) {
183 InsertPreheaderForLoop(L);
184 NumInserted++;
185 Changed = true;
186 }
187
Chris Lattner66ea98e2003-12-10 17:20:35 +0000188 // Next, check to make sure that all exit nodes of the loop only have
189 // predecessors that are inside of the loop. This check guarantees that the
190 // loop preheader/header will dominate the exit blocks. If the exit block has
Chris Lattneree628cf2006-02-12 01:59:10 +0000191 // predecessors from outside of the loop, split the edge now.
192 std::vector<BasicBlock*> ExitBlocks;
193 L->getExitBlocks(ExitBlocks);
Chris Lattnerc27e0562006-02-14 22:34:08 +0000194
Chris Lattneree628cf2006-02-12 01:59:10 +0000195 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerfed22aa2004-07-15 08:20:22 +0000196 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
197 E = ExitBlockSet.end(); I != E; ++I) {
198 BasicBlock *ExitBlock = *I;
Chris Lattnerde7aee72004-07-15 05:36:31 +0000199 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
200 PI != PE; ++PI)
Chris Lattner8587eb32006-02-11 02:13:17 +0000201 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
202 // allowed.
Chris Lattneree628cf2006-02-12 01:59:10 +0000203 if (!L->contains(*PI)) {
Chris Lattnerfed22aa2004-07-15 08:20:22 +0000204 RewriteLoopExitBlock(L, ExitBlock);
Chris Lattnerde7aee72004-07-15 05:36:31 +0000205 NumInserted++;
206 Changed = true;
207 break;
208 }
Chris Lattnerfed22aa2004-07-15 08:20:22 +0000209 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000210
Chris Lattner529b28d2004-04-13 05:05:33 +0000211 // If the header has more than two predecessors at this point (from the
212 // preheader and from multiple backedges), we must adjust the loop.
Chris Lattner3bb46572006-08-12 05:25:00 +0000213 unsigned NumBackedges = L->getNumBackEdges();
214 if (NumBackedges != 1) {
215 // If this is really a nested loop, rip it out into a child loop. Don't do
216 // this for loops with a giant number of backedges, just factor them into a
217 // common backedge instead.
218 if (NumBackedges < 8) {
219 if (Loop *NL = SeparateNestedLoop(L)) {
220 ++NumNested;
221 // This is a big restructuring change, reprocess the whole loop.
222 ProcessLoop(NL);
223 Changed = true;
224 // GCC doesn't tail recursion eliminate this.
225 goto ReprocessLoop;
226 }
Chris Lattner529b28d2004-04-13 05:05:33 +0000227 }
228
Chris Lattner3bb46572006-08-12 05:25:00 +0000229 // If we either couldn't, or didn't want to, identify nesting of the loops,
230 // insert a new block that all backedges target, then make it jump to the
231 // loop header.
Chris Lattner2ab6a732003-10-13 00:37:13 +0000232 InsertUniqueBackedgeBlock(L);
233 NumInserted++;
234 Changed = true;
235 }
236
Chris Lattner94f40322005-08-10 02:07:32 +0000237 // Scan over the PHI nodes in the loop header. Since they now have only two
238 // incoming values (the loop is canonicalized), we may have simplified the PHI
239 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
240 PHINode *PN;
Chris Lattner94f40322005-08-10 02:07:32 +0000241 for (BasicBlock::iterator I = L->getHeader()->begin();
242 (PN = dyn_cast<PHINode>(I++)); )
Chris Lattner98599ba2005-08-10 17:15:20 +0000243 if (Value *V = PN->hasConstantValue()) {
Chris Lattner94f40322005-08-10 02:07:32 +0000244 PN->replaceAllUsesWith(V);
245 PN->eraseFromParent();
246 }
247
Chris Lattner38acf9e2002-09-26 16:17:31 +0000248 return Changed;
249}
250
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000251/// SplitBlockPredecessors - Split the specified block into two blocks. We want
252/// to move the predecessors specified in the Preds list to point to the new
253/// block, leaving the remaining predecessors pointing to BB. This method
254/// updates the SSA PHINode's, but no other analyses.
255///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000256BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
257 const char *Suffix,
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000258 const std::vector<BasicBlock*> &Preds) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000259
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000260 // Create new basic block, insert right before the original block...
Chris Lattnerc24a0762004-02-04 03:58:28 +0000261 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000262
263 // The preheader first gets an unconditional branch to the loop header...
Chris Lattner108e4ab2003-11-21 16:52:05 +0000264 BranchInst *BI = new BranchInst(BB, NewBB);
Misha Brukmanfd939082005-04-21 23:48:37 +0000265
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000266 // For every PHI node in the block, insert a PHI node into NewBB where the
267 // incoming values from the out of loop edges are moved to NewBB. We have two
268 // possible cases here. If the loop is dead, we just insert dummy entries
269 // into the PHI nodes for the new edge. If the loop is not dead, we move the
270 // incoming edges in BB into new PHI nodes in NewBB.
271 //
272 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner0f98e752003-12-19 06:27:08 +0000273 // Check to see if the values being merged into the new block need PHI
274 // nodes. If so, insert them.
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000275 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
276 PHINode *PN = cast<PHINode>(I);
Chris Lattner529b28d2004-04-13 05:05:33 +0000277 ++I;
278
Chris Lattner0f98e752003-12-19 06:27:08 +0000279 // Check to see if all of the values coming in are the same. If so, we
280 // don't need to create a new PHI node.
281 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
282 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
283 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
284 InVal = 0;
285 break;
286 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000287
Chris Lattner0f98e752003-12-19 06:27:08 +0000288 // If the values coming into the block are not the same, we need a PHI.
289 if (InVal == 0) {
Chris Lattner010ba102003-12-09 23:12:55 +0000290 // Create the new PHI node, insert it into NewBB at the end of the block
291 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
Chris Lattnercec5b882005-03-25 06:37:22 +0000292 if (AA) AA->copyValue(PN, NewPHI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000293
Chris Lattner010ba102003-12-09 23:12:55 +0000294 // Move all of the edges from blocks outside the loop to the new PHI
295 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Chris Lattner529b28d2004-04-13 05:05:33 +0000296 Value *V = PN->removeIncomingValue(Preds[i], false);
Chris Lattner010ba102003-12-09 23:12:55 +0000297 NewPHI->addIncoming(V, Preds[i]);
298 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000299 InVal = NewPHI;
300 } else {
301 // Remove all of the edges coming into the PHI nodes from outside of the
302 // block.
303 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
304 PN->removeIncomingValue(Preds[i], false);
Chris Lattner010ba102003-12-09 23:12:55 +0000305 }
Chris Lattner0f98e752003-12-19 06:27:08 +0000306
307 // Add an incoming value to the PHI node in the loop for the preheader
308 // edge.
309 PN->addIncoming(InVal, NewBB);
Chris Lattner529b28d2004-04-13 05:05:33 +0000310
311 // Can we eliminate this phi node now?
Chris Lattner5e1b2312005-08-05 00:57:45 +0000312 if (Value *V = PN->hasConstantValue(true)) {
Nick Lewyckya397ce12007-04-08 01:04:30 +0000313 Instruction *I = dyn_cast<Instruction>(V);
Owen Anderson558fc742007-04-09 00:52:49 +0000314 // If I is in NewBB, the ETForest call will fail, because NewBB isn't
315 // registered in ETForest yet. Handle this case explicitly.
Nick Lewyckya397ce12007-04-08 01:04:30 +0000316 if (!I || (I->getParent() != NewBB &&
317 getAnalysis<ETForest>().dominates(I, PN))) {
Chris Lattnerc30bda72004-10-17 21:22:38 +0000318 PN->replaceAllUsesWith(V);
Chris Lattnercec5b882005-03-25 06:37:22 +0000319 if (AA) AA->deleteValue(PN);
Chris Lattnerc30bda72004-10-17 21:22:38 +0000320 BB->getInstList().erase(PN);
321 }
Chris Lattner529b28d2004-04-13 05:05:33 +0000322 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000323 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000324
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000325 // Now that the PHI nodes are updated, actually move the edges from
326 // Preds to point to NewBB instead of BB.
327 //
328 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
329 TerminatorInst *TI = Preds[i]->getTerminator();
330 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
331 if (TI->getSuccessor(s) == BB)
332 TI->setSuccessor(s, NewBB);
333 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000334
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000335 } else { // Otherwise the loop is dead...
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000336 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
337 PHINode *PN = cast<PHINode>(I);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000338 // Insert dummy values as the incoming value...
339 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000340 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000341 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000342 return NewBB;
343}
344
Chris Lattner38acf9e2002-09-26 16:17:31 +0000345/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
346/// preheader, this method is called to insert one. This method has two phases:
347/// preheader insertion and analysis updating.
348///
Chris Lattneree2c50c2003-10-12 21:43:28 +0000349void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner38acf9e2002-09-26 16:17:31 +0000350 BasicBlock *Header = L->getHeader();
351
352 // Compute the set of predecessors of the loop that are not in the loop.
353 std::vector<BasicBlock*> OutsideBlocks;
354 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
355 PI != PE; ++PI)
Chris Lattner8587eb32006-02-11 02:13:17 +0000356 if (!L->contains(*PI)) // Coming in from outside the loop?
357 OutsideBlocks.push_back(*PI); // Keep track of it...
Misha Brukmanfd939082005-04-21 23:48:37 +0000358
Chris Lattnerc3984572006-09-23 07:40:52 +0000359 // Split out the loop pre-header.
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000360 BasicBlock *NewBB =
361 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattnerc3984572006-09-23 07:40:52 +0000362
Misha Brukmanfd939082005-04-21 23:48:37 +0000363
Chris Lattner38acf9e2002-09-26 16:17:31 +0000364 //===--------------------------------------------------------------------===//
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000365 // Update analysis results now that we have performed the transformation
Chris Lattner38acf9e2002-09-26 16:17:31 +0000366 //
Misha Brukmanfd939082005-04-21 23:48:37 +0000367
Chris Lattner38acf9e2002-09-26 16:17:31 +0000368 // We know that we have loop information to update... update it now.
369 if (Loop *Parent = L->getParentLoop())
Chris Lattnerc27e0562006-02-14 22:34:08 +0000370 Parent->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner9f879cf2003-02-27 22:48:57 +0000371
Chris Lattnerc3984572006-09-23 07:40:52 +0000372 UpdateDomInfoForRevectoredPreds(NewBB, OutsideBlocks);
Chris Lattner120fce52006-09-23 08:19:21 +0000373
374 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
375 // code layout too horribly.
376 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000377}
378
Chris Lattner529b28d2004-04-13 05:05:33 +0000379/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
380/// blocks. This method is used to split exit blocks that have predecessors
381/// outside of the loop.
Chris Lattner59fb87d2004-04-18 22:27:10 +0000382BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000383 std::vector<BasicBlock*> LoopBlocks;
384 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
385 if (L->contains(*I))
386 LoopBlocks.push_back(*I);
387
Chris Lattner7e7ad492003-02-27 22:31:07 +0000388 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
389 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
390
Chris Lattnerc27e0562006-02-14 22:34:08 +0000391 // Update Loop Information - we know that the new block will be in whichever
392 // loop the Exit block is in. Note that it may not be in that immediate loop,
393 // if the successor is some other loop header. In that case, we continue
394 // walking up the loop tree to find a loop that contains both the successor
395 // block and the predecessor block.
396 Loop *SuccLoop = LI->getLoopFor(Exit);
397 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
398 SuccLoop = SuccLoop->getParentLoop();
399 if (SuccLoop)
400 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner74cd04e2003-02-28 03:07:54 +0000401
Chris Lattner2ab6a732003-10-13 00:37:13 +0000402 // Update dominator information (set, immdom, domtree, and domfrontier)
403 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
Chris Lattner59fb87d2004-04-18 22:27:10 +0000404 return NewBB;
Chris Lattner2ab6a732003-10-13 00:37:13 +0000405}
406
Chris Lattner529b28d2004-04-13 05:05:33 +0000407/// AddBlockAndPredsToSet - Add the specified block, and all of its
408/// predecessors, to the specified set, if it's not already in there. Stop
409/// predecessor traversal when we reach StopBlock.
Devang Patel58d7fbf2007-04-20 20:04:37 +0000410static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
Chris Lattner529b28d2004-04-13 05:05:33 +0000411 std::set<BasicBlock*> &Blocks) {
Devang Patel58d7fbf2007-04-20 20:04:37 +0000412 std::vector<BasicBlock *> WorkList;
413 WorkList.push_back(InputBB);
414 do {
415 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
416 if (Blocks.insert(BB).second && BB != StopBlock)
417 // If BB is not already processed and it is not a stop block then
418 // insert its predecessor in the work list
419 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
420 BasicBlock *WBB = *I;
421 WorkList.push_back(WBB);
422 }
423 } while(!WorkList.empty());
Chris Lattner529b28d2004-04-13 05:05:33 +0000424}
425
Chris Lattner1f62f822004-04-13 15:21:18 +0000426/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
427/// PHI node that tells us how to partition the loops.
Owen Andersonad190142007-04-09 22:54:50 +0000428static PHINode *FindPHIToPartitionLoops(Loop *L, ETForest *EF,
429 AliasAnalysis *AA) {
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000430 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
431 PHINode *PN = cast<PHINode>(I);
Chris Lattner1f62f822004-04-13 15:21:18 +0000432 ++I;
Nate Begemana83ba0f2005-08-04 23:24:19 +0000433 if (Value *V = PN->hasConstantValue())
Devang Patel3b57b6f2007-03-20 20:18:12 +0000434 if (!isa<Instruction>(V) || EF->dominates(cast<Instruction>(V), PN)) {
Chris Lattnerc30bda72004-10-17 21:22:38 +0000435 // This is a degenerate PHI already, don't modify it!
436 PN->replaceAllUsesWith(V);
Chris Lattnercec5b882005-03-25 06:37:22 +0000437 if (AA) AA->deleteValue(PN);
Chris Lattnerfee34112005-03-06 21:35:38 +0000438 PN->eraseFromParent();
Chris Lattnerc30bda72004-10-17 21:22:38 +0000439 continue;
440 }
441
442 // Scan this PHI node looking for a use of the PHI node by itself.
443 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
444 if (PN->getIncomingValue(i) == PN &&
445 L->contains(PN->getIncomingBlock(i)))
446 // We found something tasty to remove.
447 return PN;
Chris Lattner1f62f822004-04-13 15:21:18 +0000448 }
449 return 0;
450}
451
Chris Lattner120fce52006-09-23 08:19:21 +0000452// PlaceSplitBlockCarefully - If the block isn't already, move the new block to
453// right after some 'outside block' block. This prevents the preheader from
454// being placed inside the loop body, e.g. when the loop hasn't been rotated.
455void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
456 std::vector<BasicBlock*>&SplitPreds,
457 Loop *L) {
458 // Check to see if NewBB is already well placed.
459 Function::iterator BBI = NewBB; --BBI;
460 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
461 if (&*BBI == SplitPreds[i])
462 return;
463 }
464
465 // If it isn't already after an outside block, move it after one. This is
466 // always good as it makes the uncond branch from the outside block into a
467 // fall-through.
468
469 // Figure out *which* outside block to put this after. Prefer an outside
470 // block that neighbors a BB actually in the loop.
471 BasicBlock *FoundBB = 0;
472 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
473 Function::iterator BBI = SplitPreds[i];
474 if (++BBI != NewBB->getParent()->end() &&
475 L->contains(BBI)) {
476 FoundBB = SplitPreds[i];
477 break;
478 }
479 }
480
481 // If our heuristic for a *good* bb to place this after doesn't find
482 // anything, just pick something. It's likely better than leaving it within
483 // the loop.
484 if (!FoundBB)
485 FoundBB = SplitPreds[0];
486 NewBB->moveAfter(FoundBB);
487}
488
489
Chris Lattner529b28d2004-04-13 05:05:33 +0000490/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
491/// them out into a nested loop. This is important for code that looks like
492/// this:
493///
494/// Loop:
495/// ...
496/// br cond, Loop, Next
497/// ...
498/// br cond2, Loop, Out
499///
500/// To identify this common case, we look at the PHI nodes in the header of the
501/// loop. PHI nodes with unchanging values on one backedge correspond to values
502/// that change in the "outer" loop, but not in the "inner" loop.
503///
504/// If we are able to separate out a loop, return the new outer loop that was
505/// created.
506///
507Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
Devang Patel3b57b6f2007-03-20 20:18:12 +0000508 ETForest *EF = getAnalysisToUpdate<ETForest>();
509 PHINode *PN = FindPHIToPartitionLoops(L, EF, AA);
Chris Lattner1f62f822004-04-13 15:21:18 +0000510 if (PN == 0) return 0; // No known way to partition.
Chris Lattner529b28d2004-04-13 05:05:33 +0000511
Chris Lattner1f62f822004-04-13 15:21:18 +0000512 // Pull out all predecessors that have varying values in the loop. This
513 // handles the case when a PHI node has multiple instances of itself as
514 // arguments.
Chris Lattner529b28d2004-04-13 05:05:33 +0000515 std::vector<BasicBlock*> OuterLoopPreds;
Chris Lattner1f62f822004-04-13 15:21:18 +0000516 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
517 if (PN->getIncomingValue(i) != PN ||
518 !L->contains(PN->getIncomingBlock(i)))
519 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner529b28d2004-04-13 05:05:33 +0000520
Chris Lattner4b662422004-04-13 16:23:25 +0000521 BasicBlock *Header = L->getHeader();
Chris Lattner529b28d2004-04-13 05:05:33 +0000522 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
523
524 // Update dominator information (set, immdom, domtree, and domfrontier)
525 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
526
Chris Lattner120fce52006-09-23 08:19:21 +0000527 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
528 // code layout too horribly.
529 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
530
Chris Lattner529b28d2004-04-13 05:05:33 +0000531 // Create the new outer loop.
532 Loop *NewOuter = new Loop();
533
Chris Lattner529b28d2004-04-13 05:05:33 +0000534 // Change the parent loop to use the outer loop as its child now.
535 if (Loop *Parent = L->getParentLoop())
536 Parent->replaceChildLoopWith(L, NewOuter);
537 else
Chris Lattnerc27e0562006-02-14 22:34:08 +0000538 LI->changeTopLevelLoop(L, NewOuter);
Chris Lattner529b28d2004-04-13 05:05:33 +0000539
540 // This block is going to be our new header block: add it to this loop and all
541 // parent loops.
Chris Lattnerc27e0562006-02-14 22:34:08 +0000542 NewOuter->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner529b28d2004-04-13 05:05:33 +0000543
544 // L is now a subloop of our outer loop.
545 NewOuter->addChildLoop(L);
546
Chris Lattner529b28d2004-04-13 05:05:33 +0000547 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
548 NewOuter->addBlockEntry(L->getBlocks()[i]);
549
550 // Determine which blocks should stay in L and which should be moved out to
551 // the Outer loop now.
Chris Lattner529b28d2004-04-13 05:05:33 +0000552 std::set<BasicBlock*> BlocksInL;
553 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
Nick Lewyckya397ce12007-04-08 01:04:30 +0000554 if (EF->dominates(Header, *PI))
Chris Lattner529b28d2004-04-13 05:05:33 +0000555 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
556
557
558 // Scan all of the loop children of L, moving them to OuterLoop if they are
559 // not part of the inner loop.
560 for (Loop::iterator I = L->begin(); I != L->end(); )
561 if (BlocksInL.count((*I)->getHeader()))
562 ++I; // Loop remains in L
563 else
564 NewOuter->addChildLoop(L->removeChildLoop(I));
565
566 // Now that we know which blocks are in L and which need to be moved to
567 // OuterLoop, move any blocks that need it.
568 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
569 BasicBlock *BB = L->getBlocks()[i];
570 if (!BlocksInL.count(BB)) {
571 // Move this block to the parent, updating the exit blocks sets
572 L->removeBlockFromLoop(BB);
Chris Lattnerc27e0562006-02-14 22:34:08 +0000573 if ((*LI)[BB] == L)
574 LI->changeLoopFor(BB, NewOuter);
Chris Lattner529b28d2004-04-13 05:05:33 +0000575 --i;
576 }
577 }
578
Chris Lattner529b28d2004-04-13 05:05:33 +0000579 return NewOuter;
580}
581
582
583
Chris Lattner2ab6a732003-10-13 00:37:13 +0000584/// InsertUniqueBackedgeBlock - This method is called when the specified loop
585/// has more than one backedge in it. If this occurs, revector all of these
586/// backedges to target a new basic block and have that block branch to the loop
587/// header. This ensures that loops have exactly one backedge.
588///
589void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
590 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
591
592 // Get information about the loop
593 BasicBlock *Preheader = L->getLoopPreheader();
594 BasicBlock *Header = L->getHeader();
595 Function *F = Header->getParent();
596
597 // Figure out which basic blocks contain back-edges to the loop header.
598 std::vector<BasicBlock*> BackedgeBlocks;
599 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
600 if (*I != Preheader) BackedgeBlocks.push_back(*I);
601
602 // Create and insert the new backedge block...
603 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattner108e4ab2003-11-21 16:52:05 +0000604 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000605
606 // Move the new backedge block to right after the last backedge block.
607 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
608 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
Misha Brukmanfd939082005-04-21 23:48:37 +0000609
Chris Lattner2ab6a732003-10-13 00:37:13 +0000610 // Now that the block has been inserted into the function, create PHI nodes in
611 // the backedge block which correspond to any PHI nodes in the header block.
Alkis Evlogimenos200a3602004-09-28 02:40:37 +0000612 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
613 PHINode *PN = cast<PHINode>(I);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000614 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
615 BETerminator);
Chris Lattner55517062005-01-29 00:39:08 +0000616 NewPN->reserveOperandSpace(BackedgeBlocks.size());
Chris Lattnercec5b882005-03-25 06:37:22 +0000617 if (AA) AA->copyValue(PN, NewPN);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000618
619 // Loop over the PHI node, moving all entries except the one for the
620 // preheader over to the new PHI node.
621 unsigned PreheaderIdx = ~0U;
622 bool HasUniqueIncomingValue = true;
623 Value *UniqueValue = 0;
624 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
625 BasicBlock *IBB = PN->getIncomingBlock(i);
626 Value *IV = PN->getIncomingValue(i);
627 if (IBB == Preheader) {
628 PreheaderIdx = i;
629 } else {
630 NewPN->addIncoming(IV, IBB);
631 if (HasUniqueIncomingValue) {
632 if (UniqueValue == 0)
633 UniqueValue = IV;
634 else if (UniqueValue != IV)
635 HasUniqueIncomingValue = false;
636 }
637 }
638 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000639
Chris Lattner2ab6a732003-10-13 00:37:13 +0000640 // Delete all of the incoming values from the old PN except the preheader's
641 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
642 if (PreheaderIdx != 0) {
643 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
644 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
645 }
Chris Lattner55517062005-01-29 00:39:08 +0000646 // Nuke all entries except the zero'th.
647 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
648 PN->removeIncomingValue(e-i, false);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000649
650 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
651 PN->addIncoming(NewPN, BEBlock);
652
653 // As an optimization, if all incoming values in the new PhiNode (which is a
654 // subset of the incoming values of the old PHI node) have the same value,
655 // eliminate the PHI Node.
656 if (HasUniqueIncomingValue) {
657 NewPN->replaceAllUsesWith(UniqueValue);
Chris Lattnercec5b882005-03-25 06:37:22 +0000658 if (AA) AA->deleteValue(NewPN);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000659 BEBlock->getInstList().erase(NewPN);
660 }
661 }
662
663 // Now that all of the PHI nodes have been inserted and adjusted, modify the
664 // backedge blocks to just to the BEBlock instead of the header.
665 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
666 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
667 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
668 if (TI->getSuccessor(Op) == Header)
669 TI->setSuccessor(Op, BEBlock);
670 }
671
672 //===--- Update all analyses which we must preserve now -----------------===//
673
674 // Update Loop Information - we know that this block is now in the current
675 // loop and all parent loops.
Chris Lattnerc27e0562006-02-14 22:34:08 +0000676 L->addBasicBlockToLoop(BEBlock, *LI);
Chris Lattner2ab6a732003-10-13 00:37:13 +0000677
Chris Lattner2ab6a732003-10-13 00:37:13 +0000678 // Update dominator information (set, immdom, domtree, and domfrontier)
679 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
680}
681
Owen Anderson17cba6d2007-04-09 22:25:09 +0000682// Returns true if BasicBlock A dominates at least one block in vector B
683// Helper function for UpdateDomInfoForRevectoredPreds
Owen Andersoncc221cd2007-04-09 23:38:18 +0000684static bool BlockDominatesAny(BasicBlock* A, const std::vector<BasicBlock*>& B,
685 ETForest& ETF) {
686 for (std::vector<BasicBlock*>::const_iterator BI = B.begin(), BE = B.end();
687 BI != BE; ++BI) {
Owen Anderson0cd04612007-04-09 22:31:43 +0000688 if (ETF.dominates(A, *BI))
689 return true;
690 }
691 return false;
Owen Anderson17cba6d2007-04-09 22:25:09 +0000692}
693
Chris Lattner2ab6a732003-10-13 00:37:13 +0000694/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
Nick Lewyckya397ce12007-04-08 01:04:30 +0000695/// different kinds of dominator information (immediate dominators,
696/// dominator trees, et-forest and dominance frontiers) after a new block has
Chris Lattner2ab6a732003-10-13 00:37:13 +0000697/// been added to the CFG.
698///
Chris Lattner4f02fc22004-02-05 21:12:24 +0000699/// This only supports the case when an existing block (known as "NewBBSucc"),
700/// had some of its predecessors factored into a new basic block. This
Chris Lattner2ab6a732003-10-13 00:37:13 +0000701/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner4f02fc22004-02-05 21:12:24 +0000702/// unconditional branch to NewBBSucc, and moves some predecessors of
703/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
704/// PredBlocks, even though they are the same as
705/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattner2ab6a732003-10-13 00:37:13 +0000706///
707void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
708 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000709 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattner2ab6a732003-10-13 00:37:13 +0000710 assert(succ_begin(NewBB) != succ_end(NewBB) &&
711 ++succ_begin(NewBB) == succ_end(NewBB) &&
712 "NewBB should have a single successor!");
Chris Lattner4f02fc22004-02-05 21:12:24 +0000713 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Nick Lewyckya397ce12007-04-08 01:04:30 +0000714 ETForest& ETF = getAnalysis<ETForest>();
715
Chris Lattner4f02fc22004-02-05 21:12:24 +0000716 // The newly inserted basic block will dominate existing basic blocks iff the
717 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
718 // the non-pred blocks, then they all must be the same block!
Chris Lattner4f303bd2004-04-01 19:06:07 +0000719 //
Chris Lattner4f02fc22004-02-05 21:12:24 +0000720 bool NewBBDominatesNewBBSucc = true;
721 {
722 BasicBlock *OnePred = PredBlocks[0];
Nick Lewyckya397ce12007-04-08 01:04:30 +0000723 unsigned i = 1, e = PredBlocks.size();
Owen Anderson558fc742007-04-09 00:52:49 +0000724 for (i = 1; !ETF.isReachableFromEntry(OnePred); ++i) {
Chris Lattnerc3984572006-09-23 07:40:52 +0000725 assert(i != e && "Didn't find reachable pred?");
726 OnePred = PredBlocks[i];
727 }
728
729 for (; i != e; ++i)
Owen Anderson558fc742007-04-09 00:52:49 +0000730 if (PredBlocks[i] != OnePred && ETF.isReachableFromEntry(OnePred)){
Chris Lattner4f02fc22004-02-05 21:12:24 +0000731 NewBBDominatesNewBBSucc = false;
732 break;
733 }
734
735 if (NewBBDominatesNewBBSucc)
736 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
737 PI != E; ++PI)
Nick Lewyckya397ce12007-04-08 01:04:30 +0000738 if (*PI != NewBB && !ETF.dominates(NewBBSucc, *PI)) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000739 NewBBDominatesNewBBSucc = false;
740 break;
741 }
742 }
743
Chris Lattner4f303bd2004-04-01 19:06:07 +0000744 // The other scenario where the new block can dominate its successors are when
745 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
746 // already.
747 if (!NewBBDominatesNewBBSucc) {
748 NewBBDominatesNewBBSucc = true;
749 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
750 PI != E; ++PI)
Nick Lewyckya397ce12007-04-08 01:04:30 +0000751 if (*PI != NewBB && !ETF.dominates(NewBBSucc, *PI)) {
Chris Lattner4f303bd2004-04-01 19:06:07 +0000752 NewBBDominatesNewBBSucc = false;
753 break;
754 }
755 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000756
Owen Andersone9ed4452007-04-07 18:23:27 +0000757 BasicBlock *NewBBIDom = 0;
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000758
759 // Update DominatorTree information if it is active.
760 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Chris Lattner4f02fc22004-02-05 21:12:24 +0000761 // If we don't have ImmediateDominator info around, calculate the idom as
762 // above.
Nick Lewyckya397ce12007-04-08 01:04:30 +0000763 if (!NewBBIDom) {
764 unsigned i = 0;
765 for (i = 0; i < PredBlocks.size(); ++i)
766 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i])) {
767 NewBBIDom = PredBlocks[i];
768 break;
769 }
770 assert(i != PredBlocks.size() && "No reachable preds?");
771 for (i = i + 1; i < PredBlocks.size(); ++i) {
772 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i]))
773 NewBBIDom = ETF.nearestCommonDominator(NewBBIDom, PredBlocks[i]);
Chris Lattnerc3984572006-09-23 07:40:52 +0000774 }
Nick Lewyckya397ce12007-04-08 01:04:30 +0000775 assert(NewBBIDom && "No immediate dominator found??");
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000776 }
Nick Lewyckya397ce12007-04-08 01:04:30 +0000777 DominatorTree::Node *NewBBIDomNode = DT->getNode(NewBBIDom);
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000778
Chris Lattner4f02fc22004-02-05 21:12:24 +0000779 // Create the new dominator tree node... and set the idom of NewBB.
780 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
781
782 // If NewBB strictly dominates other blocks, then it is now the immediate
783 // dominator of NewBBSucc. Update the dominator tree as appropriate.
784 if (NewBBDominatesNewBBSucc) {
785 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
Chris Lattner4f02fc22004-02-05 21:12:24 +0000786 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
787 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000788 }
789
Chris Lattnerbaec98d2006-01-09 08:03:08 +0000790 // Update ET-Forest information if it is active.
791 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
792 EF->addNewBlock(NewBB, NewBBIDom);
793 if (NewBBDominatesNewBBSucc)
794 EF->setImmediateDominator(NewBBSucc, NewBB);
795 }
796
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000797 // Update dominance frontier information...
798 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
Chris Lattner4b662422004-04-13 16:23:25 +0000799 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
800 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
801 // a predecessor of.
Chris Lattner4f02fc22004-02-05 21:12:24 +0000802 if (NewBBDominatesNewBBSucc) {
803 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
804 if (DFI != DF->end()) {
805 DominanceFrontier::DomSetType Set = DFI->second;
806 // Filter out stuff in Set that we do not dominate a predecessor of.
807 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
808 E = Set.end(); SetI != E;) {
809 bool DominatesPred = false;
810 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
811 PI != E; ++PI)
Nick Lewyckya397ce12007-04-08 01:04:30 +0000812 if (ETF.dominates(NewBB, *PI))
Chris Lattner4f02fc22004-02-05 21:12:24 +0000813 DominatesPred = true;
814 if (!DominatesPred)
815 Set.erase(SetI++);
816 else
817 ++SetI;
818 }
Chris Lattnerdbf3cd72003-02-27 20:27:08 +0000819
Chris Lattner4f02fc22004-02-05 21:12:24 +0000820 DF->addBasicBlock(NewBB, Set);
821 }
822
823 } else {
824 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
825 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
826 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
827 DominanceFrontier::DomSetType NewDFSet;
828 NewDFSet.insert(NewBBSucc);
829 DF->addBasicBlock(NewBB, NewDFSet);
Chris Lattner4b662422004-04-13 16:23:25 +0000830 }
Chris Lattner2ab6a732003-10-13 00:37:13 +0000831
Chris Lattner4b662422004-04-13 16:23:25 +0000832 // Now we must loop over all of the dominance frontiers in the function,
833 // replacing occurrences of NewBBSucc with NewBB in some cases. All
834 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
835 // their dominance frontier must be updated to contain NewBB instead.
836 //
Owen Anderson17cba6d2007-04-09 22:25:09 +0000837 for (Function::iterator FI = NewBB->getParent()->begin(),
Owen Anderson0cd04612007-04-09 22:31:43 +0000838 FE = NewBB->getParent()->end(); FI != FE; ++FI) {
839 DominanceFrontier::iterator DFI = DF->find(FI);
840 if (DFI == DF->end()) continue; // unreachable block.
841
842 // Only consider dominators of NewBBSucc
843 if (!DFI->second.count(NewBBSucc)) continue;
Owen Andersonad190142007-04-09 22:54:50 +0000844
Owen Anderson0cd04612007-04-09 22:31:43 +0000845 if (BlockDominatesAny(FI, PredBlocks, ETF)) {
846 // If NewBBSucc should not stay in our dominator frontier, remove it.
847 // We remove it unless there is a predecessor of NewBBSucc that we
848 // dominate, but we don't strictly dominate NewBBSucc.
849 bool ShouldRemove = true;
850 if ((BasicBlock*)FI == NewBBSucc || !ETF.dominates(FI, NewBBSucc)) {
851 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
852 // Check to see if it dominates any predecessors of NewBBSucc.
853 for (pred_iterator PI = pred_begin(NewBBSucc),
854 E = pred_end(NewBBSucc); PI != E; ++PI)
855 if (ETF.dominates(FI, *PI)) {
856 ShouldRemove = false;
857 break;
858 }
859
860 if (ShouldRemove)
861 DF->removeFromFrontier(DFI, NewBBSucc);
862 DF->addToFrontier(DFI, NewBB);
863
864 break;
865 }
866 }
867 }
868 }
Chris Lattner38acf9e2002-09-26 16:17:31 +0000869}
Brian Gaeked0fde302003-11-11 22:41:34 +0000870
Owen Anderson17cba6d2007-04-09 22:25:09 +0000871