1 //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Owen Anderson and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms loops by placing phi nodes at the end of the loops for
11 // all values that are live across the loop boundary. For example, it turns
12 // the left into the right code:
14 // for (...) for (...)
19 // X3 = phi(X1, X2) X3 = phi(X1, X2)
20 // ... = X3 + 4 X4 = phi(X3)
23 // This is still valid LLVM; the extra phi nodes are purely redundant, and will
24 // be trivially eliminated by InstCombine. The major benefit of this
25 // transformation is that it makes many other loop optimizations, such as
26 // LoopUnswitching, simpler.
28 //===----------------------------------------------------------------------===//
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Function.h"
33 #include "llvm/Instructions.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Analysis/Dominators.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Support/CFG.h"
44 static Statistic<> NumLCSSA("lcssa",
45 "Number of live out of a loop variables");
47 class LCSSA : public FunctionPass {
51 LoopInfo *LI; // Loop information
52 DominatorTree *DT; // Dominator Tree for the current Loop...
53 DominanceFrontier *DF; // Current Dominance Frontier
55 virtual bool runOnFunction(Function &F);
56 bool visitSubloop(Loop* L);
57 void processInstruction(Instruction* Instr,
58 const std::vector<BasicBlock*>& LoopBlocks,
59 const std::vector<BasicBlock*>& exitBlocks);
61 /// This transformation requires natural loop information & requires that
62 /// loop preheaders be inserted into the CFG. It maintains both of these,
63 /// as well as the CFG. It also requires dominator information.
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addRequiredID(LoopSimplifyID);
68 AU.addPreservedID(LoopSimplifyID);
69 AU.addRequired<LoopInfo>();
70 AU.addRequired<DominatorTree>();
71 AU.addRequired<DominanceFrontier>();
74 std::set<Instruction*> getLoopValuesUsedOutsideLoop(Loop *L,
75 const std::vector<BasicBlock*>& LoopBlocks);
76 Instruction *getValueDominatingBlock(BasicBlock *BB,
77 std::map<BasicBlock*, Instruction*> PotDoms);
80 RegisterOpt<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
83 FunctionPass *llvm::createLCSSAPass() { return new LCSSA(); }
85 bool LCSSA::runOnFunction(Function &F) {
87 LI = &getAnalysis<LoopInfo>();
88 DF = &getAnalysis<DominanceFrontier>();
89 DT = &getAnalysis<DominatorTree>();
91 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
92 changed |= visitSubloop(*I);
98 bool LCSSA::visitSubloop(Loop* L) {
99 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
102 // Speed up queries by creating a sorted list of blocks
103 std::vector<BasicBlock*> LoopBlocks(L->block_begin(), L->block_end());
104 std::sort(LoopBlocks.begin(), LoopBlocks.end());
106 std::set<Instruction*> AffectedValues = getLoopValuesUsedOutsideLoop(L,
109 // If no values are affected, we can save a lot of work, since we know that
110 // nothing will be changed.
111 if (AffectedValues.empty())
114 std::vector<BasicBlock*> exitBlocks;
115 L->getExitBlocks(exitBlocks);
118 // Iterate over all affected values for this loop and insert Phi nodes
119 // for them in the appropriate exit blocks
121 for (std::set<Instruction*>::iterator I = AffectedValues.begin(),
122 E = AffectedValues.end(); I != E; ++I) {
123 processInstruction(*I, LoopBlocks, exitBlocks);
126 return true; // FIXME: Should be more intelligent in our return value.
129 /// processInstruction -
130 void LCSSA::processInstruction(Instruction* Instr,
131 const std::vector<BasicBlock*>& LoopBlocks,
132 const std::vector<BasicBlock*>& exitBlocks)
134 ++NumLCSSA; // We are applying the transformation
136 std::map<BasicBlock*, Instruction*> Phis;
138 // Add the base instruction to the Phis list. This makes tracking down
139 // the dominating values easier when we're filling in Phi nodes. This will
140 // be removed later, before we perform use replacement.
141 Phis[Instr->getParent()] = Instr;
143 // Phi nodes that need to be IDF-processed
144 std::vector<PHINode*> workList;
146 for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(),
147 BBE = exitBlocks.end(); BBI != BBE; ++BBI)
148 if (DT->getNode(Instr->getParent())->dominates(DT->getNode(*BBI))) {
149 PHINode *phi = new PHINode(Instr->getType(), "lcssa", (*BBI)->begin());
150 workList.push_back(phi);
154 // Phi nodes that need to have their incoming values filled.
155 std::vector<PHINode*> needIncomingValues;
157 // Calculate the IDF of these LCSSA Phi nodes, inserting new Phi's where
158 // necessary. Keep track of these new Phi's in Phis.
159 while (!workList.empty()) {
160 PHINode *CurPHI = workList.back();
163 // Even though we've removed this Phi from the work list, we still need
164 // to fill in its incoming values.
165 needIncomingValues.push_back(CurPHI);
167 // Get the current Phi's DF, and insert Phi nodes. Add these new
168 // nodes to our worklist.
169 DominanceFrontier::const_iterator it = DF->find(CurPHI->getParent());
170 if (it != DF->end()) {
171 const DominanceFrontier::DomSetType &S = it->second;
172 for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
173 PE = S.end(); P != PE; ++P) {
175 // Still doesn't have operands...
176 PHINode *phi = new PHINode(Instr->getType(), "lcssa", (*P)->begin());
179 workList.push_back(phi);
185 // Fill in all Phis we've inserted that need their incoming values filled in.
186 for (std::vector<PHINode*>::iterator IVI = needIncomingValues.begin(),
187 IVE = needIncomingValues.end(); IVI != IVE; ++IVI) {
188 for (pred_iterator PI = pred_begin((*IVI)->getParent()),
189 E = pred_end((*IVI)->getParent()); PI != E; ++PI)
190 (*IVI)->addIncoming(getValueDominatingBlock(*PI, Phis),
194 // Find all uses of the affected value, and replace them with the
196 std::vector<Instruction*> Uses;
197 for (Instruction::use_iterator UI = Instr->use_begin(), UE = Instr->use_end();
199 Instruction* use = cast<Instruction>(*UI);
200 // Don't need to update uses within the loop body
201 if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(),
203 !(std::binary_search(exitBlocks.begin(), exitBlocks.end(),
204 use->getParent()) && isa<PHINode>(use)))
208 // Deliberately remove the initial instruction from Phis set. It would mess
209 // up use-replacement.
210 Phis.erase(Instr->getParent());
212 for (std::vector<Instruction*>::iterator II = Uses.begin(), IE = Uses.end();
214 if (PHINode* phi = dyn_cast<PHINode>(*II)) {
215 for (unsigned int i = 0; i < phi->getNumIncomingValues(); ++i) {
216 Instruction* dominator =
217 getValueDominatingBlock(phi->getIncomingBlock(i), Phis);
219 if (phi->getIncomingValue(i) == Instr)
220 phi->setIncomingValue(i, dominator);
223 (*II)->replaceUsesOfWith(Instr,
224 getValueDominatingBlock((*II)->getParent(),
230 /// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
231 /// are used by instructions outside of it.
232 std::set<Instruction*> LCSSA::getLoopValuesUsedOutsideLoop(Loop *L,
233 const std::vector<BasicBlock*>& LoopBlocks) {
235 // FIXME: For large loops, we may be able to avoid a lot of use-scanning
236 // by using dominance information. In particular, if a block does not
237 // dominate any of the loop exits, then none of the values defined in the
238 // block could be used outside the loop.
240 std::set<Instruction*> AffectedValues;
241 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
243 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
244 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
246 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
247 if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), UserBB)) {
248 AffectedValues.insert(I);
253 return AffectedValues;
256 Instruction *LCSSA::getValueDominatingBlock(BasicBlock *BB,
257 std::map<BasicBlock*, Instruction*> PotDoms) {
258 DominatorTree::Node* bbNode = DT->getNode(BB);
259 while (bbNode != 0) {
260 std::map<BasicBlock*, Instruction*>::iterator I =
261 PotDoms.find(bbNode->getBlock());
262 if (I != PotDoms.end()) {
265 bbNode = bbNode->getIDom();
268 assert(0 && "No dominating value found.");