blob: 3fc9673d022464c284e62eb61de0ad9bba9c3e38 [file] [log] [blame]
Chris Lattnercf3056d2003-10-13 03:32:08 +00001//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner0bbe58f2001-11-26 18:41:20 +00009//
10// This file defines the LoopInfo class that is used to identify natural loops
11// and determine the loop depth of various nodes of the CFG. Note that the
12// loops identified may actually be several natural loops that share the same
13// header node... not just a single natural loop.
14//
15//===----------------------------------------------------------------------===//
16
Misha Brukman10d208d2004-01-30 17:26:24 +000017#include "llvm/Analysis/LoopInfo.h"
Chris Lattner92020fa2004-04-15 15:16:02 +000018#include "llvm/Constants.h"
19#include "llvm/Instructions.h"
20#include "llvm/Analysis/Dominators.h"
Chris Lattnera59cbb22002-07-27 01:12:17 +000021#include "llvm/Assembly/Writer.h"
Misha Brukman10d208d2004-01-30 17:26:24 +000022#include "llvm/Support/CFG.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000023#include "Support/DepthFirstIterator.h"
Chris Lattner0bbe58f2001-11-26 18:41:20 +000024#include <algorithm>
Chris Lattner46758a82004-04-12 20:26:17 +000025using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000026
Chris Lattner1e435162002-07-26 21:12:44 +000027static RegisterAnalysis<LoopInfo>
Chris Lattner17689df2002-07-30 16:27:52 +000028X("loops", "Natural Loop Construction", true);
Chris Lattner93193f82002-01-31 00:42:27 +000029
30//===----------------------------------------------------------------------===//
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000031// Loop implementation
Chris Lattner93193f82002-01-31 00:42:27 +000032//
Chris Lattner0f995552002-06-03 22:10:52 +000033bool Loop::contains(const BasicBlock *BB) const {
Chris Lattner0bbe58f2001-11-26 18:41:20 +000034 return find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
35}
36
Misha Brukman6b290a52002-10-11 05:31:10 +000037bool Loop::isLoopExit(const BasicBlock *BB) const {
Chris Lattner03f252f2003-09-24 22:18:35 +000038 for (succ_const_iterator SI = succ_begin(BB), SE = succ_end(BB);
Misha Brukman6b290a52002-10-11 05:31:10 +000039 SI != SE; ++SI) {
Chris Lattner5f82b8a2003-02-27 00:38:34 +000040 if (!contains(*SI))
Misha Brukman6b290a52002-10-11 05:31:10 +000041 return true;
42 }
43 return false;
44}
45
Chris Lattner2ef12362003-10-12 22:14:27 +000046/// getNumBackEdges - Calculate the number of back edges to the loop header.
47///
Misha Brukman6b290a52002-10-11 05:31:10 +000048unsigned Loop::getNumBackEdges() const {
Chris Lattner5f82b8a2003-02-27 00:38:34 +000049 unsigned NumBackEdges = 0;
50 BasicBlock *H = getHeader();
Misha Brukman6b290a52002-10-11 05:31:10 +000051
Chris Lattner2ef12362003-10-12 22:14:27 +000052 for (pred_iterator I = pred_begin(H), E = pred_end(H); I != E; ++I)
53 if (contains(*I))
54 ++NumBackEdges;
55
Chris Lattner5f82b8a2003-02-27 00:38:34 +000056 return NumBackEdges;
Misha Brukman6b290a52002-10-11 05:31:10 +000057}
58
Chris Lattner7dd46b02003-08-16 20:57:16 +000059void Loop::print(std::ostream &OS, unsigned Depth) const {
60 OS << std::string(Depth*2, ' ') << "Loop Containing: ";
Chris Lattnera59cbb22002-07-27 01:12:17 +000061
62 for (unsigned i = 0; i < getBlocks().size(); ++i) {
63 if (i) OS << ",";
Chris Lattner5f82b8a2003-02-27 00:38:34 +000064 WriteAsOperand(OS, getBlocks()[i], false);
Chris Lattnera59cbb22002-07-27 01:12:17 +000065 }
66 OS << "\n";
67
Chris Lattner329c1c62004-01-08 00:09:44 +000068 for (iterator I = begin(), E = end(); I != E; ++I)
69 (*I)->print(OS, Depth+2);
Chris Lattnera59cbb22002-07-27 01:12:17 +000070}
71
Chris Lattnerbb05f1e2003-02-28 16:54:45 +000072void Loop::dump() const {
73 print(std::cerr);
74}
75
Chris Lattner420df9b2003-02-22 21:33:11 +000076
Chris Lattnera59cbb22002-07-27 01:12:17 +000077//===----------------------------------------------------------------------===//
78// LoopInfo implementation
79//
Anand Shuklae0b6b782002-08-26 16:45:19 +000080void LoopInfo::stub() {}
Chris Lattnera59cbb22002-07-27 01:12:17 +000081
82bool LoopInfo::runOnFunction(Function &) {
83 releaseMemory();
84 Calculate(getAnalysis<DominatorSet>()); // Update
85 return false;
86}
87
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000088void LoopInfo::releaseMemory() {
Chris Lattner918c4ec2002-04-09 05:43:19 +000089 for (std::vector<Loop*>::iterator I = TopLevelLoops.begin(),
90 E = TopLevelLoops.end(); I != E; ++I)
91 delete *I; // Delete all of the loops...
92
93 BBMap.clear(); // Reset internal state of analysis
94 TopLevelLoops.clear();
95}
96
Chris Lattner93193f82002-01-31 00:42:27 +000097
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000098void LoopInfo::Calculate(const DominatorSet &DS) {
Chris Lattnera298d272002-04-28 00:15:57 +000099 BasicBlock *RootNode = DS.getRoot();
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000100
Chris Lattnera298d272002-04-28 00:15:57 +0000101 for (df_iterator<BasicBlock*> NI = df_begin(RootNode),
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000102 NE = df_end(RootNode); NI != NE; ++NI)
103 if (Loop *L = ConsiderForLoop(*NI, DS))
104 TopLevelLoops.push_back(L);
105
106 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
107 TopLevelLoops[i]->setLoopDepth(1);
108}
109
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000110void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000111 AU.setPreservesAll();
Chris Lattnerdd5b4952002-08-08 19:01:28 +0000112 AU.addRequired<DominatorSet>();
Chris Lattner93193f82002-01-31 00:42:27 +0000113}
114
Chris Lattnera59cbb22002-07-27 01:12:17 +0000115void LoopInfo::print(std::ostream &OS) const {
Chris Lattnerfce46ef2002-09-26 16:15:54 +0000116 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
117 TopLevelLoops[i]->print(OS);
Chris Lattner420df9b2003-02-22 21:33:11 +0000118#if 0
119 for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
120 E = BBMap.end(); I != E; ++I)
121 OS << "BB '" << I->first->getName() << "' level = "
122 << I->second->LoopDepth << "\n";
123#endif
Chris Lattnera59cbb22002-07-27 01:12:17 +0000124}
Chris Lattner93193f82002-01-31 00:42:27 +0000125
Chris Lattner39c987a2003-05-15 18:03:51 +0000126static bool isNotAlreadyContainedIn(Loop *SubLoop, Loop *ParentLoop) {
127 if (SubLoop == 0) return true;
128 if (SubLoop == ParentLoop) return false;
129 return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
130}
131
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000132Loop *LoopInfo::ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS) {
Chris Lattner699b3052002-09-26 05:32:50 +0000133 if (BBMap.find(BB) != BBMap.end()) return 0; // Haven't processed this node?
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000134
Chris Lattnera298d272002-04-28 00:15:57 +0000135 std::vector<BasicBlock *> TodoStack;
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000136
137 // Scan the predecessors of BB, checking to see if BB dominates any of
Chris Lattner99224ae2003-04-26 19:34:18 +0000138 // them. This identifies backedges which target this node...
Chris Lattnera298d272002-04-28 00:15:57 +0000139 for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I)
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000140 if (DS.dominates(BB, *I)) // If BB dominates it's predecessor...
141 TodoStack.push_back(*I);
142
Chris Lattner99224ae2003-04-26 19:34:18 +0000143 if (TodoStack.empty()) return 0; // No backedges to this block...
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000144
145 // Create a new loop to represent this basic block...
146 Loop *L = new Loop(BB);
147 BBMap[BB] = L;
148
Chris Lattner59dc1782003-10-22 16:41:21 +0000149 BasicBlock *EntryBlock = &BB->getParent()->getEntryBlock();
150
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000151 while (!TodoStack.empty()) { // Process all the nodes in the loop
Chris Lattnera298d272002-04-28 00:15:57 +0000152 BasicBlock *X = TodoStack.back();
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000153 TodoStack.pop_back();
154
Chris Lattner59dc1782003-10-22 16:41:21 +0000155 if (!L->contains(X) && // As of yet unprocessed??
156 DS.dominates(EntryBlock, X)) { // X is reachable from entry block?
Chris Lattner99224ae2003-04-26 19:34:18 +0000157 // Check to see if this block already belongs to a loop. If this occurs
158 // then we have a case where a loop that is supposed to be a child of the
159 // current loop was processed before the current loop. When this occurs,
160 // this child loop gets added to a part of the current loop, making it a
161 // sibling to the current loop. We have to reparent this loop.
162 if (Loop *SubLoop = const_cast<Loop*>(getLoopFor(X)))
Chris Lattner39c987a2003-05-15 18:03:51 +0000163 if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
Chris Lattner99224ae2003-04-26 19:34:18 +0000164 // Remove the subloop from it's current parent...
165 assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
166 Loop *SLP = SubLoop->ParentLoop; // SubLoopParent
167 std::vector<Loop*>::iterator I =
168 std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
169 assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?");
170 SLP->SubLoops.erase(I); // Remove from parent...
171
172 // Add the subloop to THIS loop...
173 SubLoop->ParentLoop = L;
174 L->SubLoops.push_back(SubLoop);
175 }
176
177 // Normal case, add the block to our loop...
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000178 L->Blocks.push_back(X);
Chris Lattner99224ae2003-04-26 19:34:18 +0000179
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000180 // Add all of the predecessors of X to the end of the work stack...
Chris Lattner455889a2002-02-12 22:39:50 +0000181 TodoStack.insert(TodoStack.end(), pred_begin(X), pred_end(X));
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000182 }
183 }
184
Chris Lattner420df9b2003-02-22 21:33:11 +0000185 // If there are any loops nested within this loop, create them now!
186 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
187 E = L->Blocks.end(); I != E; ++I)
188 if (Loop *NewLoop = ConsiderForLoop(*I, DS)) {
189 L->SubLoops.push_back(NewLoop);
190 NewLoop->ParentLoop = L;
191 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000192
Chris Lattner420df9b2003-02-22 21:33:11 +0000193 // Add the basic blocks that comprise this loop to the BBMap so that this
194 // loop can be found for them.
195 //
196 for (std::vector<BasicBlock*>::iterator I = L->Blocks.begin(),
197 E = L->Blocks.end(); I != E; ++I) {
198 std::map<BasicBlock*, Loop*>::iterator BBMI = BBMap.lower_bound(*I);
199 if (BBMI == BBMap.end() || BBMI->first != *I) // Not in map yet...
200 BBMap.insert(BBMI, std::make_pair(*I, L)); // Must be at this level
201 }
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000202
Chris Lattner7dd46b02003-08-16 20:57:16 +0000203 // Now that we have a list of all of the child loops of this loop, check to
204 // see if any of them should actually be nested inside of each other. We can
205 // accidentally pull loops our of their parents, so we must make sure to
206 // organize the loop nests correctly now.
207 {
208 std::map<BasicBlock*, Loop*> ContainingLoops;
209 for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
210 Loop *Child = L->SubLoops[i];
211 assert(Child->getParentLoop() == L && "Not proper child loop?");
212
213 if (Loop *ContainingLoop = ContainingLoops[Child->getHeader()]) {
214 // If there is already a loop which contains this loop, move this loop
215 // into the containing loop.
216 MoveSiblingLoopInto(Child, ContainingLoop);
217 --i; // The loop got removed from the SubLoops list.
218 } else {
219 // This is currently considered to be a top-level loop. Check to see if
220 // any of the contained blocks are loop headers for subloops we have
221 // already processed.
222 for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
223 Loop *&BlockLoop = ContainingLoops[Child->Blocks[b]];
224 if (BlockLoop == 0) { // Child block not processed yet...
225 BlockLoop = Child;
226 } else if (BlockLoop != Child) {
Chris Lattner169db9d2003-08-17 21:47:33 +0000227 Loop *SubLoop = BlockLoop;
228 // Reparent all of the blocks which used to belong to BlockLoops
229 for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
230 ContainingLoops[SubLoop->Blocks[j]] = Child;
231
Chris Lattner7dd46b02003-08-16 20:57:16 +0000232 // There is already a loop which contains this block, that means
233 // that we should reparent the loop which the block is currently
234 // considered to belong to to be a child of this loop.
Chris Lattner169db9d2003-08-17 21:47:33 +0000235 MoveSiblingLoopInto(SubLoop, Child);
Chris Lattner7dd46b02003-08-16 20:57:16 +0000236 --i; // We just shrunk the SubLoops list.
237 }
238 }
239 }
240 }
241 }
242
Chris Lattner0bbe58f2001-11-26 18:41:20 +0000243 return L;
244}
Chris Lattner699b3052002-09-26 05:32:50 +0000245
Chris Lattner7dd46b02003-08-16 20:57:16 +0000246/// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
247/// the NewParent Loop, instead of being a sibling of it.
248void LoopInfo::MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent) {
249 Loop *OldParent = NewChild->getParentLoop();
250 assert(OldParent && OldParent == NewParent->getParentLoop() &&
251 NewChild != NewParent && "Not sibling loops!");
252
253 // Remove NewChild from being a child of OldParent
254 std::vector<Loop*>::iterator I =
255 std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild);
256 assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
257 OldParent->SubLoops.erase(I); // Remove from parent's subloops list
258 NewChild->ParentLoop = 0;
259
260 InsertLoopInto(NewChild, NewParent);
261}
262
263/// InsertLoopInto - This inserts loop L into the specified parent loop. If the
264/// parent loop contains a loop which should contain L, the loop gets inserted
265/// into L instead.
266void LoopInfo::InsertLoopInto(Loop *L, Loop *Parent) {
267 BasicBlock *LHeader = L->getHeader();
268 assert(Parent->contains(LHeader) && "This loop should not be inserted here!");
269
270 // Check to see if it belongs in a child loop...
271 for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
272 if (Parent->SubLoops[i]->contains(LHeader)) {
273 InsertLoopInto(L, Parent->SubLoops[i]);
274 return;
275 }
276
277 // If not, insert it here!
278 Parent->SubLoops.push_back(L);
279 L->ParentLoop = Parent;
280}
281
Chris Lattner46758a82004-04-12 20:26:17 +0000282/// changeLoopFor - Change the top-level loop that contains BB to the
283/// specified loop. This should be used by transformations that restructure
284/// the loop hierarchy tree.
285void LoopInfo::changeLoopFor(BasicBlock *BB, Loop *L) {
286 Loop *&OldLoop = BBMap[BB];
287 assert(OldLoop && "Block not in a loop yet!");
288 OldLoop = L;
289}
Chris Lattner7dd46b02003-08-16 20:57:16 +0000290
Chris Lattner46758a82004-04-12 20:26:17 +0000291/// changeTopLevelLoop - Replace the specified loop in the top-level loops
292/// list with the indicated loop.
293void LoopInfo::changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
294 std::vector<Loop*>::iterator I = std::find(TopLevelLoops.begin(),
295 TopLevelLoops.end(), OldLoop);
296 assert(I != TopLevelLoops.end() && "Old loop not at top level!");
297 *I = NewLoop;
298 assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
299 "Loops already embedded into a subloop!");
300}
Chris Lattner7dd46b02003-08-16 20:57:16 +0000301
Chris Lattner24199db2004-04-18 05:38:05 +0000302/// removeLoop - This removes the specified top-level loop from this loop info
303/// object. The loop is not deleted, as it will presumably be inserted into
304/// another loop.
305Loop *LoopInfo::removeLoop(iterator I) {
306 assert(I != end() && "Cannot remove end iterator!");
307 Loop *L = *I;
308 assert(L->getParentLoop() == 0 && "Not a top-level loop!");
309 TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
310 return L;
311}
312
Chris Lattner3048bd12004-04-18 06:54:48 +0000313/// removeBlock - This method completely removes BB from all data structures,
314/// including all of the Loop objects it is nested in and our mapping from
315/// BasicBlocks to loops.
316void LoopInfo::removeBlock(BasicBlock *BB) {
317 std::map<BasicBlock *, Loop*>::iterator I = BBMap.find(BB);
318 if (I != BBMap.end()) {
319 for (Loop *L = I->second; L; L = L->getParentLoop())
320 L->removeBlockFromLoop(BB);
321
322 BBMap.erase(I);
323 }
324}
Chris Lattner24199db2004-04-18 05:38:05 +0000325
326
Chris Lattner92020fa2004-04-15 15:16:02 +0000327//===----------------------------------------------------------------------===//
328// APIs for simple analysis of the loop.
329//
330
Chris Lattnerf1ab4b42004-04-18 22:14:10 +0000331/// getExitBlocks - Return all of the successor blocks of this loop. These
332/// are the blocks _outside of the current loop_ which are branched to.
333///
334void Loop::getExitBlocks(std::vector<BasicBlock*> &Blocks) const {
335 for (std::vector<BasicBlock*>::const_iterator BI = Blocks.begin(),
336 BE = Blocks.end(); BI != BE; ++BI)
337 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I)
338 if (!contains(*I)) // Not in current loop?
339 Blocks.push_back(*I); // It must be an exit block...
340}
341
342
Chris Lattner699b3052002-09-26 05:32:50 +0000343/// getLoopPreheader - If there is a preheader for this loop, return it. A
344/// loop has a preheader if there is only one edge to the header of the loop
345/// from outside of the loop. If this is the case, the block branching to the
Chris Lattner92020fa2004-04-15 15:16:02 +0000346/// header of the loop is the preheader node.
Chris Lattner699b3052002-09-26 05:32:50 +0000347///
Chris Lattner92020fa2004-04-15 15:16:02 +0000348/// This method returns null if there is no preheader for the loop.
Chris Lattner699b3052002-09-26 05:32:50 +0000349///
350BasicBlock *Loop::getLoopPreheader() const {
351 // Keep track of nodes outside the loop branching to the header...
352 BasicBlock *Out = 0;
353
354 // Loop over the predecessors of the header node...
355 BasicBlock *Header = getHeader();
356 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
357 PI != PE; ++PI)
Chris Lattnerc8f25d92002-09-29 22:59:29 +0000358 if (!contains(*PI)) { // If the block is not in the loop...
359 if (Out && Out != *PI)
360 return 0; // Multiple predecessors outside the loop
Chris Lattner699b3052002-09-26 05:32:50 +0000361 Out = *PI;
362 }
Chris Lattner5a8a2912003-02-27 21:51:38 +0000363
364 // Make sure there is only one exit out of the preheader...
365 succ_iterator SI = succ_begin(Out);
366 ++SI;
367 if (SI != succ_end(Out))
368 return 0; // Multiple exits from the block, must not be a preheader.
369
Chris Lattner699b3052002-09-26 05:32:50 +0000370
371 // If there is exactly one preheader, return it. If there was zero, then Out
372 // is still null.
373 return Out;
374}
375
Chris Lattner92020fa2004-04-15 15:16:02 +0000376/// getCanonicalInductionVariable - Check to see if the loop has a canonical
377/// induction variable: an integer recurrence that starts at 0 and increments by
378/// one each time through the loop. If so, return the phi node that corresponds
379/// to it.
380///
381PHINode *Loop::getCanonicalInductionVariable() const {
382 BasicBlock *H = getHeader();
383
384 BasicBlock *Incoming = 0, *Backedge = 0;
385 pred_iterator PI = pred_begin(H);
386 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
387 Backedge = *PI++;
388 if (PI == pred_end(H)) return 0; // dead loop
389 Incoming = *PI++;
390 if (PI != pred_end(H)) return 0; // multiple backedges?
391
392 if (contains(Incoming)) {
393 if (contains(Backedge))
394 return 0;
395 std::swap(Incoming, Backedge);
396 } else if (!contains(Backedge))
397 return 0;
398
399 // Loop over all of the PHI nodes, looking for a canonical indvar.
400 for (BasicBlock::iterator I = H->begin();
401 PHINode *PN = dyn_cast<PHINode>(I); ++I)
402 if (Instruction *Inc =
403 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
404 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
405 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
406 if (CI->equalsInt(1))
407 return PN;
408
409 return 0;
410}
411
412/// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
413/// the canonical induction variable value for the "next" iteration of the loop.
414/// This always succeeds if getCanonicalInductionVariable succeeds.
415///
416Instruction *Loop::getCanonicalInductionVariableIncrement() const {
417 if (PHINode *PN = getCanonicalInductionVariable()) {
418 bool P1InLoop = contains(PN->getIncomingBlock(1));
419 return cast<Instruction>(PN->getIncomingValue(P1InLoop));
420 }
421 return 0;
422}
423
424/// getTripCount - Return a loop-invariant LLVM value indicating the number of
425/// times the loop will be executed. Note that this means that the backedge of
426/// the loop executes N-1 times. If the trip-count cannot be determined, this
427/// returns null.
428///
429Value *Loop::getTripCount() const {
430 // Canonical loops will end with a 'setne I, V', where I is the incremented
431 // canonical induction variable and V is the trip count of the loop.
432 Instruction *Inc = getCanonicalInductionVariableIncrement();
Chris Lattner24199db2004-04-18 05:38:05 +0000433 if (Inc == 0) return 0;
Chris Lattner92020fa2004-04-15 15:16:02 +0000434 PHINode *IV = cast<PHINode>(Inc->getOperand(0));
435
436 BasicBlock *BackedgeBlock =
437 IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
438
439 if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
440 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BI->getCondition()))
441 if (SCI->getOperand(0) == Inc)
442 if (BI->getSuccessor(0) == getHeader()) {
443 if (SCI->getOpcode() == Instruction::SetNE)
444 return SCI->getOperand(1);
445 } else if (SCI->getOpcode() == Instruction::SetEQ) {
446 return SCI->getOperand(1);
447 }
448
449 return 0;
450}
451
452
453//===-------------------------------------------------------------------===//
454// APIs for updating loop information after changing the CFG
455//
456
Chris Lattner699b3052002-09-26 05:32:50 +0000457/// addBasicBlockToLoop - This function is used by other analyses to update loop
458/// information. NewBB is set to be a new member of the current loop. Because
459/// of this, it is added as a member of all parent loops, and is added to the
460/// specified LoopInfo object as being in the current basic block. It is not
461/// valid to replace the loop header with this method.
462///
463void Loop::addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI) {
Chris Lattner46758a82004-04-12 20:26:17 +0000464 assert((Blocks.empty() || LI[getHeader()] == this) &&
465 "Incorrect LI specified for this loop!");
Chris Lattner699b3052002-09-26 05:32:50 +0000466 assert(NewBB && "Cannot add a null basic block to the loop!");
467 assert(LI[NewBB] == 0 && "BasicBlock already in the loop!");
468
469 // Add the loop mapping to the LoopInfo object...
470 LI.BBMap[NewBB] = this;
471
472 // Add the basic block to this loop and all parent loops...
473 Loop *L = this;
474 while (L) {
475 L->Blocks.push_back(NewBB);
476 L = L->getParentLoop();
477 }
478}
Chris Lattner5f82b8a2003-02-27 00:38:34 +0000479
Chris Lattner46758a82004-04-12 20:26:17 +0000480/// replaceChildLoopWith - This is used when splitting loops up. It replaces
481/// the OldChild entry in our children list with NewChild, and updates the
482/// parent pointers of the two loops as appropriate.
483void Loop::replaceChildLoopWith(Loop *OldChild, Loop *NewChild) {
484 assert(OldChild->ParentLoop == this && "This loop is already broken!");
485 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
486 std::vector<Loop*>::iterator I = std::find(SubLoops.begin(), SubLoops.end(),
487 OldChild);
488 assert(I != SubLoops.end() && "OldChild not in loop!");
489 *I = NewChild;
490 OldChild->ParentLoop = 0;
491 NewChild->ParentLoop = this;
492
493 // Update the loop depth of the new child.
494 NewChild->setLoopDepth(LoopDepth+1);
495}
496
497/// addChildLoop - Add the specified loop to be a child of this loop.
498///
499void Loop::addChildLoop(Loop *NewChild) {
500 assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
501 NewChild->ParentLoop = this;
502 SubLoops.push_back(NewChild);
503
504 // Update the loop depth of the new child.
505 NewChild->setLoopDepth(LoopDepth+1);
506}
507
508template<typename T>
509static void RemoveFromVector(std::vector<T*> &V, T *N) {
510 typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
511 assert(I != V.end() && "N is not in this list!");
512 V.erase(I);
513}
514
515/// removeChildLoop - This removes the specified child from being a subloop of
516/// this loop. The loop is not deleted, as it will presumably be inserted
517/// into another loop.
518Loop *Loop::removeChildLoop(iterator I) {
519 assert(I != SubLoops.end() && "Cannot remove end iterator!");
520 Loop *Child = *I;
521 assert(Child->ParentLoop == this && "Child is not a child of this loop!");
522 SubLoops.erase(SubLoops.begin()+(I-begin()));
523 Child->ParentLoop = 0;
524 return Child;
525}
526
527
528/// removeBlockFromLoop - This removes the specified basic block from the
529/// current loop, updating the Blocks and ExitBlocks lists as appropriate. This
530/// does not update the mapping in the LoopInfo class.
531void Loop::removeBlockFromLoop(BasicBlock *BB) {
532 RemoveFromVector(Blocks, BB);
Chris Lattner46758a82004-04-12 20:26:17 +0000533}