LLVM API Documentation
00001 //===- IVUsers.cpp - Induction Variable Users -------------------*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements bookkeeping for "interesting" users of expressions 00011 // computed from induction variables. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #define DEBUG_TYPE "iv-users" 00016 #include "llvm/Analysis/IVUsers.h" 00017 #include "llvm/Constants.h" 00018 #include "llvm/Instructions.h" 00019 #include "llvm/Type.h" 00020 #include "llvm/DerivedTypes.h" 00021 #include "llvm/Analysis/Dominators.h" 00022 #include "llvm/Analysis/LoopInfo.h" 00023 #include "llvm/Analysis/LoopPass.h" 00024 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 00025 #include "llvm/ADT/STLExtras.h" 00026 #include "llvm/Support/Debug.h" 00027 #include "llvm/Support/raw_ostream.h" 00028 #include <algorithm> 00029 using namespace llvm; 00030 00031 char IVUsers::ID = 0; 00032 static RegisterPass<IVUsers> 00033 X("iv-users", "Induction Variable Users", false, true); 00034 00035 Pass *llvm::createIVUsersPass() { 00036 return new IVUsers(); 00037 } 00038 00039 /// containsAddRecFromDifferentLoop - Determine whether expression S involves a 00040 /// subexpression that is an AddRec from a loop other than L. An outer loop 00041 /// of L is OK, but not an inner loop nor a disjoint loop. 00042 static bool containsAddRecFromDifferentLoop(const SCEV *S, Loop *L) { 00043 // This is very common, put it first. 00044 if (isa<SCEVConstant>(S)) 00045 return false; 00046 if (const SCEVCommutativeExpr *AE = dyn_cast<SCEVCommutativeExpr>(S)) { 00047 for (unsigned int i=0; i< AE->getNumOperands(); i++) 00048 if (containsAddRecFromDifferentLoop(AE->getOperand(i), L)) 00049 return true; 00050 return false; 00051 } 00052 if (const SCEVAddRecExpr *AE = dyn_cast<SCEVAddRecExpr>(S)) { 00053 if (const Loop *newLoop = AE->getLoop()) { 00054 if (newLoop == L) 00055 return false; 00056 // if newLoop is an outer loop of L, this is OK. 00057 if (!LoopInfo::isNotAlreadyContainedIn(L, newLoop)) 00058 return false; 00059 } 00060 return true; 00061 } 00062 if (const SCEVUDivExpr *DE = dyn_cast<SCEVUDivExpr>(S)) 00063 return containsAddRecFromDifferentLoop(DE->getLHS(), L) || 00064 containsAddRecFromDifferentLoop(DE->getRHS(), L); 00065 #if 0 00066 // SCEVSDivExpr has been backed out temporarily, but will be back; we'll 00067 // need this when it is. 00068 if (const SCEVSDivExpr *DE = dyn_cast<SCEVSDivExpr>(S)) 00069 return containsAddRecFromDifferentLoop(DE->getLHS(), L) || 00070 containsAddRecFromDifferentLoop(DE->getRHS(), L); 00071 #endif 00072 if (const SCEVCastExpr *CE = dyn_cast<SCEVCastExpr>(S)) 00073 return containsAddRecFromDifferentLoop(CE->getOperand(), L); 00074 return false; 00075 } 00076 00077 /// getSCEVStartAndStride - Compute the start and stride of this expression, 00078 /// returning false if the expression is not a start/stride pair, or true if it 00079 /// is. The stride must be a loop invariant expression, but the start may be 00080 /// a mix of loop invariant and loop variant expressions. The start cannot, 00081 /// however, contain an AddRec from a different loop, unless that loop is an 00082 /// outer loop of the current loop. 00083 static bool getSCEVStartAndStride(const SCEV *&SH, Loop *L, Loop *UseLoop, 00084 const SCEV *&Start, const SCEV *&Stride, 00085 ScalarEvolution *SE, DominatorTree *DT) { 00086 const SCEV *TheAddRec = Start; // Initialize to zero. 00087 00088 // If the outer level is an AddExpr, the operands are all start values except 00089 // for a nested AddRecExpr. 00090 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(SH)) { 00091 for (unsigned i = 0, e = AE->getNumOperands(); i != e; ++i) 00092 if (const SCEVAddRecExpr *AddRec = 00093 dyn_cast<SCEVAddRecExpr>(AE->getOperand(i))) { 00094 if (AddRec->getLoop() == L) 00095 TheAddRec = SE->getAddExpr(AddRec, TheAddRec); 00096 else 00097 return false; // Nested IV of some sort? 00098 } else { 00099 Start = SE->getAddExpr(Start, AE->getOperand(i)); 00100 } 00101 } else if (isa<SCEVAddRecExpr>(SH)) { 00102 TheAddRec = SH; 00103 } else { 00104 return false; // not analyzable. 00105 } 00106 00107 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(TheAddRec); 00108 if (!AddRec || AddRec->getLoop() != L) return false; 00109 00110 // Use getSCEVAtScope to attempt to simplify other loops out of 00111 // the picture. 00112 const SCEV *AddRecStart = AddRec->getStart(); 00113 AddRecStart = SE->getSCEVAtScope(AddRecStart, UseLoop); 00114 const SCEV *AddRecStride = AddRec->getStepRecurrence(*SE); 00115 00116 // FIXME: If Start contains an SCEVAddRecExpr from a different loop, other 00117 // than an outer loop of the current loop, reject it. LSR has no concept of 00118 // operating on more than one loop at a time so don't confuse it with such 00119 // expressions. 00120 if (containsAddRecFromDifferentLoop(AddRecStart, L)) 00121 return false; 00122 00123 Start = SE->getAddExpr(Start, AddRecStart); 00124 00125 // If stride is an instruction, make sure it dominates the loop preheader. 00126 // Otherwise we could end up with a use before def situation. 00127 if (!isa<SCEVConstant>(AddRecStride)) { 00128 BasicBlock *Preheader = L->getLoopPreheader(); 00129 if (!AddRecStride->dominates(Preheader, DT)) 00130 return false; 00131 00132 DEBUG(errs() << "[" << L->getHeader()->getName() 00133 << "] Variable stride: " << *AddRec << "\n"); 00134 } 00135 00136 Stride = AddRecStride; 00137 return true; 00138 } 00139 00140 /// IVUseShouldUsePostIncValue - We have discovered a "User" of an IV expression 00141 /// and now we need to decide whether the user should use the preinc or post-inc 00142 /// value. If this user should use the post-inc version of the IV, return true. 00143 /// 00144 /// Choosing wrong here can break dominance properties (if we choose to use the 00145 /// post-inc value when we cannot) or it can end up adding extra live-ranges to 00146 /// the loop, resulting in reg-reg copies (if we use the pre-inc value when we 00147 /// should use the post-inc value). 00148 static bool IVUseShouldUsePostIncValue(Instruction *User, Instruction *IV, 00149 Loop *L, LoopInfo *LI, DominatorTree *DT, 00150 Pass *P) { 00151 // If the user is in the loop, use the preinc value. 00152 if (L->contains(User->getParent())) return false; 00153 00154 BasicBlock *LatchBlock = L->getLoopLatch(); 00155 00156 // Ok, the user is outside of the loop. If it is dominated by the latch 00157 // block, use the post-inc value. 00158 if (DT->dominates(LatchBlock, User->getParent())) 00159 return true; 00160 00161 // There is one case we have to be careful of: PHI nodes. These little guys 00162 // can live in blocks that are not dominated by the latch block, but (since 00163 // their uses occur in the predecessor block, not the block the PHI lives in) 00164 // should still use the post-inc value. Check for this case now. 00165 PHINode *PN = dyn_cast<PHINode>(User); 00166 if (!PN) return false; // not a phi, not dominated by latch block. 00167 00168 // Look at all of the uses of IV by the PHI node. If any use corresponds to 00169 // a block that is not dominated by the latch block, give up and use the 00170 // preincremented value. 00171 unsigned NumUses = 0; 00172 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 00173 if (PN->getIncomingValue(i) == IV) { 00174 ++NumUses; 00175 if (!DT->dominates(LatchBlock, PN->getIncomingBlock(i))) 00176 return false; 00177 } 00178 00179 // Okay, all uses of IV by PN are in predecessor blocks that really are 00180 // dominated by the latch block. Use the post-incremented value. 00181 return true; 00182 } 00183 00184 /// AddUsersIfInteresting - Inspect the specified instruction. If it is a 00185 /// reducible SCEV, recursively add its users to the IVUsesByStride set and 00186 /// return true. Otherwise, return false. 00187 bool IVUsers::AddUsersIfInteresting(Instruction *I) { 00188 if (!SE->isSCEVable(I->getType())) 00189 return false; // Void and FP expressions cannot be reduced. 00190 00191 // LSR is not APInt clean, do not touch integers bigger than 64-bits. 00192 if (SE->getTypeSizeInBits(I->getType()) > 64) 00193 return false; 00194 00195 if (!Processed.insert(I)) 00196 return true; // Instruction already handled. 00197 00198 // Get the symbolic expression for this instruction. 00199 const SCEV *ISE = SE->getSCEV(I); 00200 if (isa<SCEVCouldNotCompute>(ISE)) return false; 00201 00202 // Get the start and stride for this expression. 00203 Loop *UseLoop = LI->getLoopFor(I->getParent()); 00204 const SCEV *Start = SE->getIntegerSCEV(0, ISE->getType()); 00205 const SCEV *Stride = Start; 00206 00207 if (!getSCEVStartAndStride(ISE, L, UseLoop, Start, Stride, SE, DT)) 00208 return false; // Non-reducible symbolic expression, bail out. 00209 00210 SmallPtrSet<Instruction *, 4> UniqueUsers; 00211 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 00212 UI != E; ++UI) { 00213 Instruction *User = cast<Instruction>(*UI); 00214 if (!UniqueUsers.insert(User)) 00215 continue; 00216 00217 // Do not infinitely recurse on PHI nodes. 00218 if (isa<PHINode>(User) && Processed.count(User)) 00219 continue; 00220 00221 // Descend recursively, but not into PHI nodes outside the current loop. 00222 // It's important to see the entire expression outside the loop to get 00223 // choices that depend on addressing mode use right, although we won't 00224 // consider references ouside the loop in all cases. 00225 // If User is already in Processed, we don't want to recurse into it again, 00226 // but do want to record a second reference in the same instruction. 00227 bool AddUserToIVUsers = false; 00228 if (LI->getLoopFor(User->getParent()) != L) { 00229 if (isa<PHINode>(User) || Processed.count(User) || 00230 !AddUsersIfInteresting(User)) { 00231 DOUT << "FOUND USER in other loop: " << *User << '\n' 00232 << " OF SCEV: " << *ISE << "\n"; 00233 AddUserToIVUsers = true; 00234 } 00235 } else if (Processed.count(User) || 00236 !AddUsersIfInteresting(User)) { 00237 DOUT << "FOUND USER: " << *User << '\n' 00238 << " OF SCEV: " << *ISE << "\n"; 00239 AddUserToIVUsers = true; 00240 } 00241 00242 if (AddUserToIVUsers) { 00243 IVUsersOfOneStride *StrideUses = IVUsesByStride[Stride]; 00244 if (!StrideUses) { // First occurrence of this stride? 00245 StrideOrder.push_back(Stride); 00246 StrideUses = new IVUsersOfOneStride(Stride); 00247 IVUses.push_back(StrideUses); 00248 IVUsesByStride[Stride] = StrideUses; 00249 } 00250 00251 // Okay, we found a user that we cannot reduce. Analyze the instruction 00252 // and decide what to do with it. If we are a use inside of the loop, use 00253 // the value before incrementation, otherwise use it after incrementation. 00254 if (IVUseShouldUsePostIncValue(User, I, L, LI, DT, this)) { 00255 // The value used will be incremented by the stride more than we are 00256 // expecting, so subtract this off. 00257 const SCEV *NewStart = SE->getMinusSCEV(Start, Stride); 00258 StrideUses->addUser(NewStart, User, I); 00259 StrideUses->Users.back().setIsUseOfPostIncrementedValue(true); 00260 DOUT << " USING POSTINC SCEV, START=" << *NewStart<< "\n"; 00261 } else { 00262 StrideUses->addUser(Start, User, I); 00263 } 00264 } 00265 } 00266 return true; 00267 } 00268 00269 IVUsers::IVUsers() 00270 : LoopPass(&ID) { 00271 } 00272 00273 void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const { 00274 AU.addRequired<LoopInfo>(); 00275 AU.addRequired<DominatorTree>(); 00276 AU.addRequired<ScalarEvolution>(); 00277 AU.setPreservesAll(); 00278 } 00279 00280 bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) { 00281 00282 L = l; 00283 LI = &getAnalysis<LoopInfo>(); 00284 DT = &getAnalysis<DominatorTree>(); 00285 SE = &getAnalysis<ScalarEvolution>(); 00286 00287 // Find all uses of induction variables in this loop, and categorize 00288 // them by stride. Start by finding all of the PHI nodes in the header for 00289 // this loop. If they are induction variables, inspect their uses. 00290 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) 00291 AddUsersIfInteresting(I); 00292 00293 return false; 00294 } 00295 00296 /// getReplacementExpr - Return a SCEV expression which computes the 00297 /// value of the OperandValToReplace of the given IVStrideUse. 00298 const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &U) const { 00299 // Start with zero. 00300 const SCEV *RetVal = SE->getIntegerSCEV(0, U.getParent()->Stride->getType()); 00301 // Create the basic add recurrence. 00302 RetVal = SE->getAddRecExpr(RetVal, U.getParent()->Stride, L); 00303 // Add the offset in a separate step, because it may be loop-variant. 00304 RetVal = SE->getAddExpr(RetVal, U.getOffset()); 00305 // For uses of post-incremented values, add an extra stride to compute 00306 // the actual replacement value. 00307 if (U.isUseOfPostIncrementedValue()) 00308 RetVal = SE->getAddExpr(RetVal, U.getParent()->Stride); 00309 // Evaluate the expression out of the loop, if possible. 00310 if (!L->contains(U.getUser()->getParent())) { 00311 const SCEV *ExitVal = SE->getSCEVAtScope(RetVal, L->getParentLoop()); 00312 if (ExitVal->isLoopInvariant(L)) 00313 RetVal = ExitVal; 00314 } 00315 return RetVal; 00316 } 00317 00318 void IVUsers::print(raw_ostream &OS, const Module *M) const { 00319 OS << "IV Users for loop "; 00320 WriteAsOperand(OS, L->getHeader(), false); 00321 if (SE->hasLoopInvariantBackedgeTakenCount(L)) { 00322 OS << " with backedge-taken count " 00323 << *SE->getBackedgeTakenCount(L); 00324 } 00325 OS << ":\n"; 00326 00327 for (unsigned Stride = 0, e = StrideOrder.size(); Stride != e; ++Stride) { 00328 std::map<const SCEV *, IVUsersOfOneStride*>::const_iterator SI = 00329 IVUsesByStride.find(StrideOrder[Stride]); 00330 assert(SI != IVUsesByStride.end() && "Stride doesn't exist!"); 00331 OS << " Stride " << *SI->first->getType() << " " << *SI->first << ":\n"; 00332 00333 for (ilist<IVStrideUse>::const_iterator UI = SI->second->Users.begin(), 00334 E = SI->second->Users.end(); UI != E; ++UI) { 00335 OS << " "; 00336 WriteAsOperand(OS, UI->getOperandValToReplace(), false); 00337 OS << " = "; 00338 OS << *getReplacementExpr(*UI); 00339 if (UI->isUseOfPostIncrementedValue()) 00340 OS << " (post-inc)"; 00341 OS << " in "; 00342 UI->getUser()->print(OS); 00343 OS << '\n'; 00344 } 00345 } 00346 } 00347 00348 void IVUsers::print(std::ostream &o, const Module *M) const { 00349 raw_os_ostream OS(o); 00350 print(OS, M); 00351 } 00352 00353 void IVUsers::dump() const { 00354 print(errs()); 00355 } 00356 00357 void IVUsers::releaseMemory() { 00358 IVUsesByStride.clear(); 00359 StrideOrder.clear(); 00360 Processed.clear(); 00361 } 00362 00363 void IVStrideUse::deleted() { 00364 // Remove this user from the list. 00365 Parent->Users.erase(this); 00366 // this now dangles! 00367 }