blob: 76cc32e2a42eeb2f904d33ea1207a2e635a05789 [file] [log] [blame]
Chris Lattner38acf9e2002-09-26 16:17:31 +00001//===- LoopPreheaders.cpp - Loop Preheader Insertion Pass -----------------===//
2//
3// Insert Loop pre-headers into the CFG for each function in the module. This
4// pass updates loop information and dominator information.
5//
6//===----------------------------------------------------------------------===//
7
8#include "llvm/Transforms/Scalar.h"
9#include "llvm/Analysis/Dominators.h"
10#include "llvm/Analysis/LoopInfo.h"
11#include "llvm/Function.h"
12#include "llvm/iTerminators.h"
13#include "llvm/iPHINode.h"
14#include "llvm/Constant.h"
15#include "llvm/Support/CFG.h"
16#include "Support/StatisticReporter.h"
17
18namespace {
19 Statistic<> NumInserted("preheaders\t- Number of pre-header nodes inserted");
20
21 struct Preheaders : public FunctionPass {
22 virtual bool runOnFunction(Function &F);
23
24 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
25 // We need loop information to identify the loops...
26 AU.addRequired<LoopInfo>();
27
28 AU.addPreserved<LoopInfo>();
29 AU.addPreserved<DominatorSet>();
30 AU.addPreserved<ImmediateDominators>();
31 AU.addPreserved<DominatorTree>();
32 AU.addPreservedID(BreakCriticalEdgesID); // No crit edges added....
33 }
34 private:
35 bool ProcessLoop(Loop *L);
36 void InsertPreheaderForLoop(Loop *L);
37 };
38
Chris Lattner0bd36162002-09-26 16:37:37 +000039 RegisterOpt<Preheaders> X("preheaders", "Natural loop pre-header insertion");
Chris Lattner38acf9e2002-09-26 16:17:31 +000040}
41
42// Publically exposed interface to pass...
43const PassInfo *LoopPreheadersID = X.getPassInfo();
44Pass *createLoopPreheaderInsertionPass() { return new Preheaders(); }
45
46
47/// runOnFunction - Run down all loops in the CFG (recursively, but we could do
48/// it in any convenient order) inserting preheaders...
49///
50bool Preheaders::runOnFunction(Function &F) {
51 bool Changed = false;
52 LoopInfo &LI = getAnalysis<LoopInfo>();
53
54 for (unsigned i = 0, e = LI.getTopLevelLoops().size(); i != e; ++i)
55 Changed |= ProcessLoop(LI.getTopLevelLoops()[i]);
56
57 return Changed;
58}
59
60
61/// ProcessLoop - Walk the loop structure in depth first order, ensuring that
62/// all loops have preheaders.
63///
64bool Preheaders::ProcessLoop(Loop *L) {
65 bool Changed = false;
66
67 // Does the loop already have a preheader? If so, don't modify the loop...
68 if (L->getLoopPreheader() == 0) {
69 InsertPreheaderForLoop(L);
70 NumInserted++;
71 Changed = true;
72 }
73
74 const std::vector<Loop*> &SubLoops = L->getSubLoops();
75 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
76 Changed |= ProcessLoop(SubLoops[i]);
77 return Changed;
78}
79
80
81/// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
82/// preheader, this method is called to insert one. This method has two phases:
83/// preheader insertion and analysis updating.
84///
85void Preheaders::InsertPreheaderForLoop(Loop *L) {
86 BasicBlock *Header = L->getHeader();
87
88 // Compute the set of predecessors of the loop that are not in the loop.
89 std::vector<BasicBlock*> OutsideBlocks;
90 for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
91 PI != PE; ++PI)
92 if (!L->contains(*PI)) // Coming in from outside the loop?
93 OutsideBlocks.push_back(*PI); // Keep track of it...
94
95 assert(OutsideBlocks.size() != 1 && "Loop already has a preheader!");
96
97 // Create new basic block, insert right before the header of the loop...
98 BasicBlock *NewBB = new BasicBlock(Header->getName()+".preheader", Header);
99
100 // The preheader first gets an unconditional branch to the loop header...
101 BranchInst *BI = new BranchInst(Header);
102 NewBB->getInstList().push_back(BI);
103
104 // For every PHI node in the loop body, insert a PHI node into NewBB where
105 // the incoming values from the out of loop edges are moved to NewBB. We
106 // have two possible cases here. If the loop is dead, we just insert dummy
107 // entries into the PHI nodes for the new edge. If the loop is not dead, we
108 // move the incoming edges in Header into new PHI nodes in NewBB.
109 //
110 if (!OutsideBlocks.empty()) { // Is the loop not obviously dead?
111 for (BasicBlock::iterator I = Header->begin();
112 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
113
114 // Create the new PHI node, insert it into NewBB at the end of the block
115 PHINode *NewPHI = new PHINode(PN->getType(), PN->getName()+".ph", BI);
116
117 // Move all of the edges from blocks outside the loop to the new PHI
118 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
119 Value *V = PN->removeIncomingValue(OutsideBlocks[i]);
120 NewPHI->addIncoming(V, OutsideBlocks[i]);
121 }
122
123 // Add an incoming value to the PHI node in the loop for the preheader
124 // edge
125 PN->addIncoming(NewPHI, NewBB);
126 }
127
128 // Now that the PHI nodes are updated, actually move the edges from
129 // OutsideBlocks to point to NewBB instead of Header.
130 //
131 for (unsigned i = 0, e = OutsideBlocks.size(); i != e; ++i) {
132 TerminatorInst *TI = OutsideBlocks[i]->getTerminator();
133 for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s)
134 if (TI->getSuccessor(s) == Header)
135 TI->setSuccessor(s, NewBB);
136 }
137
138 } else { // Otherwise the loop is dead...
139 for (BasicBlock::iterator I = Header->begin();
140 PHINode *PN = dyn_cast<PHINode>(&*I); ++I)
141 // Insert dummy values as the incoming value...
142 PN->addIncoming(Constant::getNullValue(PN->getType()), NewBB);
143 }
144
145
146 //===--------------------------------------------------------------------===//
147 // Update analysis results now that we have preformed the transformation
148 //
149
150 // We know that we have loop information to update... update it now.
151 if (Loop *Parent = L->getParentLoop())
152 Parent->addBasicBlockToLoop(NewBB, getAnalysis<LoopInfo>());
153
154 // Update dominator information if it is around...
155 if (DominatorSet *DS = getAnalysisToUpdate<DominatorSet>()) {
156 // We need to add information about the fact that NewBB dominates Header.
157 DS->addDominator(Header, NewBB);
158
159 // The blocks that dominate NewBB are the blocks that dominate Header,
160 // minus Header, plus NewBB.
161 DominatorSet::DomSetType DomSet = DS->getDominators(Header);
162 DomSet.erase(Header); // Header does not dominate us...
163 DS->addBasicBlock(NewBB, DomSet);
164 }
165
166 // Update immediate dominator information if we have it...
167 if (ImmediateDominators *ID = getAnalysisToUpdate<ImmediateDominators>()) {
168 // Whatever i-dominated the header node now immediately dominates NewBB
169 ID->addNewBlock(NewBB, ID->get(Header));
170
171 // The preheader now is the immediate dominator for the header node...
172 ID->setImmediateDominator(Header, NewBB);
173 }
174
175 // Update DominatorTree information if it is active.
176 if (DominatorTree *DT = getAnalysisToUpdate<DominatorTree>()) {
177 // The immediate dominator of the preheader is the immediate dominator of
178 // the old header.
179 //
180 DominatorTree::Node *HeaderNode = DT->getNode(Header);
181 DominatorTree::Node *PHNode = DT->createNewNode(NewBB, HeaderNode);
182
183 // Change the header node so that PNHode is the new immediate dominator
184 DT->changeImmediateDominator(HeaderNode, PHNode);
185 }
186}
187
188