blob: d45944d47cf5ee24162754ea043a5147c75a18ee [file] [log] [blame]
Owen Andersonf3dd3e22006-05-26 21:11:53 +00001//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
Owen Anderson8eca8912006-05-26 13:58:26 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Anderson8eca8912006-05-26 13:58:26 +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 (...)
Dan Gohmanb5650eb2007-05-11 21:10:54 +000015// if (c) if (c)
Owen Anderson8eca8912006-05-26 13:58:26 +000016// X1 = ... X1 = ...
17// else else
18// X2 = ... X2 = ...
19// X3 = phi(X1, X2) X3 = phi(X1, X2)
Dan Gohman2ad7e732008-06-03 00:57:21 +000020// ... = X3 + 4 X4 = phi(X3)
21// ... = X4 + 4
Owen Anderson8eca8912006-05-26 13:58:26 +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
Owen Andersonf3dd3e22006-05-26 21:11:53 +000030#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/Statistic.h"
Chandler Carruth756c22c2014-02-10 19:39:35 +000033#include "llvm/Analysis/AliasAnalysis.h"
Devang Patel4cd14132007-07-13 23:57:11 +000034#include "llvm/Analysis/LoopPass.h"
35#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Constants.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000037#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Function.h"
39#include "llvm/IR/Instructions.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000040#include "llvm/IR/PredIteratorCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000041#include "llvm/Pass.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000042#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000043#include "llvm/Transforms/Utils/SSAUpdater.h"
Owen Anderson8eca8912006-05-26 13:58:26 +000044using namespace llvm;
45
Chandler Carruth964daaa2014-04-22 02:55:47 +000046#define DEBUG_TYPE "lcssa"
47
Chris Lattner45f966d2006-12-19 22:17:40 +000048STATISTIC(NumLCSSA, "Number of live out of a loop variables");
49
Chandler Carruth8765cf72014-01-25 04:07:24 +000050/// Return true if the specified block is in the list.
Chris Lattner71d353d2009-10-11 02:53:37 +000051static bool isExitBlock(BasicBlock *BB,
Chandler Carruth8765cf72014-01-25 04:07:24 +000052 const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
Chris Lattner71d353d2009-10-11 02:53:37 +000053 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
54 if (ExitBlocks[i] == BB)
55 return true;
56 return false;
57}
58
Chandler Carruth8765cf72014-01-25 04:07:24 +000059/// Given an instruction in the loop, check to see if it has any uses that are
60/// outside the current loop. If so, insert LCSSA PHI nodes and rewrite the
61/// uses.
62static bool processInstruction(Loop &L, Instruction &Inst, DominatorTree &DT,
63 const SmallVectorImpl<BasicBlock *> &ExitBlocks,
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +000064 PredIteratorCache &PredCache, LoopInfo *LI) {
Chandler Carruth8765cf72014-01-25 04:07:24 +000065 SmallVector<Use *, 16> UsesToRewrite;
66
67 BasicBlock *InstBB = Inst.getParent();
68
Chandler Carruthcdf47882014-03-09 03:16:01 +000069 for (Use &U : Inst.uses()) {
70 Instruction *User = cast<Instruction>(U.getUser());
71 BasicBlock *UserBB = User->getParent();
72 if (PHINode *PN = dyn_cast<PHINode>(User))
73 UserBB = PN->getIncomingBlock(U);
Chandler Carruth8765cf72014-01-25 04:07:24 +000074
75 if (InstBB != UserBB && !L.contains(UserBB))
Chandler Carruthcdf47882014-03-09 03:16:01 +000076 UsesToRewrite.push_back(&U);
Chris Lattner71d353d2009-10-11 02:53:37 +000077 }
Gabor Greif42479492010-07-09 14:29:14 +000078
Chris Lattner71d353d2009-10-11 02:53:37 +000079 // If there are no uses outside the loop, exit with no change.
Chandler Carruth8765cf72014-01-25 04:07:24 +000080 if (UsesToRewrite.empty())
81 return false;
82
Owen Andersondad8c572006-05-31 20:55:06 +000083 ++NumLCSSA; // We are applying the transformation
Chris Lattner5a2bc782006-08-02 00:06:09 +000084
David Majnemer0bc0eef2015-08-15 02:46:08 +000085 // Invoke/CatchPad instructions are special in that their result value is not
86 // available along their unwind edge. The code below tests to see whether
87 // DomBB dominates the value, so adjust DomBB to the normal destination block,
88 // which is effectively where the value is first usable.
Chandler Carruth8765cf72014-01-25 04:07:24 +000089 BasicBlock *DomBB = Inst.getParent();
90 if (InvokeInst *Inv = dyn_cast<InvokeInst>(&Inst))
Dan Gohman7eaf50e2009-06-26 00:31:13 +000091 DomBB = Inv->getNormalDest();
David Majnemer0bc0eef2015-08-15 02:46:08 +000092 if (auto *CPI = dyn_cast<CatchPadInst>(&Inst))
93 DomBB = CPI->getNormalDest();
Dan Gohman7eaf50e2009-06-26 00:31:13 +000094
Chandler Carruth8765cf72014-01-25 04:07:24 +000095 DomTreeNode *DomNode = DT.getNode(DomBB);
Chris Lattner5a2bc782006-08-02 00:06:09 +000096
Chandler Carruth8765cf72014-01-25 04:07:24 +000097 SmallVector<PHINode *, 16> AddedPHIs;
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +000098 SmallVector<PHINode *, 8> PostProcessPHIs;
Cameron Zwarich0b8cdfb2011-03-15 07:41:25 +000099
Chris Lattner71d353d2009-10-11 02:53:37 +0000100 SSAUpdater SSAUpdate;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000101 SSAUpdate.Initialize(Inst.getType(), Inst.getName());
102
Chris Lattner71d353d2009-10-11 02:53:37 +0000103 // Insert the LCSSA phi's into all of the exit blocks dominated by the
Dan Gohmanc146c7802009-11-09 18:28:24 +0000104 // value, and add them to the Phi's map.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000105 for (SmallVectorImpl<BasicBlock *>::const_iterator BBI = ExitBlocks.begin(),
106 BBE = ExitBlocks.end();
107 BBI != BBE; ++BBI) {
Chris Lattner71d353d2009-10-11 02:53:37 +0000108 BasicBlock *ExitBB = *BBI;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000109 if (!DT.dominates(DomNode, DT.getNode(ExitBB)))
110 continue;
111
Chris Lattner71d353d2009-10-11 02:53:37 +0000112 // If we already inserted something for this BB, don't reprocess it.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000113 if (SSAUpdate.HasValueForBlock(ExitBB))
114 continue;
115
Daniel Berlinb4e7a4a2015-04-21 21:11:50 +0000116 PHINode *PN = PHINode::Create(Inst.getType(), PredCache.size(ExitBB),
Chandler Carruth8765cf72014-01-25 04:07:24 +0000117 Inst.getName() + ".lcssa", ExitBB->begin());
Chris Lattner984d6e12006-10-31 18:56:48 +0000118
Chris Lattner71d353d2009-10-11 02:53:37 +0000119 // Add inputs from inside the loop for this PHI.
Daniel Berlinb4e7a4a2015-04-21 21:11:50 +0000120 for (BasicBlock *Pred : PredCache.get(ExitBB)) {
121 PN->addIncoming(&Inst, Pred);
Dan Gohmanc146c7802009-11-09 18:28:24 +0000122
123 // If the exit block has a predecessor not within the loop, arrange for
Dan Gohmanf324dd62009-11-09 18:59:22 +0000124 // the incoming value use corresponding to that predecessor to be
Dan Gohmanc146c7802009-11-09 18:28:24 +0000125 // rewritten in terms of a different LCSSA PHI.
Daniel Berlinb4e7a4a2015-04-21 21:11:50 +0000126 if (!L.contains(Pred))
Dan Gohmanc146c7802009-11-09 18:28:24 +0000127 UsesToRewrite.push_back(
Chandler Carruth8765cf72014-01-25 04:07:24 +0000128 &PN->getOperandUse(PN->getOperandNumForIncomingValue(
129 PN->getNumIncomingValues() - 1)));
Dan Gohmanc146c7802009-11-09 18:28:24 +0000130 }
Cameron Zwarich0b8cdfb2011-03-15 07:41:25 +0000131
132 AddedPHIs.push_back(PN);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000133
Chris Lattner71d353d2009-10-11 02:53:37 +0000134 // Remember that this phi makes the value alive in this block.
135 SSAUpdate.AddAvailableValue(ExitBB, PN);
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000136
137 // LoopSimplify might fail to simplify some loops (e.g. when indirect
138 // branches are involved). In such situations, it might happen that an exit
139 // for Loop L1 is the header of a disjoint Loop L2. Thus, when we create
140 // PHIs in such an exit block, we are also inserting PHIs into L2's header.
141 // This could break LCSSA form for L2 because these inserted PHIs can also
142 // have uses outside of L2. Remember all PHIs in such situation as to
143 // revisit than later on. FIXME: Remove this if indirectbr support into
144 // LoopSimplify gets improved.
145 if (auto *OtherLoop = LI->getLoopFor(ExitBB))
146 if (!L.contains(OtherLoop))
147 PostProcessPHIs.push_back(PN);
Owen Anderson0ac33692006-06-12 07:10:16 +0000148 }
Benjamin Kramer8682ac12012-10-31 10:01:29 +0000149
Chris Lattner71d353d2009-10-11 02:53:37 +0000150 // Rewrite all uses outside the loop in terms of the new PHIs we just
151 // inserted.
152 for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {
153 // If this use is in an exit block, rewrite to use the newly inserted PHI.
154 // This is required for correctness because SSAUpdate doesn't handle uses in
155 // the same block. It assumes the PHI we inserted is at the end of the
156 // block.
157 Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());
158 BasicBlock *UserBB = User->getParent();
159 if (PHINode *PN = dyn_cast<PHINode>(User))
160 UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);
161
Chandler Carruth8765cf72014-01-25 04:07:24 +0000162 if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
Benjamin Kramerede2fe3bfd2012-10-31 16:30:03 +0000163 // Tell the VHs that the uses changed. This updates SCEV's caches.
164 if (UsesToRewrite[i]->get()->hasValueHandle())
165 ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i], UserBB->begin());
Chris Lattner71d353d2009-10-11 02:53:37 +0000166 UsesToRewrite[i]->set(UserBB->begin());
Chris Lattner5a2bc782006-08-02 00:06:09 +0000167 continue;
Owen Andersoncd76fa02006-06-01 06:05:47 +0000168 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000169
Chris Lattner71d353d2009-10-11 02:53:37 +0000170 // Otherwise, do full PHI insertion.
171 SSAUpdate.RewriteUse(*UsesToRewrite[i]);
Chris Lattner5a2bc782006-08-02 00:06:09 +0000172 }
Cameron Zwarich0b8cdfb2011-03-15 07:41:25 +0000173
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000174 // Post process PHI instructions that were inserted into another disjoint loop
175 // and update their exits properly.
176 for (auto *I : PostProcessPHIs) {
177 if (I->use_empty())
178 continue;
179
180 BasicBlock *PHIBB = I->getParent();
181 Loop *OtherLoop = LI->getLoopFor(PHIBB);
182 SmallVector<BasicBlock *, 8> EBs;
183 OtherLoop->getExitBlocks(EBs);
184 if (EBs.empty())
185 continue;
186
187 // Recurse and re-process each PHI instruction. FIXME: we should really
188 // convert this entire thing to a worklist approach where we process a
189 // vector of instructions...
190 processInstruction(*OtherLoop, *I, DT, EBs, PredCache, LI);
191 }
192
Cameron Zwarich0b8cdfb2011-03-15 07:41:25 +0000193 // Remove PHI nodes that did not have any uses rewritten.
194 for (unsigned i = 0, e = AddedPHIs.size(); i != e; ++i) {
Cameron Zwarichdbb27392011-03-15 18:42:33 +0000195 if (AddedPHIs[i]->use_empty())
Cameron Zwarich0b8cdfb2011-03-15 07:41:25 +0000196 AddedPHIs[i]->eraseFromParent();
197 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000198
Chris Lattner71d353d2009-10-11 02:53:37 +0000199 return true;
Owen Andersondad8c572006-05-31 20:55:06 +0000200}
Chris Lattner5a2bc782006-08-02 00:06:09 +0000201
Chandler Carruth8765cf72014-01-25 04:07:24 +0000202/// Return true if the specified block dominates at least
203/// one of the blocks in the specified list.
204static bool
205blockDominatesAnExit(BasicBlock *BB,
206 DominatorTree &DT,
207 const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
208 DomTreeNode *DomNode = DT.getNode(BB);
209 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
210 if (DT.dominates(DomNode, DT.getNode(ExitBlocks[i])))
211 return true;
212
213 return false;
214}
215
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000216bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI,
217 ScalarEvolution *SE) {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000218 bool Changed = false;
219
220 // Get the set of exiting blocks.
221 SmallVector<BasicBlock *, 8> ExitBlocks;
222 L.getExitBlocks(ExitBlocks);
223
224 if (ExitBlocks.empty())
225 return false;
226
227 PredIteratorCache PredCache;
228
229 // Look at all the instructions in the loop, checking to see if they have uses
230 // outside the loop. If so, rewrite those uses.
231 for (Loop::block_iterator BBI = L.block_begin(), BBE = L.block_end();
232 BBI != BBE; ++BBI) {
233 BasicBlock *BB = *BBI;
234
235 // For large loops, avoid use-scanning by using dominance information: In
236 // particular, if a block does not dominate any of the loop exits, then none
237 // of the values defined in the block could be used outside the loop.
238 if (!blockDominatesAnExit(BB, DT, ExitBlocks))
239 continue;
240
241 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
242 // Reject two common cases fast: instructions with no uses (like stores)
243 // and instructions with one use that is in the same block as this.
244 if (I->use_empty() ||
Chandler Carruthcdf47882014-03-09 03:16:01 +0000245 (I->hasOneUse() && I->user_back()->getParent() == BB &&
246 !isa<PHINode>(I->user_back())))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000247 continue;
248
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000249 Changed |= processInstruction(L, *I, DT, ExitBlocks, PredCache, LI);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000250 }
251 }
252
253 // If we modified the code, remove any caches about the loop from SCEV to
254 // avoid dangling entries.
255 // FIXME: This is a big hammer, can we clear the cache more selectively?
256 if (SE && Changed)
257 SE->forgetLoop(&L);
258
259 assert(L.isLCSSAForm(DT));
260
261 return Changed;
262}
263
Chandler Carruthd84f7762014-01-28 01:25:38 +0000264/// Process a loop nest depth first.
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000265bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI,
Chandler Carruthd84f7762014-01-28 01:25:38 +0000266 ScalarEvolution *SE) {
267 bool Changed = false;
268
269 // Recurse depth-first through inner loops.
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000270 for (Loop::iterator I = L.begin(), E = L.end(); I != E; ++I)
271 Changed |= formLCSSARecursively(**I, DT, LI, SE);
Chandler Carruthd84f7762014-01-28 01:25:38 +0000272
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000273 Changed |= formLCSSA(L, DT, LI, SE);
Chandler Carruthd84f7762014-01-28 01:25:38 +0000274 return Changed;
275}
276
Chandler Carruth8765cf72014-01-25 04:07:24 +0000277namespace {
278struct LCSSA : public FunctionPass {
279 static char ID; // Pass identification, replacement for typeid
280 LCSSA() : FunctionPass(ID) {
281 initializeLCSSAPass(*PassRegistry::getPassRegistry());
282 }
283
284 // Cached analysis information for the current function.
285 DominatorTree *DT;
286 LoopInfo *LI;
287 ScalarEvolution *SE;
288
Craig Topper3e4c6972014-03-05 09:10:37 +0000289 bool runOnFunction(Function &F) override;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000290
291 /// This transformation requires natural loop information & requires that
292 /// loop preheaders be inserted into the CFG. It maintains both of these,
293 /// as well as the CFG. It also requires dominator information.
Craig Topper3e4c6972014-03-05 09:10:37 +0000294 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000295 AU.setPreservesCFG();
296
297 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000298 AU.addRequired<LoopInfoWrapperPass>();
Chandler Carruth8765cf72014-01-25 04:07:24 +0000299 AU.addPreservedID(LoopSimplifyID);
Chandler Carruth756c22c2014-02-10 19:39:35 +0000300 AU.addPreserved<AliasAnalysis>();
Chandler Carruth8765cf72014-01-25 04:07:24 +0000301 AU.addPreserved<ScalarEvolution>();
302 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000303};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000304}
Chandler Carruth8765cf72014-01-25 04:07:24 +0000305
306char LCSSA::ID = 0;
307INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
308INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000309INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000310INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
311
312Pass *llvm::createLCSSAPass() { return new LCSSA(); }
313char &llvm::LCSSAID = LCSSA::ID;
314
315
316/// Process all loops in the function, inner-most out.
317bool LCSSA::runOnFunction(Function &F) {
318 bool Changed = false;
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000319 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth8765cf72014-01-25 04:07:24 +0000320 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
321 SE = getAnalysisIfAvailable<ScalarEvolution>();
322
323 // Simplify each loop nest in the function.
324 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000325 Changed |= formLCSSARecursively(**I, *DT, LI, SE);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000326
327 return Changed;
328}
329