For PR387:\
[oota-llvm.git] / lib / Analysis / IPA / GlobalsModRef.cpp
1 //===- GlobalsModRef.cpp - Simple Mod/Ref Analysis for Globals ------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This simple pass provides alias and mod/ref information for global values
11 // that do not have their address taken, and keeps track of whether functions
12 // read or write memory (are "pure").  For this simple (but very common) case,
13 // we can provide pretty accurate and useful information.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Module.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/CallGraph.h"
24 #include "llvm/Support/InstIterator.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/SCCIterator.h"
28 #include <set>
29 using namespace llvm;
30
31 namespace {
32   Statistic<>
33   NumNonAddrTakenGlobalVars("globalsmodref-aa",
34                             "Number of global vars without address taken");
35   Statistic<>
36   NumNonAddrTakenFunctions("globalsmodref-aa",
37                            "Number of functions without address taken");
38   Statistic<>
39   NumNoMemFunctions("globalsmodref-aa",
40                     "Number of functions that do not access memory");
41   Statistic<>
42   NumReadMemFunctions("globalsmodref-aa",
43                       "Number of functions that only read memory");
44
45   /// FunctionRecord - One instance of this structure is stored for every
46   /// function in the program.  Later, the entries for these functions are
47   /// removed if the function is found to call an external function (in which
48   /// case we know nothing about it.
49   struct FunctionRecord {
50     /// GlobalInfo - Maintain mod/ref info for all of the globals without
51     /// addresses taken that are read or written (transitively) by this
52     /// function.
53     std::map<GlobalValue*, unsigned> GlobalInfo;
54
55     unsigned getInfoForGlobal(GlobalValue *GV) const {
56       std::map<GlobalValue*, unsigned>::const_iterator I = GlobalInfo.find(GV);
57       if (I != GlobalInfo.end())
58         return I->second;
59       return 0;
60     }
61     
62     /// FunctionEffect - Capture whether or not this function reads or writes to
63     /// ANY memory.  If not, we can do a lot of aggressive analysis on it.
64     unsigned FunctionEffect;
65
66     FunctionRecord() : FunctionEffect(0) {}
67   };
68
69   /// GlobalsModRef - The actual analysis pass.
70   class GlobalsModRef : public ModulePass, public AliasAnalysis {
71     /// NonAddressTakenGlobals - The globals that do not have their addresses
72     /// taken.
73     std::set<GlobalValue*> NonAddressTakenGlobals;
74
75     /// FunctionInfo - For each function, keep track of what globals are
76     /// modified or read.
77     std::map<Function*, FunctionRecord> FunctionInfo;
78
79   public:
80     bool runOnModule(Module &M) {
81       InitializeAliasAnalysis(this);                 // set up super class
82       AnalyzeGlobals(M);                          // find non-addr taken globals
83       AnalyzeCallGraph(getAnalysis<CallGraph>(), M); // Propagate on CG
84       return false;
85     }
86
87     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88       AliasAnalysis::getAnalysisUsage(AU);
89       AU.addRequired<CallGraph>();
90       AU.setPreservesAll();                         // Does not transform code
91     }
92
93     //------------------------------------------------
94     // Implement the AliasAnalysis API
95     //  
96     AliasResult alias(const Value *V1, unsigned V1Size,
97                       const Value *V2, unsigned V2Size);
98     ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
99     ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
100       return AliasAnalysis::getModRefInfo(CS1,CS2);
101     }
102     bool hasNoModRefInfoForCalls() const { return false; }
103
104     bool doesNotAccessMemory(Function *F) {
105       if (FunctionRecord *FR = getFunctionInfo(F))
106         if (FR->FunctionEffect == 0)
107           return true;
108       return AliasAnalysis::doesNotAccessMemory(F);
109     }
110     bool onlyReadsMemory(Function *F) {
111       if (FunctionRecord *FR = getFunctionInfo(F))
112         if ((FR->FunctionEffect & Mod) == 0)
113           return true;
114       return AliasAnalysis::onlyReadsMemory(F);
115     }
116
117
118     virtual void deleteValue(Value *V);
119     virtual void copyValue(Value *From, Value *To);
120
121   private:
122     /// getFunctionInfo - Return the function info for the function, or null if
123     /// the function calls an external function (in which case we don't have
124     /// anything useful to say about it).
125     FunctionRecord *getFunctionInfo(Function *F) {
126       std::map<Function*, FunctionRecord>::iterator I = FunctionInfo.find(F);
127       if (I != FunctionInfo.end())
128         return &I->second;
129       return 0;
130     }
131
132     void AnalyzeGlobals(Module &M);
133     void AnalyzeCallGraph(CallGraph &CG, Module &M);
134     void AnalyzeSCC(std::vector<CallGraphNode *> &SCC);
135     bool AnalyzeUsesOfGlobal(Value *V, std::vector<Function*> &Readers,
136                              std::vector<Function*> &Writers);
137   };
138   
139   RegisterOpt<GlobalsModRef> X("globalsmodref-aa",
140                                "Simple mod/ref analysis for globals");
141   RegisterAnalysisGroup<AliasAnalysis, GlobalsModRef> Y;
142 }
143
144 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
145
146
147 /// AnalyzeGlobalUses - Scan through the users of all of the internal
148 /// GlobalValue's in the program.  If none of them have their "Address taken"
149 /// (really, their address passed to something nontrivial), record this fact,
150 /// and record the functions that they are used directly in.
151 void GlobalsModRef::AnalyzeGlobals(Module &M) {
152   std::vector<Function*> Readers, Writers;
153   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
154     if (I->hasInternalLinkage()) {
155       if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) {
156         // Remember that we are tracking this global.
157         NonAddressTakenGlobals.insert(I);
158         ++NumNonAddrTakenFunctions;
159       }
160       Readers.clear(); Writers.clear();
161     }
162
163   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
164     if (I->hasInternalLinkage()) {
165       if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) {
166         // Remember that we are tracking this global, and the mod/ref fns
167         NonAddressTakenGlobals.insert(I);
168         for (unsigned i = 0, e = Readers.size(); i != e; ++i)
169           FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
170
171         if (!I->isConstant())  // No need to keep track of writers to constants
172           for (unsigned i = 0, e = Writers.size(); i != e; ++i)
173             FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
174         ++NumNonAddrTakenGlobalVars;
175       }
176       Readers.clear(); Writers.clear();
177     }
178 }
179
180 /// AnalyzeUsesOfGlobal - Look at all of the users of the specified global value
181 /// derived pointer.  If this is used by anything complex (i.e., the address
182 /// escapes), return true.  Also, while we are at it, keep track of those
183 /// functions that read and write to the value.
184 bool GlobalsModRef::AnalyzeUsesOfGlobal(Value *V,
185                                         std::vector<Function*> &Readers,
186                                         std::vector<Function*> &Writers) {
187   if (!isa<PointerType>(V->getType())) return true;
188
189   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
190     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
191       Readers.push_back(LI->getParent()->getParent());
192     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
193       if (V == SI->getOperand(0)) return true;  // Storing the pointer
194       Writers.push_back(SI->getParent()->getParent());
195     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
196       if (AnalyzeUsesOfGlobal(GEP, Readers, Writers)) return true;
197     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
198       // Make sure that this is just the function being called, not that it is
199       // passing into the function.
200       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
201         if (CI->getOperand(i) == V) return true;
202     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
203       // Make sure that this is just the function being called, not that it is
204       // passing into the function.
205       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
206         if (CI->getOperand(i) == V) return true;
207     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
208       // Make sure that this is just the function being called, not that it is
209       // passing into the function.
210       for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
211         if (II->getOperand(i) == V) return true;
212     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
213       if (CE->getOpcode() == Instruction::GetElementPtr ||
214           CE->getOpcode() == Instruction::Cast) {
215         if (AnalyzeUsesOfGlobal(CE, Readers, Writers))
216           return true;
217       } else {
218         return true;
219       }        
220     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(*UI)) {
221       if (AnalyzeUsesOfGlobal(GV, Readers, Writers)) return true;
222     } else {
223       return true;
224     }
225   return false;
226 }
227
228 /// AnalyzeCallGraph - At this point, we know the functions where globals are
229 /// immediately stored to and read from.  Propagate this information up the call
230 /// graph to all callers and compute the mod/ref info for all memory for each
231 /// function.  
232 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
233   // We do a bottom-up SCC traversal of the call graph.  In other words, we
234   // visit all callees before callers (leaf-first).
235   for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I!=E; ++I)
236     if ((*I).size() != 1) {
237       AnalyzeSCC(*I);
238     } else if (Function *F = (*I)[0]->getFunction()) {
239       if (!F->isExternal()) {
240         // Nonexternal function.
241         AnalyzeSCC(*I);
242       } else {
243         // Otherwise external function.  Handle intrinsics and other special
244         // cases here.
245         if (getAnalysis<AliasAnalysis>().doesNotAccessMemory(F))
246           // If it does not access memory, process the function, causing us to
247           // realize it doesn't do anything (the body is empty).
248           AnalyzeSCC(*I);
249         else {
250           // Otherwise, don't process it.  This will cause us to conservatively
251           // assume the worst.
252         }
253       }
254     } else {
255       // Do not process the external node, assume the worst.
256     }
257 }
258
259 void GlobalsModRef::AnalyzeSCC(std::vector<CallGraphNode *> &SCC) {
260   assert(!SCC.empty() && "SCC with no functions?");
261   FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
262
263   bool CallsExternal = false;
264   unsigned FunctionEffect = 0;
265
266   // Collect the mod/ref properties due to called functions.  We only compute
267   // one mod-ref set
268   for (unsigned i = 0, e = SCC.size(); i != e && !CallsExternal; ++i)
269     for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
270          CI != E; ++CI)
271       if (Function *Callee = (*CI)->getFunction()) {
272         if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
273           // Propagate function effect up.
274           FunctionEffect |= CalleeFR->FunctionEffect;
275
276           // Incorporate callee's effects on globals into our info.
277           for (std::map<GlobalValue*, unsigned>::iterator GI =
278                  CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end();
279                GI != E; ++GI)
280             FR.GlobalInfo[GI->first] |= GI->second;
281
282         } else {
283           CallsExternal = true;
284           break;
285         }
286       } else {
287         CallsExternal = true;
288         break;
289       }
290
291   // If this SCC calls an external function, we can't say anything about it, so
292   // remove all SCC functions from the FunctionInfo map.
293   if (CallsExternal) {
294     for (unsigned i = 0, e = SCC.size(); i != e; ++i)
295       FunctionInfo.erase(SCC[i]->getFunction());
296     return;
297   }
298   
299   // Otherwise, unless we already know that this function mod/refs memory, scan
300   // the function bodies to see if there are any explicit loads or stores.
301   if (FunctionEffect != ModRef) {
302     for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
303       for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
304              E = inst_end(SCC[i]->getFunction()); 
305            II != E && FunctionEffect != ModRef; ++II)
306         if (isa<LoadInst>(*II))
307           FunctionEffect |= Ref;
308         else if (isa<StoreInst>(*II))
309           FunctionEffect |= Mod;
310   }
311
312   if ((FunctionEffect & Mod) == 0)
313     ++NumReadMemFunctions;
314   if (FunctionEffect == 0)
315     ++NumNoMemFunctions;
316   FR.FunctionEffect = FunctionEffect;
317
318   // Finally, now that we know the full effect on this SCC, clone the
319   // information to each function in the SCC.
320   for (unsigned i = 1, e = SCC.size(); i != e; ++i)
321     FunctionInfo[SCC[i]->getFunction()] = FR;
322 }
323
324
325
326 /// getUnderlyingObject - This traverses the use chain to figure out what object
327 /// the specified value points to.  If the value points to, or is derived from,
328 /// a global object, return it.
329 static const GlobalValue *getUnderlyingObject(const Value *V) {
330   if (!isa<PointerType>(V->getType())) return 0;
331
332   // If we are at some type of object... return it.
333   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
334   
335   // Traverse through different addressing mechanisms...
336   if (const Instruction *I = dyn_cast<Instruction>(V)) {
337     if (isa<CastInst>(I) || isa<GetElementPtrInst>(I))
338       return getUnderlyingObject(I->getOperand(0));
339   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
340     if (CE->getOpcode() == Instruction::Cast ||
341         CE->getOpcode() == Instruction::GetElementPtr)
342       return getUnderlyingObject(CE->getOperand(0));
343   }
344   return 0;
345 }
346
347 /// alias - If one of the pointers is to a global that we are tracking, and the
348 /// other is some random pointer, we know there cannot be an alias, because the
349 /// address of the global isn't taken.
350 AliasAnalysis::AliasResult
351 GlobalsModRef::alias(const Value *V1, unsigned V1Size,
352                      const Value *V2, unsigned V2Size) {
353   GlobalValue *GV1 = const_cast<GlobalValue*>(getUnderlyingObject(V1));
354   GlobalValue *GV2 = const_cast<GlobalValue*>(getUnderlyingObject(V2));
355
356   // If the global's address is taken, pretend we don't know it's a pointer to
357   // the global.
358   if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0;
359   if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0;
360
361   if ((GV1 || GV2) && GV1 != GV2)
362     return NoAlias;
363
364   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
365 }
366
367 AliasAnalysis::ModRefResult
368 GlobalsModRef::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
369   unsigned Known = ModRef;
370
371   // If we are asking for mod/ref info of a direct call with a pointer to a
372   // global we are tracking, return information if we have it.
373   if (GlobalValue *GV = const_cast<GlobalValue*>(getUnderlyingObject(P)))
374     if (GV->hasInternalLinkage())
375       if (Function *F = CS.getCalledFunction())
376         if (NonAddressTakenGlobals.count(GV))
377           if (FunctionRecord *FR = getFunctionInfo(F))
378             Known = FR->getInfoForGlobal(GV);
379
380   if (Known == NoModRef)
381     return NoModRef; // No need to query other mod/ref analyses
382   return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, P, Size));
383 }
384
385
386 //===----------------------------------------------------------------------===//
387 // Methods to update the analysis as a result of the client transformation.
388 //
389 void GlobalsModRef::deleteValue(Value *V) {
390   if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
391     NonAddressTakenGlobals.erase(GV);
392 }
393
394 void GlobalsModRef::copyValue(Value *From, Value *To) {
395 }