blob: b4afedab7ba2cfe99c89979a6896d11ea9446d00 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
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:
13//
14// for (...) for (...)
15// if (c) if (c)
16// X1 = ... X1 = ...
17// else else
18// X2 = ... X2 = ...
19// X3 = phi(X1, X2) X3 = phi(X1, X2)
Dan Gohman03eb27e2008-06-03 00:57:21 +000020// ... = X3 + 4 X4 = phi(X3)
21// ... = X4 + 4
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022//
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.
27//
28//===----------------------------------------------------------------------===//
29
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"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include "llvm/Analysis/Dominators.h"
37#include "llvm/Analysis/LoopPass.h"
38#include "llvm/Analysis/ScalarEvolution.h"
Chris Lattnere98866c2009-10-11 02:53:37 +000039#include "llvm/Transforms/Utils/SSAUpdater.h"
40#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/STLExtras.h"
Owen Andersonb09900b2009-04-22 08:09:13 +000042#include "llvm/Support/PredIteratorCache.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000043using namespace llvm;
44
45STATISTIC(NumLCSSA, "Number of live out of a loop variables");
46
47namespace {
Chris Lattnere98866c2009-10-11 02:53:37 +000048 struct LCSSA : public LoopPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000050 LCSSA() : LoopPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051
52 // Cached analysis information for the current function.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053 DominatorTree *DT;
54 std::vector<BasicBlock*> LoopBlocks;
Owen Andersonb09900b2009-04-22 08:09:13 +000055 PredIteratorCache PredCache;
Dan Gohman9cec4122009-09-08 15:45:00 +000056 Loop *L;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000057
58 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
59
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060 /// 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.
63 ///
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.setPreservesCFG();
Dan Gohman2fb4ae52009-11-09 18:28:24 +000066
67 // LCSSA doesn't actually require LoopSimplify, but the PassManager
68 // doesn't know how to schedule LoopSimplify by itself.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069 AU.addRequiredID(LoopSimplifyID);
70 AU.addPreservedID(LoopSimplifyID);
Dan Gohman9cec4122009-09-08 15:45:00 +000071 AU.addRequiredTransitive<LoopInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072 AU.addPreserved<LoopInfo>();
Dan Gohman9cec4122009-09-08 15:45:00 +000073 AU.addRequiredTransitive<DominatorTree>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074 AU.addPreserved<ScalarEvolution>();
Devang Patel48d15802007-07-30 20:23:45 +000075 AU.addPreserved<DominatorTree>();
76
77 // Request DominanceFrontier now, even though LCSSA does
78 // not use it. This allows Pass Manager to schedule Dominance
79 // Frontier early enough such that one LPPassManager can handle
80 // multiple loop transformation passes.
81 AU.addRequired<DominanceFrontier>();
82 AU.addPreserved<DominanceFrontier>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083 }
84 private:
Chris Lattnere98866c2009-10-11 02:53:37 +000085 bool ProcessInstruction(Instruction *Inst,
86 const SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattner7dd77a52009-10-11 01:07:15 +000087
Dan Gohman9cec4122009-09-08 15:45:00 +000088 /// verifyAnalysis() - Verify loop nest.
89 virtual void verifyAnalysis() const {
Dan Gohman9cec4122009-09-08 15:45:00 +000090 // Check the special guarantees that LCSSA makes.
Dan Gohman2dac9782009-09-28 14:38:19 +000091 assert(L->isLCSSAForm() && "LCSSA form not preserved!");
Dan Gohman9cec4122009-09-08 15:45:00 +000092 }
93
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 /// inLoop - returns true if the given block is within the current loop
Chris Lattner7dd77a52009-10-11 01:07:15 +000095 bool inLoop(BasicBlock *B) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096 return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
97 }
98 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099}
Dan Gohman089efff2008-05-13 00:00:25 +0000100
101char LCSSA::ID = 0;
102static RegisterPass<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103
Daniel Dunbar163555a2008-10-22 23:32:42 +0000104Pass *llvm::createLCSSAPass() { return new LCSSA(); }
Dan Gohman66a636e2008-05-13 02:05:11 +0000105const PassInfo *const llvm::LCSSAID = &X;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106
Chris Lattnere98866c2009-10-11 02:53:37 +0000107
108/// BlockDominatesAnExit - Return true if the specified block dominates at least
109/// one of the blocks in the specified list.
110static bool BlockDominatesAnExit(BasicBlock *BB,
111 const SmallVectorImpl<BasicBlock*> &ExitBlocks,
112 DominatorTree *DT) {
113 DomTreeNode *DomNode = DT->getNode(BB);
114 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
115 if (DT->dominates(DomNode, DT->getNode(ExitBlocks[i])))
116 return true;
117
118 return false;
119}
120
121
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122/// runOnFunction - Process all loops in the function, inner-most out.
Chris Lattnere98866c2009-10-11 02:53:37 +0000123bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {
124 L = TheLoop;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126 DT = &getAnalysis<DominatorTree>();
Devang Patel9cee7a02007-08-17 21:59:16 +0000127
Chris Lattnere98866c2009-10-11 02:53:37 +0000128 // Get the set of exiting blocks.
129 SmallVector<BasicBlock*, 8> ExitBlocks;
130 L->getExitBlocks(ExitBlocks);
131
132 if (ExitBlocks.empty())
133 return false;
134
Chris Lattner7dd77a52009-10-11 01:07:15 +0000135 // Speed up queries by creating a sorted vector of blocks.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136 LoopBlocks.clear();
137 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
Chris Lattner7dd77a52009-10-11 01:07:15 +0000138 array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139
Chris Lattnere98866c2009-10-11 02:53:37 +0000140 // Look at all the instructions in the loop, checking to see if they have uses
141 // outside the loop. If so, rewrite those uses.
142 bool MadeChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143
Chris Lattnere98866c2009-10-11 02:53:37 +0000144 for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();
145 BBI != E; ++BBI) {
146 BasicBlock *BB = *BBI;
147
148 // For large loops, avoid use-scanning by using dominance information: In
149 // particular, if a block does not dominate any of the loop exits, then none
150 // of the values defined in the block could be used outside the loop.
151 if (!BlockDominatesAnExit(BB, ExitBlocks, DT))
152 continue;
153
154 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
155 I != E; ++I) {
156 // Reject two common cases fast: instructions with no uses (like stores)
157 // and instructions with one use that is in the same block as this.
158 if (I->use_empty() ||
159 (I->hasOneUse() && I->use_back()->getParent() == BB &&
160 !isa<PHINode>(I->use_back())))
161 continue;
162
163 MadeChange |= ProcessInstruction(I, ExitBlocks);
164 }
165 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166
167 assert(L->isLCSSAForm());
Chris Lattnere98866c2009-10-11 02:53:37 +0000168 PredCache.clear();
169
170 return MadeChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171}
172
Chris Lattnere98866c2009-10-11 02:53:37 +0000173/// isExitBlock - Return true if the specified block is in the list.
174static bool isExitBlock(BasicBlock *BB,
175 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
176 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
177 if (ExitBlocks[i] == BB)
178 return true;
179 return false;
180}
181
182/// ProcessInstruction - Given an instruction in the loop, check to see if it
183/// has any uses that are outside the current loop. If so, insert LCSSA PHI
184/// nodes and rewrite the uses.
185bool LCSSA::ProcessInstruction(Instruction *Inst,
186 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
187 SmallVector<Use*, 16> UsesToRewrite;
188
189 BasicBlock *InstBB = Inst->getParent();
190
191 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
192 UI != E; ++UI) {
193 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
194 if (PHINode *PN = dyn_cast<PHINode>(*UI))
195 UserBB = PN->getIncomingBlock(UI);
196
197 if (InstBB != UserBB && !inLoop(UserBB))
198 UsesToRewrite.push_back(&UI.getUse());
199 }
200
201 // If there are no uses outside the loop, exit with no change.
202 if (UsesToRewrite.empty()) return false;
203
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204 ++NumLCSSA; // We are applying the transformation
205
Dan Gohman480cf742009-06-26 00:31:13 +0000206 // 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.
Chris Lattnere98866c2009-10-11 02:53:37 +0000210 BasicBlock *DomBB = Inst->getParent();
211 if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))
Dan Gohman480cf742009-06-26 00:31:13 +0000212 DomBB = Inv->getNormalDest();
213
214 DomTreeNode *DomNode = DT->getNode(DomBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215
Chris Lattnere98866c2009-10-11 02:53:37 +0000216 SSAUpdater SSAUpdate;
217 SSAUpdate.Initialize(Inst);
218
219 // Insert the LCSSA phi's into all of the exit blocks dominated by the
Dan Gohman2fb4ae52009-11-09 18:28:24 +0000220 // value, and add them to the Phi's map.
Chris Lattnere98866c2009-10-11 02:53:37 +0000221 for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),
Chris Lattner7dd77a52009-10-11 01:07:15 +0000222 BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {
Chris Lattnere98866c2009-10-11 02:53:37 +0000223 BasicBlock *ExitBB = *BBI;
224 if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;
225
226 // If we already inserted something for this BB, don't reprocess it.
227 if (SSAUpdate.HasValueForBlock(ExitBB)) continue;
228
229 PHINode *PN = PHINode::Create(Inst->getType(), Inst->getName()+".lcssa",
230 ExitBB->begin());
231 PN->reserveOperandSpace(PredCache.GetNumPreds(ExitBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232
Chris Lattnere98866c2009-10-11 02:53:37 +0000233 // Add inputs from inside the loop for this PHI.
Dan Gohman2fb4ae52009-11-09 18:28:24 +0000234 for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
Chris Lattnere98866c2009-10-11 02:53:37 +0000235 PN->addIncoming(Inst, *PI);
Dan Gohman2fb4ae52009-11-09 18:28:24 +0000236
237 // If the exit block has a predecessor not within the loop, arrange for
238 // the incomging value use corresponding to that predecessor to be
239 // rewritten in terms of a different LCSSA PHI.
240 if (!inLoop(*PI))
241 UsesToRewrite.push_back(
242 &PN->getOperandUse(
243 PN->getOperandNumForIncomingValue(PN->getNumIncomingValues()-1)));
244 }
Chris Lattnere98866c2009-10-11 02:53:37 +0000245
246 // Remember that this phi makes the value alive in this block.
247 SSAUpdate.AddAvailableValue(ExitBB, PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248 }
249
Chris Lattnere98866c2009-10-11 02:53:37 +0000250 // Rewrite all uses outside the loop in terms of the new PHIs we just
251 // inserted.
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
256 // block.
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]);
261
262 if (isa<PHINode>(UserBB->begin()) &&
263 isExitBlock(UserBB, ExitBlocks)) {
264 UsesToRewrite[i]->set(UserBB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 continue;
266 }
267
Chris Lattnere98866c2009-10-11 02:53:37 +0000268 // Otherwise, do full PHI insertion.
269 SSAUpdate.RewriteUse(*UsesToRewrite[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270 }
271
Chris Lattnere98866c2009-10-11 02:53:37 +0000272 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273}
274