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