1 //===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements bookkeeping for "interesting" users of expressions
11 // computed from induction variables.
13 //===----------------------------------------------------------------------===//
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/ADT/STLExtras.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/CommandLine.h"
32 static RegisterPass<IVUsers>
33 X("iv-users", "Induction Variable Users", false, true);
36 SimplifyIVUsers("simplify-iv-users", cl::Hidden, cl::init(false),
37 cl::desc("Restrict IV Users to loop-invariant strides"));
39 Pass *llvm::createIVUsersPass() {
43 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a
44 /// subexpression that is an AddRec from a loop other than L. An outer loop
45 /// of L is OK, but not an inner loop nor a disjoint loop.
46 static bool containsAddRecFromDifferentLoop(const SCEV *S, Loop *L) {
47 // This is very common, put it first.
48 if (isa<SCEVConstant>(S))
50 if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) {
51 for (unsigned int i=0; i< AE->getNumOperands(); i++)
52 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L))
56 if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) {
57 if (const Loop *newLoop = AE->getLoop()) {
60 // if newLoop is an outer loop of L, this is OK.
61 if (!LoopInfo::isNotAlreadyContainedIn(L, newLoop))
66 if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S))
67 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
68 containsAddRecFromDifferentLoop(DE->getRHS(), L);
70 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll
71 // need this when it is.
72 if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S))
73 return containsAddRecFromDifferentLoop(DE->getLHS(), L) ||
74 containsAddRecFromDifferentLoop(DE->getRHS(), L);
76 if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S))
77 return containsAddRecFromDifferentLoop(CE->getOperand(), L);
81 /// getSCEVStartAndStride - Compute the start and stride of this expression,
82 /// returning false if the expression is not a start/stride pair, or true if it
83 /// is. The stride must be a loop invariant expression, but the start may be
84 /// a mix of loop invariant and loop variant expressions. The start cannot,
85 /// however, contain an AddRec from a different loop, unless that loop is an
86 /// outer loop of the current loop.
87 static bool getSCEVStartAndStride(const SCEV *&SH, Loop *L, Loop *UseLoop,
88 const SCEV *&Start, const SCEV *&Stride,
89 ScalarEvolution *SE, DominatorTree *DT) {
90 const SCEV *TheAddRec = Start; // Initialize to zero.
92 // If the outer level is an AddExpr, the operands are all start values except
93 // for a nested AddRecExpr.
94 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) {
95 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i)
96 if (const SCEVAddRecExpr *AddRec =
97 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) {
98 if (AddRec->getLoop() == L)
99 TheAddRec = SE->getAddExpr(AddRec, TheAddRec);
101 return false; // Nested IV of some sort?
103 Start = SE->getAddExpr(Start, AE->getOperand(i));
105 } else if (isa<SCEVAddRecExpr>(SH)) {
108 return false; // not analyzable.
111 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec);
112 if (!AddRec || AddRec->getLoop() != L) return false;
114 // Use getSCEVAtScope to attempt to simplify other loops out of
116 const SCEV *AddRecStart = AddRec->getStart();
117 AddRecStart = SE->getSCEVAtScope(AddRecStart, UseLoop);
118 const SCEV *AddRecStride = AddRec->getStepRecurrence(*SE);
120 // FIXME: If Start contains an SCEVAddRecExpr from a different loop, other
121 // than an outer loop of the current loop, reject it. LSR has no concept of
122 // operating on more than one loop at a time so don't confuse it with such
124 if (containsAddRecFromDifferentLoop(AddRecStart, L))
127 Start = SE->getAddExpr(Start, AddRecStart);
129 // If stride is an instruction, make sure it properly dominates the header.
130 // Otherwise we could end up with a use before def situation.
131 if (!isa<SCEVConstant>(AddRecStride)) {
132 BasicBlock *Header = L->getHeader();
133 if (!AddRecStride->properlyDominates(Header, DT))
136 DEBUG(errs() << "[" << L->getHeader()->getName()
137 << "] Variable stride: " << *AddRec << "\n");
140 Stride = AddRecStride;
144 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression
145 /// and now we need to decide whether the user should use the preinc or post-inc
146 /// value. If this user should use the post-inc version of the IV, return true.
148 /// Choosing wrong here can break dominance properties (if we choose to use the
149 /// post-inc value when we cannot) or it can end up adding extra live-ranges to
150 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we
151 /// should use the post-inc value).
152 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV,
153 Loop *L, LoopInfo *LI, DominatorTree *DT,
155 // If the user is in the loop, use the preinc value.
156 if (L->contains(User->getParent())) return false;
158 BasicBlock *LatchBlock = L->getLoopLatch();
162 // Ok, the user is outside of the loop. If it is dominated by the latch
163 // block, use the post-inc value.
164 if (DT->dominates(LatchBlock, User->getParent()))
167 // There is one case we have to be careful of: PHI nodes. These little guys
168 // can live in blocks that are not dominated by the latch block, but (since
169 // their uses occur in the predecessor block, not the block the PHI lives in)
170 // should still use the post-inc value. Check for this case now.
171 PHINode *PN = dyn_cast<PHINode>(User);
172 if (!PN) return false; // not a phi, not dominated by latch block.
174 // Look at all of the uses of IV by the PHI node. If any use corresponds to
175 // a block that is not dominated by the latch block, give up and use the
176 // preincremented value.
177 unsigned NumUses = 0;
178 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
179 if (PN->getIncomingValue(i) == IV) {
181 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
185 // Okay, all uses of IV by PN are in predecessor blocks that really are
186 // dominated by the latch block. Use the post-incremented value.
190 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
191 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
192 /// return true. Otherwise, return false.
193 bool IVUsers::AddUsersIfInteresting(Instruction *I) {
194 if (!SE->isSCEVable(I->getType()))
195 return false; // Void and FP expressions cannot be reduced.
197 // LSR is not APInt clean, do not touch integers bigger than 64-bits.
198 if (SE->getTypeSizeInBits(I->getType()) > 64)
201 if (!Processed.insert(I))
202 return true; // Instruction already handled.
204 // Get the symbolic expression for this instruction.
205 const SCEV *ISE = SE->getSCEV(I);
206 if (isa<SCEVCouldNotCompute>(ISE)) return false;
208 // Get the start and stride for this expression.
209 Loop *UseLoop = LI->getLoopFor(I->getParent());
210 const SCEV *Start = SE->getIntegerSCEV(0, ISE->getType());
211 const SCEV *Stride = Start;
213 if (!getSCEVStartAndStride(ISE, L, UseLoop, Start, Stride, SE, DT))
214 return false; // Non-reducible symbolic expression, bail out.
216 // Keep things simple. Don't touch loop-variant strides.
217 if (SimplifyIVUsers && !Stride->isLoopInvariant(L)
218 && L->contains(I->getParent()))
221 SmallPtrSet<Instruction *, 4> UniqueUsers;
222 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
224 Instruction *User = cast<Instruction>(*UI);
225 if (!UniqueUsers.insert(User))
228 // Do not infinitely recurse on PHI nodes.
229 if (isa<PHINode>(User) && Processed.count(User))
232 // Descend recursively, but not into PHI nodes outside the current loop.
233 // It's important to see the entire expression outside the loop to get
234 // choices that depend on addressing mode use right, although we won't
235 // consider references ouside the loop in all cases.
236 // If User is already in Processed, we don't want to recurse into it again,
237 // but do want to record a second reference in the same instruction.
238 bool AddUserToIVUsers = false;
239 if (LI->getLoopFor(User->getParent()) != L) {
240 if (isa<PHINode>(User) || Processed.count(User) ||
241 !AddUsersIfInteresting(User)) {
242 DEBUG(errs() << "FOUND USER in other loop: " << *User << '\n'
243 << " OF SCEV: " << *ISE << '\n');
244 AddUserToIVUsers = true;
246 } else if (Processed.count(User) ||
247 !AddUsersIfInteresting(User)) {
248 DEBUG(errs() << "FOUND USER: " << *User << '\n'
249 << " OF SCEV: " << *ISE << '\n');
250 AddUserToIVUsers = true;
253 if (AddUserToIVUsers) {
254 IVUsersOfOneStride *StrideUses = IVUsesByStride[Stride];
255 if (!StrideUses) { // First occurrence of this stride?
256 StrideOrder.push_back(Stride);
257 StrideUses = new IVUsersOfOneStride(Stride);
258 IVUses.push_back(StrideUses);
259 IVUsesByStride[Stride] = StrideUses;
262 // Okay, we found a user that we cannot reduce. Analyze the instruction
263 // and decide what to do with it. If we are a use inside of the loop, use
264 // the value before incrementation, otherwise use it after incrementation.
265 if (IVUseShouldUsePostIncValue(User, I, L, LI, DT, this)) {
266 // The value used will be incremented by the stride more than we are
267 // expecting, so subtract this off.
268 const SCEV *NewStart = SE->getMinusSCEV(Start, Stride);
269 StrideUses->addUser(NewStart, User, I);
270 StrideUses->Users.back().setIsUseOfPostIncrementedValue(true);
271 DEBUG(errs() << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
273 StrideUses->addUser(Start, User, I);
280 void IVUsers::AddUser(const SCEV *Stride, const SCEV *Offset,
281 Instruction *User, Value *Operand) {
282 IVUsersOfOneStride *StrideUses = IVUsesByStride[Stride];
283 if (!StrideUses) { // First occurrence of this stride?
284 StrideOrder.push_back(Stride);
285 StrideUses = new IVUsersOfOneStride(Stride);
286 IVUses.push_back(StrideUses);
287 IVUsesByStride[Stride] = StrideUses;
289 IVUsesByStride[Stride]->addUser(Offset, User, Operand);
296 void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {
297 AU.addRequired<LoopInfo>();
298 AU.addRequired<DominatorTree>();
299 AU.addRequired<ScalarEvolution>();
300 AU.setPreservesAll();
303 bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
306 LI = &getAnalysis<LoopInfo>();
307 DT = &getAnalysis<DominatorTree>();
308 SE = &getAnalysis<ScalarEvolution>();
310 // Find all uses of induction variables in this loop, and categorize
311 // them by stride. Start by finding all of the PHI nodes in the header for
312 // this loop. If they are induction variables, inspect their uses.
313 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
314 AddUsersIfInteresting(I);
319 /// getReplacementExpr - Return a SCEV expression which computes the
320 /// value of the OperandValToReplace of the given IVStrideUse.
321 const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const {
323 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getParent()->Stride->getType());
324 // Create the basic add recurrence.
325 RetVal = SE->getAddRecExpr(RetVal, U.getParent()->Stride, L);
326 // Add the offset in a separate step, because it may be loop-variant.
327 RetVal = SE->getAddExpr(RetVal, U.getOffset());
328 // For uses of post-incremented values, add an extra stride to compute
329 // the actual replacement value.
330 if (U.isUseOfPostIncrementedValue())
331 RetVal = SE->getAddExpr(RetVal, U.getParent()->Stride);
332 // Evaluate the expression out of the loop, if possible.
333 if (!L->contains(U.getUser()->getParent())) {
334 const SCEV *ExitVal = SE->getSCEVAtScope(RetVal, L->getParentLoop());
335 if (ExitVal->isLoopInvariant(L))
341 void IVUsers::print(raw_ostream &OS, const Module *M) const {
342 OS << "IV Users for loop ";
343 WriteAsOperand(OS, L->getHeader(), false);
344 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
345 OS << " with backedge-taken count "
346 << *SE->getBackedgeTakenCount(L);
350 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
351 std::map<const SCEV *, IVUsersOfOneStride*>::const_iterator SI =
352 IVUsesByStride.find(StrideOrder[Stride]);
353 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
354 OS << " Stride " << *SI->first->getType() << " " << *SI->first << ":\n";
356 for (ilist<IVStrideUse>::const_iterator UI = SI->second->Users.begin(),
357 E = SI->second->Users.end(); UI != E; ++UI) {
359 WriteAsOperand(OS, UI->getOperandValToReplace(), false);
361 OS << *getReplacementExpr(*UI);
362 if (UI->isUseOfPostIncrementedValue())
365 UI->getUser()->print(OS);
371 void IVUsers::dump() const {
375 void IVUsers::releaseMemory() {
376 IVUsesByStride.clear();
381 void IVStrideUse::deleted() {
382 // Remove this user from the list.
383 Parent->Users.erase(this);