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) {}
52 // Cached analysis information for the current function.
54 std::vector<BasicBlock*> LoopBlocks;
55 PredIteratorCache PredCache;
58 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
60 /// This transformation requires natural loop information & requires that
61 /// loop preheaders be inserted into the CFG. It maintains both of these,
62 /// as well as the CFG. It also requires dominator information.
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addRequired<DominatorTree>();
68 AU.addPreserved<DominatorTree>();
69 AU.addPreserved<DominanceFrontier>();
70 AU.addRequired<LoopInfo>();
71 AU.addPreserved<LoopInfo>();
72 AU.addPreservedID(LoopSimplifyID);
73 AU.addPreserved<ScalarEvolution>();
76 bool ProcessInstruction(Instruction *Inst,
77 const SmallVectorImpl<BasicBlock*> &ExitBlocks);
79 /// verifyAnalysis() - Verify loop nest.
80 virtual void verifyAnalysis() const {
81 // Check the special guarantees that LCSSA makes.
82 assert(L->isLCSSAForm(*DT) && "LCSSA form not preserved!");
85 /// inLoop - returns true if the given block is within the current loop
86 bool inLoop(BasicBlock *B) const {
87 return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
93 static RegisterPass<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
95 Pass *llvm::createLCSSAPass() { return new LCSSA(); }
96 char &llvm::LCSSAID = LCSSA::ID;
99 /// BlockDominatesAnExit - Return true if the specified block dominates at least
100 /// one of the blocks in the specified list.
101 static bool BlockDominatesAnExit(BasicBlock *BB,
102 const SmallVectorImpl<BasicBlock*> &ExitBlocks,
104 DomTreeNode *DomNode = DT->getNode(BB);
105 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
106 if (DT->dominates(DomNode, DT->getNode(ExitBlocks[i])))
113 /// runOnFunction - Process all loops in the function, inner-most out.
114 bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {
117 DT = &getAnalysis<DominatorTree>();
119 // Get the set of exiting blocks.
120 SmallVector<BasicBlock*, 8> ExitBlocks;
121 L->getExitBlocks(ExitBlocks);
123 if (ExitBlocks.empty())
126 // Speed up queries by creating a sorted vector of blocks.
128 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
129 array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());
131 // Look at all the instructions in the loop, checking to see if they have uses
132 // outside the loop. If so, rewrite those uses.
133 bool MadeChange = false;
135 for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();
137 BasicBlock *BB = *BBI;
139 // For large loops, avoid use-scanning by using dominance information: In
140 // particular, if a block does not dominate any of the loop exits, then none
141 // of the values defined in the block could be used outside the loop.
142 if (!BlockDominatesAnExit(BB, ExitBlocks, DT))
145 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
147 // Reject two common cases fast: instructions with no uses (like stores)
148 // and instructions with one use that is in the same block as this.
149 if (I->use_empty() ||
150 (I->hasOneUse() && I->use_back()->getParent() == BB &&
151 !isa<PHINode>(I->use_back())))
154 MadeChange |= ProcessInstruction(I, ExitBlocks);
158 assert(L->isLCSSAForm(*DT));
164 /// isExitBlock - Return true if the specified block is in the list.
165 static bool isExitBlock(BasicBlock *BB,
166 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
167 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
168 if (ExitBlocks[i] == BB)
173 /// ProcessInstruction - Given an instruction in the loop, check to see if it
174 /// has any uses that are outside the current loop. If so, insert LCSSA PHI
175 /// nodes and rewrite the uses.
176 bool LCSSA::ProcessInstruction(Instruction *Inst,
177 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
178 SmallVector<Use*, 16> UsesToRewrite;
180 BasicBlock *InstBB = Inst->getParent();
182 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
185 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
186 if (PHINode *PN = dyn_cast<PHINode>(U))
187 UserBB = PN->getIncomingBlock(UI);
189 if (InstBB != UserBB && !inLoop(UserBB))
190 UsesToRewrite.push_back(&UI.getUse());
193 // If there are no uses outside the loop, exit with no change.
194 if (UsesToRewrite.empty()) return false;
196 ++NumLCSSA; // We are applying the transformation
198 // Invoke instructions are special in that their result value is not available
199 // along their unwind edge. The code below tests to see whether DomBB dominates
200 // the value, so adjust DomBB to the normal destination block, which is
201 // effectively where the value is first usable.
202 BasicBlock *DomBB = Inst->getParent();
203 if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))
204 DomBB = Inv->getNormalDest();
206 DomTreeNode *DomNode = DT->getNode(DomBB);
208 SSAUpdater SSAUpdate;
209 SSAUpdate.Initialize(Inst);
211 // Insert the LCSSA phi's into all of the exit blocks dominated by the
212 // value, and add them to the Phi's map.
213 for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),
214 BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {
215 BasicBlock *ExitBB = *BBI;
216 if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;
218 // If we already inserted something for this BB, don't reprocess it.
219 if (SSAUpdate.HasValueForBlock(ExitBB)) continue;
221 PHINode *PN = PHINode::Create(Inst->getType(), Inst->getName()+".lcssa",
223 PN->reserveOperandSpace(PredCache.GetNumPreds(ExitBB));
225 // Add inputs from inside the loop for this PHI.
226 for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
227 PN->addIncoming(Inst, *PI);
229 // If the exit block has a predecessor not within the loop, arrange for
230 // the incoming value use corresponding to that predecessor to be
231 // rewritten in terms of a different LCSSA PHI.
233 UsesToRewrite.push_back(
235 PN->getOperandNumForIncomingValue(PN->getNumIncomingValues()-1)));
238 // Remember that this phi makes the value alive in this block.
239 SSAUpdate.AddAvailableValue(ExitBB, PN);
242 // Rewrite all uses outside the loop in terms of the new PHIs we just
244 for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {
245 // If this use is in an exit block, rewrite to use the newly inserted PHI.
246 // This is required for correctness because SSAUpdate doesn't handle uses in
247 // the same block. It assumes the PHI we inserted is at the end of the
249 Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());
250 BasicBlock *UserBB = User->getParent();
251 if (PHINode *PN = dyn_cast<PHINode>(User))
252 UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);
254 if (isa<PHINode>(UserBB->begin()) &&
255 isExitBlock(UserBB, ExitBlocks)) {
256 UsesToRewrite[i]->set(UserBB->begin());
260 // Otherwise, do full PHI insertion.
261 SSAUpdate.RewriteUse(*UsesToRewrite[i]);