blob: 530e3b7a66a3568d0aef8c89fc856e52d1d1ac01 [file] [log] [blame]
Chris Lattner55d47882003-10-12 21:44:18 +00001//===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner61992f62002-09-26 16:17:31 +00009//
Chris Lattner154e4d52003-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 Lattner650096a2003-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 Lattner7710f2f2003-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 Lattner650096a2003-02-27 20:27:08 +000023//
Chris Lattnerc4622a62003-10-13 00:37:13 +000024// This pass also guarantees that loops will have exactly one backedge.
25//
Chris Lattner650096a2003-02-27 20:27:08 +000026// Note that the simplifycfg pass will clean up blocks which are split out but
Chris Lattner154e4d52003-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 Lattner61992f62002-09-26 16:17:31 +000032//
33//===----------------------------------------------------------------------===//
34
Chris Lattner45f966d2006-12-19 22:17:40 +000035#define DEBUG_TYPE "loopsimplify"
Chris Lattner61992f62002-09-26 16:17:31 +000036#include "llvm/Transforms/Scalar.h"
Chris Lattnerd0788122004-03-14 03:59:22 +000037#include "llvm/Constant.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000038#include "llvm/Instructions.h"
Chris Lattnerd0788122004-03-14 03:59:22 +000039#include "llvm/Function.h"
40#include "llvm/Type.h"
Chris Lattner514e8432005-03-25 06:37:22 +000041#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner031a3f82003-12-19 06:27:08 +000042#include "llvm/Analysis/Dominators.h"
43#include "llvm/Analysis/LoopInfo.h"
Chris Lattner61992f62002-09-26 16:17:31 +000044#include "llvm/Support/CFG.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000045#include "llvm/Support/Compiler.h"
Reid Spencer7c16caa2004-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 Lattner7710f2f2003-12-10 17:20:35 +000050using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000051
Chris Lattner45f966d2006-12-19 22:17:40 +000052STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
53STATISTIC(NumNested , "Number of nested loops split out");
Chris Lattner61992f62002-09-26 16:17:31 +000054
Chris Lattner45f966d2006-12-19 22:17:40 +000055namespace {
Chris Lattner996795b2006-06-28 23:17:24 +000056 struct VISIBILITY_HIDDEN LoopSimplify : public FunctionPass {
Chris Lattner514e8432005-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 Lattnercffbbee2006-02-14 22:34:08 +000060 LoopInfo *LI;
Chris Lattner514e8432005-03-25 06:37:22 +000061
Chris Lattner61992f62002-09-26 16:17:31 +000062 virtual bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +000063
Chris Lattner61992f62002-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 Lattner797cb2f2004-03-13 22:01:26 +000067 AU.addRequired<DominatorTree>();
Devang Patel1758cb52007-03-20 20:18:12 +000068 AU.addRequired<ETForest>();
Chris Lattner61992f62002-09-26 16:17:31 +000069
70 AU.addPreserved<LoopInfo>();
Chris Lattner61992f62002-09-26 16:17:31 +000071 AU.addPreserved<ImmediateDominators>();
Chris Lattnercda4aa62006-01-09 08:03:08 +000072 AU.addPreserved<ETForest>();
Chris Lattner61992f62002-09-26 16:17:31 +000073 AU.addPreserved<DominatorTree>();
Chris Lattner650096a2003-02-27 20:27:08 +000074 AU.addPreserved<DominanceFrontier>();
Chris Lattnerf83ce5f2005-08-10 02:07:32 +000075 AU.addPreservedID(BreakCriticalEdgesID); // No critical edges added.
Chris Lattner61992f62002-09-26 16:17:31 +000076 }
77 private:
78 bool ProcessLoop(Loop *L);
Chris Lattner650096a2003-02-27 20:27:08 +000079 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
80 const std::vector<BasicBlock*> &Preds);
Chris Lattner82782632004-04-18 22:27:10 +000081 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner61992f62002-09-26 16:17:31 +000082 void InsertPreheaderForLoop(Loop *L);
Chris Lattner84170522004-04-13 05:05:33 +000083 Loop *SeparateNestedLoop(Loop *L);
Chris Lattnerc4622a62003-10-13 00:37:13 +000084 void InsertUniqueBackedgeBlock(Loop *L);
Chris Lattner6bd6da42006-09-23 08:19:21 +000085 void PlaceSplitBlockCarefully(BasicBlock *NewBB,
86 std::vector<BasicBlock*> &SplitPreds,
87 Loop *L);
88
Chris Lattnerc4622a62003-10-13 00:37:13 +000089 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
90 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner61992f62002-09-26 16:17:31 +000091 };
92
Chris Lattnerc2d3d312006-08-27 22:42:52 +000093 RegisterPass<LoopSimplify>
Chris Lattner154e4d52003-10-12 21:43:28 +000094 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner61992f62002-09-26 16:17:31 +000095}
96
97// Publically exposed interface to pass...
Chris Lattner7710f2f2003-12-10 17:20:35 +000098const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
Chris Lattner3e860842004-09-20 04:43:15 +000099FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner61992f62002-09-26 16:17:31 +0000100
Chris Lattner61992f62002-09-26 16:17:31 +0000101/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
102/// it in any convenient order) inserting preheaders...
103///
Chris Lattner154e4d52003-10-12 21:43:28 +0000104bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner61992f62002-09-26 16:17:31 +0000105 bool Changed = false;
Chris Lattnercffbbee2006-02-14 22:34:08 +0000106 LI = &getAnalysis<LoopInfo>();
Chris Lattner514e8432005-03-25 06:37:22 +0000107 AA = getAnalysisToUpdate<AliasAnalysis>();
Chris Lattner61992f62002-09-26 16:17:31 +0000108
Chris Lattner85d99442006-08-12 04:51:20 +0000109 // Check to see that no blocks (other than the header) in loops have
110 // predecessors that are not in loops. This is not valid for natural loops,
111 // but can occur if the blocks are unreachable. Since they are unreachable we
112 // can just shamelessly destroy their terminators to make them not branch into
113 // the loop!
114 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
115 // This case can only occur for unreachable blocks. Blocks that are
116 // unreachable can't be in loops, so filter those blocks out.
117 if (LI->getLoopFor(BB)) continue;
118
119 bool BlockUnreachable = false;
120 TerminatorInst *TI = BB->getTerminator();
121
122 // Check to see if any successors of this block are non-loop-header loops
123 // that are not the header.
124 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
125 // If this successor is not in a loop, BB is clearly ok.
126 Loop *L = LI->getLoopFor(TI->getSuccessor(i));
127 if (!L) continue;
128
129 // If the succ is the loop header, and if L is a top-level loop, then this
130 // is an entrance into a loop through the header, which is also ok.
131 if (L->getHeader() == TI->getSuccessor(i) && L->getParentLoop() == 0)
132 continue;
133
134 // Otherwise, this is an entrance into a loop from some place invalid.
135 // Either the loop structure is invalid and this is not a natural loop (in
136 // which case the compiler is buggy somewhere else) or BB is unreachable.
137 BlockUnreachable = true;
138 break;
139 }
140
141 // If this block is ok, check the next one.
142 if (!BlockUnreachable) continue;
143
144 // Otherwise, this block is dead. To clean up the CFG and to allow later
145 // loop transformations to ignore this case, we delete the edges into the
146 // loop by replacing the terminator.
147
148 // Remove PHI entries from the successors.
149 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
150 TI->getSuccessor(i)->removePredecessor(BB);
151
152 // Add a new unreachable instruction.
153 new UnreachableInst(TI);
154
155 // Delete the dead terminator.
156 if (AA) AA->deleteValue(&BB->back());
157 BB->getInstList().pop_back();
158 Changed |= true;
159 }
160
Chris Lattnercffbbee2006-02-14 22:34:08 +0000161 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000162 Changed |= ProcessLoop(*I);
Chris Lattner61992f62002-09-26 16:17:31 +0000163
164 return Changed;
165}
166
Chris Lattner61992f62002-09-26 16:17:31 +0000167/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
168/// all loops have preheaders.
169///
Chris Lattner154e4d52003-10-12 21:43:28 +0000170bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000171 bool Changed = false;
Chris Lattnerf18b3962006-08-12 05:25:00 +0000172ReprocessLoop:
173
Chris Lattner9c5693f2006-02-14 23:06:02 +0000174 // Canonicalize inner loops before outer loops. Inner loop canonicalization
175 // can provide work for the outer loop to canonicalize.
176 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
177 Changed |= ProcessLoop(*I);
178
Chris Lattnerd0788122004-03-14 03:59:22 +0000179 assert(L->getBlocks()[0] == L->getHeader() &&
180 "Header isn't first block in loop?");
Chris Lattnerd0788122004-03-14 03:59:22 +0000181
Chris Lattner85d99442006-08-12 04:51:20 +0000182 // Does the loop already have a preheader? If so, don't insert one.
Chris Lattner61992f62002-09-26 16:17:31 +0000183 if (L->getLoopPreheader() == 0) {
184 InsertPreheaderForLoop(L);
185 NumInserted++;
186 Changed = true;
187 }
188
Chris Lattner7710f2f2003-12-10 17:20:35 +0000189 // Next, check to make sure that all exit nodes of the loop only have
190 // predecessors that are inside of the loop. This check guarantees that the
191 // loop preheader/header will dominate the exit blocks. If the exit block has
Chris Lattner02f53ad2006-02-12 01:59:10 +0000192 // predecessors from outside of the loop, split the edge now.
193 std::vector<BasicBlock*> ExitBlocks;
194 L->getExitBlocks(ExitBlocks);
Chris Lattnercffbbee2006-02-14 22:34:08 +0000195
Chris Lattner02f53ad2006-02-12 01:59:10 +0000196 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000197 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
198 E = ExitBlockSet.end(); I != E; ++I) {
199 BasicBlock *ExitBlock = *I;
Chris Lattnerdaa12132004-07-15 05:36:31 +0000200 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
201 PI != PE; ++PI)
Chris Lattner05bf90d2006-02-11 02:13:17 +0000202 // Must be exactly this loop: no subloops, parent loops, or non-loop preds
203 // allowed.
Chris Lattner02f53ad2006-02-12 01:59:10 +0000204 if (!L->contains(*PI)) {
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000205 RewriteLoopExitBlock(L, ExitBlock);
Chris Lattnerdaa12132004-07-15 05:36:31 +0000206 NumInserted++;
207 Changed = true;
208 break;
209 }
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000210 }
Chris Lattner650096a2003-02-27 20:27:08 +0000211
Chris Lattner84170522004-04-13 05:05:33 +0000212 // If the header has more than two predecessors at this point (from the
213 // preheader and from multiple backedges), we must adjust the loop.
Chris Lattnerf18b3962006-08-12 05:25:00 +0000214 unsigned NumBackedges = L->getNumBackEdges();
215 if (NumBackedges != 1) {
216 // If this is really a nested loop, rip it out into a child loop. Don't do
217 // this for loops with a giant number of backedges, just factor them into a
218 // common backedge instead.
219 if (NumBackedges < 8) {
220 if (Loop *NL = SeparateNestedLoop(L)) {
221 ++NumNested;
222 // This is a big restructuring change, reprocess the whole loop.
223 ProcessLoop(NL);
224 Changed = true;
225 // GCC doesn't tail recursion eliminate this.
226 goto ReprocessLoop;
227 }
Chris Lattner84170522004-04-13 05:05:33 +0000228 }
229
Chris Lattnerf18b3962006-08-12 05:25:00 +0000230 // If we either couldn't, or didn't want to, identify nesting of the loops,
231 // insert a new block that all backedges target, then make it jump to the
232 // loop header.
Chris Lattnerc4622a62003-10-13 00:37:13 +0000233 InsertUniqueBackedgeBlock(L);
234 NumInserted++;
235 Changed = true;
236 }
237
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000238 // Scan over the PHI nodes in the loop header. Since they now have only two
239 // incoming values (the loop is canonicalized), we may have simplified the PHI
240 // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
241 PHINode *PN;
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000242 for (BasicBlock::iterator I = L->getHeader()->begin();
243 (PN = dyn_cast<PHINode>(I++)); )
Chris Lattner62df7982005-08-10 17:15:20 +0000244 if (Value *V = PN->hasConstantValue()) {
Chris Lattnerf83ce5f2005-08-10 02:07:32 +0000245 PN->replaceAllUsesWith(V);
246 PN->eraseFromParent();
247 }
248
Chris Lattner61992f62002-09-26 16:17:31 +0000249 return Changed;
250}
251
Chris Lattner650096a2003-02-27 20:27:08 +0000252/// SplitBlockPredecessors - Split the specified block into two blocks. We want
253/// to move the predecessors specified in the Preds list to point to the new
254/// block, leaving the remaining predecessors pointing to BB. This method
255/// updates the SSA PHINode's, but no other analyses.
256///
Chris Lattner154e4d52003-10-12 21:43:28 +0000257BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
258 const char *Suffix,
Chris Lattner650096a2003-02-27 20:27:08 +0000259 const std::vector<BasicBlock*> &Preds) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000260
Chris Lattner650096a2003-02-27 20:27:08 +0000261 // Create new basic block, insert right before the original block...
Chris Lattner8d414ad2004-02-04 03:58:28 +0000262 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattner650096a2003-02-27 20:27:08 +0000263
264 // The preheader first gets an unconditional branch to the loop header...
Chris Lattnera2960002003-11-21 16:52:05 +0000265 BranchInst *BI = new BranchInst(BB, NewBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000266
Chris Lattner650096a2003-02-27 20:27:08 +0000267 // For every PHI node in the block, insert a PHI node into NewBB where the
268 // incoming values from the out of loop edges are moved to NewBB. We have two
269 // possible cases here. If the loop is dead, we just insert dummy entries
270 // into the PHI nodes for the new edge. If the loop is not dead, we move the
271 // incoming edges in BB into new PHI nodes in NewBB.
272 //
273 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner031a3f82003-12-19 06:27:08 +0000274 // Check to see if the values being merged into the new block need PHI
275 // nodes. If so, insert them.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000276 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
277 PHINode *PN = cast<PHINode>(I);
Chris Lattner84170522004-04-13 05:05:33 +0000278 ++I;
279
Chris Lattner031a3f82003-12-19 06:27:08 +0000280 // Check to see if all of the values coming in are the same. If so, we
281 // don't need to create a new PHI node.
282 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
283 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
284 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
285 InVal = 0;
286 break;
287 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000288
Chris Lattner031a3f82003-12-19 06:27:08 +0000289 // If the values coming into the block are not the same, we need a PHI.
290 if (InVal == 0) {
Chris Lattner6c237bc2003-12-09 23:12:55 +0000291 // Create the new PHI node, insert it into NewBB at the end of the block
292 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
Chris Lattner514e8432005-03-25 06:37:22 +0000293 if (AA) AA->copyValue(PN, NewPHI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000294
Chris Lattner6c237bc2003-12-09 23:12:55 +0000295 // Move all of the edges from blocks outside the loop to the new PHI
296 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Chris Lattner84170522004-04-13 05:05:33 +0000297 Value *V = PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000298 NewPHI->addIncoming(V, Preds[i]);
299 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000300 InVal = NewPHI;
301 } else {
302 // Remove all of the edges coming into the PHI nodes from outside of the
303 // block.
304 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
305 PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000306 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000307
308 // Add an incoming value to the PHI node in the loop for the preheader
309 // edge.
310 PN->addIncoming(InVal, NewBB);
Chris Lattner84170522004-04-13 05:05:33 +0000311
312 // Can we eliminate this phi node now?
Chris Lattner257efb22005-08-05 00:57:45 +0000313 if (Value *V = PN->hasConstantValue(true)) {
Chris Lattnere29d6342004-10-17 21:22:38 +0000314 if (!isa<Instruction>(V) ||
Owen Anderson91041952007-04-07 04:37:14 +0000315 getAnalysis<ETForest>().dominates(cast<Instruction>(V), PN)) {
Chris Lattnere29d6342004-10-17 21:22:38 +0000316 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000317 if (AA) AA->deleteValue(PN);
Chris Lattnere29d6342004-10-17 21:22:38 +0000318 BB->getInstList().erase(PN);
319 }
Chris Lattner84170522004-04-13 05:05:33 +0000320 }
Chris Lattner650096a2003-02-27 20:27:08 +0000321 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000322
Chris Lattner650096a2003-02-27 20:27:08 +0000323 // Now that the PHI nodes are updated, actually move the edges from
324 // Preds to point to NewBB instead of BB.
325 //
326 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
327 TerminatorInst *TI = Preds[i]->getTerminator();
328 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
329 if (TI->getSuccessor(s) == BB)
330 TI->setSuccessor(s, NewBB);
331 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000332
Chris Lattner650096a2003-02-27 20:27:08 +0000333 } else { // Otherwise the loop is dead...
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000334 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
335 PHINode *PN = cast<PHINode>(I);
Chris Lattner650096a2003-02-27 20:27:08 +0000336 // Insert dummy values as the incoming value...
337 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000338 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000339 }
Chris Lattner650096a2003-02-27 20:27:08 +0000340 return NewBB;
341}
342
Chris Lattner61992f62002-09-26 16:17:31 +0000343/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
344/// preheader, this method is called to insert one. This method has two phases:
345/// preheader insertion and analysis updating.
346///
Chris Lattner154e4d52003-10-12 21:43:28 +0000347void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000348 BasicBlock *Header = L->getHeader();
349
350 // Compute the set of predecessors of the loop that are not in the loop.
351 std::vector<BasicBlock*> OutsideBlocks;
352 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
353 PI != PE; ++PI)
Chris Lattner05bf90d2006-02-11 02:13:17 +0000354 if (!L->contains(*PI)) // Coming in from outside the loop?
355 OutsideBlocks.push_back(*PI); // Keep track of it...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000356
Chris Lattner608cd052006-09-23 07:40:52 +0000357 // Split out the loop pre-header.
Chris Lattner650096a2003-02-27 20:27:08 +0000358 BasicBlock *NewBB =
359 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Chris Lattner608cd052006-09-23 07:40:52 +0000360
Misha Brukmanb1c93172005-04-21 23:48:37 +0000361
Chris Lattner61992f62002-09-26 16:17:31 +0000362 //===--------------------------------------------------------------------===//
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000363 // Update analysis results now that we have performed the transformation
Chris Lattner61992f62002-09-26 16:17:31 +0000364 //
Misha Brukmanb1c93172005-04-21 23:48:37 +0000365
Chris Lattner61992f62002-09-26 16:17:31 +0000366 // We know that we have loop information to update... update it now.
367 if (Loop *Parent = L->getParentLoop())
Chris Lattnercffbbee2006-02-14 22:34:08 +0000368 Parent->addBasicBlockToLoop(NewBB, *LI);
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000369
Chris Lattner608cd052006-09-23 07:40:52 +0000370 UpdateDomInfoForRevectoredPreds(NewBB, OutsideBlocks);
Chris Lattner6bd6da42006-09-23 08:19:21 +0000371
372 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
373 // code layout too horribly.
374 PlaceSplitBlockCarefully(NewBB, OutsideBlocks, L);
Chris Lattner650096a2003-02-27 20:27:08 +0000375}
376
Chris Lattner84170522004-04-13 05:05:33 +0000377/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
378/// blocks. This method is used to split exit blocks that have predecessors
379/// outside of the loop.
Chris Lattner82782632004-04-18 22:27:10 +0000380BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattner650096a2003-02-27 20:27:08 +0000381 std::vector<BasicBlock*> LoopBlocks;
382 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
383 if (L->contains(*I))
384 LoopBlocks.push_back(*I);
385
Chris Lattner10b2b052003-02-27 22:31:07 +0000386 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
387 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
388
Chris Lattnercffbbee2006-02-14 22:34:08 +0000389 // Update Loop Information - we know that the new block will be in whichever
390 // loop the Exit block is in. Note that it may not be in that immediate loop,
391 // if the successor is some other loop header. In that case, we continue
392 // walking up the loop tree to find a loop that contains both the successor
393 // block and the predecessor block.
394 Loop *SuccLoop = LI->getLoopFor(Exit);
395 while (SuccLoop && !SuccLoop->contains(L->getHeader()))
396 SuccLoop = SuccLoop->getParentLoop();
397 if (SuccLoop)
398 SuccLoop->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner32a39c22003-02-28 03:07:54 +0000399
Chris Lattnerc4622a62003-10-13 00:37:13 +0000400 // Update dominator information (set, immdom, domtree, and domfrontier)
401 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
Chris Lattner82782632004-04-18 22:27:10 +0000402 return NewBB;
Chris Lattnerc4622a62003-10-13 00:37:13 +0000403}
404
Chris Lattner84170522004-04-13 05:05:33 +0000405/// AddBlockAndPredsToSet - Add the specified block, and all of its
406/// predecessors, to the specified set, if it's not already in there. Stop
407/// predecessor traversal when we reach StopBlock.
408static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
409 std::set<BasicBlock*> &Blocks) {
410 if (!Blocks.insert(BB).second) return; // already processed.
411 if (BB == StopBlock) return; // Stop here!
412
413 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
414 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
415}
416
Chris Lattnera6e22812004-04-13 15:21:18 +0000417/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
418/// PHI node that tells us how to partition the loops.
Devang Patel1758cb52007-03-20 20:18:12 +0000419static PHINode *FindPHIToPartitionLoops(Loop *L, ETForest *EF,
420 AliasAnalysis *AA) {
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000421 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
422 PHINode *PN = cast<PHINode>(I);
Chris Lattnera6e22812004-04-13 15:21:18 +0000423 ++I;
Nate Begemanb3923212005-08-04 23:24:19 +0000424 if (Value *V = PN->hasConstantValue())
Devang Patel1758cb52007-03-20 20:18:12 +0000425 if (!isa<Instruction>(V) || EF->dominates(cast<Instruction>(V), PN)) {
Chris Lattnere29d6342004-10-17 21:22:38 +0000426 // This is a degenerate PHI already, don't modify it!
427 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000428 if (AA) AA->deleteValue(PN);
Chris Lattnerdd3ec922005-03-06 21:35:38 +0000429 PN->eraseFromParent();
Chris Lattnere29d6342004-10-17 21:22:38 +0000430 continue;
431 }
432
433 // Scan this PHI node looking for a use of the PHI node by itself.
434 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
435 if (PN->getIncomingValue(i) == PN &&
436 L->contains(PN->getIncomingBlock(i)))
437 // We found something tasty to remove.
438 return PN;
Chris Lattnera6e22812004-04-13 15:21:18 +0000439 }
440 return 0;
441}
442
Chris Lattner6bd6da42006-09-23 08:19:21 +0000443// PlaceSplitBlockCarefully - If the block isn't already, move the new block to
444// right after some 'outside block' block. This prevents the preheader from
445// being placed inside the loop body, e.g. when the loop hasn't been rotated.
446void LoopSimplify::PlaceSplitBlockCarefully(BasicBlock *NewBB,
447 std::vector<BasicBlock*>&SplitPreds,
448 Loop *L) {
449 // Check to see if NewBB is already well placed.
450 Function::iterator BBI = NewBB; --BBI;
451 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
452 if (&*BBI == SplitPreds[i])
453 return;
454 }
455
456 // If it isn't already after an outside block, move it after one. This is
457 // always good as it makes the uncond branch from the outside block into a
458 // fall-through.
459
460 // Figure out *which* outside block to put this after. Prefer an outside
461 // block that neighbors a BB actually in the loop.
462 BasicBlock *FoundBB = 0;
463 for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
464 Function::iterator BBI = SplitPreds[i];
465 if (++BBI != NewBB->getParent()->end() &&
466 L->contains(BBI)) {
467 FoundBB = SplitPreds[i];
468 break;
469 }
470 }
471
472 // If our heuristic for a *good* bb to place this after doesn't find
473 // anything, just pick something. It's likely better than leaving it within
474 // the loop.
475 if (!FoundBB)
476 FoundBB = SplitPreds[0];
477 NewBB->moveAfter(FoundBB);
478}
479
480
Chris Lattner84170522004-04-13 05:05:33 +0000481/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
482/// them out into a nested loop. This is important for code that looks like
483/// this:
484///
485/// Loop:
486/// ...
487/// br cond, Loop, Next
488/// ...
489/// br cond2, Loop, Out
490///
491/// To identify this common case, we look at the PHI nodes in the header of the
492/// loop. PHI nodes with unchanging values on one backedge correspond to values
493/// that change in the "outer" loop, but not in the "inner" loop.
494///
495/// If we are able to separate out a loop, return the new outer loop that was
496/// created.
497///
498Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
Devang Patel1758cb52007-03-20 20:18:12 +0000499 ETForest *EF = getAnalysisToUpdate<ETForest>();
500 PHINode *PN = FindPHIToPartitionLoops(L, EF, AA);
Chris Lattnera6e22812004-04-13 15:21:18 +0000501 if (PN == 0) return 0; // No known way to partition.
Chris Lattner84170522004-04-13 05:05:33 +0000502
Chris Lattnera6e22812004-04-13 15:21:18 +0000503 // Pull out all predecessors that have varying values in the loop. This
504 // handles the case when a PHI node has multiple instances of itself as
505 // arguments.
Chris Lattner84170522004-04-13 05:05:33 +0000506 std::vector<BasicBlock*> OuterLoopPreds;
Chris Lattnera6e22812004-04-13 15:21:18 +0000507 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
508 if (PN->getIncomingValue(i) != PN ||
509 !L->contains(PN->getIncomingBlock(i)))
510 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner84170522004-04-13 05:05:33 +0000511
Chris Lattner89e959b2004-04-13 16:23:25 +0000512 BasicBlock *Header = L->getHeader();
Chris Lattner84170522004-04-13 05:05:33 +0000513 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
514
515 // Update dominator information (set, immdom, domtree, and domfrontier)
516 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
517
Chris Lattner6bd6da42006-09-23 08:19:21 +0000518 // Make sure that NewBB is put someplace intelligent, which doesn't mess up
519 // code layout too horribly.
520 PlaceSplitBlockCarefully(NewBB, OuterLoopPreds, L);
521
Chris Lattner84170522004-04-13 05:05:33 +0000522 // Create the new outer loop.
523 Loop *NewOuter = new Loop();
524
Chris Lattner84170522004-04-13 05:05:33 +0000525 // Change the parent loop to use the outer loop as its child now.
526 if (Loop *Parent = L->getParentLoop())
527 Parent->replaceChildLoopWith(L, NewOuter);
528 else
Chris Lattnercffbbee2006-02-14 22:34:08 +0000529 LI->changeTopLevelLoop(L, NewOuter);
Chris Lattner84170522004-04-13 05:05:33 +0000530
531 // This block is going to be our new header block: add it to this loop and all
532 // parent loops.
Chris Lattnercffbbee2006-02-14 22:34:08 +0000533 NewOuter->addBasicBlockToLoop(NewBB, *LI);
Chris Lattner84170522004-04-13 05:05:33 +0000534
535 // L is now a subloop of our outer loop.
536 NewOuter->addChildLoop(L);
537
Chris Lattner84170522004-04-13 05:05:33 +0000538 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
539 NewOuter->addBlockEntry(L->getBlocks()[i]);
540
541 // Determine which blocks should stay in L and which should be moved out to
542 // the Outer loop now.
Chris Lattner84170522004-04-13 05:05:33 +0000543 std::set<BasicBlock*> BlocksInL;
544 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
Owen Anderson91041952007-04-07 04:37:14 +0000545 if (EF->dominates(Header, *PI))
Chris Lattner84170522004-04-13 05:05:33 +0000546 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
547
548
549 // Scan all of the loop children of L, moving them to OuterLoop if they are
550 // not part of the inner loop.
551 for (Loop::iterator I = L->begin(); I != L->end(); )
552 if (BlocksInL.count((*I)->getHeader()))
553 ++I; // Loop remains in L
554 else
555 NewOuter->addChildLoop(L->removeChildLoop(I));
556
557 // Now that we know which blocks are in L and which need to be moved to
558 // OuterLoop, move any blocks that need it.
559 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
560 BasicBlock *BB = L->getBlocks()[i];
561 if (!BlocksInL.count(BB)) {
562 // Move this block to the parent, updating the exit blocks sets
563 L->removeBlockFromLoop(BB);
Chris Lattnercffbbee2006-02-14 22:34:08 +0000564 if ((*LI)[BB] == L)
565 LI->changeLoopFor(BB, NewOuter);
Chris Lattner84170522004-04-13 05:05:33 +0000566 --i;
567 }
568 }
569
Chris Lattner84170522004-04-13 05:05:33 +0000570 return NewOuter;
571}
572
573
574
Chris Lattnerc4622a62003-10-13 00:37:13 +0000575/// InsertUniqueBackedgeBlock - This method is called when the specified loop
576/// has more than one backedge in it. If this occurs, revector all of these
577/// backedges to target a new basic block and have that block branch to the loop
578/// header. This ensures that loops have exactly one backedge.
579///
580void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
581 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
582
583 // Get information about the loop
584 BasicBlock *Preheader = L->getLoopPreheader();
585 BasicBlock *Header = L->getHeader();
586 Function *F = Header->getParent();
587
588 // Figure out which basic blocks contain back-edges to the loop header.
589 std::vector<BasicBlock*> BackedgeBlocks;
590 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
591 if (*I != Preheader) BackedgeBlocks.push_back(*I);
592
593 // Create and insert the new backedge block...
594 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattnera2960002003-11-21 16:52:05 +0000595 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000596
597 // Move the new backedge block to right after the last backedge block.
598 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
599 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000600
Chris Lattnerc4622a62003-10-13 00:37:13 +0000601 // Now that the block has been inserted into the function, create PHI nodes in
602 // the backedge block which correspond to any PHI nodes in the header block.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000603 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
604 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000605 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
606 BETerminator);
Chris Lattnerd8e20182005-01-29 00:39:08 +0000607 NewPN->reserveOperandSpace(BackedgeBlocks.size());
Chris Lattner514e8432005-03-25 06:37:22 +0000608 if (AA) AA->copyValue(PN, NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000609
610 // Loop over the PHI node, moving all entries except the one for the
611 // preheader over to the new PHI node.
612 unsigned PreheaderIdx = ~0U;
613 bool HasUniqueIncomingValue = true;
614 Value *UniqueValue = 0;
615 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
616 BasicBlock *IBB = PN->getIncomingBlock(i);
617 Value *IV = PN->getIncomingValue(i);
618 if (IBB == Preheader) {
619 PreheaderIdx = i;
620 } else {
621 NewPN->addIncoming(IV, IBB);
622 if (HasUniqueIncomingValue) {
623 if (UniqueValue == 0)
624 UniqueValue = IV;
625 else if (UniqueValue != IV)
626 HasUniqueIncomingValue = false;
627 }
628 }
629 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000630
Chris Lattnerc4622a62003-10-13 00:37:13 +0000631 // Delete all of the incoming values from the old PN except the preheader's
632 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
633 if (PreheaderIdx != 0) {
634 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
635 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
636 }
Chris Lattnerd8e20182005-01-29 00:39:08 +0000637 // Nuke all entries except the zero'th.
638 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
639 PN->removeIncomingValue(e-i, false);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000640
641 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
642 PN->addIncoming(NewPN, BEBlock);
643
644 // As an optimization, if all incoming values in the new PhiNode (which is a
645 // subset of the incoming values of the old PHI node) have the same value,
646 // eliminate the PHI Node.
647 if (HasUniqueIncomingValue) {
648 NewPN->replaceAllUsesWith(UniqueValue);
Chris Lattner514e8432005-03-25 06:37:22 +0000649 if (AA) AA->deleteValue(NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000650 BEBlock->getInstList().erase(NewPN);
651 }
652 }
653
654 // Now that all of the PHI nodes have been inserted and adjusted, modify the
655 // backedge blocks to just to the BEBlock instead of the header.
656 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
657 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
658 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
659 if (TI->getSuccessor(Op) == Header)
660 TI->setSuccessor(Op, BEBlock);
661 }
662
663 //===--- Update all analyses which we must preserve now -----------------===//
664
665 // Update Loop Information - we know that this block is now in the current
666 // loop and all parent loops.
Chris Lattnercffbbee2006-02-14 22:34:08 +0000667 L->addBasicBlockToLoop(BEBlock, *LI);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000668
Chris Lattnerc4622a62003-10-13 00:37:13 +0000669 // Update dominator information (set, immdom, domtree, and domfrontier)
670 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
671}
672
673/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
674/// different kinds of dominator information (dominator sets, immediate
675/// dominators, dominator trees, and dominance frontiers) after a new block has
676/// been added to the CFG.
677///
Chris Lattner14ab84a2004-02-05 21:12:24 +0000678/// This only supports the case when an existing block (known as "NewBBSucc"),
679/// had some of its predecessors factored into a new basic block. This
Chris Lattnerc4622a62003-10-13 00:37:13 +0000680/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner14ab84a2004-02-05 21:12:24 +0000681/// unconditional branch to NewBBSucc, and moves some predecessors of
682/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
683/// PredBlocks, even though they are the same as
684/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattnerc4622a62003-10-13 00:37:13 +0000685///
686void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
687 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000688 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattnerc4622a62003-10-13 00:37:13 +0000689 assert(succ_begin(NewBB) != succ_end(NewBB) &&
690 ++succ_begin(NewBB) == succ_end(NewBB) &&
691 "NewBB should have a single successor!");
Chris Lattner14ab84a2004-02-05 21:12:24 +0000692 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Owen Anderson706e9702007-04-07 06:56:47 +0000693 ETForest& ETF = getAnalysis<ETForest>();
694
Chris Lattner14ab84a2004-02-05 21:12:24 +0000695 // The newly inserted basic block will dominate existing basic blocks iff the
696 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
697 // the non-pred blocks, then they all must be the same block!
Chris Lattner146d0df2004-04-01 19:06:07 +0000698 //
Chris Lattner14ab84a2004-02-05 21:12:24 +0000699 bool NewBBDominatesNewBBSucc = true;
700 {
701 BasicBlock *OnePred = PredBlocks[0];
Chris Lattner608cd052006-09-23 07:40:52 +0000702 unsigned i, e = PredBlocks.size();
Owen Anderson706e9702007-04-07 06:56:47 +0000703 for (i = 1; !ETF.dominates(&OnePred->getParent()->getEntryBlock(), OnePred); ++i) {
Chris Lattner608cd052006-09-23 07:40:52 +0000704 assert(i != e && "Didn't find reachable pred?");
705 OnePred = PredBlocks[i];
706 }
707
708 for (; i != e; ++i)
Owen Anderson706e9702007-04-07 06:56:47 +0000709 if (PredBlocks[i] != OnePred &&
710 ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), OnePred)) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000711 NewBBDominatesNewBBSucc = false;
712 break;
713 }
714
715 if (NewBBDominatesNewBBSucc)
716 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
717 PI != E; ++PI)
Owen Anderson706e9702007-04-07 06:56:47 +0000718 if (*PI != NewBB && !ETF.dominates(NewBBSucc, *PI)) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000719 NewBBDominatesNewBBSucc = false;
720 break;
721 }
722 }
723
Chris Lattner146d0df2004-04-01 19:06:07 +0000724 // The other scenario where the new block can dominate its successors are when
725 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
726 // already.
727 if (!NewBBDominatesNewBBSucc) {
728 NewBBDominatesNewBBSucc = true;
729 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
730 PI != E; ++PI)
Owen Anderson706e9702007-04-07 06:56:47 +0000731 if (*PI != NewBB && !ETF.dominates(NewBBSucc, *PI)) {
Chris Lattner146d0df2004-04-01 19:06:07 +0000732 NewBBDominatesNewBBSucc = false;
733 break;
734 }
735 }
Chris Lattner650096a2003-02-27 20:27:08 +0000736
Chris Lattner650096a2003-02-27 20:27:08 +0000737 BasicBlock *NewBBIDom = 0;
Owen Anderson706e9702007-04-07 06:56:47 +0000738
739 // Update immediate dominator information if we have it.
Chris Lattner650096a2003-02-27 20:27:08 +0000740 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
Owen Anderson706e9702007-04-07 06:56:47 +0000741 unsigned i = 0;
742 for (i = 0; i < PredBlocks.size(); ++i)
743 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i])) {
744 NewBBIDom = PredBlocks[i];
745 break;
746 }
747 assert(i != PredBlocks.size() && "No reachable preds?");
748 for (i = i + 1; i < PredBlocks.size(); ++i) {
749 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i]))
750 NewBBIDom = ETF.nearestCommonDominator(NewBBIDom, PredBlocks[i]);
Chris Lattner608cd052006-09-23 07:40:52 +0000751 }
Owen Anderson706e9702007-04-07 06:56:47 +0000752 assert(NewBBIDom && "No immediate dominator found??");
753
Chris Lattner650096a2003-02-27 20:27:08 +0000754 // Set the immediate dominator now...
Owen Anderson706e9702007-04-07 06:56:47 +0000755 ID->addNewBlock(NewBB, NewBBIDom);
Chris Lattner14ab84a2004-02-05 21:12:24 +0000756
757 // If NewBB strictly dominates other blocks, we need to update their idom's
758 // now. The only block that need adjustment is the NewBBSucc block, whose
759 // idom should currently be set to PredBlocks[0].
Chris Lattner59fdf742004-04-01 19:21:46 +0000760 if (NewBBDominatesNewBBSucc)
Chris Lattner14ab84a2004-02-05 21:12:24 +0000761 ID->setImmediateDominator(NewBBSucc, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000762 }
763
764 // Update DominatorTree information if it is active.
765 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000766 // If we don't have ImmediateDominator info around, calculate the idom as
767 // above.
Owen Anderson706e9702007-04-07 06:56:47 +0000768 if (!NewBBIDom) {
769 unsigned i = 0;
770 for (i = 0; i < PredBlocks.size(); ++i)
771 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i])) {
772 NewBBIDom = PredBlocks[i];
773 break;
774 }
775 assert(i != PredBlocks.size() && "No reachable preds?");
776 for (i = i + 1; i < PredBlocks.size(); ++i) {
777 if (ETF.dominates(&PredBlocks[i]->getParent()->getEntryBlock(), PredBlocks[i]))
778 NewBBIDom = ETF.nearestCommonDominator(NewBBIDom, PredBlocks[i]);
Chris Lattner608cd052006-09-23 07:40:52 +0000779 }
Owen Anderson706e9702007-04-07 06:56:47 +0000780 assert(NewBBIDom && "No immediate dominator found??");
Chris Lattner650096a2003-02-27 20:27:08 +0000781 }
Owen Anderson706e9702007-04-07 06:56:47 +0000782 DominatorTree::Node *NewBBIDomNode = DT->getNode(NewBBIDom);
Chris Lattner650096a2003-02-27 20:27:08 +0000783
Chris Lattner14ab84a2004-02-05 21:12:24 +0000784 // Create the new dominator tree node... and set the idom of NewBB.
785 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
786
787 // If NewBB strictly dominates other blocks, then it is now the immediate
788 // dominator of NewBBSucc. Update the dominator tree as appropriate.
789 if (NewBBDominatesNewBBSucc) {
790 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
Chris Lattner14ab84a2004-02-05 21:12:24 +0000791 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
792 }
Chris Lattner650096a2003-02-27 20:27:08 +0000793 }
794
Chris Lattnercda4aa62006-01-09 08:03:08 +0000795 // Update ET-Forest information if it is active.
796 if (ETForest *EF = getAnalysisToUpdate<ETForest>()) {
797 EF->addNewBlock(NewBB, NewBBIDom);
798 if (NewBBDominatesNewBBSucc)
799 EF->setImmediateDominator(NewBBSucc, NewBB);
800 }
801
Chris Lattner650096a2003-02-27 20:27:08 +0000802 // Update dominance frontier information...
803 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
Chris Lattner89e959b2004-04-13 16:23:25 +0000804 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
805 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
806 // a predecessor of.
Chris Lattner14ab84a2004-02-05 21:12:24 +0000807 if (NewBBDominatesNewBBSucc) {
808 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
809 if (DFI != DF->end()) {
810 DominanceFrontier::DomSetType Set = DFI->second;
811 // Filter out stuff in Set that we do not dominate a predecessor of.
812 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
813 E = Set.end(); SetI != E;) {
814 bool DominatesPred = false;
815 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
816 PI != E; ++PI)
Owen Anderson706e9702007-04-07 06:56:47 +0000817 if (ETF.dominates(NewBB, *PI))
Chris Lattner14ab84a2004-02-05 21:12:24 +0000818 DominatesPred = true;
819 if (!DominatesPred)
820 Set.erase(SetI++);
821 else
822 ++SetI;
823 }
Chris Lattner650096a2003-02-27 20:27:08 +0000824
Chris Lattner14ab84a2004-02-05 21:12:24 +0000825 DF->addBasicBlock(NewBB, Set);
826 }
827
828 } else {
829 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
830 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
831 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
832 DominanceFrontier::DomSetType NewDFSet;
833 NewDFSet.insert(NewBBSucc);
834 DF->addBasicBlock(NewBB, NewDFSet);
Chris Lattner89e959b2004-04-13 16:23:25 +0000835 }
Chris Lattnerc4622a62003-10-13 00:37:13 +0000836
Chris Lattner89e959b2004-04-13 16:23:25 +0000837 // Now we must loop over all of the dominance frontiers in the function,
838 // replacing occurrences of NewBBSucc with NewBB in some cases. All
839 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
840 // their dominance frontier must be updated to contain NewBB instead.
841 //
842 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
843 BasicBlock *Pred = PredBlocks[i];
844 // Get all of the dominators of the predecessor...
Owen Anderson706e9702007-04-07 06:56:47 +0000845 // FIXME: There's probably a better way to do this...
846 std::vector<BasicBlock*> PredDoms;
847 for (Function::iterator I = Pred->getParent()->begin(),
848 E = Pred->getParent()->end(); I != E; ++I)
849 if (ETF.dominates(&(*I), Pred))
850 PredDoms.push_back(I);
851
852 for (std::vector<BasicBlock*>::const_iterator PDI = PredDoms.begin(),
Chris Lattner89e959b2004-04-13 16:23:25 +0000853 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
854 BasicBlock *PredDom = *PDI;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000855
Chris Lattner89e959b2004-04-13 16:23:25 +0000856 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
857 // dominate NewBBSucc but did dominate a predecessor of it. Now we
858 // change this entry to include NewBB in the DF instead of NewBBSucc.
859 DominanceFrontier::iterator DFI = DF->find(PredDom);
860 assert(DFI != DF->end() && "No dominance frontier for node?");
861 if (DFI->second.count(NewBBSucc)) {
862 // If NewBBSucc should not stay in our dominator frontier, remove it.
863 // We remove it unless there is a predecessor of NewBBSucc that we
864 // dominate, but we don't strictly dominate NewBBSucc.
865 bool ShouldRemove = true;
Owen Anderson706e9702007-04-07 06:56:47 +0000866 if (PredDom == NewBBSucc || !ETF.dominates(PredDom, NewBBSucc)) {
Chris Lattner89e959b2004-04-13 16:23:25 +0000867 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
868 // Check to see if it dominates any predecessors of NewBBSucc.
869 for (pred_iterator PI = pred_begin(NewBBSucc),
870 E = pred_end(NewBBSucc); PI != E; ++PI)
Owen Anderson706e9702007-04-07 06:56:47 +0000871 if (ETF.dominates(PredDom, *PI)) {
Chris Lattner89e959b2004-04-13 16:23:25 +0000872 ShouldRemove = false;
873 break;
874 }
Chris Lattner650096a2003-02-27 20:27:08 +0000875 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000876
Chris Lattner89e959b2004-04-13 16:23:25 +0000877 if (ShouldRemove)
878 DF->removeFromFrontier(DFI, NewBBSucc);
879 DF->addToFrontier(DFI, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000880 }
881 }
882 }
Chris Lattner650096a2003-02-27 20:27:08 +0000883 }
Chris Lattner61992f62002-09-26 16:17:31 +0000884}
Brian Gaeke960707c2003-11-11 22:41:34 +0000885