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