Complete rewrite of this pass to be faster, use less memory, be easier to
[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
69   /// GlobalsModRef - The actual analysis pass.
70   class GlobalsModRef : public Pass, 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 run(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     bool hasNoModRefInfoForCalls() const { return false; }
100
101     bool doesNotAccessMemory(Function *F) {
102       if (FunctionRecord *FR = getFunctionInfo(F))
103         if (FR->FunctionEffect == 0)
104           return true;
105       return AliasAnalysis::doesNotAccessMemory(F);
106     }
107     bool onlyReadsMemory(Function *F) {
108       if (FunctionRecord *FR = getFunctionInfo(F))
109         if ((FR->FunctionEffect & Mod) == 0)
110           return true;
111       return AliasAnalysis::onlyReadsMemory(F);
112     }
113
114
115     virtual void deleteValue(Value *V);
116     virtual void copyValue(Value *From, Value *To);
117
118   private:
119     /// getFunctionInfo - Return the function info for the function, or null if
120     /// the function calls an external function (in which case we don't have
121     /// anything useful to say about it).
122     FunctionRecord *getFunctionInfo(Function *F) {
123       std::map<Function*, FunctionRecord>::iterator I = FunctionInfo.find(F);
124       if (I != FunctionInfo.end())
125         return &I->second;
126       return 0;
127     }
128
129     void AnalyzeGlobals(Module &M);
130     void AnalyzeCallGraph(CallGraph &CG, Module &M);
131     void AnalyzeSCC(std::vector<CallGraphNode *> &SCC);
132     bool AnalyzeUsesOfGlobal(Value *V, std::vector<Function*> &Readers,
133                              std::vector<Function*> &Writers);
134   };
135   
136   RegisterOpt<GlobalsModRef> X("globalsmodref-aa",
137                                "Simple mod/ref analysis for globals");
138   RegisterAnalysisGroup<AliasAnalysis, GlobalsModRef> Y;
139 }
140
141 Pass *llvm::createGlobalsModRefPass() { return new GlobalsModRef(); }
142
143
144 /// AnalyzeGlobalUses - Scan through the users of all of the internal
145 /// GlobalValue's in the program.  If none of them have their "Address taken"
146 /// (really, their address passed to something nontrivial), record this fact,
147 /// and record the functions that they are used directly in.
148 void GlobalsModRef::AnalyzeGlobals(Module &M) {
149   std::vector<Function*> Readers, Writers;
150   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
151     if (I->hasInternalLinkage()) {
152       if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) {
153         // Remember that we are tracking this global.
154         NonAddressTakenGlobals.insert(I);
155         ++NumNonAddrTakenFunctions;
156       }
157       Readers.clear(); Writers.clear();
158     }
159
160   for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
161     if (I->hasInternalLinkage()) {
162       if (!AnalyzeUsesOfGlobal(I, Readers, Writers)) {
163         // Remember that we are tracking this global, and the mod/ref fns
164         NonAddressTakenGlobals.insert(I);
165         for (unsigned i = 0, e = Readers.size(); i != e; ++i)
166           FunctionInfo[Readers[i]].GlobalInfo[I] |= Ref;
167
168         if (!I->isConstant())  // No need to keep track of writers to constants
169           for (unsigned i = 0, e = Writers.size(); i != e; ++i)
170             FunctionInfo[Writers[i]].GlobalInfo[I] |= Mod;
171         ++NumNonAddrTakenGlobalVars;
172       }
173       Readers.clear(); Writers.clear();
174     }
175 }
176
177 /// AnalyzeUsesOfGlobal - Look at all of the users of the specified global value
178 /// derived pointer.  If this is used by anything complex (i.e., the address
179 /// escapes), return true.  Also, while we are at it, keep track of those
180 /// functions that read and write to the value.
181 bool GlobalsModRef::AnalyzeUsesOfGlobal(Value *V,
182                                         std::vector<Function*> &Readers,
183                                         std::vector<Function*> &Writers) {
184   if (!isa<PointerType>(V->getType())) return true;
185
186   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
187     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
188       Readers.push_back(LI->getParent()->getParent());
189     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
190       if (V == SI->getOperand(0)) return true;  // Storing the pointer
191       Writers.push_back(SI->getParent()->getParent());
192     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
193       if (AnalyzeUsesOfGlobal(GEP, Readers, Writers)) return true;
194     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
195       // Make sure that this is just the function being called, not that it is
196       // passing into the function.
197       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
198         if (CI->getOperand(i) == V) return true;
199     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
200       // Make sure that this is just the function being called, not that it is
201       // passing into the function.
202       for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
203         if (CI->getOperand(i) == V) return true;
204     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
205       // Make sure that this is just the function being called, not that it is
206       // passing into the function.
207       for (unsigned i = 3, e = II->getNumOperands(); i != e; ++i)
208         if (II->getOperand(i) == V) return true;
209     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
210       if (CE->getOpcode() == Instruction::GetElementPtr ||
211           CE->getOpcode() == Instruction::Cast) {
212         if (AnalyzeUsesOfGlobal(CE, Readers, Writers))
213           return true;
214       } else {
215         return true;
216       }        
217     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(*UI)) {
218       if (AnalyzeUsesOfGlobal(GV, Readers, Writers)) return true;
219     } else {
220       return true;
221     }
222   return false;
223 }
224
225 /// AnalyzeCallGraph - At this point, we know the functions where globals are
226 /// immediately stored to and read from.  Propagate this information up the call
227 /// graph to all callers and compute the mod/ref info for all memory for each
228 /// function.  
229 void GlobalsModRef::AnalyzeCallGraph(CallGraph &CG, Module &M) {
230   DEBUG(std::cerr << "GlobalsModRef: Analyze Call Graph\n");
231
232   // We do a bottom-up SCC traversal of the call graph.  In other words, we
233   // visit all callees before callers (leaf-first).
234   for (scc_iterator<CallGraph*> I = scc_begin(&CG), E = scc_end(&CG); I!=E; ++I)
235     // Do not call AnalyzeSCC on the external function node.
236     if ((*I).size() != 1 || (*I)[0]->getFunction())
237       AnalyzeSCC(*I);
238 }
239
240 void GlobalsModRef::AnalyzeSCC(std::vector<CallGraphNode *> &SCC) {
241   assert(!SCC.empty() && "SCC with no functions?");
242   FunctionRecord &FR = FunctionInfo[SCC[0]->getFunction()];
243
244   bool CallsExternal = false;
245   unsigned FunctionEffect = 0;
246
247   // Collect the mod/ref properties due to called functions.  We only compute
248   // one mod-ref set
249   for (unsigned i = 0, e = SCC.size(); i != e && !CallsExternal; ++i)
250     for (CallGraphNode::iterator CI = SCC[i]->begin(), E = SCC[i]->end();
251          CI != E; ++CI)
252       if (Function *Callee = (*CI)->getFunction()) {
253         if (FunctionRecord *CalleeFR = getFunctionInfo(Callee)) {
254           // Propagate function effect up.
255           FunctionEffect |= CalleeFR->FunctionEffect;
256
257           // Incorporate callee's effects on globals into our info.
258           for (std::map<GlobalValue*, unsigned>::iterator GI =
259                  CalleeFR->GlobalInfo.begin(), E = CalleeFR->GlobalInfo.end();
260                GI != E; ++GI)
261             FR.GlobalInfo[GI->first] |= GI->second;
262
263         } else {
264           CallsExternal = true;
265           break;
266         }
267       } else {
268         CallsExternal = true;
269         break;
270       }
271
272   // If this SCC calls an external function, we can't say anything about it, so
273   // remove all SCC functions from the FunctionInfo map.
274   if (CallsExternal) {
275     for (unsigned i = 0, e = SCC.size(); i != e; ++i)
276       FunctionInfo.erase(SCC[i]->getFunction());
277     return;
278   }
279   
280   // Otherwise, unless we already know that this function mod/refs memory, scan
281   // the function bodies to see if there are any explicit loads or stores.
282   if (FunctionEffect != ModRef) {
283     for (unsigned i = 0, e = SCC.size(); i != e && FunctionEffect != ModRef;++i)
284       for (inst_iterator II = inst_begin(SCC[i]->getFunction()),
285              E = inst_end(SCC[i]->getFunction()); 
286            II != E && FunctionEffect != ModRef; ++II)
287         if (isa<LoadInst>(*II))
288           FunctionEffect |= Ref;
289         else if (isa<StoreInst>(*II))
290           FunctionEffect |= Mod;
291   }
292
293   if ((FunctionEffect & Mod) == 0)
294     ++NumReadMemFunctions;
295   if (FunctionEffect == 0)
296     ++NumNoMemFunctions;
297   FR.FunctionEffect = FunctionEffect;
298
299   // Finally, now that we know the full effect on this SCC, clone the
300   // information to each function in the SCC.
301   for (unsigned i = 1, e = SCC.size(); i != e; ++i)
302     FunctionInfo[SCC[i]->getFunction()] = FR;
303 }
304
305
306
307 /// getUnderlyingObject - This traverses the use chain to figure out what object
308 /// the specified value points to.  If the value points to, or is derived from,
309 /// a global object, return it.
310 static const GlobalValue *getUnderlyingObject(const Value *V) {
311   if (!isa<PointerType>(V->getType())) return 0;
312
313   // If we are at some type of object... return it.
314   if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
315   
316   // Traverse through different addressing mechanisms...
317   if (const Instruction *I = dyn_cast<Instruction>(V)) {
318     if (isa<CastInst>(I) || isa<GetElementPtrInst>(I))
319       return getUnderlyingObject(I->getOperand(0));
320   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
321     if (CE->getOpcode() == Instruction::Cast ||
322         CE->getOpcode() == Instruction::GetElementPtr)
323       return getUnderlyingObject(CE->getOperand(0));
324   }
325   return 0;
326 }
327
328 /// alias - If one of the pointers is to a global that we are tracking, and the
329 /// other is some random pointer, we know there cannot be an alias, because the
330 /// address of the global isn't taken.
331 AliasAnalysis::AliasResult
332 GlobalsModRef::alias(const Value *V1, unsigned V1Size,
333                      const Value *V2, unsigned V2Size) {
334   GlobalValue *GV1 = const_cast<GlobalValue*>(getUnderlyingObject(V1));
335   GlobalValue *GV2 = const_cast<GlobalValue*>(getUnderlyingObject(V2));
336
337   // If the global's address is taken, pretend we don't know it's a pointer to
338   // the global.
339   if (GV1 && !NonAddressTakenGlobals.count(GV1)) GV1 = 0;
340   if (GV2 && !NonAddressTakenGlobals.count(GV2)) GV2 = 0;
341
342   if ((GV1 || GV2) && GV1 != GV2)
343     return NoAlias;
344
345   return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
346 }
347
348 AliasAnalysis::ModRefResult
349 GlobalsModRef::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
350   unsigned Known = ModRef;
351
352   // If we are asking for mod/ref info of a direct call with a pointer to a
353   // global we are tracking, return information if we have it.
354   if (GlobalValue *GV = const_cast<GlobalValue*>(getUnderlyingObject(P)))
355     if (GV->hasInternalLinkage())
356       if (Function *F = CS.getCalledFunction())
357         if (NonAddressTakenGlobals.count(GV))
358           if (FunctionRecord *FR = getFunctionInfo(F))
359             Known = FR->getInfoForGlobal(GV);
360
361   if (Known == NoModRef)
362     return NoModRef; // No need to query other mod/ref analyses
363   return ModRefResult(Known & AliasAnalysis::getModRefInfo(CS, P, Size));
364 }
365
366
367 //===----------------------------------------------------------------------===//
368 // Methods to update the analysis as a result of the client transformation.
369 //
370 void GlobalsModRef::deleteValue(Value *V) {
371   if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
372     NonAddressTakenGlobals.erase(GV);
373 }
374
375 void GlobalsModRef::copyValue(Value *From, Value *To) {
376 }