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/ADT/STLExtras.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Analysis/Dominators.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/LoopPass.h"
37 #include "llvm/Analysis/ScalarEvolution.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/PredIteratorCache.h"
43 #include "llvm/Transforms/Utils/SSAUpdater.h"
46 STATISTIC(NumLCSSA, "Number of live out of a loop variables");
49 struct LCSSA : public LoopPass {
50 static char ID; // Pass identification, replacement for typeid
51 LCSSA() : LoopPass(ID) {
52 initializeLCSSAPass(*PassRegistry::getPassRegistry());
55 // Cached analysis information for the current function.
59 PredIteratorCache PredCache;
62 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
64 /// This transformation requires natural loop information & requires that
65 /// loop preheaders be inserted into the CFG. It maintains both of these,
66 /// as well as the CFG. It also requires dominator information.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
71 AU.addRequired<DominatorTree>();
72 AU.addRequired<LoopInfo>();
73 AU.addPreservedID(LoopSimplifyID);
74 AU.addPreserved<AliasAnalysis>();
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!");
90 INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
91 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
92 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
93 INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
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>();
118 LI = &getAnalysis<LoopInfo>();
119 SE = getAnalysisIfAvailable<ScalarEvolution>();
121 // Get the set of exiting blocks.
122 SmallVector<BasicBlock*, 8> ExitBlocks;
123 L->getExitBlocks(ExitBlocks);
125 if (ExitBlocks.empty())
128 // Look at all the instructions in the loop, checking to see if they have uses
129 // outside the loop. If so, rewrite those uses.
130 bool MadeChange = false;
132 for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();
134 BasicBlock *BB = *BBI;
136 // For large loops, avoid use-scanning by using dominance information: In
137 // particular, if a block does not dominate any of the loop exits, then none
138 // of the values defined in the block could be used outside the loop.
139 if (!BlockDominatesAnExit(BB, ExitBlocks, DT))
142 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
144 // Reject two common cases fast: instructions with no uses (like stores)
145 // and instructions with one use that is in the same block as this.
146 if (I->use_empty() ||
147 (I->hasOneUse() && I->use_back()->getParent() == BB &&
148 !isa<PHINode>(I->use_back())))
151 MadeChange |= ProcessInstruction(I, ExitBlocks);
155 // If we modified the code, remove any caches about the loop from SCEV to
156 // avoid dangling entries.
157 // FIXME: This is a big hammer, can we clear the cache more selectively?
158 if (SE && MadeChange)
161 assert(L->isLCSSAForm(*DT));
167 /// isExitBlock - Return true if the specified block is in the list.
168 static bool isExitBlock(BasicBlock *BB,
169 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
170 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
171 if (ExitBlocks[i] == BB)
176 /// ProcessInstruction - Given an instruction in the loop, check to see if it
177 /// has any uses that are outside the current loop. If so, insert LCSSA PHI
178 /// nodes and rewrite the uses.
179 bool LCSSA::ProcessInstruction(Instruction *Inst,
180 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
181 SmallVector<Use*, 16> UsesToRewrite;
183 BasicBlock *InstBB = Inst->getParent();
185 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
188 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
189 if (PHINode *PN = dyn_cast<PHINode>(U))
190 UserBB = PN->getIncomingBlock(UI);
192 if (InstBB != UserBB && !L->contains(UserBB))
193 UsesToRewrite.push_back(&UI.getUse());
196 // If there are no uses outside the loop, exit with no change.
197 if (UsesToRewrite.empty()) return false;
199 ++NumLCSSA; // We are applying the transformation
201 // Invoke instructions are special in that their result value is not available
202 // along their unwind edge. The code below tests to see whether DomBB dominates
203 // the value, so adjust DomBB to the normal destination block, which is
204 // effectively where the value is first usable.
205 BasicBlock *DomBB = Inst->getParent();
206 if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))
207 DomBB = Inv->getNormalDest();
209 DomTreeNode *DomNode = DT->getNode(DomBB);
211 SmallVector<PHINode*, 16> AddedPHIs;
213 SSAUpdater SSAUpdate;
214 SSAUpdate.Initialize(Inst->getType(), Inst->getName());
216 // Insert the LCSSA phi's into all of the exit blocks dominated by the
217 // value, and add them to the Phi's map.
218 for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),
219 BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {
220 BasicBlock *ExitBB = *BBI;
221 if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;
223 // If we already inserted something for this BB, don't reprocess it.
224 if (SSAUpdate.HasValueForBlock(ExitBB)) continue;
226 PHINode *PN = PHINode::Create(Inst->getType(),
227 PredCache.GetNumPreds(ExitBB),
228 Inst->getName()+".lcssa",
231 // Add inputs from inside the loop for this PHI.
232 for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
233 PN->addIncoming(Inst, *PI);
235 // If the exit block has a predecessor not within the loop, arrange for
236 // the incoming value use corresponding to that predecessor to be
237 // rewritten in terms of a different LCSSA PHI.
238 if (!L->contains(*PI))
239 UsesToRewrite.push_back(
241 PN->getOperandNumForIncomingValue(PN->getNumIncomingValues()-1)));
244 AddedPHIs.push_back(PN);
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 // Tell the VHs that the uses changed. This updates SCEV's caches.
265 if (UsesToRewrite[i]->get()->hasValueHandle())
266 ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i], UserBB->begin());
267 UsesToRewrite[i]->set(UserBB->begin());
271 // Otherwise, do full PHI insertion.
272 SSAUpdate.RewriteUse(*UsesToRewrite[i]);
275 // Remove PHI nodes that did not have any uses rewritten.
276 for (unsigned i = 0, e = AddedPHIs.size(); i != e; ++i) {
277 if (AddedPHIs[i]->use_empty())
278 AddedPHIs[i]->eraseFromParent();