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"
46 static Statistic<> NumLCSSA("lcssa",
47 "Number of live out of a loop variables");
49 class LCSSA : public FunctionPass {
53 LoopInfo *LI; // Loop information
54 DominatorTree *DT; // Dominator Tree for the current Loop...
55 DominanceFrontier *DF; // Current Dominance Frontier
57 virtual bool runOnFunction(Function &F);
58 bool visitSubloop(Loop* L);
59 void processInstruction(Instruction* Instr,
60 const std::vector<BasicBlock*>& LoopBlocks,
61 const std::vector<BasicBlock*>& exitBlocks);
63 /// This transformation requires natural loop information & requires that
64 /// loop preheaders be inserted into the CFG. It maintains both of these,
65 /// as well as the CFG. It also requires dominator information.
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addRequiredID(LoopSimplifyID);
70 AU.addPreservedID(LoopSimplifyID);
71 AU.addRequired<LoopInfo>();
72 AU.addPreserved<LoopInfo>();
73 AU.addRequired<DominatorTree>();
74 AU.addRequired<DominanceFrontier>();
77 std::set<Instruction*> getLoopValuesUsedOutsideLoop(Loop *L,
78 const std::vector<BasicBlock*>& LoopBlocks);
79 Instruction *getValueDominatingBlock(BasicBlock *BB,
80 std::map<BasicBlock*, Instruction*> PotDoms);
83 RegisterOpt<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
86 FunctionPass *llvm::createLCSSAPass() { return new LCSSA(); }
88 bool LCSSA::runOnFunction(Function &F) {
90 LI = &getAnalysis<LoopInfo>();
91 DF = &getAnalysis<DominanceFrontier>();
92 DT = &getAnalysis<DominatorTree>();
94 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
95 changed |= visitSubloop(*I);
101 bool LCSSA::visitSubloop(Loop* L) {
102 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
105 // Speed up queries by creating a sorted list of blocks
106 std::vector<BasicBlock*> LoopBlocks(L->block_begin(), L->block_end());
107 std::sort(LoopBlocks.begin(), LoopBlocks.end());
109 std::set<Instruction*> AffectedValues = getLoopValuesUsedOutsideLoop(L,
112 // If no values are affected, we can save a lot of work, since we know that
113 // nothing will be changed.
114 if (AffectedValues.empty())
117 std::vector<BasicBlock*> exitBlocks;
118 L->getExitBlocks(exitBlocks);
121 // Iterate over all affected values for this loop and insert Phi nodes
122 // for them in the appropriate exit blocks
124 for (std::set<Instruction*>::iterator I = AffectedValues.begin(),
125 E = AffectedValues.end(); I != E; ++I) {
126 processInstruction(*I, LoopBlocks, exitBlocks);
129 return true; // FIXME: Should be more intelligent in our return value.
132 /// processInstruction -
133 void LCSSA::processInstruction(Instruction* Instr,
134 const std::vector<BasicBlock*>& LoopBlocks,
135 const std::vector<BasicBlock*>& exitBlocks)
137 ++NumLCSSA; // We are applying the transformation
139 std::map<BasicBlock*, Instruction*> Phis;
140 Phis[Instr->getParent()] = Instr;
142 // Phi nodes that need to be IDF-processed
143 std::vector<PHINode*> workList;
145 for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(),
146 BBE = exitBlocks.end(); BBI != BBE; ++BBI) {
147 PHINode *phi = new PHINode(Instr->getType(), "lcssa", (*BBI)->begin());
148 workList.push_back(phi);
151 // Since LoopSimplify has been run, we know that all of these predecessors
152 // are in the loop, so just hook them up in the obvious manner.
153 //for (pred_iterator PI = pred_begin(*BBI), PE = pred_end(*BBI); PI != PE;
155 // phi->addIncoming(Instr, *PI);
158 // Calculate the IDF of these LCSSA Phi nodes, inserting new Phi's where
159 // necessary. Keep track of these new Phi's in Phis.
160 while (!workList.empty()) {
161 PHINode *CurPHI = workList.back();
164 // Get the current Phi's DF, and insert Phi nodes. Add these new
165 // nodes to our worklist.
166 DominanceFrontier::const_iterator it = DF->find(CurPHI->getParent());
167 if (it != DF->end()) {
168 const DominanceFrontier::DomSetType &S = it->second;
169 for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
170 PE = S.end(); P != PE; ++P) {
172 // Still doesn't have operands...
173 PHINode *phi = new PHINode(Instr->getType(), "lcssa");
174 (*P)->getInstList().insert((*P)->front(), phi);
177 workList.push_back(phi);
182 // Get the predecessor blocks of the current Phi, and use them to hook up
183 // the operands of the current Phi to any members of DFPhis that dominate
184 // it. This is a nop for the Phis inserted directly in the exit blocks,
185 // since they are not dominated by any members of DFPhis.
186 for (pred_iterator PI = pred_begin(CurPHI->getParent()),
187 E = pred_end(CurPHI->getParent()); PI != E; ++PI)
188 CurPHI->addIncoming(getValueDominatingBlock(*PI, Phis),
192 // Find all uses of the affected value, and replace them with the
194 std::vector<Instruction*> Uses;
195 for (Instruction::use_iterator UI = Instr->use_begin(), UE = Instr->use_end();
197 Instruction* use = cast<Instruction>(*UI);
198 // Don't need to update uses within the loop body
199 if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(),
201 !(std::binary_search(exitBlocks.begin(), exitBlocks.end(),
202 use->getParent()) && isa<PHINode>(use)))
206 // Deliberately remove the initial instruction from Phis set.
207 Phis.erase(Instr->getParent());
209 for (std::vector<Instruction*>::iterator II = Uses.begin(), IE = Uses.end();
211 (*II)->replaceUsesOfWith(Instr, getValueDominatingBlock((*II)->getParent(),
216 /// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
217 /// are used by instructions outside of it.
218 std::set<Instruction*> LCSSA::getLoopValuesUsedOutsideLoop(Loop *L,
219 const std::vector<BasicBlock*>& LoopBlocks) {
221 // FIXME: For large loops, we may be able to avoid a lot of use-scanning
222 // by using dominance information. In particular, if a block does not
223 // dominate any of the loop exits, then none of the values defined in the
224 // block could be used outside the loop.
226 std::set<Instruction*> AffectedValues;
227 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
229 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
230 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
232 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
233 if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), UserBB)) {
234 AffectedValues.insert(I);
239 return AffectedValues;
242 Instruction *LCSSA::getValueDominatingBlock(BasicBlock *BB,
243 std::map<BasicBlock*, Instruction*> PotDoms) {
244 for (std::map<BasicBlock*, Instruction*>::iterator MI = PotDoms.begin(),
245 ME = PotDoms.end(); MI != ME; ++MI)
246 if (DT->getNode((*MI).first)->dominates(DT->getNode(BB)))
249 // FIXME: Should assert false