xref: /llvm-project/llvm/lib/Transforms/Utils/LCSSA.cpp (revision 71d353dd485cc17335dacd8583f521361edf37ec)
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 #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"
36 #include "llvm/Analysis/Dominators.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Analysis/ScalarEvolution.h"
39 #include "llvm/Transforms/Utils/SSAUpdater.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/Support/PredIteratorCache.h"
43 using namespace llvm;
44 
45 STATISTIC(NumLCSSA, "Number of live out of a loop variables");
46 
47 namespace {
48   struct LCSSA : public LoopPass {
49     static char ID; // Pass identification, replacement for typeid
50     LCSSA() : LoopPass(&ID) {}
51 
52     // Cached analysis information for the current function.
53     LoopInfo *LI;
54     DominatorTree *DT;
55     std::vector<BasicBlock*> LoopBlocks;
56     PredIteratorCache PredCache;
57     Loop *L;
58 
59     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
60 
61     /// This transformation requires natural loop information & requires that
62     /// loop preheaders be inserted into the CFG.  It maintains both of these,
63     /// as well as the CFG.  It also requires dominator information.
64     ///
65     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
66       AU.setPreservesCFG();
67       AU.addRequiredID(LoopSimplifyID);
68       AU.addPreservedID(LoopSimplifyID);
69       AU.addRequiredTransitive<LoopInfo>();
70       AU.addPreserved<LoopInfo>();
71       AU.addRequiredTransitive<DominatorTree>();
72       AU.addPreserved<ScalarEvolution>();
73       AU.addPreserved<DominatorTree>();
74 
75       // Request DominanceFrontier now, even though LCSSA does
76       // not use it. This allows Pass Manager to schedule Dominance
77       // Frontier early enough such that one LPPassManager can handle
78       // multiple loop transformation passes.
79       AU.addRequired<DominanceFrontier>();
80       AU.addPreserved<DominanceFrontier>();
81     }
82   private:
83     bool ProcessInstruction(Instruction *Inst,
84                             const SmallVectorImpl<BasicBlock*> &ExitBlocks);
85 
86     /// verifyAnalysis() - Verify loop nest.
87     virtual void verifyAnalysis() const {
88       // Check the special guarantees that LCSSA makes.
89       assert(L->isLCSSAForm() && "LCSSA form not preserved!");
90     }
91 
92     /// inLoop - returns true if the given block is within the current loop
93     bool inLoop(BasicBlock *B) const {
94       return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
95     }
96   };
97 }
98 
99 char LCSSA::ID = 0;
100 static RegisterPass<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
101 
102 Pass *llvm::createLCSSAPass() { return new LCSSA(); }
103 const PassInfo *const llvm::LCSSAID = &X;
104 
105 
106 /// BlockDominatesAnExit - Return true if the specified block dominates at least
107 /// one of the blocks in the specified list.
108 static bool BlockDominatesAnExit(BasicBlock *BB,
109                                  const SmallVectorImpl<BasicBlock*> &ExitBlocks,
110                                  DominatorTree *DT) {
111   DomTreeNode *DomNode = DT->getNode(BB);
112   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
113     if (DT->dominates(DomNode, DT->getNode(ExitBlocks[i])))
114       return true;
115 
116   return false;
117 }
118 
119 
120 /// runOnFunction - Process all loops in the function, inner-most out.
121 bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {
122   L = TheLoop;
123 
124   LI = &LPM.getAnalysis<LoopInfo>();
125   DT = &getAnalysis<DominatorTree>();
126 
127   // Get the set of exiting blocks.
128   SmallVector<BasicBlock*, 8> ExitBlocks;
129   L->getExitBlocks(ExitBlocks);
130 
131   if (ExitBlocks.empty())
132     return false;
133 
134   // Speed up queries by creating a sorted vector of blocks.
135   LoopBlocks.clear();
136   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
137   array_pod_sort(LoopBlocks.begin(), LoopBlocks.end());
138 
139   // Look at all the instructions in the loop, checking to see if they have uses
140   // outside the loop.  If so, rewrite those uses.
141   bool MadeChange = false;
142 
143   for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();
144        BBI != E; ++BBI) {
145     BasicBlock *BB = *BBI;
146 
147     // For large loops, avoid use-scanning by using dominance information:  In
148     // particular, if a block does not dominate any of the loop exits, then none
149     // of the values defined in the block could be used outside the loop.
150     if (!BlockDominatesAnExit(BB, ExitBlocks, DT))
151       continue;
152 
153     for (BasicBlock::iterator I = BB->begin(), E = BB->end();
154          I != E; ++I) {
155       // Reject two common cases fast: instructions with no uses (like stores)
156       // and instructions with one use that is in the same block as this.
157       if (I->use_empty() ||
158           (I->hasOneUse() && I->use_back()->getParent() == BB &&
159            !isa<PHINode>(I->use_back())))
160         continue;
161 
162       MadeChange |= ProcessInstruction(I, ExitBlocks);
163     }
164   }
165 
166   assert(L->isLCSSAForm());
167   PredCache.clear();
168 
169   return MadeChange;
170 }
171 
172 /// isExitBlock - Return true if the specified block is in the list.
173 static bool isExitBlock(BasicBlock *BB,
174                         const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
175   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
176     if (ExitBlocks[i] == BB)
177       return true;
178   return false;
179 }
180 
181 /// ProcessInstruction - Given an instruction in the loop, check to see if it
182 /// has any uses that are outside the current loop.  If so, insert LCSSA PHI
183 /// nodes and rewrite the uses.
184 bool LCSSA::ProcessInstruction(Instruction *Inst,
185                                const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
186   SmallVector<Use*, 16> UsesToRewrite;
187 
188   BasicBlock *InstBB = Inst->getParent();
189 
190   for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
191        UI != E; ++UI) {
192     BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
193     if (PHINode *PN = dyn_cast<PHINode>(*UI))
194       UserBB = PN->getIncomingBlock(UI);
195 
196     if (InstBB != UserBB && !inLoop(UserBB))
197       UsesToRewrite.push_back(&UI.getUse());
198   }
199 
200   // If there are no uses outside the loop, exit with no change.
201   if (UsesToRewrite.empty()) return false;
202 
203   ++NumLCSSA; // We are applying the transformation
204 
205   // Invoke instructions are special in that their result value is not available
206   // along their unwind edge. The code below tests to see whether DomBB dominates
207   // the value, so adjust DomBB to the normal destination block, which is
208   // effectively where the value is first usable.
209   BasicBlock *DomBB = Inst->getParent();
210   if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))
211     DomBB = Inv->getNormalDest();
212 
213   DomTreeNode *DomNode = DT->getNode(DomBB);
214 
215   SSAUpdater SSAUpdate;
216   SSAUpdate.Initialize(Inst);
217 
218   // Insert the LCSSA phi's into all of the exit blocks dominated by the
219   // value., and add them to the Phi's map.
220   for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),
221       BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {
222     BasicBlock *ExitBB = *BBI;
223     if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;
224 
225     // If we already inserted something for this BB, don't reprocess it.
226     if (SSAUpdate.HasValueForBlock(ExitBB)) continue;
227 
228     PHINode *PN = PHINode::Create(Inst->getType(), Inst->getName()+".lcssa",
229                                   ExitBB->begin());
230     PN->reserveOperandSpace(PredCache.GetNumPreds(ExitBB));
231 
232     // Add inputs from inside the loop for this PHI.
233     for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI)
234       PN->addIncoming(Inst, *PI);
235 
236     // Remember that this phi makes the value alive in this block.
237     SSAUpdate.AddAvailableValue(ExitBB, PN);
238   }
239 
240   // Rewrite all uses outside the loop in terms of the new PHIs we just
241   // inserted.
242   for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {
243     // If this use is in an exit block, rewrite to use the newly inserted PHI.
244     // This is required for correctness because SSAUpdate doesn't handle uses in
245     // the same block.  It assumes the PHI we inserted is at the end of the
246     // block.
247     Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());
248     BasicBlock *UserBB = User->getParent();
249     if (PHINode *PN = dyn_cast<PHINode>(User))
250       UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);
251 
252     if (isa<PHINode>(UserBB->begin()) &&
253         isExitBlock(UserBB, ExitBlocks)) {
254       UsesToRewrite[i]->set(UserBB->begin());
255       continue;
256     }
257 
258     // Otherwise, do full PHI insertion.
259     SSAUpdate.RewriteUse(*UsesToRewrite[i]);
260   }
261 
262   return true;
263 }
264 
265