LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
LCSSA.cpp
Go to the documentation of this file.
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/ADT/STLExtras.h"
33 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Analysis/LoopPass.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/Pass.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) {
52  }
53 
54  // Cached analysis information for the current function.
55  DominatorTree *DT;
56  LoopInfo *LI;
57  ScalarEvolution *SE;
58  PredIteratorCache PredCache;
59  Loop *L;
60 
61  virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
62 
63  /// This transformation requires natural loop information & requires that
64  /// loop preheaders be inserted into the CFG. It maintains both of these,
65  /// as well as the CFG. It also requires dominator information.
66  ///
67  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68  AU.setPreservesCFG();
69 
71  AU.addRequired<LoopInfo>();
74  }
75  private:
76  bool ProcessInstruction(Instruction *Inst,
77  const SmallVectorImpl<BasicBlock*> &ExitBlocks);
78 
79  /// verifyAnalysis() - Verify loop nest.
80  virtual void verifyAnalysis() const {
81  // Check the special guarantees that LCSSA makes.
82  assert(L->isLCSSAForm(*DT) && "LCSSA form not preserved!");
83  }
84  };
85 }
86 
87 char LCSSA::ID = 0;
88 INITIALIZE_PASS_BEGIN(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
91 INITIALIZE_PASS_END(LCSSA, "lcssa", "Loop-Closed SSA Form Pass", false, false)
92 
93 Pass *llvm::createLCSSAPass() { return new LCSSA(); }
95 
96 
97 /// BlockDominatesAnExit - Return true if the specified block dominates at least
98 /// one of the blocks in the specified list.
100  const SmallVectorImpl<BasicBlock*> &ExitBlocks,
101  DominatorTree *DT) {
102  DomTreeNode *DomNode = DT->getNode(BB);
103  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
104  if (DT->dominates(DomNode, DT->getNode(ExitBlocks[i])))
105  return true;
106 
107  return false;
108 }
109 
110 
111 /// runOnFunction - Process all loops in the function, inner-most out.
112 bool LCSSA::runOnLoop(Loop *TheLoop, LPPassManager &LPM) {
113  L = TheLoop;
114 
115  DT = &getAnalysis<DominatorTree>();
116  LI = &getAnalysis<LoopInfo>();
117  SE = getAnalysisIfAvailable<ScalarEvolution>();
118 
119  // Get the set of exiting blocks.
120  SmallVector<BasicBlock*, 8> ExitBlocks;
121  L->getExitBlocks(ExitBlocks);
122 
123  if (ExitBlocks.empty())
124  return false;
125 
126  // Look at all the instructions in the loop, checking to see if they have uses
127  // outside the loop. If so, rewrite those uses.
128  bool MadeChange = false;
129 
130  for (Loop::block_iterator BBI = L->block_begin(), E = L->block_end();
131  BBI != E; ++BBI) {
132  BasicBlock *BB = *BBI;
133 
134  // For large loops, avoid use-scanning by using dominance information: In
135  // particular, if a block does not dominate any of the loop exits, then none
136  // of the values defined in the block could be used outside the loop.
137  if (!BlockDominatesAnExit(BB, ExitBlocks, DT))
138  continue;
139 
140  for (BasicBlock::iterator I = BB->begin(), E = BB->end();
141  I != E; ++I) {
142  // Reject two common cases fast: instructions with no uses (like stores)
143  // and instructions with one use that is in the same block as this.
144  if (I->use_empty() ||
145  (I->hasOneUse() && I->use_back()->getParent() == BB &&
146  !isa<PHINode>(I->use_back())))
147  continue;
148 
149  MadeChange |= ProcessInstruction(I, ExitBlocks);
150  }
151  }
152 
153  // If we modified the code, remove any caches about the loop from SCEV to
154  // avoid dangling entries.
155  // FIXME: This is a big hammer, can we clear the cache more selectively?
156  if (SE && MadeChange)
157  SE->forgetLoop(L);
158 
159  assert(L->isLCSSAForm(*DT));
160  PredCache.clear();
161 
162  return MadeChange;
163 }
164 
165 /// isExitBlock - Return true if the specified block is in the list.
166 static bool isExitBlock(BasicBlock *BB,
167  const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
168  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
169  if (ExitBlocks[i] == BB)
170  return true;
171  return false;
172 }
173 
174 /// ProcessInstruction - Given an instruction in the loop, check to see if it
175 /// has any uses that are outside the current loop. If so, insert LCSSA PHI
176 /// nodes and rewrite the uses.
177 bool LCSSA::ProcessInstruction(Instruction *Inst,
178  const SmallVectorImpl<BasicBlock*> &ExitBlocks) {
179  SmallVector<Use*, 16> UsesToRewrite;
180 
181  BasicBlock *InstBB = Inst->getParent();
182 
183  for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
184  UI != E; ++UI) {
185  User *U = *UI;
186  BasicBlock *UserBB = cast<Instruction>(U)->getParent();
187  if (PHINode *PN = dyn_cast<PHINode>(U))
188  UserBB = PN->getIncomingBlock(UI);
189 
190  if (InstBB != UserBB && !L->contains(UserBB))
191  UsesToRewrite.push_back(&UI.getUse());
192  }
193 
194  // If there are no uses outside the loop, exit with no change.
195  if (UsesToRewrite.empty()) return false;
196 
197  ++NumLCSSA; // We are applying the transformation
198 
199  // Invoke instructions are special in that their result value is not available
200  // along their unwind edge. The code below tests to see whether DomBB dominates
201  // the value, so adjust DomBB to the normal destination block, which is
202  // effectively where the value is first usable.
203  BasicBlock *DomBB = Inst->getParent();
204  if (InvokeInst *Inv = dyn_cast<InvokeInst>(Inst))
205  DomBB = Inv->getNormalDest();
206 
207  DomTreeNode *DomNode = DT->getNode(DomBB);
208 
209  SmallVector<PHINode*, 16> AddedPHIs;
210 
211  SSAUpdater SSAUpdate;
212  SSAUpdate.Initialize(Inst->getType(), Inst->getName());
213 
214  // Insert the LCSSA phi's into all of the exit blocks dominated by the
215  // value, and add them to the Phi's map.
216  for (SmallVectorImpl<BasicBlock*>::const_iterator BBI = ExitBlocks.begin(),
217  BBE = ExitBlocks.end(); BBI != BBE; ++BBI) {
218  BasicBlock *ExitBB = *BBI;
219  if (!DT->dominates(DomNode, DT->getNode(ExitBB))) continue;
220 
221  // If we already inserted something for this BB, don't reprocess it.
222  if (SSAUpdate.HasValueForBlock(ExitBB)) continue;
223 
224  PHINode *PN = PHINode::Create(Inst->getType(),
225  PredCache.GetNumPreds(ExitBB),
226  Inst->getName()+".lcssa",
227  ExitBB->begin());
228 
229  // Add inputs from inside the loop for this PHI.
230  for (BasicBlock **PI = PredCache.GetPreds(ExitBB); *PI; ++PI) {
231  PN->addIncoming(Inst, *PI);
232 
233  // If the exit block has a predecessor not within the loop, arrange for
234  // the incoming value use corresponding to that predecessor to be
235  // rewritten in terms of a different LCSSA PHI.
236  if (!L->contains(*PI))
237  UsesToRewrite.push_back(
238  &PN->getOperandUse(
240  }
241 
242  AddedPHIs.push_back(PN);
243 
244  // Remember that this phi makes the value alive in this block.
245  SSAUpdate.AddAvailableValue(ExitBB, PN);
246  }
247 
248  // Rewrite all uses outside the loop in terms of the new PHIs we just
249  // inserted.
250  for (unsigned i = 0, e = UsesToRewrite.size(); i != e; ++i) {
251  // If this use is in an exit block, rewrite to use the newly inserted PHI.
252  // This is required for correctness because SSAUpdate doesn't handle uses in
253  // the same block. It assumes the PHI we inserted is at the end of the
254  // block.
255  Instruction *User = cast<Instruction>(UsesToRewrite[i]->getUser());
256  BasicBlock *UserBB = User->getParent();
257  if (PHINode *PN = dyn_cast<PHINode>(User))
258  UserBB = PN->getIncomingBlock(*UsesToRewrite[i]);
259 
260  if (isa<PHINode>(UserBB->begin()) &&
261  isExitBlock(UserBB, ExitBlocks)) {
262  // Tell the VHs that the uses changed. This updates SCEV's caches.
263  if (UsesToRewrite[i]->get()->hasValueHandle())
264  ValueHandleBase::ValueIsRAUWd(*UsesToRewrite[i], UserBB->begin());
265  UsesToRewrite[i]->set(UserBB->begin());
266  continue;
267  }
268 
269  // Otherwise, do full PHI insertion.
270  SSAUpdate.RewriteUse(*UsesToRewrite[i]);
271  }
272 
273  // Remove PHI nodes that did not have any uses rewritten.
274  for (unsigned i = 0, e = AddedPHIs.size(); i != e; ++i) {
275  if (AddedPHIs[i]->use_empty())
276  AddedPHIs[i]->eraseFromParent();
277  }
278 
279  return true;
280 }
281 
const Use & getOperandUse(unsigned i) const
Definition: User.h:99
use_iterator use_end()
Definition: Value.h:152
DomTreeNode * getNode(BasicBlock *BB) const
Definition: Dominators.h:844
static bool BlockDominatesAnExit(BasicBlock *BB, const SmallVectorImpl< BasicBlock * > &ExitBlocks, DominatorTree *DT)
Definition: LCSSA.cpp:99
AnalysisUsage & addPreserved()
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition: SSAUpdater.h:37
void addIncoming(Value *V, BasicBlock *BB)
static PassRegistry * getPassRegistry()
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
Definition: SSAUpdater.cpp:45
virtual void verifyAnalysis() const
Definition: Pass.cpp:83
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
Definition: SSAUpdater.cpp:58
virtual void getAnalysisUsage(AnalysisUsage &) const
Definition: Pass.cpp:75
LoopInfoBase< BlockT, LoopT > * LI
Definition: LoopInfoImpl.h:411
StringRef getName() const
Definition: Value.cpp:167
iterator begin()
Definition: BasicBlock.h:193
static unsigned getOperandNumForIncomingValue(unsigned i)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:167
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:172
STATISTIC(NumLCSSA,"Number of live out of a loop variables")
ID
LLVM Calling Convention Representation.
Definition: CallingConv.h:26
#define false
Definition: ConvertUTF.c:64
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:56
AnalysisUsage & addPreservedID(const void *ID)
static void ValueIsRAUWd(Value *Old, Value *New)
Definition: Value.cpp:677
unsigned getNumIncomingValues() const
LLVM Basic Block Representation.
Definition: BasicBlock.h:72
char & LCSSAID
Definition: LCSSA.cpp:94
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=0)
BasicBlock * getIncomingBlock(unsigned i) const
bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.
Definition: SSAUpdater.cpp:54
bool dominates(const DomTreeNode *A, const DomTreeNode *B) const
Definition: Dominators.h:801
char & LoopSimplifyID
Pass * createLCSSAPass()
Definition: LCSSA.cpp:93
iterator end()
Definition: BasicBlock.h:195
Type * getType() const
Definition: Value.h:111
void initializeLCSSAPass(PassRegistry &)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:164
void setPreservesCFG()
Definition: Pass.cpp:249
std::vector< BlockT * >::const_iterator block_iterator
Definition: LoopInfo.h:139
use_iterator use_begin()
Definition: Value.h:150
#define I(x, y, z)
Definition: MD5.cpp:54
static const Function * getParent(const Value *V)
static bool isExitBlock(BasicBlock *BB, const SmallVectorImpl< BasicBlock * > &ExitBlocks)
isExitBlock - Return true if the specified block is in the list.
Definition: LCSSA.cpp:166
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
Definition: SSAUpdater.cpp:177
const BasicBlock * getParent() const
Definition: Instruction.h:52