blob: 0bff2b94e9d2d31f4a5c6b22e200878eb5a27eaf [file] [log] [blame]
Duncan Sands9e89ba32008-12-31 16:14:43 +00001//===- 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
Duncan Sandsb2f22792009-01-02 11:46:24 +000012// 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.
Duncan Sands9e89ba32008-12-31 16:14:43 +000018//
19//===----------------------------------------------------------------------===//
20
21#define DEBUG_TYPE "functionattrs"
22#include "llvm/Transforms/IPO.h"
23#include "llvm/CallGraphSCCPass.h"
24#include "llvm/GlobalVariable.h"
Devang Patelcd119912009-03-03 00:28:44 +000025#include "llvm/IntrinsicInst.h"
Nick Lewycky199aa3c2009-03-08 06:20:47 +000026#include "llvm/Analysis/AliasAnalysis.h"
Duncan Sands9e89ba32008-12-31 16:14:43 +000027#include "llvm/Analysis/CallGraph.h"
Duncan Sands8556d2a2009-01-18 12:19:30 +000028#include "llvm/Analysis/CaptureTracking.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000029#include "llvm/Analysis/MemoryBuiltins.h"
Duncan Sands338cd6b2009-01-02 11:54:37 +000030#include "llvm/ADT/SmallSet.h"
Duncan Sands9e89ba32008-12-31 16:14:43 +000031#include "llvm/ADT/Statistic.h"
Nick Lewycky199aa3c2009-03-08 06:20:47 +000032#include "llvm/ADT/UniqueVector.h"
Duncan Sands9e89ba32008-12-31 16:14:43 +000033#include "llvm/Support/InstIterator.h"
34using namespace llvm;
35
36STATISTIC(NumReadNone, "Number of functions marked readnone");
37STATISTIC(NumReadOnly, "Number of functions marked readonly");
38STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
Nick Lewycky199aa3c2009-03-08 06:20:47 +000039STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Duncan Sands9e89ba32008-12-31 16:14:43 +000040
41namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000042 struct FunctionAttrs : public CallGraphSCCPass {
Duncan Sands9e89ba32008-12-31 16:14:43 +000043 static char ID; // Pass identification, replacement for typeid
44 FunctionAttrs() : CallGraphSCCPass(&ID) {}
45
46 // runOnSCC - Analyze the SCC, performing the transformation if possible.
Chris Lattner5095e3d2009-08-31 00:19:58 +000047 bool runOnSCC(std::vector<CallGraphNode *> &SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +000048
49 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
50 bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);
51
52 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
53 bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);
54
Nick Lewycky199aa3c2009-03-08 06:20:47 +000055 // IsFunctionMallocLike - Does this function allocate new memory?
56 bool IsFunctionMallocLike(Function *F,
Chris Lattner98a27ce2009-08-31 04:09:04 +000057 SmallPtrSet<Function*, 8> &) const;
Nick Lewycky199aa3c2009-03-08 06:20:47 +000058
59 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
60 bool AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC);
61
Duncan Sands9e89ba32008-12-31 16:14:43 +000062 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.setPreservesCFG();
64 CallGraphSCCPass::getAnalysisUsage(AU);
65 }
66
67 bool PointsToLocalMemory(Value *V);
68 };
69}
70
71char FunctionAttrs::ID = 0;
72static RegisterPass<FunctionAttrs>
73X("functionattrs", "Deduce function attributes");
74
75Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
76
77
78/// PointsToLocalMemory - Returns whether the given pointer value points to
79/// memory that is local to the function. Global constants are considered
80/// local to all functions.
81bool FunctionAttrs::PointsToLocalMemory(Value *V) {
82 V = V->getUnderlyingObject();
83 // An alloca instruction defines local memory.
84 if (isa<AllocaInst>(V))
85 return true;
86 // A global constant counts as local memory for our purposes.
87 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
88 return GV->isConstant();
89 // Could look through phi nodes and selects here, but it doesn't seem
90 // to be useful in practice.
91 return false;
92}
93
94/// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
95bool FunctionAttrs::AddReadAttrs(const std::vector<CallGraphNode *> &SCC) {
Chris Lattner98a27ce2009-08-31 04:09:04 +000096 SmallPtrSet<Function*, 8> SCCNodes;
Duncan Sands9e89ba32008-12-31 16:14:43 +000097
98 // Fill SCCNodes with the elements of the SCC. Used for quickly
99 // looking up whether a given CallGraphNode is in this SCC.
100 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
Chris Lattner98a27ce2009-08-31 04:09:04 +0000101 SCCNodes.insert(SCC[i]->getFunction());
Duncan Sands9e89ba32008-12-31 16:14:43 +0000102
103 // Check if any of the functions in the SCC read or write memory. If they
104 // write memory then they can't be marked readnone or readonly.
105 bool ReadsMemory = false;
106 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
107 Function *F = SCC[i]->getFunction();
108
109 if (F == 0)
110 // External node - may write memory. Just give up.
111 return false;
112
113 if (F->doesNotAccessMemory())
114 // Already perfect!
115 continue;
116
117 // Definitions with weak linkage may be overridden at linktime with
118 // something that writes memory, so treat them like declarations.
119 if (F->isDeclaration() || F->mayBeOverridden()) {
120 if (!F->onlyReadsMemory())
121 // May write memory. Just give up.
122 return false;
123
124 ReadsMemory = true;
125 continue;
126 }
127
128 // Scan the function body for instructions that may read or write memory.
129 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
130 Instruction *I = &*II;
131
132 // Some instructions can be ignored even if they read or write memory.
133 // Detect these now, skipping to the next instruction if one is found.
134 CallSite CS = CallSite::get(I);
Chris Lattner98a27ce2009-08-31 04:09:04 +0000135 if (CS.getInstruction() && CS.getCalledFunction()) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000136 // Ignore calls to functions in the same SCC.
Chris Lattner98a27ce2009-08-31 04:09:04 +0000137 if (SCCNodes.count(CS.getCalledFunction()))
Duncan Sands9e89ba32008-12-31 16:14:43 +0000138 continue;
Duncan Sands7c422ac2010-01-06 08:45:52 +0000139 // Ignore intrinsics that only access local memory.
140 if (unsigned id = CS.getCalledFunction()->getIntrinsicID())
141 if (AliasAnalysis::getModRefBehavior(id) ==
142 AliasAnalysis::AccessesArguments) {
143 // Check that all pointer arguments point to local memory.
144 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
145 CI != CE; ++CI) {
146 Value *Arg = *CI;
147 if (isa<PointerType>(Arg->getType()) && !PointsToLocalMemory(Arg))
148 // Writes memory. Just give up.
149 return false;
150 }
151 // Only reads and writes local memory.
152 continue;
153 }
Duncan Sands9e89ba32008-12-31 16:14:43 +0000154 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
155 // Ignore loads from local memory.
156 if (PointsToLocalMemory(LI->getPointerOperand()))
157 continue;
158 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
159 // Ignore stores to local memory.
160 if (PointsToLocalMemory(SI->getPointerOperand()))
161 continue;
162 }
163
164 // Any remaining instructions need to be taken seriously! Check if they
165 // read or write memory.
166 if (I->mayWriteToMemory())
167 // Writes memory. Just give up.
168 return false;
Duncan Sandscfd0ebe2009-05-06 08:42:00 +0000169
Victor Hernandeza276c602009-10-17 01:18:07 +0000170 if (isMalloc(I))
Victor Hernandez83d63912009-09-18 22:35:49 +0000171 // malloc claims not to write memory! PR3754.
Duncan Sandscfd0ebe2009-05-06 08:42:00 +0000172 return false;
173
Duncan Sands9e89ba32008-12-31 16:14:43 +0000174 // If this instruction may read memory, remember that.
175 ReadsMemory |= I->mayReadFromMemory();
176 }
177 }
178
179 // Success! Functions in this SCC do not access memory, or only read memory.
180 // Give them the appropriate attribute.
181 bool MadeChange = false;
182 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
183 Function *F = SCC[i]->getFunction();
184
185 if (F->doesNotAccessMemory())
186 // Already perfect!
187 continue;
188
189 if (F->onlyReadsMemory() && ReadsMemory)
190 // No change.
191 continue;
192
193 MadeChange = true;
194
195 // Clear out any existing attributes.
196 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
197
198 // Add in the new attribute.
199 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
200
201 if (ReadsMemory)
Duncan Sandsb2f22792009-01-02 11:46:24 +0000202 ++NumReadOnly;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000203 else
Duncan Sandsb2f22792009-01-02 11:46:24 +0000204 ++NumReadNone;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000205 }
206
207 return MadeChange;
208}
209
Duncan Sands9e89ba32008-12-31 16:14:43 +0000210/// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
211bool FunctionAttrs::AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC) {
212 bool Changed = false;
213
214 // Check each function in turn, determining which pointer arguments are not
215 // captured.
216 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
217 Function *F = SCC[i]->getFunction();
218
219 if (F == 0)
220 // External node - skip it;
221 continue;
222
223 // Definitions with weak linkage may be overridden at linktime with
224 // something that writes memory, so treat them like declarations.
225 if (F->isDeclaration() || F->mayBeOverridden())
226 continue;
227
228 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
Duncan Sands17da06f2008-12-31 18:08:59 +0000229 if (isa<PointerType>(A->getType()) && !A->hasNoCaptureAttr() &&
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000230 !PointerMayBeCaptured(A, true, /*StoreCaptures=*/false)) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000231 A->addAttr(Attribute::NoCapture);
Nick Lewycky6b056862009-01-02 03:46:56 +0000232 ++NumNoCapture;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000233 Changed = true;
234 }
235 }
236
237 return Changed;
238}
239
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000240/// IsFunctionMallocLike - A function is malloc-like if it returns either null
Nick Lewycky4bfba9d2009-03-08 17:08:09 +0000241/// or a pointer that doesn't alias any other pointer visible to the caller.
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000242bool FunctionAttrs::IsFunctionMallocLike(Function *F,
Chris Lattner98a27ce2009-08-31 04:09:04 +0000243 SmallPtrSet<Function*, 8> &SCCNodes) const {
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000244 UniqueVector<Value *> FlowsToReturn;
245 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
246 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
247 FlowsToReturn.insert(Ret->getReturnValue());
248
249 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
250 Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
251
252 if (Constant *C = dyn_cast<Constant>(RetVal)) {
253 if (!C->isNullValue() && !isa<UndefValue>(C))
254 return false;
255
256 continue;
257 }
258
259 if (isa<Argument>(RetVal))
260 return false;
261
262 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
263 switch (RVI->getOpcode()) {
264 // Extend the analysis by looking upwards.
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000265 case Instruction::BitCast:
Victor Hernandez83d63912009-09-18 22:35:49 +0000266 case Instruction::GetElementPtr:
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000267 FlowsToReturn.insert(RVI->getOperand(0));
268 continue;
269 case Instruction::Select: {
270 SelectInst *SI = cast<SelectInst>(RVI);
271 FlowsToReturn.insert(SI->getTrueValue());
272 FlowsToReturn.insert(SI->getFalseValue());
Chris Lattner439044f2009-09-27 21:29:28 +0000273 continue;
274 }
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000275 case Instruction::PHI: {
276 PHINode *PN = cast<PHINode>(RVI);
277 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
278 FlowsToReturn.insert(PN->getIncomingValue(i));
Chris Lattner439044f2009-09-27 21:29:28 +0000279 continue;
280 }
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000281
282 // Check whether the pointer came from an allocation.
283 case Instruction::Alloca:
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000284 break;
285 case Instruction::Call:
286 case Instruction::Invoke: {
287 CallSite CS(RVI);
288 if (CS.paramHasAttr(0, Attribute::NoAlias))
289 break;
290 if (CS.getCalledFunction() &&
Chris Lattner98a27ce2009-08-31 04:09:04 +0000291 SCCNodes.count(CS.getCalledFunction()))
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000292 break;
293 } // fall-through
294 default:
295 return false; // Did not come from an allocation.
296 }
297
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000298 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000299 return false;
300 }
301
302 return true;
303}
304
305/// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
306bool FunctionAttrs::AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC) {
Chris Lattner98a27ce2009-08-31 04:09:04 +0000307 SmallPtrSet<Function*, 8> SCCNodes;
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000308
309 // Fill SCCNodes with the elements of the SCC. Used for quickly
310 // looking up whether a given CallGraphNode is in this SCC.
311 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
Chris Lattner98a27ce2009-08-31 04:09:04 +0000312 SCCNodes.insert(SCC[i]->getFunction());
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000313
Nick Lewycky4bfba9d2009-03-08 17:08:09 +0000314 // Check each function in turn, determining which functions return noalias
315 // pointers.
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000316 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
317 Function *F = SCC[i]->getFunction();
318
319 if (F == 0)
320 // External node - skip it;
321 return false;
322
323 // Already noalias.
324 if (F->doesNotAlias(0))
325 continue;
326
327 // Definitions with weak linkage may be overridden at linktime, so
328 // treat them like declarations.
329 if (F->isDeclaration() || F->mayBeOverridden())
330 return false;
331
332 // We annotate noalias return values, which are only applicable to
333 // pointer types.
334 if (!isa<PointerType>(F->getReturnType()))
335 continue;
336
337 if (!IsFunctionMallocLike(F, SCCNodes))
338 return false;
339 }
340
341 bool MadeChange = false;
342 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
343 Function *F = SCC[i]->getFunction();
344 if (F->doesNotAlias(0) || !isa<PointerType>(F->getReturnType()))
345 continue;
346
347 F->setDoesNotAlias(0);
348 ++NumNoAlias;
349 MadeChange = true;
350 }
351
352 return MadeChange;
353}
354
Chris Lattner5095e3d2009-08-31 00:19:58 +0000355bool FunctionAttrs::runOnSCC(std::vector<CallGraphNode *> &SCC) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000356 bool Changed = AddReadAttrs(SCC);
357 Changed |= AddNoCaptureAttrs(SCC);
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000358 Changed |= AddNoAliasAttrs(SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +0000359 return Changed;
360}