1 //===- FunctionAttrs.cpp - Pass which marks functions readnone or readonly ===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
19 //===----------------------------------------------------------------------===//
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"
33 STATISTIC(NumReadNone, "Number of functions marked readnone");
34 STATISTIC(NumReadOnly, "Number of functions marked readonly");
35 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
38 struct VISIBILITY_HIDDEN FunctionAttrs : public CallGraphSCCPass {
39 static char ID; // Pass identification, replacement for typeid
40 FunctionAttrs() : CallGraphSCCPass(&ID) {}
42 // runOnSCC - Analyze the SCC, performing the transformation if possible.
43 bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
45 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
46 bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);
48 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
49 bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);
51 // isCaptured - Return true if this pointer value may be captured.
52 bool isCaptured(Function &F, Value *V);
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 CallGraphSCCPass::getAnalysisUsage(AU);
59 bool PointsToLocalMemory(Value *V);
63 char FunctionAttrs::ID = 0;
64 static RegisterPass<FunctionAttrs>
65 X("functionattrs", "Deduce function attributes");
67 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
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))
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.
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>();
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]);
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();
103 // External node - may write memory. Just give up.
106 if (F->doesNotAccessMemory())
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.
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;
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()]))
132 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
133 // Ignore loads from local memory.
134 if (PointsToLocalMemory(LI->getPointerOperand()))
136 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
137 // Ignore stores to local memory.
138 if (PointsToLocalMemory(SI->getPointerOperand()))
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.
147 // If this instruction may read memory, remember that.
148 ReadsMemory |= I->mayReadFromMemory();
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();
158 if (F->doesNotAccessMemory())
162 if (F->onlyReadsMemory() && ReadsMemory)
168 // Clear out any existing attributes.
169 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
171 // Add in the new attribute.
172 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
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;
188 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
190 Use *U = &UI.getUse();
192 Worklist.push_back(U);
195 while (!Worklist.empty()) {
196 Use *U = Worklist.pop_back_val();
197 Instruction *I = cast<Instruction>(U->getUser());
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.
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)
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.
231 // Only passed via 'nocapture' arguments, or is the called function - not
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();
238 Use *U = &UI.getUse();
239 if (Visited.insert(U))
240 Worklist.push_back(U);
243 // Something else - be conservative and say it is captured.
248 // All uses examined - not captured.
252 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
253 bool FunctionAttrs::AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC) {
254 bool Changed = false;
256 // Check each function in turn, determining which pointer arguments are not
258 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
259 Function *F = SCC[i]->getFunction();
262 // External node - skip it;
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
268 if (F->onlyReadsMemory() && F->getReturnType() == Type::VoidTy) {
269 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end();
271 if (isa<PointerType>(A->getType()) && !A->hasNoCaptureAttr()) {
272 A->addAttr(Attribute::NoCapture);
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())
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);
296 bool FunctionAttrs::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
297 bool Changed = AddReadAttrs(SCC);
298 Changed |= AddNoCaptureAttrs(SCC);