blob: da1a6550a497bb68304711ae208cd52f07d5c3b1 [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
35#include "llvm/Transforms/Scalar.h"
Chris Lattnerd0788122004-03-14 03:59:22 +000036#include "llvm/Constant.h"
Misha Brukman63b38bd2004-07-29 17:30:56 +000037#include "llvm/Instructions.h"
Chris Lattnerd0788122004-03-14 03:59:22 +000038#include "llvm/Function.h"
39#include "llvm/Type.h"
Chris Lattner514e8432005-03-25 06:37:22 +000040#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner031a3f82003-12-19 06:27:08 +000041#include "llvm/Analysis/Dominators.h"
42#include "llvm/Analysis/LoopInfo.h"
Chris Lattner61992f62002-09-26 16:17:31 +000043#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000044#include "llvm/ADT/SetOperations.h"
45#include "llvm/ADT/SetVector.h"
46#include "llvm/ADT/Statistic.h"
47#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattner7710f2f2003-12-10 17:20:35 +000048using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000049
Chris Lattner61992f62002-09-26 16:17:31 +000050namespace {
Chris Lattner154e4d52003-10-12 21:43:28 +000051 Statistic<>
Chris Lattner7710f2f2003-12-10 17:20:35 +000052 NumInserted("loopsimplify", "Number of pre-header or exit blocks inserted");
Chris Lattner84170522004-04-13 05:05:33 +000053 Statistic<>
54 NumNested("loopsimplify", "Number of nested loops split out");
Chris Lattner61992f62002-09-26 16:17:31 +000055
Chris Lattner154e4d52003-10-12 21:43:28 +000056 struct 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;
60
Chris Lattner61992f62002-09-26 16:17:31 +000061 virtual bool runOnFunction(Function &F);
Misha Brukmanb1c93172005-04-21 23:48:37 +000062
Chris Lattner61992f62002-09-26 16:17:31 +000063 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 // We need loop information to identify the loops...
65 AU.addRequired<LoopInfo>();
Chris Lattner650096a2003-02-27 20:27:08 +000066 AU.addRequired<DominatorSet>();
Chris Lattner797cb2f2004-03-13 22:01:26 +000067 AU.addRequired<DominatorTree>();
Chris Lattner61992f62002-09-26 16:17:31 +000068
69 AU.addPreserved<LoopInfo>();
70 AU.addPreserved<DominatorSet>();
71 AU.addPreserved<ImmediateDominators>();
72 AU.addPreserved<DominatorTree>();
Chris Lattner650096a2003-02-27 20:27:08 +000073 AU.addPreserved<DominanceFrontier>();
Chris Lattner61992f62002-09-26 16:17:31 +000074 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
75 }
76 private:
77 bool ProcessLoop(Loop *L);
Chris Lattner650096a2003-02-27 20:27:08 +000078 BasicBlock *SplitBlockPredecessors(BasicBlock *BB, const char *Suffix,
79 const std::vector<BasicBlock*> &Preds);
Chris Lattner82782632004-04-18 22:27:10 +000080 BasicBlock *RewriteLoopExitBlock(Loop *L, BasicBlock *Exit);
Chris Lattner61992f62002-09-26 16:17:31 +000081 void InsertPreheaderForLoop(Loop *L);
Chris Lattner84170522004-04-13 05:05:33 +000082 Loop *SeparateNestedLoop(Loop *L);
Chris Lattnerc4622a62003-10-13 00:37:13 +000083 void InsertUniqueBackedgeBlock(Loop *L);
84
85 void UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
86 std::vector<BasicBlock*> &PredBlocks);
Chris Lattner61992f62002-09-26 16:17:31 +000087 };
88
Chris Lattner154e4d52003-10-12 21:43:28 +000089 RegisterOpt<LoopSimplify>
90 X("loopsimplify", "Canonicalize natural loops", true);
Chris Lattner61992f62002-09-26 16:17:31 +000091}
92
93// Publically exposed interface to pass...
Chris Lattner7710f2f2003-12-10 17:20:35 +000094const PassInfo *llvm::LoopSimplifyID = X.getPassInfo();
Chris Lattner3e860842004-09-20 04:43:15 +000095FunctionPass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
Chris Lattner61992f62002-09-26 16:17:31 +000096
Chris Lattner61992f62002-09-26 16:17:31 +000097/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
98/// it in any convenient order) inserting preheaders...
99///
Chris Lattner154e4d52003-10-12 21:43:28 +0000100bool LoopSimplify::runOnFunction(Function &F) {
Chris Lattner61992f62002-09-26 16:17:31 +0000101 bool Changed = false;
102 LoopInfo &LI = getAnalysis<LoopInfo>();
Chris Lattner514e8432005-03-25 06:37:22 +0000103 AA = getAnalysisToUpdate<AliasAnalysis>();
Chris Lattner61992f62002-09-26 16:17:31 +0000104
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000105 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
106 Changed |= ProcessLoop(*I);
Chris Lattner61992f62002-09-26 16:17:31 +0000107
108 return Changed;
109}
110
111
112/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
113/// all loops have preheaders.
114///
Chris Lattner154e4d52003-10-12 21:43:28 +0000115bool LoopSimplify::ProcessLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000116 bool Changed = false;
117
Chris Lattnerd0788122004-03-14 03:59:22 +0000118 // Check to see that no blocks (other than the header) in the loop have
119 // predecessors that are not in the loop. This is not valid for natural
120 // loops, but can occur if the blocks are unreachable. Since they are
121 // unreachable we can just shamelessly destroy their terminators to make them
122 // not branch into the loop!
123 assert(L->getBlocks()[0] == L->getHeader() &&
124 "Header isn't first block in loop?");
125 for (unsigned i = 1, e = L->getBlocks().size(); i != e; ++i) {
126 BasicBlock *LoopBB = L->getBlocks()[i];
127 Retry:
128 for (pred_iterator PI = pred_begin(LoopBB), E = pred_end(LoopBB);
129 PI != E; ++PI)
130 if (!L->contains(*PI)) {
131 // This predecessor is not in the loop. Kill its terminator!
132 BasicBlock *DeadBlock = *PI;
133 for (succ_iterator SI = succ_begin(DeadBlock), E = succ_end(DeadBlock);
134 SI != E; ++SI)
135 (*SI)->removePredecessor(DeadBlock); // Remove PHI node entries
136
137 // Delete the dead terminator.
Chris Lattner514e8432005-03-25 06:37:22 +0000138 if (AA) AA->deleteValue(&DeadBlock->back());
Chris Lattnerd0788122004-03-14 03:59:22 +0000139 DeadBlock->getInstList().pop_back();
140
141 Value *RetVal = 0;
142 if (LoopBB->getParent()->getReturnType() != Type::VoidTy)
143 RetVal = Constant::getNullValue(LoopBB->getParent()->getReturnType());
144 new ReturnInst(RetVal, DeadBlock);
145 goto Retry; // We just invalidated the pred_iterator. Retry.
146 }
147 }
148
Chris Lattner61992f62002-09-26 16:17:31 +0000149 // Does the loop already have a preheader? If so, don't modify the loop...
150 if (L->getLoopPreheader() == 0) {
151 InsertPreheaderForLoop(L);
152 NumInserted++;
153 Changed = true;
154 }
155
Chris Lattner7710f2f2003-12-10 17:20:35 +0000156 // Next, check to make sure that all exit nodes of the loop only have
157 // predecessors that are inside of the loop. This check guarantees that the
158 // loop preheader/header will dominate the exit blocks. If the exit block has
159 // predecessors from outside of the loop, split the edge now.
Chris Lattnerd72c3eb2004-04-18 22:14:10 +0000160 std::vector<BasicBlock*> ExitBlocks;
161 L->getExitBlocks(ExitBlocks);
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000162
163 SetVector<BasicBlock*> ExitBlockSet(ExitBlocks.begin(), ExitBlocks.end());
164 for (SetVector<BasicBlock*>::iterator I = ExitBlockSet.begin(),
165 E = ExitBlockSet.end(); I != E; ++I) {
166 BasicBlock *ExitBlock = *I;
Chris Lattnerdaa12132004-07-15 05:36:31 +0000167 for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
168 PI != PE; ++PI)
169 if (!L->contains(*PI)) {
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000170 RewriteLoopExitBlock(L, ExitBlock);
Chris Lattnerdaa12132004-07-15 05:36:31 +0000171 NumInserted++;
172 Changed = true;
173 break;
174 }
Chris Lattnerf2c018c2004-07-15 08:20:22 +0000175 }
Chris Lattner650096a2003-02-27 20:27:08 +0000176
Chris Lattner84170522004-04-13 05:05:33 +0000177 // If the header has more than two predecessors at this point (from the
178 // preheader and from multiple backedges), we must adjust the loop.
Chris Lattnerc4622a62003-10-13 00:37:13 +0000179 if (L->getNumBackEdges() != 1) {
Chris Lattner84170522004-04-13 05:05:33 +0000180 // If this is really a nested loop, rip it out into a child loop.
181 if (Loop *NL = SeparateNestedLoop(L)) {
182 ++NumNested;
183 // This is a big restructuring change, reprocess the whole loop.
184 ProcessLoop(NL);
185 return true;
186 }
187
Chris Lattnerc4622a62003-10-13 00:37:13 +0000188 InsertUniqueBackedgeBlock(L);
189 NumInserted++;
190 Changed = true;
191 }
192
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000193 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
194 Changed |= ProcessLoop(*I);
Chris Lattner61992f62002-09-26 16:17:31 +0000195 return Changed;
196}
197
Chris Lattner650096a2003-02-27 20:27:08 +0000198/// SplitBlockPredecessors - Split the specified block into two blocks. We want
199/// to move the predecessors specified in the Preds list to point to the new
200/// block, leaving the remaining predecessors pointing to BB. This method
201/// updates the SSA PHINode's, but no other analyses.
202///
Chris Lattner154e4d52003-10-12 21:43:28 +0000203BasicBlock *LoopSimplify::SplitBlockPredecessors(BasicBlock *BB,
204 const char *Suffix,
Chris Lattner650096a2003-02-27 20:27:08 +0000205 const std::vector<BasicBlock*> &Preds) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000206
Chris Lattner650096a2003-02-27 20:27:08 +0000207 // Create new basic block, insert right before the original block...
Chris Lattner8d414ad2004-02-04 03:58:28 +0000208 BasicBlock *NewBB = new BasicBlock(BB->getName()+Suffix, BB->getParent(), BB);
Chris Lattner650096a2003-02-27 20:27:08 +0000209
210 // The preheader first gets an unconditional branch to the loop header...
Chris Lattnera2960002003-11-21 16:52:05 +0000211 BranchInst *BI = new BranchInst(BB, NewBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000212
Chris Lattner650096a2003-02-27 20:27:08 +0000213 // For every PHI node in the block, insert a PHI node into NewBB where the
214 // incoming values from the out of loop edges are moved to NewBB. We have two
215 // possible cases here. If the loop is dead, we just insert dummy entries
216 // into the PHI nodes for the new edge. If the loop is not dead, we move the
217 // incoming edges in BB into new PHI nodes in NewBB.
218 //
219 if (!Preds.empty()) { // Is the loop not obviously dead?
Chris Lattner031a3f82003-12-19 06:27:08 +0000220 // Check to see if the values being merged into the new block need PHI
221 // nodes. If so, insert them.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000222 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ) {
223 PHINode *PN = cast<PHINode>(I);
Chris Lattner84170522004-04-13 05:05:33 +0000224 ++I;
225
Chris Lattner031a3f82003-12-19 06:27:08 +0000226 // Check to see if all of the values coming in are the same. If so, we
227 // don't need to create a new PHI node.
228 Value *InVal = PN->getIncomingValueForBlock(Preds[0]);
229 for (unsigned i = 1, e = Preds.size(); i != e; ++i)
230 if (InVal != PN->getIncomingValueForBlock(Preds[i])) {
231 InVal = 0;
232 break;
233 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000234
Chris Lattner031a3f82003-12-19 06:27:08 +0000235 // If the values coming into the block are not the same, we need a PHI.
236 if (InVal == 0) {
Chris Lattner6c237bc2003-12-09 23:12:55 +0000237 // Create the new PHI node, insert it into NewBB at the end of the block
238 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
Chris Lattner514e8432005-03-25 06:37:22 +0000239 if (AA) AA->copyValue(PN, NewPHI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000240
Chris Lattner6c237bc2003-12-09 23:12:55 +0000241 // Move all of the edges from blocks outside the loop to the new PHI
242 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Chris Lattner84170522004-04-13 05:05:33 +0000243 Value *V = PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000244 NewPHI->addIncoming(V, Preds[i]);
245 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000246 InVal = NewPHI;
247 } else {
248 // Remove all of the edges coming into the PHI nodes from outside of the
249 // block.
250 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
251 PN->removeIncomingValue(Preds[i], false);
Chris Lattner6c237bc2003-12-09 23:12:55 +0000252 }
Chris Lattner031a3f82003-12-19 06:27:08 +0000253
254 // Add an incoming value to the PHI node in the loop for the preheader
255 // edge.
256 PN->addIncoming(InVal, NewBB);
Chris Lattner84170522004-04-13 05:05:33 +0000257
258 // Can we eliminate this phi node now?
Chris Lattner257efb22005-08-05 00:57:45 +0000259 if (Value *V = PN->hasConstantValue(true)) {
Chris Lattnere29d6342004-10-17 21:22:38 +0000260 if (!isa<Instruction>(V) ||
261 getAnalysis<DominatorSet>().dominates(cast<Instruction>(V), PN)) {
262 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000263 if (AA) AA->deleteValue(PN);
Chris Lattnere29d6342004-10-17 21:22:38 +0000264 BB->getInstList().erase(PN);
265 }
Chris Lattner84170522004-04-13 05:05:33 +0000266 }
Chris Lattner650096a2003-02-27 20:27:08 +0000267 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000268
Chris Lattner650096a2003-02-27 20:27:08 +0000269 // Now that the PHI nodes are updated, actually move the edges from
270 // Preds to point to NewBB instead of BB.
271 //
272 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
273 TerminatorInst *TI = Preds[i]->getTerminator();
274 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
275 if (TI->getSuccessor(s) == BB)
276 TI->setSuccessor(s, NewBB);
277 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000278
Chris Lattner650096a2003-02-27 20:27:08 +0000279 } else { // Otherwise the loop is dead...
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000280 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I) {
281 PHINode *PN = cast<PHINode>(I);
Chris Lattner650096a2003-02-27 20:27:08 +0000282 // Insert dummy values as the incoming value...
283 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000284 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000285 }
Chris Lattner650096a2003-02-27 20:27:08 +0000286 return NewBB;
287}
288
Chris Lattner61992f62002-09-26 16:17:31 +0000289/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
290/// preheader, this method is called to insert one. This method has two phases:
291/// preheader insertion and analysis updating.
292///
Chris Lattner154e4d52003-10-12 21:43:28 +0000293void LoopSimplify::InsertPreheaderForLoop(Loop *L) {
Chris Lattner61992f62002-09-26 16:17:31 +0000294 BasicBlock *Header = L->getHeader();
295
296 // Compute the set of predecessors of the loop that are not in the loop.
297 std::vector<BasicBlock*> OutsideBlocks;
298 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
299 PI != PE; ++PI)
300 if (!L->contains(*PI)) // Coming in from outside the loop?
301 OutsideBlocks.push_back(*PI); // Keep track of it...
Misha Brukmanb1c93172005-04-21 23:48:37 +0000302
Chris Lattner650096a2003-02-27 20:27:08 +0000303 // Split out the loop pre-header
304 BasicBlock *NewBB =
305 SplitBlockPredecessors(Header, ".preheader", OutsideBlocks);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000306
Chris Lattner61992f62002-09-26 16:17:31 +0000307 //===--------------------------------------------------------------------===//
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000308 // Update analysis results now that we have performed the transformation
Chris Lattner61992f62002-09-26 16:17:31 +0000309 //
Misha Brukmanb1c93172005-04-21 23:48:37 +0000310
Chris Lattner61992f62002-09-26 16:17:31 +0000311 // We know that we have loop information to update... update it now.
312 if (Loop *Parent = L->getParentLoop())
313 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000314
315 // If the header for the loop used to be an exit node for another loop, then
316 // we need to update this to know that the loop-preheader is now the exit
317 // node. Note that the only loop that could have our header as an exit node
Chris Lattner08950252003-05-12 22:04:34 +0000318 // is a sibling loop, ie, one with the same parent loop, or one if it's
319 // children.
320 //
Chris Lattner59d2d7f2004-01-08 00:09:44 +0000321 LoopInfo::iterator ParentLoops, ParentLoopsE;
322 if (Loop *Parent = L->getParentLoop()) {
323 ParentLoops = Parent->begin();
324 ParentLoopsE = Parent->end();
325 } else { // Must check top-level loops...
326 ParentLoops = getAnalysis<LoopInfo>().begin();
327 ParentLoopsE = getAnalysis<LoopInfo>().end();
328 }
Chris Lattnerf2d9f942003-02-27 22:48:57 +0000329
Chris Lattner650096a2003-02-27 20:27:08 +0000330 DominatorSet &DS = getAnalysis<DominatorSet>(); // Update dominator info
Chris Lattner797cb2f2004-03-13 22:01:26 +0000331 DominatorTree &DT = getAnalysis<DominatorTree>();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000332
Chris Lattnerdb5b8f42004-03-16 06:00:15 +0000333
334 // Update the dominator tree information.
335 // The immediate dominator of the preheader is the immediate dominator of
336 // the old header.
337 DominatorTree::Node *PHDomTreeNode =
338 DT.createNewNode(NewBB, DT.getNode(Header)->getIDom());
339
340 // Change the header node so that PNHode is the new immediate dominator
341 DT.changeImmediateDominator(DT.getNode(Header), PHDomTreeNode);
Chris Lattner797cb2f2004-03-13 22:01:26 +0000342
Chris Lattner650096a2003-02-27 20:27:08 +0000343 {
Chris Lattner61992f62002-09-26 16:17:31 +0000344 // The blocks that dominate NewBB are the blocks that dominate Header,
345 // minus Header, plus NewBB.
Chris Lattner650096a2003-02-27 20:27:08 +0000346 DominatorSet::DomSetType DomSet = DS.getDominators(Header);
Chris Lattner61992f62002-09-26 16:17:31 +0000347 DomSet.erase(Header); // Header does not dominate us...
Chris Lattner650096a2003-02-27 20:27:08 +0000348 DS.addBasicBlock(NewBB, DomSet);
Chris Lattner03a9e152002-09-29 21:41:38 +0000349
350 // The newly created basic block dominates all nodes dominated by Header.
Chris Lattnerdb5b8f42004-03-16 06:00:15 +0000351 for (df_iterator<DominatorTree::Node*> DFI = df_begin(PHDomTreeNode),
352 E = df_end(PHDomTreeNode); DFI != E; ++DFI)
353 DS.addDominator((*DFI)->getBlock(), NewBB);
Chris Lattner61992f62002-09-26 16:17:31 +0000354 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000355
Chris Lattner61992f62002-09-26 16:17:31 +0000356 // Update immediate dominator information if we have it...
357 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
358 // Whatever i-dominated the header node now immediately dominates NewBB
359 ID->addNewBlock(NewBB, ID->get(Header));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000360
Chris Lattner61992f62002-09-26 16:17:31 +0000361 // The preheader now is the immediate dominator for the header node...
362 ID->setImmediateDominator(Header, NewBB);
363 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000364
Chris Lattner650096a2003-02-27 20:27:08 +0000365 // Update dominance frontier information...
366 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
367 // The DF(NewBB) is just (DF(Header)-Header), because NewBB dominates
368 // everything that Header does, and it strictly dominates Header in
369 // addition.
370 assert(DF->find(Header) != DF->end() && "Header node doesn't have DF set?");
371 DominanceFrontier::DomSetType NewDFSet = DF->find(Header)->second;
372 NewDFSet.erase(Header);
373 DF->addBasicBlock(NewBB, NewDFSet);
374
375 // Now we must loop over all of the dominance frontiers in the function,
Misha Brukman4ace48e2003-09-09 21:54:45 +0000376 // replacing occurrences of Header with NewBB in some cases. If a block
Chris Lattner650096a2003-02-27 20:27:08 +0000377 // dominates a (now) predecessor of NewBB, but did not strictly dominate
378 // Header, it will have Header in it's DF set, but should now have NewBB in
379 // its set.
380 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
381 // Get all of the dominators of the predecessor...
382 const DominatorSet::DomSetType &PredDoms =
383 DS.getDominators(OutsideBlocks[i]);
384 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
385 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
386 BasicBlock *PredDom = *PDI;
387 // If the loop header is in DF(PredDom), then PredDom didn't dominate
388 // the header but did dominate a predecessor outside of the loop. Now
389 // we change this entry to include the preheader in the DF instead of
390 // the header.
391 DominanceFrontier::iterator DFI = DF->find(PredDom);
392 assert(DFI != DF->end() && "No dominance frontier for node?");
393 if (DFI->second.count(Header)) {
394 DF->removeFromFrontier(DFI, Header);
395 DF->addToFrontier(DFI, NewBB);
396 }
397 }
398 }
399 }
400}
401
Chris Lattner84170522004-04-13 05:05:33 +0000402/// RewriteLoopExitBlock - Ensure that the loop preheader dominates all exit
403/// blocks. This method is used to split exit blocks that have predecessors
404/// outside of the loop.
Chris Lattner82782632004-04-18 22:27:10 +0000405BasicBlock *LoopSimplify::RewriteLoopExitBlock(Loop *L, BasicBlock *Exit) {
Chris Lattner650096a2003-02-27 20:27:08 +0000406 DominatorSet &DS = getAnalysis<DominatorSet>();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000407
Chris Lattner650096a2003-02-27 20:27:08 +0000408 std::vector<BasicBlock*> LoopBlocks;
409 for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I)
410 if (L->contains(*I))
411 LoopBlocks.push_back(*I);
412
Chris Lattner10b2b052003-02-27 22:31:07 +0000413 assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
414 BasicBlock *NewBB = SplitBlockPredecessors(Exit, ".loopexit", LoopBlocks);
415
Chris Lattner4e2fbfb2003-02-27 21:50:19 +0000416 // Update Loop Information - we know that the new block will be in the parent
417 // loop of L.
418 if (Loop *Parent = L->getParentLoop())
419 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
Chris Lattner32a39c22003-02-28 03:07:54 +0000420
Chris Lattnerc4622a62003-10-13 00:37:13 +0000421 // Update dominator information (set, immdom, domtree, and domfrontier)
422 UpdateDomInfoForRevectoredPreds(NewBB, LoopBlocks);
Chris Lattner82782632004-04-18 22:27:10 +0000423 return NewBB;
Chris Lattnerc4622a62003-10-13 00:37:13 +0000424}
425
Chris Lattner84170522004-04-13 05:05:33 +0000426/// AddBlockAndPredsToSet - Add the specified block, and all of its
427/// predecessors, to the specified set, if it's not already in there. Stop
428/// predecessor traversal when we reach StopBlock.
429static void AddBlockAndPredsToSet(BasicBlock *BB, BasicBlock *StopBlock,
430 std::set<BasicBlock*> &Blocks) {
431 if (!Blocks.insert(BB).second) return; // already processed.
432 if (BB == StopBlock) return; // Stop here!
433
434 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
435 AddBlockAndPredsToSet(*I, StopBlock, Blocks);
436}
437
Chris Lattnera6e22812004-04-13 15:21:18 +0000438/// FindPHIToPartitionLoops - The first part of loop-nestification is to find a
439/// PHI node that tells us how to partition the loops.
Chris Lattner514e8432005-03-25 06:37:22 +0000440static PHINode *FindPHIToPartitionLoops(Loop *L, DominatorSet &DS,
441 AliasAnalysis *AA) {
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000442 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
443 PHINode *PN = cast<PHINode>(I);
Chris Lattnera6e22812004-04-13 15:21:18 +0000444 ++I;
Nate Begemanb3923212005-08-04 23:24:19 +0000445 if (Value *V = PN->hasConstantValue())
Chris Lattnere29d6342004-10-17 21:22:38 +0000446 if (!isa<Instruction>(V) || DS.dominates(cast<Instruction>(V), PN)) {
447 // This is a degenerate PHI already, don't modify it!
448 PN->replaceAllUsesWith(V);
Chris Lattner514e8432005-03-25 06:37:22 +0000449 if (AA) AA->deleteValue(PN);
Chris Lattnerdd3ec922005-03-06 21:35:38 +0000450 PN->eraseFromParent();
Chris Lattnere29d6342004-10-17 21:22:38 +0000451 continue;
452 }
453
454 // Scan this PHI node looking for a use of the PHI node by itself.
455 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
456 if (PN->getIncomingValue(i) == PN &&
457 L->contains(PN->getIncomingBlock(i)))
458 // We found something tasty to remove.
459 return PN;
Chris Lattnera6e22812004-04-13 15:21:18 +0000460 }
461 return 0;
462}
463
Chris Lattner84170522004-04-13 05:05:33 +0000464/// SeparateNestedLoop - If this loop has multiple backedges, try to pull one of
465/// them out into a nested loop. This is important for code that looks like
466/// this:
467///
468/// Loop:
469/// ...
470/// br cond, Loop, Next
471/// ...
472/// br cond2, Loop, Out
473///
474/// To identify this common case, we look at the PHI nodes in the header of the
475/// loop. PHI nodes with unchanging values on one backedge correspond to values
476/// that change in the "outer" loop, but not in the "inner" loop.
477///
478/// If we are able to separate out a loop, return the new outer loop that was
479/// created.
480///
481Loop *LoopSimplify::SeparateNestedLoop(Loop *L) {
Chris Lattner514e8432005-03-25 06:37:22 +0000482 PHINode *PN = FindPHIToPartitionLoops(L, getAnalysis<DominatorSet>(), AA);
Chris Lattnera6e22812004-04-13 15:21:18 +0000483 if (PN == 0) return 0; // No known way to partition.
Chris Lattner84170522004-04-13 05:05:33 +0000484
Chris Lattnera6e22812004-04-13 15:21:18 +0000485 // Pull out all predecessors that have varying values in the loop. This
486 // handles the case when a PHI node has multiple instances of itself as
487 // arguments.
Chris Lattner84170522004-04-13 05:05:33 +0000488 std::vector<BasicBlock*> OuterLoopPreds;
Chris Lattnera6e22812004-04-13 15:21:18 +0000489 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
490 if (PN->getIncomingValue(i) != PN ||
491 !L->contains(PN->getIncomingBlock(i)))
492 OuterLoopPreds.push_back(PN->getIncomingBlock(i));
Chris Lattner84170522004-04-13 05:05:33 +0000493
Chris Lattner89e959b2004-04-13 16:23:25 +0000494 BasicBlock *Header = L->getHeader();
Chris Lattner84170522004-04-13 05:05:33 +0000495 BasicBlock *NewBB = SplitBlockPredecessors(Header, ".outer", OuterLoopPreds);
496
497 // Update dominator information (set, immdom, domtree, and domfrontier)
498 UpdateDomInfoForRevectoredPreds(NewBB, OuterLoopPreds);
499
500 // Create the new outer loop.
501 Loop *NewOuter = new Loop();
502
503 LoopInfo &LI = getAnalysis<LoopInfo>();
504
505 // Change the parent loop to use the outer loop as its child now.
506 if (Loop *Parent = L->getParentLoop())
507 Parent->replaceChildLoopWith(L, NewOuter);
508 else
509 LI.changeTopLevelLoop(L, NewOuter);
510
511 // This block is going to be our new header block: add it to this loop and all
512 // parent loops.
513 NewOuter->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
514
515 // L is now a subloop of our outer loop.
516 NewOuter->addChildLoop(L);
517
Chris Lattner84170522004-04-13 05:05:33 +0000518 for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i)
519 NewOuter->addBlockEntry(L->getBlocks()[i]);
520
521 // Determine which blocks should stay in L and which should be moved out to
522 // the Outer loop now.
523 DominatorSet &DS = getAnalysis<DominatorSet>();
524 std::set<BasicBlock*> BlocksInL;
525 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header); PI!=E; ++PI)
526 if (DS.dominates(Header, *PI))
527 AddBlockAndPredsToSet(*PI, Header, BlocksInL);
528
529
530 // Scan all of the loop children of L, moving them to OuterLoop if they are
531 // not part of the inner loop.
532 for (Loop::iterator I = L->begin(); I != L->end(); )
533 if (BlocksInL.count((*I)->getHeader()))
534 ++I; // Loop remains in L
535 else
536 NewOuter->addChildLoop(L->removeChildLoop(I));
537
538 // Now that we know which blocks are in L and which need to be moved to
539 // OuterLoop, move any blocks that need it.
540 for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
541 BasicBlock *BB = L->getBlocks()[i];
542 if (!BlocksInL.count(BB)) {
543 // Move this block to the parent, updating the exit blocks sets
544 L->removeBlockFromLoop(BB);
545 if (LI[BB] == L)
546 LI.changeLoopFor(BB, NewOuter);
547 --i;
548 }
549 }
550
Chris Lattner84170522004-04-13 05:05:33 +0000551 return NewOuter;
552}
553
554
555
Chris Lattnerc4622a62003-10-13 00:37:13 +0000556/// InsertUniqueBackedgeBlock - This method is called when the specified loop
557/// has more than one backedge in it. If this occurs, revector all of these
558/// backedges to target a new basic block and have that block branch to the loop
559/// header. This ensures that loops have exactly one backedge.
560///
561void LoopSimplify::InsertUniqueBackedgeBlock(Loop *L) {
562 assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
563
564 // Get information about the loop
565 BasicBlock *Preheader = L->getLoopPreheader();
566 BasicBlock *Header = L->getHeader();
567 Function *F = Header->getParent();
568
569 // Figure out which basic blocks contain back-edges to the loop header.
570 std::vector<BasicBlock*> BackedgeBlocks;
571 for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I)
572 if (*I != Preheader) BackedgeBlocks.push_back(*I);
573
574 // Create and insert the new backedge block...
575 BasicBlock *BEBlock = new BasicBlock(Header->getName()+".backedge", F);
Chris Lattnera2960002003-11-21 16:52:05 +0000576 BranchInst *BETerminator = new BranchInst(Header, BEBlock);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000577
578 // Move the new backedge block to right after the last backedge block.
579 Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
580 F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000581
Chris Lattnerc4622a62003-10-13 00:37:13 +0000582 // Now that the block has been inserted into the function, create PHI nodes in
583 // the backedge block which correspond to any PHI nodes in the header block.
Alkis Evlogimenos3ce42ec2004-09-28 02:40:37 +0000584 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
585 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000586 PHINode *NewPN = new PHINode(PN->getType(), PN->getName()+".be",
587 BETerminator);
Chris Lattnerd8e20182005-01-29 00:39:08 +0000588 NewPN->reserveOperandSpace(BackedgeBlocks.size());
Chris Lattner514e8432005-03-25 06:37:22 +0000589 if (AA) AA->copyValue(PN, NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000590
591 // Loop over the PHI node, moving all entries except the one for the
592 // preheader over to the new PHI node.
593 unsigned PreheaderIdx = ~0U;
594 bool HasUniqueIncomingValue = true;
595 Value *UniqueValue = 0;
596 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
597 BasicBlock *IBB = PN->getIncomingBlock(i);
598 Value *IV = PN->getIncomingValue(i);
599 if (IBB == Preheader) {
600 PreheaderIdx = i;
601 } else {
602 NewPN->addIncoming(IV, IBB);
603 if (HasUniqueIncomingValue) {
604 if (UniqueValue == 0)
605 UniqueValue = IV;
606 else if (UniqueValue != IV)
607 HasUniqueIncomingValue = false;
608 }
609 }
610 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000611
Chris Lattnerc4622a62003-10-13 00:37:13 +0000612 // Delete all of the incoming values from the old PN except the preheader's
613 assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
614 if (PreheaderIdx != 0) {
615 PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
616 PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
617 }
Chris Lattnerd8e20182005-01-29 00:39:08 +0000618 // Nuke all entries except the zero'th.
619 for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
620 PN->removeIncomingValue(e-i, false);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000621
622 // Finally, add the newly constructed PHI node as the entry for the BEBlock.
623 PN->addIncoming(NewPN, BEBlock);
624
625 // As an optimization, if all incoming values in the new PhiNode (which is a
626 // subset of the incoming values of the old PHI node) have the same value,
627 // eliminate the PHI Node.
628 if (HasUniqueIncomingValue) {
629 NewPN->replaceAllUsesWith(UniqueValue);
Chris Lattner514e8432005-03-25 06:37:22 +0000630 if (AA) AA->deleteValue(NewPN);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000631 BEBlock->getInstList().erase(NewPN);
632 }
633 }
634
635 // Now that all of the PHI nodes have been inserted and adjusted, modify the
636 // backedge blocks to just to the BEBlock instead of the header.
637 for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
638 TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
639 for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
640 if (TI->getSuccessor(Op) == Header)
641 TI->setSuccessor(Op, BEBlock);
642 }
643
644 //===--- Update all analyses which we must preserve now -----------------===//
645
646 // Update Loop Information - we know that this block is now in the current
647 // loop and all parent loops.
648 L->addBasicBlockToLoop(BEBlock, getAnalysis<LoopInfo>());
649
Chris Lattnerc4622a62003-10-13 00:37:13 +0000650 // Update dominator information (set, immdom, domtree, and domfrontier)
651 UpdateDomInfoForRevectoredPreds(BEBlock, BackedgeBlocks);
652}
653
654/// UpdateDomInfoForRevectoredPreds - This method is used to update the four
655/// different kinds of dominator information (dominator sets, immediate
656/// dominators, dominator trees, and dominance frontiers) after a new block has
657/// been added to the CFG.
658///
Chris Lattner14ab84a2004-02-05 21:12:24 +0000659/// This only supports the case when an existing block (known as "NewBBSucc"),
660/// had some of its predecessors factored into a new basic block. This
Chris Lattnerc4622a62003-10-13 00:37:13 +0000661/// transformation inserts a new basic block ("NewBB"), with a single
Chris Lattner14ab84a2004-02-05 21:12:24 +0000662/// unconditional branch to NewBBSucc, and moves some predecessors of
663/// "NewBBSucc" to now branch to NewBB. These predecessors are listed in
664/// PredBlocks, even though they are the same as
665/// pred_begin(NewBB)/pred_end(NewBB).
Chris Lattnerc4622a62003-10-13 00:37:13 +0000666///
667void LoopSimplify::UpdateDomInfoForRevectoredPreds(BasicBlock *NewBB,
668 std::vector<BasicBlock*> &PredBlocks) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000669 assert(!PredBlocks.empty() && "No predblocks??");
Chris Lattnerc4622a62003-10-13 00:37:13 +0000670 assert(succ_begin(NewBB) != succ_end(NewBB) &&
671 ++succ_begin(NewBB) == succ_end(NewBB) &&
672 "NewBB should have a single successor!");
Chris Lattner14ab84a2004-02-05 21:12:24 +0000673 BasicBlock *NewBBSucc = *succ_begin(NewBB);
Chris Lattnerc4622a62003-10-13 00:37:13 +0000674 DominatorSet &DS = getAnalysis<DominatorSet>();
675
Chris Lattner146d0df2004-04-01 19:06:07 +0000676 // Update dominator information... The blocks that dominate NewBB are the
677 // intersection of the dominators of predecessors, plus the block itself.
678 //
679 DominatorSet::DomSetType NewBBDomSet = DS.getDominators(PredBlocks[0]);
680 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
681 set_intersect(NewBBDomSet, DS.getDominators(PredBlocks[i]));
682 NewBBDomSet.insert(NewBB); // All blocks dominate themselves...
683 DS.addBasicBlock(NewBB, NewBBDomSet);
684
Chris Lattner14ab84a2004-02-05 21:12:24 +0000685 // The newly inserted basic block will dominate existing basic blocks iff the
686 // PredBlocks dominate all of the non-pred blocks. If all predblocks dominate
687 // the non-pred blocks, then they all must be the same block!
Chris Lattner146d0df2004-04-01 19:06:07 +0000688 //
Chris Lattner14ab84a2004-02-05 21:12:24 +0000689 bool NewBBDominatesNewBBSucc = true;
690 {
691 BasicBlock *OnePred = PredBlocks[0];
692 for (unsigned i = 1, e = PredBlocks.size(); i != e; ++i)
693 if (PredBlocks[i] != OnePred) {
694 NewBBDominatesNewBBSucc = false;
695 break;
696 }
697
698 if (NewBBDominatesNewBBSucc)
699 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
700 PI != E; ++PI)
Chris Lattner2dd1c8d2004-02-05 23:20:59 +0000701 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000702 NewBBDominatesNewBBSucc = false;
703 break;
704 }
705 }
706
Chris Lattner146d0df2004-04-01 19:06:07 +0000707 // The other scenario where the new block can dominate its successors are when
708 // all predecessors of NewBBSucc that are not NewBB are dominated by NewBBSucc
709 // already.
710 if (!NewBBDominatesNewBBSucc) {
711 NewBBDominatesNewBBSucc = true;
712 for (pred_iterator PI = pred_begin(NewBBSucc), E = pred_end(NewBBSucc);
713 PI != E; ++PI)
714 if (*PI != NewBB && !DS.dominates(NewBBSucc, *PI)) {
715 NewBBDominatesNewBBSucc = false;
716 break;
717 }
718 }
Chris Lattner650096a2003-02-27 20:27:08 +0000719
Chris Lattner14ab84a2004-02-05 21:12:24 +0000720 // If NewBB dominates some blocks, then it will dominate all blocks that
Chris Lattnerc0c953f2004-02-05 22:33:26 +0000721 // NewBBSucc does.
Chris Lattner14ab84a2004-02-05 21:12:24 +0000722 if (NewBBDominatesNewBBSucc) {
723 BasicBlock *PredBlock = PredBlocks[0];
724 Function *F = NewBB->getParent();
725 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattnerc0c953f2004-02-05 22:33:26 +0000726 if (DS.dominates(NewBBSucc, I))
Chris Lattner14ab84a2004-02-05 21:12:24 +0000727 DS.addDominator(I, NewBB);
728 }
729
Chris Lattner650096a2003-02-27 20:27:08 +0000730 // Update immediate dominator information if we have it...
731 BasicBlock *NewBBIDom = 0;
732 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000733 // To find the immediate dominator of the new exit node, we trace up the
734 // immediate dominators of a predecessor until we find a basic block that
735 // dominates the exit block.
Chris Lattner650096a2003-02-27 20:27:08 +0000736 //
Chris Lattnerc4622a62003-10-13 00:37:13 +0000737 BasicBlock *Dom = PredBlocks[0]; // Some random predecessor...
Chris Lattner650096a2003-02-27 20:27:08 +0000738 while (!NewBBDomSet.count(Dom)) { // Loop until we find a dominator...
739 assert(Dom != 0 && "No shared dominator found???");
740 Dom = ID->get(Dom);
741 }
742
743 // Set the immediate dominator now...
744 ID->addNewBlock(NewBB, Dom);
745 NewBBIDom = Dom; // Reuse this if calculating DominatorTree info...
Chris Lattner14ab84a2004-02-05 21:12:24 +0000746
747 // If NewBB strictly dominates other blocks, we need to update their idom's
748 // now. The only block that need adjustment is the NewBBSucc block, whose
749 // idom should currently be set to PredBlocks[0].
Chris Lattner59fdf742004-04-01 19:21:46 +0000750 if (NewBBDominatesNewBBSucc)
Chris Lattner14ab84a2004-02-05 21:12:24 +0000751 ID->setImmediateDominator(NewBBSucc, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000752 }
753
754 // Update DominatorTree information if it is active.
755 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
Chris Lattner14ab84a2004-02-05 21:12:24 +0000756 // If we don't have ImmediateDominator info around, calculate the idom as
757 // above.
Chris Lattner650096a2003-02-27 20:27:08 +0000758 DominatorTree::Node *NewBBIDomNode;
759 if (NewBBIDom) {
760 NewBBIDomNode = DT->getNode(NewBBIDom);
761 } else {
Chris Lattnerc4622a62003-10-13 00:37:13 +0000762 NewBBIDomNode = DT->getNode(PredBlocks[0]); // Random pred
Chris Lattnerbb9d03b2003-09-11 16:26:13 +0000763 while (!NewBBDomSet.count(NewBBIDomNode->getBlock())) {
Chris Lattner650096a2003-02-27 20:27:08 +0000764 NewBBIDomNode = NewBBIDomNode->getIDom();
765 assert(NewBBIDomNode && "No shared dominator found??");
766 }
767 }
768
Chris Lattner14ab84a2004-02-05 21:12:24 +0000769 // Create the new dominator tree node... and set the idom of NewBB.
770 DominatorTree::Node *NewBBNode = DT->createNewNode(NewBB, NewBBIDomNode);
771
772 // If NewBB strictly dominates other blocks, then it is now the immediate
773 // dominator of NewBBSucc. Update the dominator tree as appropriate.
774 if (NewBBDominatesNewBBSucc) {
775 DominatorTree::Node *NewBBSuccNode = DT->getNode(NewBBSucc);
Chris Lattner14ab84a2004-02-05 21:12:24 +0000776 DT->changeImmediateDominator(NewBBSuccNode, NewBBNode);
777 }
Chris Lattner650096a2003-02-27 20:27:08 +0000778 }
779
780 // Update dominance frontier information...
781 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
Chris Lattner89e959b2004-04-13 16:23:25 +0000782 // If NewBB dominates NewBBSucc, then DF(NewBB) is now going to be the
783 // DF(PredBlocks[0]) without the stuff that the new block does not dominate
784 // a predecessor of.
Chris Lattner14ab84a2004-02-05 21:12:24 +0000785 if (NewBBDominatesNewBBSucc) {
786 DominanceFrontier::iterator DFI = DF->find(PredBlocks[0]);
787 if (DFI != DF->end()) {
788 DominanceFrontier::DomSetType Set = DFI->second;
789 // Filter out stuff in Set that we do not dominate a predecessor of.
790 for (DominanceFrontier::DomSetType::iterator SetI = Set.begin(),
791 E = Set.end(); SetI != E;) {
792 bool DominatesPred = false;
793 for (pred_iterator PI = pred_begin(*SetI), E = pred_end(*SetI);
794 PI != E; ++PI)
795 if (DS.dominates(NewBB, *PI))
796 DominatesPred = true;
797 if (!DominatesPred)
798 Set.erase(SetI++);
799 else
800 ++SetI;
801 }
Chris Lattner650096a2003-02-27 20:27:08 +0000802
Chris Lattner14ab84a2004-02-05 21:12:24 +0000803 DF->addBasicBlock(NewBB, Set);
804 }
805
806 } else {
807 // DF(NewBB) is {NewBBSucc} because NewBB does not strictly dominate
808 // NewBBSucc, but it does dominate itself (and there is an edge (NewBB ->
809 // NewBBSucc)). NewBBSucc is the single successor of NewBB.
810 DominanceFrontier::DomSetType NewDFSet;
811 NewDFSet.insert(NewBBSucc);
812 DF->addBasicBlock(NewBB, NewDFSet);
Chris Lattner89e959b2004-04-13 16:23:25 +0000813 }
Chris Lattnerc4622a62003-10-13 00:37:13 +0000814
Chris Lattner89e959b2004-04-13 16:23:25 +0000815 // Now we must loop over all of the dominance frontiers in the function,
816 // replacing occurrences of NewBBSucc with NewBB in some cases. All
817 // blocks that dominate a block in PredBlocks and contained NewBBSucc in
818 // their dominance frontier must be updated to contain NewBB instead.
819 //
820 for (unsigned i = 0, e = PredBlocks.size(); i != e; ++i) {
821 BasicBlock *Pred = PredBlocks[i];
822 // Get all of the dominators of the predecessor...
823 const DominatorSet::DomSetType &PredDoms = DS.getDominators(Pred);
824 for (DominatorSet::DomSetType::const_iterator PDI = PredDoms.begin(),
825 PDE = PredDoms.end(); PDI != PDE; ++PDI) {
826 BasicBlock *PredDom = *PDI;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000827
Chris Lattner89e959b2004-04-13 16:23:25 +0000828 // If the NewBBSucc node is in DF(PredDom), then PredDom didn't
829 // dominate NewBBSucc but did dominate a predecessor of it. Now we
830 // change this entry to include NewBB in the DF instead of NewBBSucc.
831 DominanceFrontier::iterator DFI = DF->find(PredDom);
832 assert(DFI != DF->end() && "No dominance frontier for node?");
833 if (DFI->second.count(NewBBSucc)) {
834 // If NewBBSucc should not stay in our dominator frontier, remove it.
835 // We remove it unless there is a predecessor of NewBBSucc that we
836 // dominate, but we don't strictly dominate NewBBSucc.
837 bool ShouldRemove = true;
838 if (PredDom == NewBBSucc || !DS.dominates(PredDom, NewBBSucc)) {
839 // Okay, we know that PredDom does not strictly dominate NewBBSucc.
840 // Check to see if it dominates any predecessors of NewBBSucc.
841 for (pred_iterator PI = pred_begin(NewBBSucc),
842 E = pred_end(NewBBSucc); PI != E; ++PI)
843 if (DS.dominates(PredDom, *PI)) {
844 ShouldRemove = false;
845 break;
846 }
Chris Lattner650096a2003-02-27 20:27:08 +0000847 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000848
Chris Lattner89e959b2004-04-13 16:23:25 +0000849 if (ShouldRemove)
850 DF->removeFromFrontier(DFI, NewBBSucc);
851 DF->addToFrontier(DFI, NewBB);
Chris Lattner650096a2003-02-27 20:27:08 +0000852 }
853 }
854 }
Chris Lattner650096a2003-02-27 20:27:08 +0000855 }
Chris Lattner61992f62002-09-26 16:17:31 +0000856}
Brian Gaeke960707c2003-11-11 22:41:34 +0000857