blob: 193dd3895da3cfa43997a0c9a5e1ee097071145c [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
Owen Anderson75693222010-08-06 18:33:48 +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
Dan Gohman170c5192010-07-26 18:11:16 +000067 AU.addRequired<DominatorTree>();
Dan Gohman687cee62010-07-16 17:58:45 +000068 AU.addPreserved<DominatorTree>();
69 AU.addPreserved<DominanceFrontier>();
Dan Gohman170c5192010-07-26 18:11:16 +000070 AU.addRequired<LoopInfo>();
Dan Gohman687cee62010-07-16 17:58:45 +000071 AU.addPreserved<LoopInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072 AU.addPreservedID(LoopSimplifyID);
Dan Gohman687cee62010-07-16 17:58:45 +000073 AU.addPreserved<ScalarEvolution>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074 }
75 private:
Chris Lattnere98866c2009-10-11 02:53:37 +000076 bool ProcessInstruction(Instruction *Inst,
77 const SmallVectorImpl<BasicBlock*> &ExitBlocks);
Chris Lattner7dd77a52009-10-11 01:07:15 +000078
Dan Gohman9cec4122009-09-08 15:45:00 +000079 /// verifyAnalysis() - Verify loop nest.
80 virtual void verifyAnalysis() const {
Dan Gohman9cec4122009-09-08 15:45:00 +000081 // Check the special guarantees that LCSSA makes.
Dan Gohmana76b5582010-03-10 19:38:49 +000082 assert(L->isLCSSAForm(*DT) && "LCSSA form not preserved!");
Dan Gohman9cec4122009-09-08 15:45:00 +000083 }
84
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085 /// inLoop - returns true if the given block is within the current loop
Chris Lattner7dd77a52009-10-11 01:07:15 +000086 bool inLoop(BasicBlock *B) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087 return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
88 }
89 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090}
Dan Gohman089efff2008-05-13 00:00:25 +000091
92char LCSSA::ID = 0;
Owen Andersoncdb0c032010-10-12 19:48:12 +000093INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
94INITIALIZE_PASS_DEPENDENCY(DominatorTree)
95INITIALIZE_PASS_DEPENDENCY(DominanceFrontier)
96INITIALIZE_PASS_DEPENDENCY(LoopInfo)
97INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
98INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
99INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100
Daniel Dunbar163555a2008-10-22 23:32:42 +0000101Pass *llvm::createLCSSAPass() { return new LCSSA(); }
Owen Anderson75693222010-08-06 18:33:48 +0000102char &llvm::LCSSAID = LCSSA::ID;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103
Chris Lattnere98866c2009-10-11 02:53:37 +0000104
105/// BlockDominatesAnExit - Return true if the specified block dominates at least
106/// one of the blocks in the specified list.
107static bool BlockDominatesAnExit(BasicBlock *BB,
108 const SmallVectorImpl<BasicBlock*> &ExitBlocks,
109 DominatorTree *DT) {
110 DomTreeNode *DomNode = DT->getNode(BB);
111 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
112 if (DT->dominates(DomNode, DT->getNode(ExitBlocks[i])))
113 return true;
114
115 return false;
116}
117
118
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000119/// runOnFunction - Process all loops in the function, inner-most out.
Chris Lattnere98866c2009-10-11 02:53:37 +0000120bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {
121 L = TheLoop;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 DT = &getAnalysis<DominatorTree>();
Devang Patel9cee7a02007-08-17 21:59:16 +0000124
Chris Lattnere98866c2009-10-11 02:53:37 +0000125 // Get the set of exiting blocks.
126 SmallVector<BasicBlock*, 8> ExitBlocks;
127 L->getExitBlocks(ExitBlocks);
128
129 if (ExitBlocks.empty())
130 return false;
131
Chris Lattner7dd77a52009-10-11 01:07:15 +0000132 // Speed up queries by creating a sorted vector of blocks.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133 LoopBlocks.clear();
134 LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
Chris Lattner7dd77a52009-10-11 01:07:15 +0000135 array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136
Chris Lattnere98866c2009-10-11 02:53:37 +0000137 // Look at all the instructions in the loop, checking to see if they have uses
138 // outside the loop. If so, rewrite those uses.
139 bool MadeChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140
Chris Lattnere98866c2009-10-11 02:53:37 +0000141 for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();
142 BBI != E; ++BBI) {
143 BasicBlock *BB = *BBI;
144
145 // For large loops, avoid use-scanning by using dominance information: In
146 // particular, if a block does not dominate any of the loop exits, then none
147 // of the values defined in the block could be used outside the loop.
148 if (!BlockDominatesAnExit(BB, ExitBlocks, DT))
149 continue;
150
151 for (BasicBlock::iterator I = BB->begin(), E = BB->end();
152 I != E; ++I) {
153 // Reject two common cases fast: instructions with no uses (like stores)
154 // and instructions with one use that is in the same block as this.
155 if (I->use_empty() ||
156 (I->hasOneUse() && I->use_back()->getParent() == BB &&
157 !isa<PHINode>(I->use_back())))
158 continue;
159
160 MadeChange |= ProcessInstruction(I, ExitBlocks);
161 }
162 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163
Dan Gohmana76b5582010-03-10 19:38:49 +0000164 assert(L->isLCSSAForm(*DT));
Chris Lattnere98866c2009-10-11 02:53:37 +0000165 PredCache.clear();
166
167 return MadeChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000168}
169
Chris Lattnere98866c2009-10-11 02:53:37 +0000170/// isExitBlock - Return true if the specified block is in the list.
171static bool isExitBlock(BasicBlock *BB,
172 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
173 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
174 if (ExitBlocks[i] == BB)
175 return true;
176 return false;
177}
178
179/// ProcessInstruction - Given an instruction in the loop, check to see if it
180/// has any uses that are outside the current loop. If so, insert LCSSA PHI
181/// nodes and rewrite the uses.
182bool LCSSA::ProcessInstruction(Instruction *Inst,
183 const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
184 SmallVector<Use*, 16> UsesToRewrite;
185
186 BasicBlock *InstBB = Inst->getParent();
187
188 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
189 UI != E; ++UI) {
Gabor Greif6e927cb2010-07-09 14:29:14 +0000190 User *U = *UI;
191 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
192 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattnere98866c2009-10-11 02:53:37 +0000193 UserBB = PN->getIncomingBlock(UI);
194
195 if (InstBB != UserBB && !inLoop(UserBB))
196 UsesToRewrite.push_back(&UI.getUse());
197 }
Gabor Greif6e927cb2010-07-09 14:29:14 +0000198
Chris Lattnere98866c2009-10-11 02:53:37 +0000199 // If there are no uses outside the loop, exit with no change.
200 if (UsesToRewrite.empty()) return false;
201
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202 ++NumLCSSA; // We are applying the transformation
203
Dan Gohman480cf742009-06-26 00:31:13 +0000204 // Invoke instructions are special in that their result value is not available
205 // along their unwind edge. The code below tests to see whether DomBB dominates
206 // the value, so adjust DomBB to the normal destination block, which is
207 // effectively where the value is first usable.
Chris Lattnere98866c2009-10-11 02:53:37 +0000208 BasicBlock *DomBB = Inst->getParent();
209 if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))
Dan Gohman480cf742009-06-26 00:31:13 +0000210 DomBB = Inv->getNormalDest();
211
212 DomTreeNode *DomNode = DT->getNode(DomBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213
Chris Lattnere98866c2009-10-11 02:53:37 +0000214 SSAUpdater SSAUpdate;
Duncan Sands538ebf32010-09-02 08:14:03 +0000215 SSAUpdate.Initialize(Inst->getType(), Inst->getName());
Chris Lattnere98866c2009-10-11 02:53:37 +0000216
217 // Insert the LCSSA phi's into all of the exit blocks dominated by the
Dan Gohman2fb4ae52009-11-09 18:28:24 +0000218 // value, and add them to the Phi's map.
Chris Lattnere98866c2009-10-11 02:53:37 +0000219 for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),
Chris Lattner7dd77a52009-10-11 01:07:15 +0000220 BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {
Chris Lattnere98866c2009-10-11 02:53:37 +0000221 BasicBlock *ExitBB = *BBI;
222 if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;
223
224 // If we already inserted something for this BB, don't reprocess it.
225 if (SSAUpdate.HasValueForBlock(ExitBB)) continue;
226
227 PHINode *PN = PHINode::Create(Inst->getType(), Inst->getName()+".lcssa",
228 ExitBB->begin());
229 PN->reserveOperandSpace(PredCache.GetNumPreds(ExitBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230
Chris Lattnere98866c2009-10-11 02:53:37 +0000231 // Add inputs from inside the loop for this PHI.
Dan Gohman2fb4ae52009-11-09 18:28:24 +0000232 for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
Chris Lattnere98866c2009-10-11 02:53:37 +0000233 PN->addIncoming(Inst, *PI);
Dan Gohman2fb4ae52009-11-09 18:28:24 +0000234
235 // If the exit block has a predecessor not within the loop, arrange for
Dan Gohman0273f182009-11-09 18:59:22 +0000236 // the incoming value use corresponding to that predecessor to be
Dan Gohman2fb4ae52009-11-09 18:28:24 +0000237 // rewritten in terms of a different LCSSA PHI.
238 if (!inLoop(*PI))
239 UsesToRewrite.push_back(
240 &PN->getOperandUse(
241 PN->getOperandNumForIncomingValue(PN->getNumIncomingValues()-1)));
242 }
Chris Lattnere98866c2009-10-11 02:53:37 +0000243
244 // Remember that this phi makes the value alive in this block.
245 SSAUpdate.AddAvailableValue(ExitBB, PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 }
247
Chris Lattnere98866c2009-10-11 02:53:37 +0000248 // Rewrite all uses outside the loop in terms of the new PHIs we just
249 // inserted.
250 for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {
251 // If this use is in an exit block, rewrite to use the newly inserted PHI.
252 // This is required for correctness because SSAUpdate doesn't handle uses in
253 // the same block. It assumes the PHI we inserted is at the end of the
254 // block.
255 Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());
256 BasicBlock *UserBB = User->getParent();
257 if (PHINode *PN = dyn_cast<PHINode>(User))
258 UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);
259
260 if (isa<PHINode>(UserBB->begin()) &&
261 isExitBlock(UserBB, ExitBlocks)) {
262 UsesToRewrite[i]->set(UserBB->begin());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 continue;
264 }
265
Chris Lattnere98866c2009-10-11 02:53:37 +0000266 // Otherwise, do full PHI insertion.
267 SSAUpdate.RewriteUse(*UsesToRewrite[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 }
269
Chris Lattnere98866c2009-10-11 02:53:37 +0000270 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271}
272