LLVM  mainline
IVUsers.cpp
Go to the documentation of this file.
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 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/Analysis/AssumptionCache.h"
00017 #include "llvm/Analysis/CodeMetrics.h"
00018 #include "llvm/Analysis/IVUsers.h"
00019 #include "llvm/Analysis/LoopPass.h"
00020 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
00021 #include "llvm/Analysis/ValueTracking.h"
00022 #include "llvm/IR/Constants.h"
00023 #include "llvm/IR/DataLayout.h"
00024 #include "llvm/IR/DerivedTypes.h"
00025 #include "llvm/IR/Dominators.h"
00026 #include "llvm/IR/Instructions.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/IR/Type.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include <algorithm>
00032 using namespace llvm;
00033 
00034 #define DEBUG_TYPE "iv-users"
00035 
00036 char IVUsers::ID = 0;
00037 INITIALIZE_PASS_BEGIN(IVUsers, "iv-users",
00038                       "Induction Variable Users", false, true)
00039 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00040 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
00041 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00042 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
00043 INITIALIZE_PASS_END(IVUsers, "iv-users",
00044                       "Induction Variable Users", false, true)
00045 
00046 Pass *llvm::createIVUsersPass() {
00047   return new IVUsers();
00048 }
00049 
00050 /// isInteresting - Test whether the given expression is "interesting" when
00051 /// used by the given expression, within the context of analyzing the
00052 /// given loop.
00053 static bool isInteresting(const SCEV *S, const Instruction *I, const Loop *L,
00054                           ScalarEvolution *SE, LoopInfo *LI) {
00055   // An addrec is interesting if it's affine or if it has an interesting start.
00056   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
00057     // Keep things simple. Don't touch loop-variant strides unless they're
00058     // only used outside the loop and we can simplify them.
00059     if (AR->getLoop() == L)
00060       return AR->isAffine() ||
00061              (!L->contains(I) &&
00062               SE->getSCEVAtScope(AR, LI->getLoopFor(I->getParent())) != AR);
00063     // Otherwise recurse to see if the start value is interesting, and that
00064     // the step value is not interesting, since we don't yet know how to
00065     // do effective SCEV expansions for addrecs with interesting steps.
00066     return isInteresting(AR->getStart(), I, L, SE, LI) &&
00067           !isInteresting(AR->getStepRecurrence(*SE), I, L, SE, LI);
00068   }
00069 
00070   // An add is interesting if exactly one of its operands is interesting.
00071   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
00072     bool AnyInterestingYet = false;
00073     for (SCEVAddExpr::op_iterator OI = Add->op_begin(), OE = Add->op_end();
00074          OI != OE; ++OI)
00075       if (isInteresting(*OI, I, L, SE, LI)) {
00076         if (AnyInterestingYet)
00077           return false;
00078         AnyInterestingYet = true;
00079       }
00080     return AnyInterestingYet;
00081   }
00082 
00083   // Nothing else is interesting here.
00084   return false;
00085 }
00086 
00087 /// Return true if all loop headers that dominate this block are in simplified
00088 /// form.
00089 static bool isSimplifiedLoopNest(BasicBlock *BB, const DominatorTree *DT,
00090                                  const LoopInfo *LI,
00091                                  SmallPtrSetImpl<Loop*> &SimpleLoopNests) {
00092   Loop *NearestLoop = nullptr;
00093   for (DomTreeNode *Rung = DT->getNode(BB);
00094        Rung; Rung = Rung->getIDom()) {
00095     BasicBlock *DomBB = Rung->getBlock();
00096     Loop *DomLoop = LI->getLoopFor(DomBB);
00097     if (DomLoop && DomLoop->getHeader() == DomBB) {
00098       // If the domtree walk reaches a loop with no preheader, return false.
00099       if (!DomLoop->isLoopSimplifyForm())
00100         return false;
00101       // If we have already checked this loop nest, stop checking.
00102       if (SimpleLoopNests.count(DomLoop))
00103         break;
00104       // If we have not already checked this loop nest, remember the loop
00105       // header nearest to BB. The nearest loop may not contain BB.
00106       if (!NearestLoop)
00107         NearestLoop = DomLoop;
00108     }
00109   }
00110   if (NearestLoop)
00111     SimpleLoopNests.insert(NearestLoop);
00112   return true;
00113 }
00114 
00115 /// AddUsersImpl - Inspect the specified instruction.  If it is a
00116 /// reducible SCEV, recursively add its users to the IVUsesByStride set and
00117 /// return true.  Otherwise, return false.
00118 bool IVUsers::AddUsersImpl(Instruction *I,
00119                            SmallPtrSetImpl<Loop*> &SimpleLoopNests) {
00120   const DataLayout &DL = I->getModule()->getDataLayout();
00121 
00122   // Add this IV user to the Processed set before returning false to ensure that
00123   // all IV users are members of the set. See IVUsers::isIVUserOrOperand.
00124   if (!Processed.insert(I).second)
00125     return true;    // Instruction already handled.
00126 
00127   if (!SE->isSCEVable(I->getType()))
00128     return false;   // Void and FP expressions cannot be reduced.
00129 
00130   // IVUsers is used by LSR which assumes that all SCEV expressions are safe to
00131   // pass to SCEVExpander. Expressions are not safe to expand if they represent
00132   // operations that are not safe to speculate, namely integer division.
00133   if (!isa<PHINode>(I) && !isSafeToSpeculativelyExecute(I))
00134     return false;
00135 
00136   // LSR is not APInt clean, do not touch integers bigger than 64-bits.
00137   // Also avoid creating IVs of non-native types. For example, we don't want a
00138   // 64-bit IV in 32-bit code just because the loop has one 64-bit cast.
00139   uint64_t Width = SE->getTypeSizeInBits(I->getType());
00140   if (Width > 64 || !DL.isLegalInteger(Width))
00141     return false;
00142 
00143   // Don't attempt to promote ephemeral values to indvars. They will be removed
00144   // later anyway.
00145   if (EphValues.count(I))
00146     return false;
00147 
00148   // Get the symbolic expression for this instruction.
00149   const SCEV *ISE = SE->getSCEV(I);
00150 
00151   // If we've come to an uninteresting expression, stop the traversal and
00152   // call this a user.
00153   if (!isInteresting(ISE, I, L, SE, LI))
00154     return false;
00155 
00156   SmallPtrSet<Instruction *, 4> UniqueUsers;
00157   for (Use &U : I->uses()) {
00158     Instruction *User = cast<Instruction>(U.getUser());
00159     if (!UniqueUsers.insert(User).second)
00160       continue;
00161 
00162     // Do not infinitely recurse on PHI nodes.
00163     if (isa<PHINode>(User) && Processed.count(User))
00164       continue;
00165 
00166     // Only consider IVUsers that are dominated by simplified loop
00167     // headers. Otherwise, SCEVExpander will crash.
00168     BasicBlock *UseBB = User->getParent();
00169     // A phi's use is live out of its predecessor block.
00170     if (PHINode *PHI = dyn_cast<PHINode>(User)) {
00171       unsigned OperandNo = U.getOperandNo();
00172       unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
00173       UseBB = PHI->getIncomingBlock(ValNo);
00174     }
00175     if (!isSimplifiedLoopNest(UseBB, DT, LI, SimpleLoopNests))
00176       return false;
00177 
00178     // Descend recursively, but not into PHI nodes outside the current loop.
00179     // It's important to see the entire expression outside the loop to get
00180     // choices that depend on addressing mode use right, although we won't
00181     // consider references outside the loop in all cases.
00182     // If User is already in Processed, we don't want to recurse into it again,
00183     // but do want to record a second reference in the same instruction.
00184     bool AddUserToIVUsers = false;
00185     if (LI->getLoopFor(User->getParent()) != L) {
00186       if (isa<PHINode>(User) || Processed.count(User) ||
00187           !AddUsersImpl(User, SimpleLoopNests)) {
00188         DEBUG(dbgs() << "FOUND USER in other loop: " << *User << '\n'
00189                      << "   OF SCEV: " << *ISE << '\n');
00190         AddUserToIVUsers = true;
00191       }
00192     } else if (Processed.count(User) || !AddUsersImpl(User, SimpleLoopNests)) {
00193       DEBUG(dbgs() << "FOUND USER: " << *User << '\n'
00194                    << "   OF SCEV: " << *ISE << '\n');
00195       AddUserToIVUsers = true;
00196     }
00197 
00198     if (AddUserToIVUsers) {
00199       // Okay, we found a user that we cannot reduce.
00200       IVStrideUse &NewUse = AddUser(User, I);
00201       // Autodetect the post-inc loop set, populating NewUse.PostIncLoops.
00202       // The regular return value here is discarded; instead of recording
00203       // it, we just recompute it when we need it.
00204       const SCEV *OriginalISE = ISE;
00205       ISE = TransformForPostIncUse(NormalizeAutodetect,
00206                                    ISE, User, I,
00207                                    NewUse.PostIncLoops,
00208                                    *SE, *DT);
00209 
00210       // PostIncNormalization effectively simplifies the expression under
00211       // pre-increment assumptions. Those assumptions (no wrapping) might not
00212       // hold for the post-inc value. Catch such cases by making sure the
00213       // transformation is invertible.
00214       if (OriginalISE != ISE) {
00215         const SCEV *DenormalizedISE =
00216           TransformForPostIncUse(Denormalize, ISE, User, I,
00217               NewUse.PostIncLoops, *SE, *DT);
00218 
00219         // If we normalized the expression, but denormalization doesn't give the
00220         // original one, discard this user.
00221         if (OriginalISE != DenormalizedISE) {
00222           DEBUG(dbgs() << "   DISCARDING (NORMALIZATION ISN'T INVERTIBLE): "
00223                        << *ISE << '\n');
00224           IVUses.pop_back();
00225           return false;
00226         }
00227       }
00228       DEBUG(if (SE->getSCEV(I) != ISE)
00229               dbgs() << "   NORMALIZED TO: " << *ISE << '\n');
00230     }
00231   }
00232   return true;
00233 }
00234 
00235 bool IVUsers::AddUsersIfInteresting(Instruction *I) {
00236   // SCEVExpander can only handle users that are dominated by simplified loop
00237   // entries. Keep track of all loops that are only dominated by other simple
00238   // loops so we don't traverse the domtree for each user.
00239   SmallPtrSet<Loop*,16> SimpleLoopNests;
00240 
00241   return AddUsersImpl(I, SimpleLoopNests);
00242 }
00243 
00244 IVStrideUse &IVUsers::AddUser(Instruction *User, Value *Operand) {
00245   IVUses.push_back(new IVStrideUse(this, User, Operand));
00246   return IVUses.back();
00247 }
00248 
00249 IVUsers::IVUsers()
00250     : LoopPass(ID) {
00251   initializeIVUsersPass(*PassRegistry::getPassRegistry());
00252 }
00253 
00254 void IVUsers::getAnalysisUsage(AnalysisUsage &AU) const {
00255   AU.addRequired<AssumptionCacheTracker>();
00256   AU.addRequired<LoopInfoWrapperPass>();
00257   AU.addRequired<DominatorTreeWrapperPass>();
00258   AU.addRequired<ScalarEvolutionWrapperPass>();
00259   AU.setPreservesAll();
00260 }
00261 
00262 bool IVUsers::runOnLoop(Loop *l, LPPassManager &LPM) {
00263 
00264   L = l;
00265   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
00266       *L->getHeader()->getParent());
00267   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
00268   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00269   SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
00270 
00271   // Collect ephemeral values so that AddUsersIfInteresting skips them.
00272   EphValues.clear();
00273   CodeMetrics::collectEphemeralValues(L, AC, EphValues);
00274 
00275   // Find all uses of induction variables in this loop, and categorize
00276   // them by stride.  Start by finding all of the PHI nodes in the header for
00277   // this loop.  If they are induction variables, inspect their uses.
00278   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I)
00279     (void)AddUsersIfInteresting(&*I);
00280 
00281   return false;
00282 }
00283 
00284 void IVUsers::print(raw_ostream &OS, const Module *M) const {
00285   OS << "IV Users for loop ";
00286   L->getHeader()->printAsOperand(OS, false);
00287   if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
00288     OS << " with backedge-taken count "
00289        << *SE->getBackedgeTakenCount(L);
00290   }
00291   OS << ":\n";
00292 
00293   for (ilist<IVStrideUse>::const_iterator UI = IVUses.begin(),
00294        E = IVUses.end(); UI != E; ++UI) {
00295     OS << "  ";
00296     UI->getOperandValToReplace()->printAsOperand(OS, false);
00297     OS << " = " << *getReplacementExpr(*UI);
00298     for (PostIncLoopSet::const_iterator
00299          I = UI->PostIncLoops.begin(),
00300          E = UI->PostIncLoops.end(); I != E; ++I) {
00301       OS << " (post-inc with loop ";
00302       (*I)->getHeader()->printAsOperand(OS, false);
00303       OS << ")";
00304     }
00305     OS << " in  ";
00306     if (UI->getUser())
00307       UI->getUser()->print(OS);
00308     else
00309       OS << "Printing <null> User";
00310     OS << '\n';
00311   }
00312 }
00313 
00314 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00315 void IVUsers::dump() const {
00316   print(dbgs());
00317 }
00318 #endif
00319 
00320 void IVUsers::releaseMemory() {
00321   Processed.clear();
00322   IVUses.clear();
00323 }
00324 
00325 /// getReplacementExpr - Return a SCEV expression which computes the
00326 /// value of the OperandValToReplace.
00327 const SCEV *IVUsers::getReplacementExpr(const IVStrideUse &IU) const {
00328   return SE->getSCEV(IU.getOperandValToReplace());
00329 }
00330 
00331 /// getExpr - Return the expression for the use.
00332 const SCEV *IVUsers::getExpr(const IVStrideUse &IU) const {
00333   return
00334     TransformForPostIncUse(Normalize, getReplacementExpr(IU),
00335                            IU.getUser(), IU.getOperandValToReplace(),
00336                            const_cast<PostIncLoopSet &>(IU.getPostIncLoops()),
00337                            *SE, *DT);
00338 }
00339 
00340 static const SCEVAddRecExpr *findAddRecForLoop(const SCEV *S, const Loop *L) {
00341   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
00342     if (AR->getLoop() == L)
00343       return AR;
00344     return findAddRecForLoop(AR->getStart(), L);
00345   }
00346 
00347   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
00348     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
00349          I != E; ++I)
00350       if (const SCEVAddRecExpr *AR = findAddRecForLoop(*I, L))
00351         return AR;
00352     return nullptr;
00353   }
00354 
00355   return nullptr;
00356 }
00357 
00358 const SCEV *IVUsers::getStride(const IVStrideUse &IU, const Loop *L) const {
00359   if (const SCEVAddRecExpr *AR = findAddRecForLoop(getExpr(IU), L))
00360     return AR->getStepRecurrence(*SE);
00361   return nullptr;
00362 }
00363 
00364 void IVStrideUse::transformToPostInc(const Loop *L) {
00365   PostIncLoops.insert(L);
00366 }
00367 
00368 void IVStrideUse::deleted() {
00369   // Remove this user from the list.
00370   Parent->Processed.erase(this->getUser());
00371   Parent->IVUses.erase(this);
00372   // this now dangles!
00373 }