xref: /llvm-project/llvm/lib/Transforms/Utils/LCSSA.cpp (revision 37104d7189cb71e6a606ad2aab5e761e61540787)
1 //===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass transforms loops by placing phi nodes at the end of the loops for
10 // all values that are live across the loop boundary.  For example, it turns
11 // the left into the right code:
12 //
13 // for (...)                for (...)
14 //   if (c)                   if (c)
15 //     X1 = ...                 X1 = ...
16 //   else                     else
17 //     X2 = ...                 X2 = ...
18 //   X3 = phi(X1, X2)         X3 = phi(X1, X2)
19 // ... = X3 + 4             X4 = phi(X3)
20 //                          ... = X4 + 4
21 //
22 // This is still valid LLVM; the extra phi nodes are purely redundant, and will
23 // be trivially eliminated by InstCombine.  The major benefit of this
24 // transformation is that it makes many other loop optimizations, such as
25 // LoopUnswitching, simpler.
26 //
27 //===----------------------------------------------------------------------===//
28 
29 #include "llvm/Transforms/Utils/LCSSA.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/BasicAliasAnalysis.h"
34 #include "llvm/Analysis/BranchProbabilityInfo.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/Transforms/Utils/Local.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/Dominators.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/PredIteratorCache.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Transforms/Utils.h"
48 #include "llvm/Transforms/Utils/LoopUtils.h"
49 #include "llvm/Transforms/Utils/SSAUpdater.h"
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "lcssa"
53 
54 STATISTIC(NumLCSSA, "Number of live out of a loop variables");
55 
56 #ifdef EXPENSIVE_CHECKS
57 static bool VerifyLoopLCSSA = true;
58 #else
59 static bool VerifyLoopLCSSA = false;
60 #endif
61 static cl::opt<bool, true>
62     VerifyLoopLCSSAFlag("verify-loop-lcssa", cl::location(VerifyLoopLCSSA),
63                         cl::Hidden,
64                         cl::desc("Verify loop lcssa form (time consuming)"));
65 
66 /// Return true if the specified block is in the list.
67 static bool isExitBlock(BasicBlock *BB,
68                         const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
69   return is_contained(ExitBlocks, BB);
70 }
71 
72 /// For every instruction from the worklist, check to see if it has any uses
73 /// that are outside the current loop.  If so, insert LCSSA PHI nodes and
74 /// rewrite the uses.
75 bool llvm::formLCSSAForInstructions(SmallVectorImpl<Instruction *> &Worklist,
76                                     DominatorTree &DT, LoopInfo &LI) {
77   SmallVector<Use *, 16> UsesToRewrite;
78   SmallSetVector<PHINode *, 16> PHIsToRemove;
79   PredIteratorCache PredCache;
80   bool Changed = false;
81 
82   // Cache the Loop ExitBlocks across this loop.  We expect to get a lot of
83   // instructions within the same loops, computing the exit blocks is
84   // expensive, and we're not mutating the loop structure.
85   SmallDenseMap<Loop*, SmallVector<BasicBlock *,1>> LoopExitBlocks;
86 
87   while (!Worklist.empty()) {
88     UsesToRewrite.clear();
89 
90     Instruction *I = Worklist.pop_back_val();
91     assert(!I->getType()->isTokenTy() && "Tokens shouldn't be in the worklist");
92     BasicBlock *InstBB = I->getParent();
93     Loop *L = LI.getLoopFor(InstBB);
94     assert(L && "Instruction belongs to a BB that's not part of a loop");
95     if (!LoopExitBlocks.count(L))
96       L->getExitBlocks(LoopExitBlocks[L]);
97     assert(LoopExitBlocks.count(L));
98     const SmallVectorImpl<BasicBlock *> &ExitBlocks = LoopExitBlocks[L];
99 
100     if (ExitBlocks.empty())
101       continue;
102 
103     for (Use &U : I->uses()) {
104       Instruction *User = cast<Instruction>(U.getUser());
105       BasicBlock *UserBB = User->getParent();
106       if (auto *PN = dyn_cast<PHINode>(User))
107         UserBB = PN->getIncomingBlock(U);
108 
109       if (InstBB != UserBB && !L->contains(UserBB))
110         UsesToRewrite.push_back(&U);
111     }
112 
113     // If there are no uses outside the loop, exit with no change.
114     if (UsesToRewrite.empty())
115       continue;
116 
117     ++NumLCSSA; // We are applying the transformation
118 
119     // Invoke instructions are special in that their result value is not
120     // available along their unwind edge. The code below tests to see whether
121     // DomBB dominates the value, so adjust DomBB to the normal destination
122     // block, which is effectively where the value is first usable.
123     BasicBlock *DomBB = InstBB;
124     if (auto *Inv = dyn_cast<InvokeInst>(I))
125       DomBB = Inv->getNormalDest();
126 
127     DomTreeNode *DomNode = DT.getNode(DomBB);
128 
129     SmallVector<PHINode *, 16> AddedPHIs;
130     SmallVector<PHINode *, 8> PostProcessPHIs;
131 
132     SmallVector<PHINode *, 4> InsertedPHIs;
133     SSAUpdater SSAUpdate(&InsertedPHIs);
134     SSAUpdate.Initialize(I->getType(), I->getName());
135 
136     // Insert the LCSSA phi's into all of the exit blocks dominated by the
137     // value, and add them to the Phi's map.
138     for (BasicBlock *ExitBB : ExitBlocks) {
139       if (!DT.dominates(DomNode, DT.getNode(ExitBB)))
140         continue;
141 
142       // If we already inserted something for this BB, don't reprocess it.
143       if (SSAUpdate.HasValueForBlock(ExitBB))
144         continue;
145 
146       PHINode *PN = PHINode::Create(I->getType(), PredCache.size(ExitBB),
147                                     I->getName() + ".lcssa", &ExitBB->front());
148       // Get the debug location from the original instruction.
149       PN->setDebugLoc(I->getDebugLoc());
150       // Add inputs from inside the loop for this PHI.
151       for (BasicBlock *Pred : PredCache.get(ExitBB)) {
152         PN->addIncoming(I, Pred);
153 
154         // If the exit block has a predecessor not within the loop, arrange for
155         // the incoming value use corresponding to that predecessor to be
156         // rewritten in terms of a different LCSSA PHI.
157         if (!L->contains(Pred))
158           UsesToRewrite.push_back(
159               &PN->getOperandUse(PN->getOperandNumForIncomingValue(
160                   PN->getNumIncomingValues() - 1)));
161       }
162 
163       AddedPHIs.push_back(PN);
164 
165       // Remember that this phi makes the value alive in this block.
166       SSAUpdate.AddAvailableValue(ExitBB, PN);
167 
168       // LoopSimplify might fail to simplify some loops (e.g. when indirect
169       // branches are involved). In such situations, it might happen that an
170       // exit for Loop L1 is the header of a disjoint Loop L2. Thus, when we
171       // create PHIs in such an exit block, we are also inserting PHIs into L2's
172       // header. This could break LCSSA form for L2 because these inserted PHIs
173       // can also have uses outside of L2. Remember all PHIs in such situation
174       // as to revisit than later on. FIXME: Remove this if indirectbr support
175       // into LoopSimplify gets improved.
176       if (auto *OtherLoop = LI.getLoopFor(ExitBB))
177         if (!L->contains(OtherLoop))
178           PostProcessPHIs.push_back(PN);
179     }
180 
181     // Rewrite all uses outside the loop in terms of the new PHIs we just
182     // inserted.
183     for (Use *UseToRewrite : UsesToRewrite) {
184       // If this use is in an exit block, rewrite to use the newly inserted PHI.
185       // This is required for correctness because SSAUpdate doesn't handle uses
186       // in the same block.  It assumes the PHI we inserted is at the end of the
187       // block.
188       Instruction *User = cast<Instruction>(UseToRewrite->getUser());
189       BasicBlock *UserBB = User->getParent();
190       if (auto *PN = dyn_cast<PHINode>(User))
191         UserBB = PN->getIncomingBlock(*UseToRewrite);
192 
193       if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {
194         // Tell the VHs that the uses changed. This updates SCEV's caches.
195         if (UseToRewrite->get()->hasValueHandle())
196           ValueHandleBase::ValueIsRAUWd(*UseToRewrite, &UserBB->front());
197         UseToRewrite->set(&UserBB->front());
198         continue;
199       }
200 
201       // If we added a single PHI, it must dominate all uses and we can directly
202       // rename it.
203       if (AddedPHIs.size() == 1) {
204         // Tell the VHs that the uses changed. This updates SCEV's caches.
205         // We might call ValueIsRAUWd multiple times for the same value.
206         if (UseToRewrite->get()->hasValueHandle())
207           ValueHandleBase::ValueIsRAUWd(*UseToRewrite, AddedPHIs[0]);
208         UseToRewrite->set(AddedPHIs[0]);
209         continue;
210       }
211 
212       // Otherwise, do full PHI insertion.
213       SSAUpdate.RewriteUse(*UseToRewrite);
214     }
215 
216     SmallVector<DbgValueInst *, 4> DbgValues;
217     llvm::findDbgValues(DbgValues, I);
218 
219     // Update pre-existing debug value uses that reside outside the loop.
220     auto &Ctx = I->getContext();
221     for (auto DVI : DbgValues) {
222       BasicBlock *UserBB = DVI->getParent();
223       if (InstBB == UserBB || L->contains(UserBB))
224         continue;
225       // We currently only handle debug values residing in blocks that were
226       // traversed while rewriting the uses. If we inserted just a single PHI,
227       // we will handle all relevant debug values.
228       Value *V = AddedPHIs.size() == 1 ? AddedPHIs[0]
229                                        : SSAUpdate.FindValueForBlock(UserBB);
230       if (V)
231         DVI->setOperand(0, MetadataAsValue::get(Ctx, ValueAsMetadata::get(V)));
232     }
233 
234     // SSAUpdater might have inserted phi-nodes inside other loops. We'll need
235     // to post-process them to keep LCSSA form.
236     for (PHINode *InsertedPN : InsertedPHIs) {
237       if (auto *OtherLoop = LI.getLoopFor(InsertedPN->getParent()))
238         if (!L->contains(OtherLoop))
239           PostProcessPHIs.push_back(InsertedPN);
240     }
241 
242     // Post process PHI instructions that were inserted into another disjoint
243     // loop and update their exits properly.
244     for (auto *PostProcessPN : PostProcessPHIs)
245       if (!PostProcessPN->use_empty())
246         Worklist.push_back(PostProcessPN);
247 
248     // Keep track of PHI nodes that we want to remove because they did not have
249     // any uses rewritten. If the new PHI is used, store it so that we can
250     // try to propagate dbg.value intrinsics to it.
251     SmallVector<PHINode *, 2> NeedDbgValues;
252     for (PHINode *PN : AddedPHIs)
253       if (PN->use_empty())
254         PHIsToRemove.insert(PN);
255       else
256         NeedDbgValues.push_back(PN);
257     insertDebugValuesForPHIs(InstBB, NeedDbgValues);
258     Changed = true;
259   }
260   // Remove PHI nodes that did not have any uses rewritten. We need to redo the
261   // use_empty() check here, because even if the PHI node wasn't used when added
262   // to PHIsToRemove, later added PHI nodes can be using it.  This cleanup is
263   // not guaranteed to handle trees/cycles of PHI nodes that only are used by
264   // each other. Such situations has only been noticed when the input IR
265   // contains unreachable code, and leaving some extra redundant PHI nodes in
266   // such situations is considered a minor problem.
267   for (PHINode *PN : PHIsToRemove)
268     if (PN->use_empty())
269       PN->eraseFromParent();
270   return Changed;
271 }
272 
273 // Compute the set of BasicBlocks in the loop `L` dominating at least one exit.
274 static void computeBlocksDominatingExits(
275     Loop &L, DominatorTree &DT, SmallVector<BasicBlock *, 8> &ExitBlocks,
276     SmallSetVector<BasicBlock *, 8> &BlocksDominatingExits) {
277   SmallVector<BasicBlock *, 8> BBWorklist;
278 
279   // We start from the exit blocks, as every block trivially dominates itself
280   // (not strictly).
281   for (BasicBlock *BB : ExitBlocks)
282     BBWorklist.push_back(BB);
283 
284   while (!BBWorklist.empty()) {
285     BasicBlock *BB = BBWorklist.pop_back_val();
286 
287     // Check if this is a loop header. If this is the case, we're done.
288     if (L.getHeader() == BB)
289       continue;
290 
291     // Otherwise, add its immediate predecessor in the dominator tree to the
292     // worklist, unless we visited it already.
293     BasicBlock *IDomBB = DT.getNode(BB)->getIDom()->getBlock();
294 
295     // Exit blocks can have an immediate dominator not beloinging to the
296     // loop. For an exit block to be immediately dominated by another block
297     // outside the loop, it implies not all paths from that dominator, to the
298     // exit block, go through the loop.
299     // Example:
300     //
301     // |---- A
302     // |     |
303     // |     B<--
304     // |     |  |
305     // |---> C --
306     //       |
307     //       D
308     //
309     // C is the exit block of the loop and it's immediately dominated by A,
310     // which doesn't belong to the loop.
311     if (!L.contains(IDomBB))
312       continue;
313 
314     if (BlocksDominatingExits.insert(IDomBB))
315       BBWorklist.push_back(IDomBB);
316   }
317 }
318 
319 bool llvm::formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI,
320                      ScalarEvolution *SE) {
321   bool Changed = false;
322 
323 #ifdef EXPENSIVE_CHECKS
324   // Verify all sub-loops are in LCSSA form already.
325   for (Loop *SubLoop: L)
326     assert(SubLoop->isRecursivelyLCSSAForm(DT, *LI) && "Subloop not in LCSSA!");
327 #endif
328 
329   SmallVector<BasicBlock *, 8> ExitBlocks;
330   L.getExitBlocks(ExitBlocks);
331   if (ExitBlocks.empty())
332     return false;
333 
334   SmallSetVector<BasicBlock *, 8> BlocksDominatingExits;
335 
336   // We want to avoid use-scanning leveraging dominance informations.
337   // If a block doesn't dominate any of the loop exits, the none of the values
338   // defined in the loop can be used outside.
339   // We compute the set of blocks fullfilling the conditions in advance
340   // walking the dominator tree upwards until we hit a loop header.
341   computeBlocksDominatingExits(L, DT, ExitBlocks, BlocksDominatingExits);
342 
343   SmallVector<Instruction *, 8> Worklist;
344 
345   // Look at all the instructions in the loop, checking to see if they have uses
346   // outside the loop.  If so, put them into the worklist to rewrite those uses.
347   for (BasicBlock *BB : BlocksDominatingExits) {
348     // Skip blocks that are part of any sub-loops, they must be in LCSSA
349     // already.
350     if (LI->getLoopFor(BB) != &L)
351       continue;
352     for (Instruction &I : *BB) {
353       // Reject two common cases fast: instructions with no uses (like stores)
354       // and instructions with one use that is in the same block as this.
355       if (I.use_empty() ||
356           (I.hasOneUse() && I.user_back()->getParent() == BB &&
357            !isa<PHINode>(I.user_back())))
358         continue;
359 
360       // Tokens cannot be used in PHI nodes, so we skip over them.
361       // We can run into tokens which are live out of a loop with catchswitch
362       // instructions in Windows EH if the catchswitch has one catchpad which
363       // is inside the loop and another which is not.
364       if (I.getType()->isTokenTy())
365         continue;
366 
367       Worklist.push_back(&I);
368     }
369   }
370   Changed = formLCSSAForInstructions(Worklist, DT, *LI);
371 
372   // If we modified the code, remove any caches about the loop from SCEV to
373   // avoid dangling entries.
374   // FIXME: This is a big hammer, can we clear the cache more selectively?
375   if (SE && Changed)
376     SE->forgetLoop(&L);
377 
378   assert(L.isLCSSAForm(DT));
379 
380   return Changed;
381 }
382 
383 /// Process a loop nest depth first.
384 bool llvm::formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI,
385                                 ScalarEvolution *SE) {
386   bool Changed = false;
387 
388   // Recurse depth-first through inner loops.
389   for (Loop *SubLoop : L.getSubLoops())
390     Changed |= formLCSSARecursively(*SubLoop, DT, LI, SE);
391 
392   Changed |= formLCSSA(L, DT, LI, SE);
393   return Changed;
394 }
395 
396 /// Process all loops in the function, inner-most out.
397 static bool formLCSSAOnAllLoops(LoopInfo *LI, DominatorTree &DT,
398                                 ScalarEvolution *SE) {
399   bool Changed = false;
400   for (auto &L : *LI)
401     Changed |= formLCSSARecursively(*L, DT, LI, SE);
402   return Changed;
403 }
404 
405 namespace {
406 struct LCSSAWrapperPass : public FunctionPass {
407   static char ID; // Pass identification, replacement for typeid
408   LCSSAWrapperPass() : FunctionPass(ID) {
409     initializeLCSSAWrapperPassPass(*PassRegistry::getPassRegistry());
410   }
411 
412   // Cached analysis information for the current function.
413   DominatorTree *DT;
414   LoopInfo *LI;
415   ScalarEvolution *SE;
416 
417   bool runOnFunction(Function &F) override;
418   void verifyAnalysis() const override {
419     // This check is very expensive. On the loop intensive compiles it may cause
420     // up to 10x slowdown. Currently it's disabled by default. LPPassManager
421     // always does limited form of the LCSSA verification. Similar reasoning
422     // was used for the LoopInfo verifier.
423     if (VerifyLoopLCSSA) {
424       assert(all_of(*LI,
425                     [&](Loop *L) {
426                       return L->isRecursivelyLCSSAForm(*DT, *LI);
427                     }) &&
428              "LCSSA form is broken!");
429     }
430   };
431 
432   /// This transformation requires natural loop information & requires that
433   /// loop preheaders be inserted into the CFG.  It maintains both of these,
434   /// as well as the CFG.  It also requires dominator information.
435   void getAnalysisUsage(AnalysisUsage &AU) const override {
436     AU.setPreservesCFG();
437 
438     AU.addRequired<DominatorTreeWrapperPass>();
439     AU.addRequired<LoopInfoWrapperPass>();
440     AU.addPreservedID(LoopSimplifyID);
441     AU.addPreserved<AAResultsWrapperPass>();
442     AU.addPreserved<BasicAAWrapperPass>();
443     AU.addPreserved<GlobalsAAWrapperPass>();
444     AU.addPreserved<ScalarEvolutionWrapperPass>();
445     AU.addPreserved<SCEVAAWrapperPass>();
446     AU.addPreserved<BranchProbabilityInfoWrapperPass>();
447 
448     // This is needed to perform LCSSA verification inside LPPassManager
449     AU.addRequired<LCSSAVerificationPass>();
450     AU.addPreserved<LCSSAVerificationPass>();
451   }
452 };
453 }
454 
455 char LCSSAWrapperPass::ID = 0;
456 INITIALIZE_PASS_BEGIN(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass",
457                       false, false)
458 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
459 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
460 INITIALIZE_PASS_DEPENDENCY(LCSSAVerificationPass)
461 INITIALIZE_PASS_END(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass",
462                     false, false)
463 
464 Pass *llvm::createLCSSAPass() { return new LCSSAWrapperPass(); }
465 char &llvm::LCSSAID = LCSSAWrapperPass::ID;
466 
467 /// Transform \p F into loop-closed SSA form.
468 bool LCSSAWrapperPass::runOnFunction(Function &F) {
469   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
470   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
471   auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
472   SE = SEWP ? &SEWP->getSE() : nullptr;
473 
474   return formLCSSAOnAllLoops(LI, *DT, SE);
475 }
476 
477 PreservedAnalyses LCSSAPass::run(Function &F, FunctionAnalysisManager &AM) {
478   auto &LI = AM.getResult<LoopAnalysis>(F);
479   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
480   auto *SE = AM.getCachedResult<ScalarEvolutionAnalysis>(F);
481   if (!formLCSSAOnAllLoops(&LI, DT, SE))
482     return PreservedAnalyses::all();
483 
484   PreservedAnalyses PA;
485   PA.preserveSet<CFGAnalyses>();
486   PA.preserve<BasicAA>();
487   PA.preserve<GlobalsAA>();
488   PA.preserve<SCEVAA>();
489   PA.preserve<ScalarEvolutionAnalysis>();
490   // BPI maps terminators to probabilities, since we don't modify the CFG, no
491   // updates are needed to preserve it.
492   PA.preserve<BranchProbabilityAnalysis>();
493   return PA;
494 }
495