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/Assembly/AsmAnnotationWriter.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
32 INITIALIZE_PASS(IVUsers, "iv-users", "Induction Variable Users", false, true);
34 Pass *llvm::createIVUsersPass() {
38 /// isInteresting - Test whether the given expression is "interesting" when
39 /// used by the given expression, within the context of analyzing the
41 static bool isInteresting(const SCEV *S, const Instruction *I, const Loop *L,
42 ScalarEvolution *SE) {
43 // An addrec is interesting if it's affine or if it has an interesting start.
44 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
45 // Keep things simple. Don't touch loop-variant strides.
46 if (AR->getLoop() == L)
47 return AR->isAffine() || !L->contains(I);
48 // Otherwise recurse to see if the start value is interesting, and that
49 // the step value is not interesting, since we don't yet know how to
50 // do effective SCEV expansions for addrecs with interesting steps.
51 return isInteresting(AR->getStart(), I, L, SE) &&
52 !isInteresting(AR->getStepRecurrence(*SE), I, L, SE);
55 // An add is interesting if exactly one of its operands is interesting.
56 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
57 bool AnyInterestingYet = false;
58 for (SCEVAddExpr::op_iterator OI = Add->op_begin(), OE = Add->op_end();
60 if (isInteresting(*OI, I, L, SE)) {
61 if (AnyInterestingYet)
63 AnyInterestingYet = true;
65 return AnyInterestingYet;
68 // Nothing else is interesting here.
72 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a
73 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
74 /// return true. Otherwise, return false.
75 bool IVUsers::AddUsersIfInteresting(Instruction *I) {
76 if (!SE->isSCEVable(I->getType()))
77 return false; // Void and FP expressions cannot be reduced.
79 // LSR is not APInt clean, do not touch integers bigger than 64-bits.
80 if (SE->getTypeSizeInBits(I->getType()) > 64)
83 if (!Processed.insert(I))
84 return true; // Instruction already handled.
86 // Get the symbolic expression for this instruction.
87 const SCEV *ISE = SE->getSCEV(I);
89 // If we've come to an uninteresting expression, stop the traversal and
91 if (!isInteresting(ISE, I, L, SE))
94 SmallPtrSet<Instruction *, 4> UniqueUsers;
95 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
97 Instruction *User = cast<Instruction>(*UI);
98 if (!UniqueUsers.insert(User))
101 // Do not infinitely recurse on PHI nodes.
102 if (isa<PHINode>(User) && Processed.count(User))
105 // Descend recursively, but not into PHI nodes outside the current loop.
106 // It's important to see the entire expression outside the loop to get
107 // choices that depend on addressing mode use right, although we won't
108 // consider references outside the loop in all cases.
109 // If User is already in Processed, we don't want to recurse into it again,
110 // but do want to record a second reference in the same instruction.
111 bool AddUserToIVUsers = false;
112 if (LI->getLoopFor(User->getParent()) != L) {
113 if (isa<PHINode>(User) || Processed.count(User) ||
114 !AddUsersIfInteresting(User)) {
115 DEBUG(dbgs() << "FOUND USER in other loop: " << *User << '\n'
116 << " OF SCEV: " << *ISE << '\n');
117 AddUserToIVUsers = true;
119 } else if (Processed.count(User) ||
120 !AddUsersIfInteresting(User)) {
121 DEBUG(dbgs() << "FOUND USER: " << *User << '\n'
122 << " OF SCEV: " << *ISE << '\n');
123 AddUserToIVUsers = true;
126 if (AddUserToIVUsers) {
127 // Okay, we found a user that we cannot reduce.
128 IVUses.push_back(new IVStrideUse(this, User, I));
129 IVStrideUse &NewUse = IVUses.back();
130 // Transform the expression into a normalized form.
131 ISE = TransformForPostIncUse(NormalizeAutodetect,
135 DEBUG(dbgs() << " NORMALIZED TO: " << *ISE << '\n');
141 IVStrideUse &IVUsers::AddUser(Instruction *User, Value *Operand) {
142 IVUses.push_back(new IVStrideUse(this, User, Operand));
143 return IVUses.back();
150 void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {
151 AU.addRequired<LoopInfo>();
152 AU.addRequired<DominatorTree>();
153 AU.addRequired<ScalarEvolution>();
154 AU.setPreservesAll();
157 bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
160 LI = &getAnalysis<LoopInfo>();
161 DT = &getAnalysis<DominatorTree>();
162 SE = &getAnalysis<ScalarEvolution>();
164 // Find all uses of induction variables in this loop, and categorize
165 // them by stride. Start by finding all of the PHI nodes in the header for
166 // this loop. If they are induction variables, inspect their uses.
167 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
168 (void)AddUsersIfInteresting(I);
173 void IVUsers::print(raw_ostream &OS, const Module *M) const {
174 OS << "IV Users for loop ";
175 WriteAsOperand(OS, L->getHeader(), false);
176 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
177 OS << " with backedge-taken count "
178 << *SE->getBackedgeTakenCount(L);
182 // Use a default AssemblyAnnotationWriter to suppress the default info
183 // comments, which aren't relevant here.
184 AssemblyAnnotationWriter Annotator;
185 for (ilist<IVStrideUse>::const_iterator UI = IVUses.begin(),
186 E = IVUses.end(); UI != E; ++UI) {
188 WriteAsOperand(OS, UI->getOperandValToReplace(), false);
189 OS << " = " << *getReplacementExpr(*UI);
190 for (PostIncLoopSet::const_iterator
191 I = UI->PostIncLoops.begin(),
192 E = UI->PostIncLoops.end(); I != E; ++I) {
193 OS << " (post-inc with loop ";
194 WriteAsOperand(OS, (*I)->getHeader(), false);
198 UI->getUser()->print(OS, &Annotator);
203 void IVUsers::dump() const {
207 void IVUsers::releaseMemory() {
212 /// getReplacementExpr - Return a SCEV expression which computes the
213 /// value of the OperandValToReplace.
214 const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &IU) const {
215 return SE->getSCEV(IU.getOperandValToReplace());
218 /// getExpr - Return the expression for the use.
219 const SCEV *IVUsers::getExpr(const IVStrideUse &IU) const {
221 TransformForPostIncUse(Normalize, getReplacementExpr(IU),
222 IU.getUser(), IU.getOperandValToReplace(),
223 const_cast<PostIncLoopSet &>(IU.getPostIncLoops()),
227 static const SCEVAddRecExpr *findAddRecForLoop(const SCEV *S, const Loop *L) {
228 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
229 if (AR->getLoop() == L)
231 return findAddRecForLoop(AR->getStart(), L);
234 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
235 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
237 if (const SCEVAddRecExpr *AR = findAddRecForLoop(*I, L))
245 const SCEV *IVUsers::getStride(const IVStrideUse &IU, const Loop *L) const {
246 if (const SCEVAddRecExpr *AR = findAddRecForLoop(getExpr(IU), L))
247 return AR->getStepRecurrence(*SE);
251 void IVStrideUse::transformToPostInc(const Loop *L) {
252 PostIncLoops.insert(L);
255 void IVStrideUse::deleted() {
256 // Remove this user from the list.
257 Parent->IVUses.erase(this);