blob: d3dcab0052b612c5fa8401af76147d89e4986cdd [file] [log] [blame]
Dan Gohman81db61a2009-05-12 02:17:14 +00001//===- 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"
Dan Gohman81db61a2009-05-12 02:17:14 +000022#include "llvm/Analysis/LoopPass.h"
23#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Dan Gohman4207d6a2010-02-10 20:42:37 +000024#include "llvm/Assembly/AsmAnnotationWriter.h"
Dan Gohman81db61a2009-05-12 02:17:14 +000025#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.
Dan Gohman0bba49c2009-07-07 17:06:11 +000042static bool containsAddRecFromDifferentLoop(const SCEV *S, Loop *L) {
Dan Gohman81db61a2009-05-12 02:17:14 +000043 // 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.
Dan Gohman92329c72009-12-18 01:24:09 +000057 if (newLoop->contains(L))
Dan Gohman81db61a2009-05-12 02:17:14 +000058 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.
Dan Gohman0bba49c2009-07-07 17:06:11 +000083static bool getSCEVStartAndStride(const SCEV *&SH, Loop *L, Loop *UseLoop,
84 const SCEV *&Start, const SCEV *&Stride,
Dan Gohman81db61a2009-05-12 02:17:14 +000085 ScalarEvolution *SE, DominatorTree *DT) {
Dan Gohman0bba49c2009-07-07 17:06:11 +000086 const SCEV *TheAddRec = Start; // Initialize to zero.
Dan Gohman81db61a2009-05-12 02:17:14 +000087
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 }
Dan Gohman81db61a2009-05-12 02:17:14 +0000101 } 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.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000112 const SCEV *AddRecStart = AddRec->getStart();
Dan Gohman743e41e2009-06-15 18:38:59 +0000113 AddRecStart = SE->getSCEVAtScope(AddRecStart, UseLoop);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000114 const SCEV *AddRecStride = AddRec->getStepRecurrence(*SE);
Dan Gohman81db61a2009-05-12 02:17:14 +0000115
116 // FIXME: If Start contains an SCEVAddRecExpr from a different loop, other
117 // than an outer loop of the current loop, reject it. LSR has no concept of
118 // operating on more than one loop at a time so don't confuse it with such
119 // expressions.
120 if (containsAddRecFromDifferentLoop(AddRecStart, L))
121 return false;
122
Dan Gohman81db61a2009-05-12 02:17:14 +0000123 Start = SE->getAddExpr(Start, AddRecStart);
124
Dan Gohman00cb6732009-09-27 15:30:00 +0000125 // If stride is an instruction, make sure it properly dominates the header.
Dan Gohman743e41e2009-06-15 18:38:59 +0000126 // Otherwise we could end up with a use before def situation.
127 if (!isa<SCEVConstant>(AddRecStride)) {
Dan Gohman00cb6732009-09-27 15:30:00 +0000128 BasicBlock *Header = L->getHeader();
129 if (!AddRecStride->properlyDominates(Header, DT))
Dan Gohman81db61a2009-05-12 02:17:14 +0000130 return false;
131
Dan Gohman30733292010-01-09 18:17:45 +0000132 DEBUG(dbgs() << "[";
133 WriteAsOperand(dbgs(), L->getHeader(), /*PrintType=*/false);
134 dbgs() << "] Variable stride: " << *AddRec << "\n");
Dan Gohman81db61a2009-05-12 02:17:14 +0000135 }
136
Dan Gohman743e41e2009-06-15 18:38:59 +0000137 Stride = AddRecStride;
Dan Gohman81db61a2009-05-12 02:17:14 +0000138 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.
Dan Gohman92329c72009-12-18 01:24:09 +0000153 if (L->contains(User)) return false;
Dan Gohman81db61a2009-05-12 02:17:14 +0000154
155 BasicBlock *LatchBlock = L->getLoopLatch();
Dan Gohmana6a4aae2009-11-05 19:41:37 +0000156 if (!LatchBlock)
157 return false;
Dan Gohman81db61a2009-05-12 02:17:14 +0000158
159 // Ok, the user is outside of the loop. If it is dominated by the latch
160 // block, use the post-inc value.
161 if (DT->dominates(LatchBlock, User->getParent()))
162 return true;
163
164 // There is one case we have to be careful of: PHI nodes. These little guys
165 // can live in blocks that are not dominated by the latch block, but (since
166 // their uses occur in the predecessor block, not the block the PHI lives in)
167 // should still use the post-inc value. Check for this case now.
168 PHINode *PN = dyn_cast<PHINode>(User);
169 if (!PN) return false; // not a phi, not dominated by latch block.
170
171 // Look at all of the uses of IV by the PHI node. If any use corresponds to
172 // a block that is not dominated by the latch block, give up and use the
173 // preincremented value.
174 unsigned NumUses = 0;
175 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
176 if (PN->getIncomingValue(i) == IV) {
177 ++NumUses;
178 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i)))
179 return false;
180 }
181
182 // Okay, all uses of IV by PN are in predecessor blocks that really are
183 // dominated by the latch block. Use the post-incremented value.
184 return true;
185}
186
187/// AddUsersIfInteresting - Inspect the specified instruction. If it is a
188/// reducible SCEV, recursively add its users to the IVUsesByStride set and
189/// return true. Otherwise, return false.
190bool IVUsers::AddUsersIfInteresting(Instruction *I) {
191 if (!SE->isSCEVable(I->getType()))
192 return false; // Void and FP expressions cannot be reduced.
193
194 // LSR is not APInt clean, do not touch integers bigger than 64-bits.
195 if (SE->getTypeSizeInBits(I->getType()) > 64)
196 return false;
197
198 if (!Processed.insert(I))
199 return true; // Instruction already handled.
200
201 // Get the symbolic expression for this instruction.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000202 const SCEV *ISE = SE->getSCEV(I);
Dan Gohman81db61a2009-05-12 02:17:14 +0000203 if (isa<SCEVCouldNotCompute>(ISE)) return false;
204
205 // Get the start and stride for this expression.
206 Loop *UseLoop = LI->getLoopFor(I->getParent());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000207 const SCEV *Start = SE->getIntegerSCEV(0, ISE->getType());
208 const SCEV *Stride = Start;
Dan Gohman81db61a2009-05-12 02:17:14 +0000209
Dan Gohman4e8a9852009-06-18 16:54:06 +0000210 if (!getSCEVStartAndStride(ISE, L, UseLoop, Start, Stride, SE, DT))
Dan Gohman81db61a2009-05-12 02:17:14 +0000211 return false; // Non-reducible symbolic expression, bail out.
212
Jim Grosbach97200e42009-11-19 02:05:44 +0000213 // Keep things simple. Don't touch loop-variant strides.
Dan Gohman92329c72009-12-18 01:24:09 +0000214 if (!Stride->isLoopInvariant(L) && L->contains(I))
Jim Grosbach97200e42009-11-19 02:05:44 +0000215 return false;
216
Dan Gohman81db61a2009-05-12 02:17:14 +0000217 SmallPtrSet<Instruction *, 4> UniqueUsers;
218 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
219 UI != E; ++UI) {
220 Instruction *User = cast<Instruction>(*UI);
221 if (!UniqueUsers.insert(User))
222 continue;
223
224 // Do not infinitely recurse on PHI nodes.
225 if (isa<PHINode>(User) && Processed.count(User))
226 continue;
227
228 // Descend recursively, but not into PHI nodes outside the current loop.
229 // It's important to see the entire expression outside the loop to get
230 // choices that depend on addressing mode use right, although we won't
231 // consider references ouside the loop in all cases.
232 // If User is already in Processed, we don't want to recurse into it again,
233 // but do want to record a second reference in the same instruction.
234 bool AddUserToIVUsers = false;
235 if (LI->getLoopFor(User->getParent()) != L) {
236 if (isa<PHINode>(User) || Processed.count(User) ||
237 !AddUsersIfInteresting(User)) {
David Greene63c45602009-12-23 20:20:46 +0000238 DEBUG(dbgs() << "FOUND USER in other loop: " << *User << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000239 << " OF SCEV: " << *ISE << '\n');
Dan Gohman81db61a2009-05-12 02:17:14 +0000240 AddUserToIVUsers = true;
241 }
242 } else if (Processed.count(User) ||
243 !AddUsersIfInteresting(User)) {
David Greene63c45602009-12-23 20:20:46 +0000244 DEBUG(dbgs() << "FOUND USER: " << *User << '\n'
Chris Lattnerbdff5482009-08-23 04:37:46 +0000245 << " OF SCEV: " << *ISE << '\n');
Dan Gohman81db61a2009-05-12 02:17:14 +0000246 AddUserToIVUsers = true;
247 }
248
249 if (AddUserToIVUsers) {
250 IVUsersOfOneStride *StrideUses = IVUsesByStride[Stride];
251 if (!StrideUses) { // First occurrence of this stride?
252 StrideOrder.push_back(Stride);
253 StrideUses = new IVUsersOfOneStride(Stride);
254 IVUses.push_back(StrideUses);
255 IVUsesByStride[Stride] = StrideUses;
256 }
257
258 // Okay, we found a user that we cannot reduce. Analyze the instruction
259 // and decide what to do with it. If we are a use inside of the loop, use
260 // the value before incrementation, otherwise use it after incrementation.
261 if (IVUseShouldUsePostIncValue(User, I, L, LI, DT, this)) {
262 // The value used will be incremented by the stride more than we are
263 // expecting, so subtract this off.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000264 const SCEV *NewStart = SE->getMinusSCEV(Start, Stride);
Dan Gohman4e8a9852009-06-18 16:54:06 +0000265 StrideUses->addUser(NewStart, User, I);
Dan Gohman81db61a2009-05-12 02:17:14 +0000266 StrideUses->Users.back().setIsUseOfPostIncrementedValue(true);
David Greene63c45602009-12-23 20:20:46 +0000267 DEBUG(dbgs() << " USING POSTINC SCEV, START=" << *NewStart<< "\n");
Dan Gohman81db61a2009-05-12 02:17:14 +0000268 } else {
Dan Gohman4e8a9852009-06-18 16:54:06 +0000269 StrideUses->addUser(Start, User, I);
Dan Gohman81db61a2009-05-12 02:17:14 +0000270 }
271 }
272 }
273 return true;
274}
275
Evan Cheng586f69a2009-11-12 07:35:05 +0000276void IVUsers::AddUser(const SCEV *Stride, const SCEV *Offset,
277 Instruction *User, Value *Operand) {
278 IVUsersOfOneStride *StrideUses = IVUsesByStride[Stride];
279 if (!StrideUses) { // First occurrence of this stride?
280 StrideOrder.push_back(Stride);
281 StrideUses = new IVUsersOfOneStride(Stride);
282 IVUses.push_back(StrideUses);
283 IVUsesByStride[Stride] = StrideUses;
284 }
285 IVUsesByStride[Stride]->addUser(Offset, User, Operand);
286}
287
Dan Gohman81db61a2009-05-12 02:17:14 +0000288IVUsers::IVUsers()
289 : LoopPass(&ID) {
290}
291
292void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {
293 AU.addRequired<LoopInfo>();
294 AU.addRequired<DominatorTree>();
295 AU.addRequired<ScalarEvolution>();
296 AU.setPreservesAll();
297}
298
299bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
300
301 L = l;
302 LI = &getAnalysis<LoopInfo>();
303 DT = &getAnalysis<DominatorTree>();
304 SE = &getAnalysis<ScalarEvolution>();
305
306 // Find all uses of induction variables in this loop, and categorize
307 // them by stride. Start by finding all of the PHI nodes in the header for
308 // this loop. If they are induction variables, inspect their uses.
309 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
310 AddUsersIfInteresting(I);
311
312 return false;
313}
314
315/// getReplacementExpr - Return a SCEV expression which computes the
316/// value of the OperandValToReplace of the given IVStrideUse.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000317const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const {
Dan Gohman81db61a2009-05-12 02:17:14 +0000318 // Start with zero.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000319 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getParent()->Stride->getType());
Dan Gohman81db61a2009-05-12 02:17:14 +0000320 // Create the basic add recurrence.
321 RetVal = SE->getAddRecExpr(RetVal, U.getParent()->Stride, L);
322 // Add the offset in a separate step, because it may be loop-variant.
323 RetVal = SE->getAddExpr(RetVal, U.getOffset());
324 // For uses of post-incremented values, add an extra stride to compute
325 // the actual replacement value.
326 if (U.isUseOfPostIncrementedValue())
327 RetVal = SE->getAddExpr(RetVal, U.getParent()->Stride);
Dan Gohman81db61a2009-05-12 02:17:14 +0000328 return RetVal;
329}
330
Dan Gohmanbafbbdd2010-01-19 21:55:32 +0000331/// getCanonicalExpr - Return a SCEV expression which computes the
332/// value of the SCEV of the given IVStrideUse, ignoring the
333/// isUseOfPostIncrementedValue flag.
334const SCEV *IVUsers::getCanonicalExpr(const IVStrideUse &U) const {
335 // Start with zero.
336 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getParent()->Stride->getType());
337 // Create the basic add recurrence.
338 RetVal = SE->getAddRecExpr(RetVal, U.getParent()->Stride, L);
339 // Add the offset in a separate step, because it may be loop-variant.
340 RetVal = SE->getAddExpr(RetVal, U.getOffset());
341 return RetVal;
342}
343
Dan Gohman4207d6a2010-02-10 20:42:37 +0000344namespace {
345
346// Suppress extraneous comments.
347class IVUsersAsmAnnotator : public AssemblyAnnotationWriter {};
348
349}
350
Dan Gohman81db61a2009-05-12 02:17:14 +0000351void IVUsers::print(raw_ostream &OS, const Module *M) const {
352 OS << "IV Users for loop ";
353 WriteAsOperand(OS, L->getHeader(), false);
354 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
355 OS << " with backedge-taken count "
356 << *SE->getBackedgeTakenCount(L);
357 }
358 OS << ":\n";
359
Dan Gohman4207d6a2010-02-10 20:42:37 +0000360 IVUsersAsmAnnotator Annotator;
Dan Gohman81db61a2009-05-12 02:17:14 +0000361 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000362 std::map<const SCEV *, IVUsersOfOneStride*>::const_iterator SI =
Dan Gohman81db61a2009-05-12 02:17:14 +0000363 IVUsesByStride.find(StrideOrder[Stride]);
364 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!");
365 OS << " Stride " << *SI->first->getType() << " " << *SI->first << ":\n";
366
367 for (ilist<IVStrideUse>::const_iterator UI = SI->second->Users.begin(),
368 E = SI->second->Users.end(); UI != E; ++UI) {
369 OS << " ";
370 WriteAsOperand(OS, UI->getOperandValToReplace(), false);
371 OS << " = ";
372 OS << *getReplacementExpr(*UI);
373 if (UI->isUseOfPostIncrementedValue())
374 OS << " (post-inc)";
375 OS << " in ";
Dan Gohman4207d6a2010-02-10 20:42:37 +0000376 UI->getUser()->print(OS, &Annotator);
Dan Gohmand9ef1a82009-07-14 00:32:49 +0000377 OS << '\n';
Dan Gohman81db61a2009-05-12 02:17:14 +0000378 }
379 }
380}
381
Dan Gohman81db61a2009-05-12 02:17:14 +0000382void IVUsers::dump() const {
David Greene63c45602009-12-23 20:20:46 +0000383 print(dbgs());
Dan Gohman81db61a2009-05-12 02:17:14 +0000384}
385
386void IVUsers::releaseMemory() {
387 IVUsesByStride.clear();
388 StrideOrder.clear();
Evan Cheng04149f72009-12-17 09:39:49 +0000389 Processed.clear();
Dan Gohman6bec5bb2009-12-18 00:06:20 +0000390 IVUses.clear();
Dan Gohman81db61a2009-05-12 02:17:14 +0000391}
392
393void IVStrideUse::deleted() {
394 // Remove this user from the list.
395 Parent->Users.erase(this);
396 // this now dangles!
397}
Bill Wendlingf7d84832010-02-01 22:51:23 +0000398
399void IVUsersOfOneStride::print(raw_ostream &OS) const {
400 OS << "IV Users of one stride:\n";
401
402 if (Stride)
403 OS << " Stride: " << *Stride << '\n';
404
405 OS << " Users:\n";
406
407 unsigned Count = 1;
408
409 for (ilist<IVStrideUse>::const_iterator
410 I = Users.begin(), E = Users.end(); I != E; ++I) {
411 const IVStrideUse &SU = *I;
412 OS << " " << Count++ << '\n';
413 OS << " Offset: " << *SU.getOffset() << '\n';
414 OS << " Instr: " << *SU << '\n';
415 }
416}
417
418void IVUsersOfOneStride::dump() const {
419 print(dbgs());
420}