xref: /llvm-project/llvm/lib/Transforms/Utils/LCSSA.cpp (revision ac07270828e6d34acbae9584789e8709a18b258a)
1 //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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)
20 // ... = X3 + 4             X4 = phi(X3)
21 //                          ... = X4 + 4
22 //
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 #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/BasicAliasAnalysis.h"
35 #include "llvm/Analysis/GlobalsModRef.h"
36 #include "llvm/Analysis/LoopPass.h"
37 #include "llvm/Analysis/ScalarEvolution.h"
38 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/Dominators.h"
41 #include "llvm/IR/Function.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/PredIteratorCache.h"
44 #include "llvm/Pass.h"
45 #include "llvm/Transforms/Utils/LoopUtils.h"
46 #include "llvm/Transforms/Utils/SSAUpdater.h"
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "lcssa"
50 
51 STATISTIC(NumLCSSA, "Number of live out of a loop variables");
52 
53 /// Return true if the specified block is in the list.
54 static bool isExitBlock(BasicBlock *BB,
55                         const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
56   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
57     if (ExitBlocks[i] == BB)
58       return true;
59   return false;
60 }
61 
62 /// Given an instruction in the loop, check to see if it has any uses that are
63 /// outside the current loop.  If so, insert LCSSA PHI nodes and rewrite the
64 /// uses.
65 static bool processInstruction(Loop &L, Instruction &Inst, DominatorTree &DT,
66                                const SmallVectorImpl<BasicBlock *> &ExitBlocks,
67                                PredIteratorCache &PredCache, LoopInfo *LI) {
68   SmallVector<Use *, 16> UsesToRewrite;
69 
70   // Tokens cannot be used in PHI nodes, so we skip over them.
71   // We can run into tokens which are live out of a loop with catchswitch
72   // instructions in Windows EH if the catchswitch has one catchpad which
73   // is inside the loop and another which is not.
74   if (Inst.getType()->isTokenTy())
75     return false;
76 
77   BasicBlock *InstBB = Inst.getParent();
78 
79   for (Use &U : Inst.uses()) {
80     Instruction *User = cast<Instruction>(U.getUser());
81     BasicBlock *UserBB = User->getParent();
82     if (PHINode *PN = dyn_cast<PHINode>(User))
83       UserBB = PN->getIncomingBlock(U);
84 
85     if (InstBB != UserBB && !L.contains(UserBB))
86       UsesToRewrite.push_back(&U);
87   }
88 
89   // If there are no uses outside the loop, exit with no change.
90   if (UsesToRewrite.empty())
91     return false;
92 
93   ++NumLCSSA; // We are applying the transformation
94 
95   // Invoke instructions are special in that their result value is not available
96   // along their unwind edge. The code below tests to see whether DomBB
97   // dominates the value, so adjust DomBB to the normal destination block,
98   // which is effectively where the value is first usable.
99   BasicBlock *DomBB = Inst.getParent();
100   if (InvokeInst *Inv = dyn_cast<InvokeInst>(&Inst))
101     DomBB = Inv->getNormalDest();
102 
103   DomTreeNode *DomNode = DT.getNode(DomBB);
104 
105   SmallVector<PHINode *, 16> AddedPHIs;
106   SmallVector<PHINode *, 8> PostProcessPHIs;
107 
108   SSAUpdater SSAUpdate;
109   SSAUpdate.Initialize(Inst.getType(), Inst.getName());
110 
111   // Insert the LCSSA phi's into all of the exit blocks dominated by the
112   // value, and add them to the Phi's map.
113   for (BasicBlock *ExitBB : ExitBlocks) {
114     if (!DT.dominates(DomNode, DT.getNode(ExitBB)))
115       continue;
116 
117     // If we already inserted something for this BB, don't reprocess it.
118     if (SSAUpdate.HasValueForBlock(ExitBB))
119       continue;
120 
121     PHINode *PN = PHINode::Create(Inst.getType(), PredCache.size(ExitBB),
122                                   Inst.getName() + ".lcssa", &ExitBB->front());
123 
124     // Add inputs from inside the loop for this PHI.
125     for (BasicBlock *Pred : PredCache.get(ExitBB)) {
126       PN->addIncoming(&Inst, Pred);
127 
128       // If the exit block has a predecessor not within the loop, arrange for
129       // the incoming value use corresponding to that predecessor to be
130       // rewritten in terms of a different LCSSA PHI.
131       if (!L.contains(Pred))
132         UsesToRewrite.push_back(
133             &PN->getOperandUse(PN->getOperandNumForIncomingValue(
134                  PN->getNumIncomingValues() - 1)));
135     }
136 
137     AddedPHIs.push_back(PN);
138 
139     // Remember that this phi makes the value alive in this block.
140     SSAUpdate.AddAvailableValue(ExitBB, PN);
141 
142     // LoopSimplify might fail to simplify some loops (e.g. when indirect
143     // branches are involved). In such situations, it might happen that an exit
144     // for Loop L1 is the header of a disjoint Loop L2. Thus, when we create
145     // PHIs in such an exit block, we are also inserting PHIs into L2's header.
146     // This could break LCSSA form for L2 because these inserted PHIs can also
147     // have uses outside of L2. Remember all PHIs in such situation as to
148     // revisit than later on. FIXME: Remove this if indirectbr support into
149     // LoopSimplify gets improved.
150     if (auto *OtherLoop = LI->getLoopFor(ExitBB))
151       if (!L.contains(OtherLoop))
152         PostProcessPHIs.push_back(PN);
153   }
154 
155   // Rewrite all uses outside the loop in terms of the new PHIs we just
156   // inserted.
157   for (Use *UseToRewrite : UsesToRewrite) {
158     // If this use is in an exit block, rewrite to use the newly inserted PHI.
159     // This is required for correctness because SSAUpdate doesn't handle uses in
160     // the same block.  It assumes the PHI we inserted is at the end of the
161     // block.
162     Instruction *User = cast<Instruction>(UseToRewrite->getUser());
163     BasicBlock *UserBB = User->getParent();
164     if (PHINode *PN = dyn_cast<PHINode>(User))
165       UserBB = PN->getIncomingBlock(*UseToRewrite);
166 
167     if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
168       // Tell the VHs that the uses changed. This updates SCEV's caches.
169       if (UseToRewrite->get()->hasValueHandle())
170         ValueHandleBase::ValueIsRAUWd(*UseToRewrite, &UserBB->front());
171       UseToRewrite->set(&UserBB->front());
172       continue;
173     }
174 
175     // Otherwise, do full PHI insertion.
176     SSAUpdate.RewriteUse(*UseToRewrite);
177   }
178 
179   // Post process PHI instructions that were inserted into another disjoint loop
180   // and update their exits properly.
181   for (auto *I : PostProcessPHIs) {
182     if (I->use_empty())
183       continue;
184 
185     BasicBlock *PHIBB = I->getParent();
186     Loop *OtherLoop = LI->getLoopFor(PHIBB);
187     SmallVector<BasicBlock *, 8> EBs;
188     OtherLoop->getExitBlocks(EBs);
189     if (EBs.empty())
190       continue;
191 
192     // Recurse and re-process each PHI instruction. FIXME: we should really
193     // convert this entire thing to a worklist approach where we process a
194     // vector of instructions...
195     processInstruction(*OtherLoop, *I, DT, EBs, PredCache, LI);
196   }
197 
198   // Remove PHI nodes that did not have any uses rewritten.
199   for (PHINode *PN : AddedPHIs)
200     if (PN->use_empty())
201       PN->eraseFromParent();
202 
203   return true;
204 }
205 
206 /// Return true if the specified block dominates at least
207 /// one of the blocks in the specified list.
208 static bool
209 blockDominatesAnExit(BasicBlock *BB,
210                      DominatorTree &DT,
211                      const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
212   DomTreeNode *DomNode = DT.getNode(BB);
213   for (BasicBlock *ExitBB : ExitBlocks)
214     if (DT.dominates(DomNode, DT.getNode(ExitBB)))
215       return true;
216 
217   return false;
218 }
219 
220 bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI,
221                      ScalarEvolution *SE) {
222   bool Changed = false;
223 
224   // Get the set of exiting blocks.
225   SmallVector<BasicBlock *, 8> ExitBlocks;
226   L.getExitBlocks(ExitBlocks);
227 
228   if (ExitBlocks.empty())
229     return false;
230 
231   PredIteratorCache PredCache;
232 
233   // Look at all the instructions in the loop, checking to see if they have uses
234   // outside the loop.  If so, rewrite those uses.
235   for (BasicBlock *BB : L.blocks()) {
236     // For large loops, avoid use-scanning by using dominance information:  In
237     // particular, if a block does not dominate any of the loop exits, then none
238     // of the values defined in the block could be used outside the loop.
239     if (!blockDominatesAnExit(BB, DT, ExitBlocks))
240       continue;
241 
242     for (Instruction &I : *BB) {
243       // Reject two common cases fast: instructions with no uses (like stores)
244       // and instructions with one use that is in the same block as this.
245       if (I.use_empty() ||
246           (I.hasOneUse() && I.user_back()->getParent() == BB &&
247            !isa<PHINode>(I.user_back())))
248         continue;
249 
250       Changed |= processInstruction(L, I, DT, ExitBlocks, PredCache, LI);
251     }
252   }
253 
254   // If we modified the code, remove any caches about the loop from SCEV to
255   // avoid dangling entries.
256   // FIXME: This is a big hammer, can we clear the cache more selectively?
257   if (SE && Changed)
258     SE->forgetLoop(&L);
259 
260   assert(L.isLCSSAForm(DT));
261 
262   return Changed;
263 }
264 
265 /// Process a loop nest depth first.
266 bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI,
267                                 ScalarEvolution *SE) {
268   bool Changed = false;
269 
270   // Recurse depth-first through inner loops.
271   for (Loop *SubLoop : L.getSubLoops())
272     Changed |= formLCSSARecursively(*SubLoop, DT, LI, SE);
273 
274   Changed |= formLCSSA(L, DT, LI, SE);
275   return Changed;
276 }
277 
278 namespace {
279 struct LCSSA : public FunctionPass {
280   static char ID; // Pass identification, replacement for typeid
281   LCSSA() : FunctionPass(ID) {
282     initializeLCSSAPass(*PassRegistry::getPassRegistry());
283   }
284 
285   // Cached analysis information for the current function.
286   DominatorTree *DT;
287   LoopInfo *LI;
288   ScalarEvolution *SE;
289 
290   bool runOnFunction(Function &F) override;
291 
292   /// This transformation requires natural loop information & requires that
293   /// loop preheaders be inserted into the CFG.  It maintains both of these,
294   /// as well as the CFG.  It also requires dominator information.
295   void getAnalysisUsage(AnalysisUsage &AU) const override {
296     AU.setPreservesCFG();
297 
298     AU.addRequired<DominatorTreeWrapperPass>();
299     AU.addRequired<LoopInfoWrapperPass>();
300     AU.addPreservedID(LoopSimplifyID);
301     AU.addPreserved<AAResultsWrapperPass>();
302     AU.addPreserved<BasicAAWrapperPass>();
303     AU.addPreserved<GlobalsAAWrapperPass>();
304     AU.addPreserved<ScalarEvolutionWrapperPass>();
305     AU.addPreserved<SCEVAAWrapperPass>();
306   }
307 };
308 }
309 
310 char LCSSA::ID = 0;
311 INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
312 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
313 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
314 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
315 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
316 INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
317 
318 Pass *llvm::createLCSSAPass() { return new LCSSA(); }
319 char &llvm::LCSSAID = LCSSA::ID;
320 
321 
322 /// Process all loops in the function, inner-most out.
323 bool LCSSA::runOnFunction(Function &F) {
324   bool Changed = false;
325   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
326   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
327   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
328   SE = SEWP ? &SEWP->getSE() : nullptr;
329 
330   // Simplify each loop nest in the function.
331   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
332     Changed |= formLCSSARecursively(**I, *DT, LI, SE);
333 
334   return Changed;
335 }
336 
337