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 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/AliasAnalysis.h"
34 #include "llvm/Analysis/GlobalsModRef.h"
35 #include "llvm/Analysis/LoopPass.h"
36 #include "llvm/Analysis/ScalarEvolution.h"
37 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Dominators.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/PredIteratorCache.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Transforms/Utils/LoopUtils.h"
45 #include "llvm/Transforms/Utils/SSAUpdater.h"
48 #define DEBUG_TYPE "lcssa"
50 STATISTIC(NumLCSSA, "Number of live out of a loop variables");
52 /// Return true if the specified block is in the list.
53 static bool isExitBlock(BasicBlock *BB,
54 const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
55 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
56 if (ExitBlocks[i] == BB)
61 /// Given an instruction in the loop, check to see if it has any uses that are
62 /// outside the current loop. If so, insert LCSSA PHI nodes and rewrite the
64 static bool processInstruction(Loop &L, Instruction &Inst, DominatorTree &DT,
65 const SmallVectorImpl<BasicBlock *> &ExitBlocks,
66 PredIteratorCache &PredCache, LoopInfo *LI) {
67 SmallVector<Use *, 16> UsesToRewrite;
69 BasicBlock *InstBB = Inst.getParent();
71 for (Use &U : Inst.uses()) {
72 Instruction *User = cast<Instruction>(U.getUser());
73 BasicBlock *UserBB = User->getParent();
74 if (PHINode *PN = dyn_cast<PHINode>(User))
75 UserBB = PN->getIncomingBlock(U);
77 if (InstBB != UserBB && !L.contains(UserBB))
78 UsesToRewrite.push_back(&U);
81 // If there are no uses outside the loop, exit with no change.
82 if (UsesToRewrite.empty())
85 ++NumLCSSA; // We are applying the transformation
87 // Invoke/CatchPad instructions are special in that their result value is not
88 // available along their unwind edge. The code below tests to see whether
89 // DomBB dominates the value, so adjust DomBB to the normal destination block,
90 // which is effectively where the value is first usable.
91 BasicBlock *DomBB = Inst.getParent();
92 if (InvokeInst *Inv = dyn_cast<InvokeInst>(&Inst))
93 DomBB = Inv->getNormalDest();
94 if (auto *CPI = dyn_cast<CatchPadInst>(&Inst))
95 DomBB = CPI->getNormalDest();
97 DomTreeNode *DomNode = DT.getNode(DomBB);
99 SmallVector<PHINode *, 16> AddedPHIs;
100 SmallVector<PHINode *, 8> PostProcessPHIs;
102 SSAUpdater SSAUpdate;
103 SSAUpdate.Initialize(Inst.getType(), Inst.getName());
105 // Insert the LCSSA phi's into all of the exit blocks dominated by the
106 // value, and add them to the Phi's map.
107 for (BasicBlock *ExitBB : ExitBlocks) {
108 if (!DT.dominates(DomNode, DT.getNode(ExitBB)))
111 // If we already inserted something for this BB, don't reprocess it.
112 if (SSAUpdate.HasValueForBlock(ExitBB))
115 PHINode *PN = PHINode::Create(Inst.getType(), PredCache.size(ExitBB),
116 Inst.getName() + ".lcssa", &ExitBB->front());
118 // Add inputs from inside the loop for this PHI.
119 for (BasicBlock *Pred : PredCache.get(ExitBB)) {
120 PN->addIncoming(&Inst, Pred);
122 // If the exit block has a predecessor not within the loop, arrange for
123 // the incoming value use corresponding to that predecessor to be
124 // rewritten in terms of a different LCSSA PHI.
125 if (!L.contains(Pred))
126 UsesToRewrite.push_back(
127 &PN->getOperandUse(PN->getOperandNumForIncomingValue(
128 PN->getNumIncomingValues() - 1)));
131 AddedPHIs.push_back(PN);
133 // Remember that this phi makes the value alive in this block.
134 SSAUpdate.AddAvailableValue(ExitBB, PN);
136 // LoopSimplify might fail to simplify some loops (e.g. when indirect
137 // branches are involved). In such situations, it might happen that an exit
138 // for Loop L1 is the header of a disjoint Loop L2. Thus, when we create
139 // PHIs in such an exit block, we are also inserting PHIs into L2's header.
140 // This could break LCSSA form for L2 because these inserted PHIs can also
141 // have uses outside of L2. Remember all PHIs in such situation as to
142 // revisit than later on. FIXME: Remove this if indirectbr support into
143 // LoopSimplify gets improved.
144 if (auto *OtherLoop = LI->getLoopFor(ExitBB))
145 if (!L.contains(OtherLoop))
146 PostProcessPHIs.push_back(PN);
149 // Rewrite all uses outside the loop in terms of the new PHIs we just
151 for (Use *UseToRewrite : UsesToRewrite) {
152 // If this use is in an exit block, rewrite to use the newly inserted PHI.
153 // This is required for correctness because SSAUpdate doesn't handle uses in
154 // the same block. It assumes the PHI we inserted is at the end of the
156 Instruction *User = cast<Instruction>(UseToRewrite->getUser());
157 BasicBlock *UserBB = User->getParent();
158 if (PHINode *PN = dyn_cast<PHINode>(User))
159 UserBB = PN->getIncomingBlock(*UseToRewrite);
161 if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
162 // Tell the VHs that the uses changed. This updates SCEV's caches.
163 if (UseToRewrite->get()->hasValueHandle())
164 ValueHandleBase::ValueIsRAUWd(*UseToRewrite, &UserBB->front());
165 UseToRewrite->set(&UserBB->front());
169 // Otherwise, do full PHI insertion.
170 SSAUpdate.RewriteUse(*UseToRewrite);
173 // Post process PHI instructions that were inserted into another disjoint loop
174 // and update their exits properly.
175 for (auto *I : PostProcessPHIs) {
179 BasicBlock *PHIBB = I->getParent();
180 Loop *OtherLoop = LI->getLoopFor(PHIBB);
181 SmallVector<BasicBlock *, 8> EBs;
182 OtherLoop->getExitBlocks(EBs);
186 // Recurse and re-process each PHI instruction. FIXME: we should really
187 // convert this entire thing to a worklist approach where we process a
188 // vector of instructions...
189 processInstruction(*OtherLoop, *I, DT, EBs, PredCache, LI);
192 // Remove PHI nodes that did not have any uses rewritten.
193 for (PHINode *PN : AddedPHIs)
195 PN->eraseFromParent();
200 /// Return true if the specified block dominates at least
201 /// one of the blocks in the specified list.
203 blockDominatesAnExit(BasicBlock *BB,
205 const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
206 DomTreeNode *DomNode = DT.getNode(BB);
207 for (BasicBlock *ExitBB : ExitBlocks)
208 if (DT.dominates(DomNode, DT.getNode(ExitBB)))
214 bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI,
215 ScalarEvolution *SE) {
216 bool Changed = false;
218 // Get the set of exiting blocks.
219 SmallVector<BasicBlock *, 8> ExitBlocks;
220 L.getExitBlocks(ExitBlocks);
222 if (ExitBlocks.empty())
225 PredIteratorCache PredCache;
227 // Look at all the instructions in the loop, checking to see if they have uses
228 // outside the loop. If so, rewrite those uses.
229 for (BasicBlock *BB : L.blocks()) {
230 // For large loops, avoid use-scanning by using dominance information: In
231 // particular, if a block does not dominate any of the loop exits, then none
232 // of the values defined in the block could be used outside the loop.
233 if (!blockDominatesAnExit(BB, DT, ExitBlocks))
236 for (Instruction &I : *BB) {
237 // Reject two common cases fast: instructions with no uses (like stores)
238 // and instructions with one use that is in the same block as this.
240 (I.hasOneUse() && I.user_back()->getParent() == BB &&
241 !isa<PHINode>(I.user_back())))
244 Changed |= processInstruction(L, I, DT, ExitBlocks, PredCache, LI);
248 // If we modified the code, remove any caches about the loop from SCEV to
249 // avoid dangling entries.
250 // FIXME: This is a big hammer, can we clear the cache more selectively?
254 assert(L.isLCSSAForm(DT));
259 /// Process a loop nest depth first.
260 bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI,
261 ScalarEvolution *SE) {
262 bool Changed = false;
264 // Recurse depth-first through inner loops.
265 for (Loop *SubLoop : L.getSubLoops())
266 Changed |= formLCSSARecursively(*SubLoop, DT, LI, SE);
268 Changed |= formLCSSA(L, DT, LI, SE);
273 struct LCSSA : public FunctionPass {
274 static char ID; // Pass identification, replacement for typeid
275 LCSSA() : FunctionPass(ID) {
276 initializeLCSSAPass(*PassRegistry::getPassRegistry());
279 // Cached analysis information for the current function.
284 bool runOnFunction(Function &F) override;
286 /// This transformation requires natural loop information & requires that
287 /// loop preheaders be inserted into the CFG. It maintains both of these,
288 /// as well as the CFG. It also requires dominator information.
289 void getAnalysisUsage(AnalysisUsage &AU) const override {
290 AU.setPreservesCFG();
292 AU.addRequired<DominatorTreeWrapperPass>();
293 AU.addRequired<LoopInfoWrapperPass>();
294 AU.addPreservedID(LoopSimplifyID);
295 AU.addPreserved<AAResultsWrapperPass>();
296 AU.addPreserved<GlobalsAAWrapperPass>();
297 AU.addPreserved<ScalarEvolutionWrapperPass>();
298 AU.addPreserved<SCEVAAWrapperPass>();
304 INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
305 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
306 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
307 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
308 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
309 INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
311 Pass *llvm::createLCSSAPass() { return new LCSSA(); }
312 char &llvm::LCSSAID = LCSSA::ID;
315 /// Process all loops in the function, inner-most out.
316 bool LCSSA::runOnFunction(Function &F) {
317 bool Changed = false;
318 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
319 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
320 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
321 SE = SEWP ? &SEWP->getSE() : nullptr;
323 // Simplify each loop nest in the function.
324 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
325 Changed |= formLCSSARecursively(**I, *DT, LI, SE);