GlobalsModRef.cpp revision 218893
14Srgrimes//===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
24Srgrimes//
34Srgrimes//                     The LLVM Compiler Infrastructure
44Srgrimes//
54Srgrimes// This file is distributed under the University of Illinois Open Source
64Srgrimes// License. See LICENSE.TXT for details.
74Srgrimes//
84Srgrimes//===----------------------------------------------------------------------===//
94Srgrimes//
104Srgrimes// This simple pass provides alias and mod/ref information for global values
114Srgrimes// that do not have their address taken, and keeps track of whether functions
124Srgrimes// read or write memory (are "pure").  For this simple (but very common) case,
134Srgrimes// we can provide pretty accurate and useful information.
144Srgrimes//
154Srgrimes//===----------------------------------------------------------------------===//
164Srgrimes
174Srgrimes#define DEBUG_TYPE "globalsmodref-aa"
184Srgrimes#include "llvm/Analysis/Passes.h"
194Srgrimes#include "llvm/Module.h"
204Srgrimes#include "llvm/Pass.h"
214Srgrimes#include "llvm/Instructions.h"
224Srgrimes#include "llvm/Constants.h"
234Srgrimes#include "llvm/DerivedTypes.h"
244Srgrimes#include "llvm/Analysis/AliasAnalysis.h"
254Srgrimes#include "llvm/Analysis/CallGraph.h"
264Srgrimes#include "llvm/Analysis/MemoryBuiltins.h"
274Srgrimes#include "llvm/Analysis/ValueTracking.h"
284Srgrimes#include "llvm/Support/CommandLine.h"
294Srgrimes#include "llvm/Support/InstIterator.h"
304Srgrimes#include "llvm/ADT/Statistic.h"
314Srgrimes#include "llvm/ADT/SCCIterator.h"
324Srgrimes#include <set>
334Srgrimesusing namespace llvm;
344Srgrimes
354SrgrimesSTATISTIC(NumNonAddrTakenGlobalVars,
364Srgrimes          "Number of global vars without address taken");
374SrgrimesSTATISTIC(NumNonAddrTakenFunctions,"Number of functions without address taken");
38620SrgrimesSTATISTIC(NumNoMemFunctions, "Number of functions that do not access memory");
3919268SjulianSTATISTIC(NumReadMemFunctions, "Number of functions that only read memory");
404SrgrimesSTATISTIC(NumIndirectGlobalVars, "Number of indirect global objects");
414Srgrimes
422056Swollmannamespace {
4312675Sjulian  /// FunctionRecord - One instance of this structure is stored for every
4412675Sjulian  /// function in the program.  Later, the entries for these functions are
4512675Sjulian  /// removed if the function is found to call an external function (in which
461549Srgrimes  /// case we know nothing about it.
475764Sbde  struct FunctionRecord {
4812675Sjulian    /// GlobalInfo - Maintain mod/ref info for all of the globals without
4918951Sjulian    /// addresses taken that are read or written (transitively) by this
5012701Sphk    /// function.
512056Swollman    std::map<const GlobalValue*, unsigned> GlobalInfo;
522056Swollman
534Srgrimes    /// MayReadAnyGlobal - May read global variables, but it is not known which.
5412701Sphk    bool MayReadAnyGlobal;
552056Swollman
564Srgrimes    unsigned getInfoForGlobal(const GlobalValue *GV) const {
578023Sbde      unsigned Effect = MayReadAnyGlobal ? AliasAnalysis::Ref : 0;
588047Sbde      std::map<const GlobalValue*, unsigned>::const_iterator I =
598047Sbde        GlobalInfo.find(GV);
608047Sbde      if (I != GlobalInfo.end())
615764Sbde        Effect |= I->second;
6210666Sbde      return Effect;
6310666Sbde    }
6410666Sbde
6510666Sbde    /// FunctionEffect - Capture whether or not this function reads or writes to
663728Sphk    /// ANY memory.  If not, we can do a lot of aggressive analysis on it.
672423Sdg    unsigned FunctionEffect;
68849Sdg
693728Sphk    FunctionRecord() : MayReadAnyGlobal (false), FunctionEffect(0) {}
70849Sdg  };
714Srgrimes
724Srgrimes  /// GlobalsModRef - The actual analysis pass.
734Srgrimes  class GlobalsModRef : public ModulePass, public AliasAnalysis {
7412675Sjulian    /// NonAddressTakenGlobals - The globals that do not have their addresses
7512675Sjulian    /// taken.
7612675Sjulian    std::set<const GlobalValue*> NonAddressTakenGlobals;
7712675Sjulian
7812675Sjulian    /// IndirectGlobals - The memory pointed to by this global is known to be
7912675Sjulian    /// 'owned' by the global.
8012675Sjulian    std::set<const GlobalValue*> IndirectGlobals;
8112675Sjulian
8212678Sphk    /// AllocsForIndirectGlobals - If an instruction allocates memory for an
8312675Sjulian    /// indirect global, this map indicates which one.
8412675Sjulian    std::map<const Value*, const GlobalValue*> AllocsForIndirectGlobals;
8512675Sjulian
8612675Sjulian    /// FunctionInfo - For each function, keep track of what globals are
874Srgrimes    /// modified or read.
8812701Sphk    std::map<const Function*, FunctionRecord> FunctionInfo;
8912701Sphk
9012701Sphk  public:
9112701Sphk    static char ID;
9218951Sjulian    GlobalsModRef() : ModulePass(ID) {
9319268Sjulian      initializeGlobalsModRefPass(*PassRegistry::getPassRegistry());
9412701Sphk    }
957680Sjoerg
967680Sjoerg    bool runOnModule(Module &M) {
977680Sjoerg      InitializeAliasAnalysis(this);                 // set up super class
987680Sjoerg      AnalyzeGlobals(M);                          // find non-addr taken globals
994Srgrimes      AnalyzeCallGraph(getAnalysis<CallGraph>(), M); // Propagate on CG
1006731Sbde      return false;
1016731Sbde    }
1025764Sbde
1035764Sbde    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1045764Sbde      AliasAnalysis::getAnalysisUsage(AU);
1057588Sjoerg      AU.addRequired<CallGraph>();
10612675Sjulian      AU.setPreservesAll();                         // Does not transform code
10712675Sjulian    }
10812675Sjulian
1095764Sbde    //------------------------------------------------
110798Swollman    // Implement the AliasAnalysis API
1114Srgrimes    //
1124Srgrimes    AliasResult alias(const Location &LocA, const Location &LocB);
11310665Sbde    ModRefResult getModRefInfo(ImmutableCallSite CS,
1144Srgrimes                               const Location &Loc);
1154Srgrimes    ModRefResult getModRefInfo(ImmutableCallSite CS1,
11610665Sbde                               ImmutableCallSite CS2) {
1174Srgrimes      return AliasAnalysis::getModRefInfo(CS1, CS2);
11810665Sbde    }
1194Srgrimes
1204Srgrimes    /// getModRefBehavior - Return the behavior of the specified function if
1214Srgrimes    /// called from the specified call site.  The call site may be null in which
12210665Sbde    /// case the most generic behavior of this function should be returned.
12310665Sbde    ModRefBehavior getModRefBehavior(const Function *F) {
1244Srgrimes      ModRefBehavior Min = UnknownModRefBehavior;
12510665Sbde
1264Srgrimes      if (FunctionRecord *FR = getFunctionInfo(F)) {
12718951Sjulian        if (FR->FunctionEffect == 0)
12818951Sjulian          Min = DoesNotAccessMemory;
12918951Sjulian        else if ((FR->FunctionEffect & Mod) == 0)
13018951Sjulian          Min = OnlyReadsMemory;
13118951Sjulian      }
13218951Sjulian
13318951Sjulian      return ModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
13418951Sjulian    }
13518951Sjulian
13618951Sjulian    /// getModRefBehavior - Return the behavior of the specified function if
13718951Sjulian    /// called from the specified call site.  The call site may be null in which
13818951Sjulian    /// case the most generic behavior of this function should be returned.
13910665Sbde    ModRefBehavior getModRefBehavior(ImmutableCallSite CS) {
1404Srgrimes      ModRefBehavior Min = UnknownModRefBehavior;
14110665Sbde
14210665Sbde      if (const Function* F = CS.getCalledFunction())
1434Srgrimes        if (FunctionRecord *FR = getFunctionInfo(F)) {
14410665Sbde          if (FR->FunctionEffect == 0)
14510665Sbde            Min = DoesNotAccessMemory;
1464Srgrimes          else if ((FR->FunctionEffect & Mod) == 0)
14710665Sbde            Min = OnlyReadsMemory;
14810665Sbde        }
14910665Sbde
15010665Sbde      return ModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
15110665Sbde    }
15210665Sbde
15310665Sbde    virtual void deleteValue(Value *V);
15410665Sbde    virtual void copyValue(Value *From, Value *To);
15510665Sbde    virtual void addEscapingUse(Use &U);
15610665Sbde
15710665Sbde    /// getAdjustedAnalysisPointer - This method is used when a pass implements
15810665Sbde    /// an analysis interface through multiple inheritance.  If needed, it
15910665Sbde    /// should override this to adjust the this pointer as needed for the
16010665Sbde    /// specified pass info.
16110665Sbde    virtual void *getAdjustedAnalysisPointer(AnalysisID PI) {
16210665Sbde      if (PI == &AliasAnalysis::ID)
16310665Sbde        return (AliasAnalysis*)this;
16410665Sbde      return this;
1655764Sbde    }
1665764Sbde
16712813Sjulian  private:
1685764Sbde    /// getFunctionInfo - Return the function info for the function, or null if
1695764Sbde    /// we don't have anything useful to say about it.
1705764Sbde    FunctionRecord *getFunctionInfo(const Function *F) {
1715764Sbde      std::map<const Function*, FunctionRecord>::iterator I =
1727588Sjoerg        FunctionInfo.find(F);
17312701Sphk      if (I != FunctionInfo.end())
1744Srgrimes        return &I->second;
1754Srgrimes      return 0;
17612675Sjulian    }
1774Srgrimes
1784Srgrimes    void AnalyzeGlobals(Module &M);
1794Srgrimes    void AnalyzeCallGraph(CallGraph &CG, Module &M);
1804Srgrimes    bool AnalyzeUsesOfPointer(Value *V, std::vector<Function*> &Readers,
1814Srgrimes                              std::vector<Function*> &Writers,
1825764Sbde                              GlobalValue *OkayStoreDest = 0);
1835764Sbde    bool AnalyzeIndirectGlobalMemory(GlobalValue *GV);
1841007Sdg  };
1854Srgrimes}
1864Srgrimes
1875764Sbdechar GlobalsModRef::ID = 0;
1885764SbdeINITIALIZE_AG_PASS_BEGIN(GlobalsModRef, AliasAnalysis,
1895764Sbde                "globalsmodref-aa", "Simple mod/ref analysis for globals",
1905764Sbde                false, true, false)
1915764SbdeINITIALIZE_AG_DEPENDENCY(CallGraph)
1925764SbdeINITIALIZE_AG_PASS_END(GlobalsModRef, AliasAnalysis,
1935764Sbde                "globalsmodref-aa", "Simple mod/ref analysis for globals",
1945764Sbde                false, true, false)
1955764Sbde
1965764SbdePass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
1974Srgrimes
1988876Srgrimes/// AnalyzeGlobals - Scan through the users of all of the internal
19912675Sjulian/// GlobalValue's in the program.  If none of them have their "address taken"
2004Srgrimes/// (really, their address passed to something nontrivial), record this fact,
2014Srgrimes/// and record the functions that they are used directly in.
2024Srgrimesvoid GlobalsModRef::AnalyzeGlobals(Module &M) {
2034Srgrimes  std::vector<Function*> Readers, Writers;
2044Srgrimes  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
2055764Sbde    if (I->hasLocalLinkage()) {
2061007Sdg      if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
2074Srgrimes        // Remember that we are tracking this global.
2084Srgrimes        NonAddressTakenGlobals.insert(I);
2095764Sbde        ++NumNonAddrTakenFunctions;
2105764Sbde      }
2117588Sjoerg      Readers.clear(); Writers.clear();
2125764Sbde    }
2137588Sjoerg
2147588Sjoerg  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
2157588Sjoerg       I != E; ++I)
2167588Sjoerg    if (I->hasLocalLinkage()) {
2177588Sjoerg      if (!AnalyzeUsesOfPointer(I, Readers, Writers)) {
2187588Sjoerg        // Remember that we are tracking this global, and the mod/ref fns
2197588Sjoerg        NonAddressTakenGlobals.insert(I);
2205764Sbde
2217588Sjoerg        for (unsigned i = 0, e = Readers.size(); i != e; ++i)
2225764Sbde          FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
2237588Sjoerg
2245764Sbde        if (!I->isConstant())  // No need to keep track of writers to constants
2255764Sbde          for (unsigned i = 0, e = Writers.size(); i != e; ++i)
2265764Sbde            FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
2275764Sbde        ++NumNonAddrTakenGlobalVars;
2285764Sbde
2295764Sbde        // If this global holds a pointer type, see if it is an indirect global.
2304Srgrimes        if (I->getType()->getElementType()->isPointerTy() &&
2318876Srgrimes            AnalyzeIndirectGlobalMemory(I))
23212675Sjulian          ++NumIndirectGlobalVars;
2334Srgrimes      }
2344Srgrimes      Readers.clear(); Writers.clear();
2354Srgrimes    }
236798Swollman}
2374Srgrimes
23818951Sjulian/// AnalyzeUsesOfPointer - Look at all of the users of the specified pointer.
2394Srgrimes/// If this is used by anything complex (i.e., the address escapes), return
2404Srgrimes/// true.  Also, while we are at it, keep track of those functions that read and
24112813Sjulian/// write to the value.
2424Srgrimes///
2438876Srgrimes/// If OkayStoreDest is non-null, stores into this global are allowed.
24412675Sjulianbool GlobalsModRef::AnalyzeUsesOfPointer(Value *V,
2454Srgrimes                                         std::vector<Function*> &Readers,
2464Srgrimes                                         std::vector<Function*> &Writers,
2474Srgrimes                                         GlobalValue *OkayStoreDest) {
248798Swollman  if (!V->getType()->isPointerTy()) return true;
2494Srgrimes
25018951Sjulian  for (Value::use_iterator UI = V->use_begin(), E=V->use_end(); UI != E; ++UI) {
2514Srgrimes    User *U = *UI;
2521021Sdg    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2534Srgrimes      Readers.push_back(LI->getParent()->getParent());
2544Srgrimes    } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2554Srgrimes      if (V == SI->getOperand(1)) {
25612813Sjulian        Writers.push_back(SI->getParent()->getParent());
2574Srgrimes      } else if (SI->getOperand(1) != OkayStoreDest) {
2588876Srgrimes        return true;  // Storing the pointer
25912675Sjulian      }
2604Srgrimes    } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
2614Srgrimes      if (AnalyzeUsesOfPointer(GEP, Readers, Writers)) return true;
262798Swollman    } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
2634Srgrimes      if (AnalyzeUsesOfPointer(BCI, Readers, Writers, OkayStoreDest))
264798Swollman        return true;
2654Srgrimes    } else if (isFreeCall(U)) {
2664Srgrimes      Writers.push_back(cast<Instruction>(U)->getParent()->getParent());
2674Srgrimes    } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
2684Srgrimes      // Make sure that this is just the function being called, not that it is
26918951Sjulian      // passing into the function.
2704Srgrimes      for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
2714Srgrimes        if (CI->getArgOperand(i) == V) return true;
2724Srgrimes    } else if (InvokeInst *II = dyn_cast<InvokeInst>(U)) {
2734Srgrimes      // Make sure that this is just the function being called, not that it is
2744Srgrimes      // passing into the function.
2754Srgrimes      for (unsigned i = 0, e = II->getNumArgOperands(); i != e; ++i)
2764Srgrimes        if (II->getArgOperand(i) == V) return true;
2774Srgrimes    } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
2784Srgrimes      if (CE->getOpcode() == Instruction::GetElementPtr ||
2794Srgrimes          CE->getOpcode() == Instruction::BitCast) {
2804Srgrimes        if (AnalyzeUsesOfPointer(CE, Readers, Writers))
2814Srgrimes          return true;
2824Srgrimes      } else {
28312813Sjulian        return true;
2844Srgrimes      }
2854Srgrimes    } else if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) {
28612675Sjulian      if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
2874Srgrimes        return true;  // Allow comparison against null.
2884Srgrimes    } else {
2894Srgrimes      return true;
2904Srgrimes    }
2914Srgrimes  }
29218951Sjulian
2934Srgrimes  return false;
2946712Spst}
2956712Spst
2966712Spst/// AnalyzeIndirectGlobalMemory - We found an non-address-taken global variable
29712813Sjulian/// which holds a pointer type.  See if the global always points to non-aliased
2984Srgrimes/// heap memory: that is, all initializers of the globals are allocations, and
2994Srgrimes/// those allocations have no use other than initialization of the global.
300798Swollman/// Further, all loads out of GV must directly use the memory, not store the
3014Srgrimes/// pointer somewhere.  If this is true, we consider the memory pointed to by
3024Srgrimes/// GV to be owned by GV and can disambiguate other pointers from it.
3035160Sjoergbool GlobalsModRef::AnalyzeIndirectGlobalMemory(GlobalValue *GV) {
30418951Sjulian  // Keep track of values related to the allocation of the memory, f.e. the
30519268Sjulian  // value produced by the malloc call and any casts.
3065160Sjoerg  std::vector<Value*> AllocRelatedValues;
3075160Sjoerg
3085160Sjoerg  // Walk the user list of the global.  If we find anything other than a direct
3094Srgrimes  // load or store, bail out.
3104Srgrimes  for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
3113728Sphk    User *U = *I;
3123728Sphk    if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
3133728Sphk      // The pointer loaded from the global can only be used in simple ways:
31418951Sjulian      // we allow addressing of it and loading storing to it.  We do *not* allow
31518287Sbde      // storing the loaded pointer somewhere else or passing to a function.
3163728Sphk      std::vector<Function*> ReadersWriters;
3173728Sphk      if (AnalyzeUsesOfPointer(LI, ReadersWriters, ReadersWriters))
3183728Sphk        return false;  // Loaded pointer escapes.
319798Swollman      // TODO: Could try some IP mod/ref of the loaded pointer.
3204Srgrimes    } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
3214Srgrimes      // Storing the global itself.
3224Srgrimes      if (SI->getOperand(0) == GV) return false;
32318951Sjulian
3244Srgrimes      // If storing the null pointer, ignore it.
3254Srgrimes      if (isa<ConstantPointerNull>(SI->getOperand(0)))
3264Srgrimes        continue;
3274Srgrimes
3289217Sbde      // Check the value being stored.
3294Srgrimes      Value *Ptr = GetUnderlyingObject(SI->getOperand(0));
3304Srgrimes
3314Srgrimes      if (isMalloc(Ptr)) {
33212517Sjulian        // Okay, easy case.
33312517Sjulian      } else if (CallInst *CI = dyn_cast<CallInst>(Ptr)) {
33412675Sjulian        Function *F = CI->getCalledFunction();
33512675Sjulian        if (!F || !F->isDeclaration()) return false;     // Too hard to analyze.
33612517Sjulian        if (F->getName() != "calloc") return false;   // Not calloc.
33712517Sjulian      } else {
33812517Sjulian        return false;  // Too hard to analyze.
33912517Sjulian      }
34012517Sjulian
34112517Sjulian      // Analyze all uses of the allocation.  If any of them are used in a
34212517Sjulian      // non-simple way (e.g. stored to another global) bail out.
34312517Sjulian      std::vector<Function*> ReadersWriters;
34414880Sbde      if (AnalyzeUsesOfPointer(Ptr, ReadersWriters, ReadersWriters, GV))
34514880Sbde        return false;  // Loaded pointer escapes.
34614880Sbde
34712517Sjulian      // Remember that this allocation is related to the indirect global.
34812521Sjulian      AllocRelatedValues.push_back(Ptr);
34912517Sjulian    } else {
35012517Sjulian      // Something complex, bail out.
35112517Sjulian      return false;
35212517Sjulian    }
35312517Sjulian  }
354
355  // Okay, this is an indirect global.  Remember all of the allocations for
356  // this global in AllocsForIndirectGlobals.
357  while (!AllocRelatedValues.empty()) {
358    AllocsForIndirectGlobals[AllocRelatedValues.back()] = GV;
359    AllocRelatedValues.pop_back();
360  }
361  IndirectGlobals.insert(GV);
362  return true;
363}
364
365/// AnalyzeCallGraph - At this point, we know the functions where globals are
366/// immediately stored to and read from.  Propagate this information up the call
367/// graph to all callers and compute the mod/ref info for all memory for each
368/// function.
369void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
370  // We do a bottom-up SCC traversal of the call graph.  In other words, we
371  // visit all callees before callers (leaf-first).
372  for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I != E;
373       ++I) {
374    std::vector<CallGraphNode *> &SCC = *I;
375    assert(!SCC.empty() && "SCC with no functions?");
376
377    if (!SCC[0]->getFunction()) {
378      // Calls externally - can't say anything useful.  Remove any existing
379      // function records (may have been created when scanning globals).
380      for (unsigned i = 0, e = SCC.size(); i != e; ++i)
381        FunctionInfo.erase(SCC[i]->getFunction());
382      continue;
383    }
384
385    FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
386
387    bool KnowNothing = false;
388    unsigned FunctionEffect = 0;
389
390    // Collect the mod/ref properties due to called functions.  We only compute
391    // one mod-ref set.
392    for (unsigned i = 0, e = SCC.size(); i != e && !KnowNothing; ++i) {
393      Function *F = SCC[i]->getFunction();
394      if (!F) {
395        KnowNothing = true;
396        break;
397      }
398
399      if (F->isDeclaration()) {
400        // Try to get mod/ref behaviour from function attributes.
401        if (F->doesNotAccessMemory()) {
402          // Can't do better than that!
403        } else if (F->onlyReadsMemory()) {
404          FunctionEffect |= Ref;
405          if (!F->isIntrinsic())
406            // This function might call back into the module and read a global -
407            // consider every global as possibly being read by this function.
408            FR.MayReadAnyGlobal = true;
409        } else {
410          FunctionEffect |= ModRef;
411          // Can't say anything useful unless it's an intrinsic - they don't
412          // read or write global variables of the kind considered here.
413          KnowNothing = !F->isIntrinsic();
414        }
415        continue;
416      }
417
418      for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
419           CI != E && !KnowNothing; ++CI)
420        if (Function *Callee = CI->second->getFunction()) {
421          if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
422            // Propagate function effect up.
423            FunctionEffect |= CalleeFR->FunctionEffect;
424
425            // Incorporate callee's effects on globals into our info.
426            for (std::map<const GlobalValue*, unsigned>::iterator GI =
427                   CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end();
428                 GI != E; ++GI)
429              FR.GlobalInfo[GI->first] |= GI->second;
430            FR.MayReadAnyGlobal |= CalleeFR->MayReadAnyGlobal;
431          } else {
432            // Can't say anything about it.  However, if it is inside our SCC,
433            // then nothing needs to be done.
434            CallGraphNode *CalleeNode = CG[Callee];
435            if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end())
436              KnowNothing = true;
437          }
438        } else {
439          KnowNothing = true;
440        }
441    }
442
443    // If we can't say anything useful about this SCC, remove all SCC functions
444    // from the FunctionInfo map.
445    if (KnowNothing) {
446      for (unsigned i = 0, e = SCC.size(); i != e; ++i)
447        FunctionInfo.erase(SCC[i]->getFunction());
448      continue;
449    }
450
451    // Scan the function bodies for explicit loads or stores.
452    for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
453      for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
454             E = inst_end(SCC[i]->getFunction());
455           II != E && FunctionEffect != ModRef; ++II)
456        if (isa<LoadInst>(*II)) {
457          FunctionEffect |= Ref;
458          if (cast<LoadInst>(*II).isVolatile())
459            // Volatile loads may have side-effects, so mark them as writing
460            // memory (for example, a flag inside the processor).
461            FunctionEffect |= Mod;
462        } else if (isa<StoreInst>(*II)) {
463          FunctionEffect |= Mod;
464          if (cast<StoreInst>(*II).isVolatile())
465            // Treat volatile stores as reading memory somewhere.
466            FunctionEffect |= Ref;
467        } else if (isMalloc(&cast<Instruction>(*II)) ||
468                   isFreeCall(&cast<Instruction>(*II))) {
469          FunctionEffect |= ModRef;
470        }
471
472    if ((FunctionEffect & Mod) == 0)
473      ++NumReadMemFunctions;
474    if (FunctionEffect == 0)
475      ++NumNoMemFunctions;
476    FR.FunctionEffect = FunctionEffect;
477
478    // Finally, now that we know the full effect on this SCC, clone the
479    // information to each function in the SCC.
480    for (unsigned i = 1, e = SCC.size(); i != e; ++i)
481      FunctionInfo[SCC[i]->getFunction()] = FR;
482  }
483}
484
485
486
487/// alias - If one of the pointers is to a global that we are tracking, and the
488/// other is some random pointer, we know there cannot be an alias, because the
489/// address of the global isn't taken.
490AliasAnalysis::AliasResult
491GlobalsModRef::alias(const Location &LocA,
492                     const Location &LocB) {
493  // Get the base object these pointers point to.
494  const Value *UV1 = GetUnderlyingObject(LocA.Ptr);
495  const Value *UV2 = GetUnderlyingObject(LocB.Ptr);
496
497  // If either of the underlying values is a global, they may be non-addr-taken
498  // globals, which we can answer queries about.
499  const GlobalValue *GV1 = dyn_cast<GlobalValue>(UV1);
500  const GlobalValue *GV2 = dyn_cast<GlobalValue>(UV2);
501  if (GV1 || GV2) {
502    // If the global's address is taken, pretend we don't know it's a pointer to
503    // the global.
504    if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0;
505    if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0;
506
507    // If the two pointers are derived from two different non-addr-taken
508    // globals, or if one is and the other isn't, we know these can't alias.
509    if ((GV1 || GV2) && GV1 != GV2)
510      return NoAlias;
511
512    // Otherwise if they are both derived from the same addr-taken global, we
513    // can't know the two accesses don't overlap.
514  }
515
516  // These pointers may be based on the memory owned by an indirect global.  If
517  // so, we may be able to handle this.  First check to see if the base pointer
518  // is a direct load from an indirect global.
519  GV1 = GV2 = 0;
520  if (const LoadInst *LI = dyn_cast<LoadInst>(UV1))
521    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
522      if (IndirectGlobals.count(GV))
523        GV1 = GV;
524  if (const LoadInst *LI = dyn_cast<LoadInst>(UV2))
525    if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getOperand(0)))
526      if (IndirectGlobals.count(GV))
527        GV2 = GV;
528
529  // These pointers may also be from an allocation for the indirect global.  If
530  // so, also handle them.
531  if (AllocsForIndirectGlobals.count(UV1))
532    GV1 = AllocsForIndirectGlobals[UV1];
533  if (AllocsForIndirectGlobals.count(UV2))
534    GV2 = AllocsForIndirectGlobals[UV2];
535
536  // Now that we know whether the two pointers are related to indirect globals,
537  // use this to disambiguate the pointers.  If either pointer is based on an
538  // indirect global and if they are not both based on the same indirect global,
539  // they cannot alias.
540  if ((GV1 || GV2) && GV1 != GV2)
541    return NoAlias;
542
543  return AliasAnalysis::alias(LocA, LocB);
544}
545
546AliasAnalysis::ModRefResult
547GlobalsModRef::getModRefInfo(ImmutableCallSite CS,
548                             const Location &Loc) {
549  unsigned Known = ModRef;
550
551  // If we are asking for mod/ref info of a direct call with a pointer to a
552  // global we are tracking, return information if we have it.
553  if (const GlobalValue *GV =
554        dyn_cast<GlobalValue>(GetUnderlyingObject(Loc.Ptr)))
555    if (GV->hasLocalLinkage())
556      if (const Function *F = CS.getCalledFunction())
557        if (NonAddressTakenGlobals.count(GV))
558          if (const FunctionRecord *FR = getFunctionInfo(F))
559            Known = FR->getInfoForGlobal(GV);
560
561  if (Known == NoModRef)
562    return NoModRef; // No need to query other mod/ref analyses
563  return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, Loc));
564}
565
566
567//===----------------------------------------------------------------------===//
568// Methods to update the analysis as a result of the client transformation.
569//
570void GlobalsModRef::deleteValue(Value *V) {
571  if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
572    if (NonAddressTakenGlobals.erase(GV)) {
573      // This global might be an indirect global.  If so, remove it and remove
574      // any AllocRelatedValues for it.
575      if (IndirectGlobals.erase(GV)) {
576        // Remove any entries in AllocsForIndirectGlobals for this global.
577        for (std::map<const Value*, const GlobalValue*>::iterator
578             I = AllocsForIndirectGlobals.begin(),
579             E = AllocsForIndirectGlobals.end(); I != E; ) {
580          if (I->second == GV) {
581            AllocsForIndirectGlobals.erase(I++);
582          } else {
583            ++I;
584          }
585        }
586      }
587    }
588  }
589
590  // Otherwise, if this is an allocation related to an indirect global, remove
591  // it.
592  AllocsForIndirectGlobals.erase(V);
593
594  AliasAnalysis::deleteValue(V);
595}
596
597void GlobalsModRef::copyValue(Value *From, Value *To) {
598  AliasAnalysis::copyValue(From, To);
599}
600
601void GlobalsModRef::addEscapingUse(Use &U) {
602  // For the purposes of this analysis, it is conservatively correct to treat
603  // a newly escaping value equivalently to a deleted one.  We could perhaps
604  // be more precise by processing the new use and attempting to update our
605  // saved analysis results to accomodate it.
606  deleteValue(U);
607
608  AliasAnalysis::addEscapingUse(U);
609}
610