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