Simplify this code; no need for a custom subclass if it doesn't need
[oota-llvm.git] / lib / Analysis / IVUsers.cpp
1 //===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===//
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 file implements bookkeeping for "interesting" users of expressions
11 // computed from induction variables.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "iv-users"
16 #include "llvm/Analysis/IVUsers.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Type.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
24 #include "llvm/Assembly/AsmAnnotationWriter.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 using namespace llvm;
30
31 char IVUsers::ID = 0;
32 static RegisterPass<IVUsers>
33 X("iv-users", "Induction Variable Users", false, true);
34
35 Pass *llvm::createIVUsersPass() {
36   return new IVUsers();
37 }
38
39 /// CollectSubexprs - Split S into subexpressions which can be pulled out into
40 /// separate registers.
41 static void CollectSubexprs(const SCEV *S,
42                             SmallVectorImpl<const SCEV *> &Ops,
43                             ScalarEvolution &SE) {
44   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
45     // Break out add operands.
46     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
47          I != E; ++I)
48       CollectSubexprs(*I, Ops, SE);
49     return;
50   } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
51     // Split a non-zero base out of an addrec.
52     if (!AR->getStart()->isZero()) {
53       CollectSubexprs(AR->getStart(), Ops, SE);
54       CollectSubexprs(SE.getAddRecExpr(SE.getIntegerSCEV(0, AR->getType()),
55                                        AR->getStepRecurrence(SE),
56                                        AR->getLoop()), Ops, SE);
57       return;
58     }
59   }
60
61   // Otherwise use the value itself.
62   Ops.push_back(S);
63 }
64
65 /// getSCEVStartAndStride - Compute the start and stride of this expression,
66 /// returning false if the expression is not a start/stride pair, or true if it
67 /// is.  The stride must be a loop invariant expression, but the start may be
68 /// a mix of loop invariant and loop variant expressions.  The start cannot,
69 /// however, contain an AddRec from a different loop, unless that loop is an
70 /// outer loop of the current loop.
71 static bool getSCEVStartAndStride(const SCEV *&SH, Loop *L, Loop *UseLoop,
72                                   const SCEV *&Start, const SCEV *&Stride,
73                                   ScalarEvolution *SE, DominatorTree *DT) {
74   const SCEV *TheAddRec = Start;   // Initialize to zero.
75
76   // If the outer level is an AddExpr, the operands are all start values except
77   // for a nested AddRecExpr.
78   if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
79     for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
80       if (const SCEVAddRecExpr *AddRec =
81              dyn_cast<SCEVAddRecExpr>(AE->getOperand(i)))
82         TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
83       else
84         Start = SE->getAddExpr(Start, AE->getOperand(i));
85   } else if (isa<SCEVAddRecExpr>(SH)) {
86     TheAddRec = SH;
87   } else {
88     return false;  // not analyzable.
89   }
90
91   // Break down TheAddRec into its component parts.
92   SmallVector<const SCEV *, 4> Subexprs;
93   CollectSubexprs(TheAddRec, Subexprs, *SE);
94
95   // Look for an addrec on the current loop among the parts.
96   const SCEV *AddRecStride = 0;
97   for (SmallVectorImpl<const SCEV *>::iterator I = Subexprs.begin(),
98        E = Subexprs.end(); I != E; ++I) {
99     const SCEV *S = *I;
100     if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
101       if (AR->getLoop() == L) {
102         *I = AR->getStart();
103         AddRecStride = AR->getStepRecurrence(*SE);
104         break;
105       }
106   }
107   if (!AddRecStride)
108     return false;
109
110   // Add up everything else into a start value (which may not be
111   // loop-invariant).
112   const SCEV *AddRecStart = SE->getAddExpr(Subexprs);
113
114   // Use getSCEVAtScope to attempt to simplify other loops out of
115   // the picture.
116   AddRecStart = SE->getSCEVAtScope(AddRecStart, UseLoop);
117
118   Start = SE->getAddExpr(Start, AddRecStart);
119
120   // If stride is an instruction, make sure it properly dominates the header.
121   // Otherwise we could end up with a use before def situation.
122   if (!isa<SCEVConstant>(AddRecStride)) {
123     BasicBlock *Header = L->getHeader();
124     if (!AddRecStride->properlyDominates(Header, DT))
125       return false;
126
127     DEBUG(dbgs() << "[";
128           WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
129           dbgs() << "] Variable stride: " << *AddRecStride << "\n");
130   }
131
132   Stride = AddRecStride;
133   return true;
134 }
135
136 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
137 /// and now we need to decide whether the user should use the preinc or post-inc
138 /// value.  If this user should use the post-inc version of the IV, return true.
139 ///
140 /// Choosing wrong here can break dominance properties (if we choose to use the
141 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
142 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
143 /// should use the post-inc value).
144 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
145                                        Loop *L, LoopInfo *LI, DominatorTree *DT,
146                                        Pass *P) {
147   // If the user is in the loop, use the preinc value.
148   if (L->contains(User)) return false;
149
150   BasicBlock *LatchBlock = L->getLoopLatch();
151   if (!LatchBlock)
152     return false;
153
154   // Ok, the user is outside of the loop.  If it is dominated by the latch
155   // block, use the post-inc value.
156   if (DT->dominates(LatchBlock, User->getParent()))
157     return true;
158
159   // There is one case we have to be careful of: PHI nodes.  These little guys
160   // can live in blocks that are not dominated by the latch block, but (since
161   // their uses occur in the predecessor block, not the block the PHI lives in)
162   // should still use the post-inc value.  Check for this case now.
163   PHINode *PN = dyn_cast<PHINode>(User);
164   if (!PN) return false;  // not a phi, not dominated by latch block.
165
166   // Look at all of the uses of IV by the PHI node.  If any use corresponds to
167   // a block that is not dominated by the latch block, give up and use the
168   // preincremented value.
169   unsigned NumUses = 0;
170   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
171     if (PN->getIncomingValue(i) == IV) {
172       ++NumUses;
173       if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
174         return false;
175     }
176
177   // Okay, all uses of IV by PN are in predecessor blocks that really are
178   // dominated by the latch block.  Use the post-incremented value.
179   return true;
180 }
181
182 /// AddUsersIfInteresting - Inspect the specified instruction.  If it is a
183 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
184 /// return true.  Otherwise, return false.
185 bool IVUsers::AddUsersIfInteresting(Instruction *I) {
186   if (!SE->isSCEVable(I->getType()))
187     return false;   // Void and FP expressions cannot be reduced.
188
189   // LSR is not APInt clean, do not touch integers bigger than 64-bits.
190   if (SE->getTypeSizeInBits(I->getType()) > 64)
191     return false;
192
193   if (!Processed.insert(I))
194     return true;    // Instruction already handled.
195
196   // Get the symbolic expression for this instruction.
197   const SCEV *ISE = SE->getSCEV(I);
198   if (isa<SCEVCouldNotCompute>(ISE)) return false;
199
200   // Get the start and stride for this expression.
201   Loop *UseLoop = LI->getLoopFor(I->getParent());
202   const SCEV *Start = SE->getIntegerSCEV(0, ISE->getType());
203   const SCEV *Stride = Start;
204
205   if (!getSCEVStartAndStride(ISE, L, UseLoop, Start, Stride, SE, DT))
206     return false;  // Non-reducible symbolic expression, bail out.
207
208   // Keep things simple. Don't touch loop-variant strides.
209   if (!Stride->isLoopInvariant(L) && L->contains(I))
210     return false;
211
212   SmallPtrSet<Instruction *, 4> UniqueUsers;
213   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
214        UI != E; ++UI) {
215     Instruction *User = cast<Instruction>(*UI);
216     if (!UniqueUsers.insert(User))
217       continue;
218
219     // Do not infinitely recurse on PHI nodes.
220     if (isa<PHINode>(User) && Processed.count(User))
221       continue;
222
223     // Descend recursively, but not into PHI nodes outside the current loop.
224     // It's important to see the entire expression outside the loop to get
225     // choices that depend on addressing mode use right, although we won't
226     // consider references ouside the loop in all cases.
227     // If User is already in Processed, we don't want to recurse into it again,
228     // but do want to record a second reference in the same instruction.
229     bool AddUserToIVUsers = false;
230     if (LI->getLoopFor(User->getParent()) != L) {
231       if (isa<PHINode>(User) || Processed.count(User) ||
232           !AddUsersIfInteresting(User)) {
233         DEBUG(dbgs() << "FOUND USER in other loop: " << *User << '\n'
234                      << "   OF SCEV: " << *ISE << '\n');
235         AddUserToIVUsers = true;
236       }
237     } else if (Processed.count(User) ||
238                !AddUsersIfInteresting(User)) {
239       DEBUG(dbgs() << "FOUND USER: " << *User << '\n'
240                    << "   OF SCEV: " << *ISE << '\n');
241       AddUserToIVUsers = true;
242     }
243
244     if (AddUserToIVUsers) {
245       // Okay, we found a user that we cannot reduce.  Analyze the instruction
246       // and decide what to do with it.  If we are a use inside of the loop, use
247       // the value before incrementation, otherwise use it after incrementation.
248       if (IVUseShouldUsePostIncValue(User, I, L, LI, DT, this)) {
249         // The value used will be incremented by the stride more than we are
250         // expecting, so subtract this off.
251         const SCEV *NewStart = SE->getMinusSCEV(Start, Stride);
252         IVUses.push_back(new IVStrideUse(this, Stride, NewStart, User, I));
253         IVUses.back().setIsUseOfPostIncrementedValue(true);
254         DEBUG(dbgs() << "   USING POSTINC SCEV, START=" << *NewStart<< "\n");
255       } else {
256         IVUses.push_back(new IVStrideUse(this, Stride, Start, User, I));
257       }
258     }
259   }
260   return true;
261 }
262
263 IVStrideUse &IVUsers::AddUser(const SCEV *Stride, const SCEV *Offset,
264                               Instruction *User, Value *Operand) {
265   IVUses.push_back(new IVStrideUse(this, Stride, Offset, User, Operand));
266   return IVUses.back();
267 }
268
269 IVUsers::IVUsers()
270  : LoopPass(&ID) {
271 }
272
273 void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {
274   AU.addRequired<LoopInfo>();
275   AU.addRequired<DominatorTree>();
276   AU.addRequired<ScalarEvolution>();
277   AU.setPreservesAll();
278 }
279
280 bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
281
282   L = l;
283   LI = &getAnalysis<LoopInfo>();
284   DT = &getAnalysis<DominatorTree>();
285   SE = &getAnalysis<ScalarEvolution>();
286
287   // Find all uses of induction variables in this loop, and categorize
288   // them by stride.  Start by finding all of the PHI nodes in the header for
289   // this loop.  If they are induction variables, inspect their uses.
290   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
291     AddUsersIfInteresting(I);
292
293   return false;
294 }
295
296 /// getReplacementExpr - Return a SCEV expression which computes the
297 /// value of the OperandValToReplace of the given IVStrideUse.
298 const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const {
299   // Start with zero.
300   const SCEV *RetVal = SE->getIntegerSCEV(0, U.getStride()->getType());
301   // Create the basic add recurrence.
302   RetVal = SE->getAddRecExpr(RetVal, U.getStride(), L);
303   // Add the offset in a separate step, because it may be loop-variant.
304   RetVal = SE->getAddExpr(RetVal, U.getOffset());
305   // For uses of post-incremented values, add an extra stride to compute
306   // the actual replacement value.
307   if (U.isUseOfPostIncrementedValue())
308     RetVal = SE->getAddExpr(RetVal, U.getStride());
309   return RetVal;
310 }
311
312 /// getCanonicalExpr - Return a SCEV expression which computes the
313 /// value of the SCEV of the given IVStrideUse, ignoring the 
314 /// isUseOfPostIncrementedValue flag.
315 const SCEV *IVUsers::getCanonicalExpr(const IVStrideUse &U) const {
316   // Start with zero.
317   const SCEV *RetVal = SE->getIntegerSCEV(0, U.getStride()->getType());
318   // Create the basic add recurrence.
319   RetVal = SE->getAddRecExpr(RetVal, U.getStride(), L);
320   // Add the offset in a separate step, because it may be loop-variant.
321   RetVal = SE->getAddExpr(RetVal, U.getOffset());
322   return RetVal;
323 }
324
325 void IVUsers::print(raw_ostream &OS, const Module *M) const {
326   OS << "IV Users for loop ";
327   WriteAsOperand(OS, L->getHeader(), false);
328   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
329     OS << " with backedge-taken count "
330        << *SE->getBackedgeTakenCount(L);
331   }
332   OS << ":\n";
333
334   // Use a defualt AssemblyAnnotationWriter to suppress the default info
335   // comments, which aren't relevant here.
336   AssemblyAnnotationWriter Annotator;
337   for (ilist<IVStrideUse>::const_iterator UI = IVUses.begin(),
338        E = IVUses.end(); UI != E; ++UI) {
339     OS << "  ";
340     WriteAsOperand(OS, UI->getOperandValToReplace(), false);
341     OS << " = "
342        << *getReplacementExpr(*UI);
343     if (UI->isUseOfPostIncrementedValue())
344       OS << " (post-inc)";
345     OS << " in  ";
346     UI->getUser()->print(OS, &Annotator);
347     OS << '\n';
348   }
349 }
350
351 void IVUsers::dump() const {
352   print(dbgs());
353 }
354
355 void IVUsers::releaseMemory() {
356   Processed.clear();
357   IVUses.clear();
358 }
359
360 void IVStrideUse::deleted() {
361   // Remove this user from the list.
362   Parent->IVUses.erase(this);
363   // this now dangles!
364 }