Rename AddReadAttrs to FunctionAttrs, and teach it how
[oota-llvm.git] / lib / Transforms / IPO / FunctionAttrs.cpp
1 //===- FunctionAttrs.cpp - Pass which marks functions readnone or readonly ===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a simple interprocedural pass which walks the
11 // call-graph, looking for functions which do not access or only read
12 // non-local memory, and marking them readnone/readonly.  It implements
13 // this as a bottom-up traversal of the call-graph.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "functionattrs"
18 #include "llvm/Transforms/IPO.h"
19 #include "llvm/CallGraphSCCPass.h"
20 #include "llvm/GlobalVariable.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Analysis/CallGraph.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/InstIterator.h"
27 using namespace llvm;
28
29 STATISTIC(NumReadNone, "Number of functions marked readnone");
30 STATISTIC(NumReadOnly, "Number of functions marked readonly");
31 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
32
33 namespace {
34   struct VISIBILITY_HIDDEN FunctionAttrs : public CallGraphSCCPass {
35     static char ID; // Pass identification, replacement for typeid
36     FunctionAttrs() : CallGraphSCCPass(&ID) {}
37
38     // runOnSCC - Analyze the SCC, performing the transformation if possible.
39     bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
40
41     // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
42     bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);
43
44     // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
45     bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);
46
47     // isCaptured - Returns whether this pointer value is captured.
48     bool isCaptured(Function &F, Value *V);
49
50     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51       AU.setPreservesCFG();
52       CallGraphSCCPass::getAnalysisUsage(AU);
53     }
54
55     bool PointsToLocalMemory(Value *V);
56   };
57 }
58
59 char FunctionAttrs::ID = 0;
60 static RegisterPass<FunctionAttrs>
61 X("functionattrs", "Deduce function attributes");
62
63 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
64
65
66 /// PointsToLocalMemory - Returns whether the given pointer value points to
67 /// memory that is local to the function.  Global constants are considered
68 /// local to all functions.
69 bool FunctionAttrs::PointsToLocalMemory(Value *V) {
70   V = V->getUnderlyingObject();
71   // An alloca instruction defines local memory.
72   if (isa<AllocaInst>(V))
73     return true;
74   // A global constant counts as local memory for our purposes.
75   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
76     return GV->isConstant();
77   // Could look through phi nodes and selects here, but it doesn't seem
78   // to be useful in practice.
79   return false;
80 }
81
82 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
83 bool FunctionAttrs::AddReadAttrs(const std::vector<CallGraphNode *> &SCC) {
84   SmallPtrSet<CallGraphNode*, 8> SCCNodes;
85   CallGraph &CG = getAnalysis<CallGraph>();
86
87   // Fill SCCNodes with the elements of the SCC.  Used for quickly
88   // looking up whether a given CallGraphNode is in this SCC.
89   for (unsigned i = 0, e = SCC.size(); i != e; ++i)
90     SCCNodes.insert(SCC[i]);
91
92   // Check if any of the functions in the SCC read or write memory.  If they
93   // write memory then they can't be marked readnone or readonly.
94   bool ReadsMemory = false;
95   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
96     Function *F = SCC[i]->getFunction();
97
98     if (F == 0)
99       // External node - may write memory.  Just give up.
100       return false;
101
102     if (F->doesNotAccessMemory())
103       // Already perfect!
104       continue;
105
106     // Definitions with weak linkage may be overridden at linktime with
107     // something that writes memory, so treat them like declarations.
108     if (F->isDeclaration() || F->mayBeOverridden()) {
109       if (!F->onlyReadsMemory())
110         // May write memory.  Just give up.
111         return false;
112
113       ReadsMemory = true;
114       continue;
115     }
116
117     // Scan the function body for instructions that may read or write memory.
118     for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
119       Instruction *I = &*II;
120
121       // Some instructions can be ignored even if they read or write memory.
122       // Detect these now, skipping to the next instruction if one is found.
123       CallSite CS = CallSite::get(I);
124       if (CS.getInstruction()) {
125         // Ignore calls to functions in the same SCC.
126         if (SCCNodes.count(CG[CS.getCalledFunction()]))
127           continue;
128       } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
129         // Ignore loads from local memory.
130         if (PointsToLocalMemory(LI->getPointerOperand()))
131           continue;
132       } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
133         // Ignore stores to local memory.
134         if (PointsToLocalMemory(SI->getPointerOperand()))
135           continue;
136       }
137
138       // Any remaining instructions need to be taken seriously!  Check if they
139       // read or write memory.
140       if (I->mayWriteToMemory())
141         // Writes memory.  Just give up.
142         return false;
143       // If this instruction may read memory, remember that.
144       ReadsMemory |= I->mayReadFromMemory();
145     }
146   }
147
148   // Success!  Functions in this SCC do not access memory, or only read memory.
149   // Give them the appropriate attribute.
150   bool MadeChange = false;
151   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
152     Function *F = SCC[i]->getFunction();
153
154     if (F->doesNotAccessMemory())
155       // Already perfect!
156       continue;
157
158     if (F->onlyReadsMemory() && ReadsMemory)
159       // No change.
160       continue;
161
162     MadeChange = true;
163
164     // Clear out any existing attributes.
165     F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
166
167     // Add in the new attribute.
168     F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
169
170     if (ReadsMemory)
171       NumReadOnly++;
172     else
173       NumReadNone++;
174   }
175
176   return MadeChange;
177 }
178
179 /// isCaptured - Returns whether this pointer value is captured.
180 bool FunctionAttrs::isCaptured(Function &F, Value *V) {
181   SmallVector<Use*, 16> Worklist;
182   SmallPtrSet<Use*, 16> Visited;
183
184   for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
185        ++UI) {
186     Use *U = &UI.getUse();
187     Visited.insert(U);
188     Worklist.push_back(U);
189   }
190
191   while (!Worklist.empty()) {
192     Use *U = Worklist.pop_back_val();
193     Instruction *I = cast<Instruction>(U->getUser());
194     V = U->get();
195
196     if (isa<LoadInst>(I)) {
197       // Loading a pointer does not cause it to escape.
198       continue;
199     }
200
201     if (isa<StoreInst>(I)) {
202       if (V == I->getOperand(0))
203         // Stored the pointer - escapes.  TODO: improve this.
204         return true;
205       // Storing to the pointee does not cause the pointer to escape.
206       continue;
207     }
208
209     CallSite CS = CallSite::get(I);
210     if (CS.getInstruction()) {
211       // Does not escape if only passed via 'nocapture' arguments.  Note
212       // that calling a function pointer does not in itself cause that
213       // function pointer to escape.  This is a subtle point considering
214       // that (for example) the callee might return its own address.  It
215       // is analogous to saying that loading a value from a pointer does
216       // not cause the pointer to escape, even though the loaded value
217       // might be the pointer itself (think of self-referential objects).
218       CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
219       for (CallSite::arg_iterator A = B; A != E; ++A)
220         if (A->get() == V && !CS.paramHasAttr(A-B+1, Attribute::NoCapture))
221           // The parameter is not marked 'nocapture' - escapes.
222           return true;
223       // Only passed via 'nocapture' arguments, or is the called function.
224       // Does not escape.
225       continue;
226     }
227
228     if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
229       // Type conversion or calculating an offset.  Does not escape if the new
230       // value doesn't.
231       for (Instruction::use_iterator UI = I->use_begin(), UE = I->use_end();
232            UI != UE; ++UI) {
233         Use *U = &UI.getUse();
234         if (Visited.insert(U))
235           Worklist.push_back(U);
236       }
237       continue;
238     }
239
240     // Something else - be conservative and say it escapes.
241     return true;
242   }
243
244   return false;
245 }
246
247 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
248 bool FunctionAttrs::AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC) {
249   bool Changed = false;
250
251   // Check each function in turn, determining which pointer arguments are not
252   // captured.
253   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
254     Function *F = SCC[i]->getFunction();
255
256     if (F == 0)
257       // External node - skip it;
258       continue;
259
260     // Definitions with weak linkage may be overridden at linktime with
261     // something that writes memory, so treat them like declarations.
262     if (F->isDeclaration() || F->mayBeOverridden())
263       continue;
264
265     for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
266       if (isa<PointerType>(A->getType()) && !isCaptured(*F, A)) {
267         A->addAttr(Attribute::NoCapture);
268         NumNoCapture++;
269         Changed = true;
270       }
271   }
272
273   return Changed;
274 }
275
276 bool FunctionAttrs::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
277   bool Changed = AddReadAttrs(SCC);
278   Changed |= AddNoCaptureAttrs(SCC);
279   return Changed;
280 }