1 //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 #define DEBUG_TYPE "lcssa"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Constants.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Function.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/Analysis/Dominators.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Analysis/ScalarEvolution.h"
39 #include "llvm/Transforms/Utils/SSAUpdater.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/Support/PredIteratorCache.h"
45 STATISTIC(NumLCSSA, "Number of live out of a loop variables");
48 struct LCSSA : public LoopPass {
49 static char ID; // Pass identification, replacement for typeid
50 LCSSA() : LoopPass(ID) {
51 initializeLCSSAPass(*PassRegistry::getPassRegistry());
54 // Cached analysis information for the current function.
56 std::vector<BasicBlock*> LoopBlocks;
57 PredIteratorCache PredCache;
60 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
62 /// This transformation requires natural loop information & requires that
63 /// loop preheaders be inserted into the CFG. It maintains both of these,
64 /// as well as the CFG. It also requires dominator information.
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 AU.addRequired<DominatorTree>();
70 AU.addPreserved<DominatorTree>();
71 AU.addPreserved<DominanceFrontier>();
72 AU.addRequired<LoopInfo>();
73 AU.addPreserved<LoopInfo>();
74 AU.addPreservedID(LoopSimplifyID);
75 AU.addPreserved<ScalarEvolution>();
78 bool ProcessInstruction(Instruction *Inst,
79 const SmallVectorImpl<BasicBlock*> &ExitBlocks);
81 /// verifyAnalysis() - Verify loop nest.
82 virtual void verifyAnalysis() const {
83 // Check the special guarantees that LCSSA makes.
84 assert(L->isLCSSAForm(*DT) && "LCSSA form not preserved!");
87 /// inLoop - returns true if the given block is within the current loop
88 bool inLoop(BasicBlock *B) const {
89 return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
95 INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
96 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
97 INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
98 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
99 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
100 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
101 INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
103 Pass *llvm::createLCSSAPass() { return new LCSSA(); }
104 char &llvm::LCSSAID = LCSSA::ID;
107 /// BlockDominatesAnExit - Return true if the specified block dominates at least
108 /// one of the blocks in the specified list.
109 static bool BlockDominatesAnExit(BasicBlock *BB,
110 const SmallVectorImpl<BasicBlock*> &ExitBlocks,
112 DomTreeNode *DomNode = DT->getNode(BB);
113 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
114 if (DT->dominates(DomNode, DT->getNode(ExitBlocks[i])))
121 /// runOnFunction - Process all loops in the function, inner-most out.
122 bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {
125 DT = &getAnalysis<DominatorTree>();
127 // Get the set of exiting blocks.
128 SmallVector<BasicBlock*, 8> ExitBlocks;
129 L->getExitBlocks(ExitBlocks);
131 if (ExitBlocks.empty())
134 // Speed up queries by creating a sorted vector of blocks.
136 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
137 array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());
139 // Look at all the instructions in the loop, checking to see if they have uses
140 // outside the loop. If so, rewrite those uses.
141 bool MadeChange = false;
143 for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();
145 BasicBlock *BB = *BBI;
147 // For large loops, avoid use-scanning by using dominance information: In
148 // particular, if a block does not dominate any of the loop exits, then none
149 // of the values defined in the block could be used outside the loop.
150 if (!BlockDominatesAnExit(BB, ExitBlocks, DT))
153 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
155 // Reject two common cases fast: instructions with no uses (like stores)
156 // and instructions with one use that is in the same block as this.
157 if (I->use_empty() ||
158 (I->hasOneUse() && I->use_back()->getParent() == BB &&
159 !isa<PHINode>(I->use_back())))
162 MadeChange |= ProcessInstruction(I, ExitBlocks);
166 assert(L->isLCSSAForm(*DT));
172 /// isExitBlock - Return true if the specified block is in the list.
173 static bool isExitBlock(BasicBlock *BB,
174 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
175 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
176 if (ExitBlocks[i] == BB)
181 /// ProcessInstruction - Given an instruction in the loop, check to see if it
182 /// has any uses that are outside the current loop. If so, insert LCSSA PHI
183 /// nodes and rewrite the uses.
184 bool LCSSA::ProcessInstruction(Instruction *Inst,
185 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
186 SmallVector<Use*, 16> UsesToRewrite;
188 BasicBlock *InstBB = Inst->getParent();
190 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
193 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
194 if (PHINode *PN = dyn_cast<PHINode>(U))
195 UserBB = PN->getIncomingBlock(UI);
197 if (InstBB != UserBB && !inLoop(UserBB))
198 UsesToRewrite.push_back(&UI.getUse());
201 // If there are no uses outside the loop, exit with no change.
202 if (UsesToRewrite.empty()) return false;
204 ++NumLCSSA; // We are applying the transformation
206 // Invoke instructions are special in that their result value is not available
207 // along their unwind edge. The code below tests to see whether DomBB dominates
208 // the value, so adjust DomBB to the normal destination block, which is
209 // effectively where the value is first usable.
210 BasicBlock *DomBB = Inst->getParent();
211 if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))
212 DomBB = Inv->getNormalDest();
214 DomTreeNode *DomNode = DT->getNode(DomBB);
216 SSAUpdater SSAUpdate;
217 SSAUpdate.Initialize(Inst->getType(), Inst->getName());
219 // Insert the LCSSA phi's into all of the exit blocks dominated by the
220 // value, and add them to the Phi's map.
221 for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),
222 BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {
223 BasicBlock *ExitBB = *BBI;
224 if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;
226 // If we already inserted something for this BB, don't reprocess it.
227 if (SSAUpdate.HasValueForBlock(ExitBB)) continue;
229 PHINode *PN = PHINode::Create(Inst->getType(), Inst->getName()+".lcssa",
231 PN->reserveOperandSpace(PredCache.GetNumPreds(ExitBB));
233 // Add inputs from inside the loop for this PHI.
234 for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
235 PN->addIncoming(Inst, *PI);
237 // If the exit block has a predecessor not within the loop, arrange for
238 // the incoming value use corresponding to that predecessor to be
239 // rewritten in terms of a different LCSSA PHI.
241 UsesToRewrite.push_back(
243 PN->getOperandNumForIncomingValue(PN->getNumIncomingValues()-1)));
246 // Remember that this phi makes the value alive in this block.
247 SSAUpdate.AddAvailableValue(ExitBB, PN);
250 // Rewrite all uses outside the loop in terms of the new PHIs we just
252 for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {
253 // If this use is in an exit block, rewrite to use the newly inserted PHI.
254 // This is required for correctness because SSAUpdate doesn't handle uses in
255 // the same block. It assumes the PHI we inserted is at the end of the
257 Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());
258 BasicBlock *UserBB = User->getParent();
259 if (PHINode *PN = dyn_cast<PHINode>(User))
260 UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);
262 if (isa<PHINode>(UserBB->begin()) &&
263 isExitBlock(UserBB, ExitBlocks)) {
264 UsesToRewrite[i]->set(UserBB->begin());
268 // Otherwise, do full PHI insertion.
269 SSAUpdate.RewriteUse(*UsesToRewrite[i]);