blob: be5d827e8e5f2ca59fcdd26a386d6418397b0a70 [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"
Duncan Sands338cd6b2009-01-02 11:54:37 +000029#include "llvm/ADT/SmallSet.h"
Duncan Sands9e89ba32008-12-31 16:14:43 +000030#include "llvm/ADT/Statistic.h"
Nick Lewycky199aa3c2009-03-08 06:20:47 +000031#include "llvm/ADT/UniqueVector.h"
Duncan Sands9e89ba32008-12-31 16:14:43 +000032#include "llvm/Support/InstIterator.h"
33using namespace llvm;
34
35STATISTIC(NumReadNone, "Number of functions marked readnone");
36STATISTIC(NumReadOnly, "Number of functions marked readonly");
37STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
Nick Lewycky199aa3c2009-03-08 06:20:47 +000038STATISTIC(NumNoAlias, "Number of function returns marked noalias");
Duncan Sands9e89ba32008-12-31 16:14:43 +000039
40namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000041 struct FunctionAttrs : public CallGraphSCCPass {
Duncan Sands9e89ba32008-12-31 16:14:43 +000042 static char ID; // Pass identification, replacement for typeid
Dan Gohman3c97f7a2010-11-08 16:10:15 +000043 FunctionAttrs() : CallGraphSCCPass(ID), AA(0) {
Owen Anderson081c34b2010-10-19 17:21:58 +000044 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
45 }
Duncan Sands9e89ba32008-12-31 16:14:43 +000046
47 // runOnSCC - Analyze the SCC, performing the transformation if possible.
Chris Lattner2decb222010-04-16 22:42:17 +000048 bool runOnSCC(CallGraphSCC &SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +000049
50 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +000051 bool AddReadAttrs(const CallGraphSCC &SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +000052
53 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +000054 bool AddNoCaptureAttrs(const CallGraphSCC &SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +000055
Nick Lewycky199aa3c2009-03-08 06:20:47 +000056 // IsFunctionMallocLike - Does this function allocate new memory?
57 bool IsFunctionMallocLike(Function *F,
Chris Lattner98a27ce2009-08-31 04:09:04 +000058 SmallPtrSet<Function*, 8> &) const;
Nick Lewycky199aa3c2009-03-08 06:20:47 +000059
60 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +000061 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
Nick Lewycky199aa3c2009-03-08 06:20:47 +000062
Duncan Sands9e89ba32008-12-31 16:14:43 +000063 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.setPreservesCFG();
Dan Gohman3c97f7a2010-11-08 16:10:15 +000065 AU.addRequired<AliasAnalysis>();
Duncan Sands9e89ba32008-12-31 16:14:43 +000066 CallGraphSCCPass::getAnalysisUsage(AU);
67 }
68
Dan Gohman3c97f7a2010-11-08 16:10:15 +000069 private:
70 AliasAnalysis *AA;
Duncan Sands9e89ba32008-12-31 16:14:43 +000071 };
72}
73
74char FunctionAttrs::ID = 0;
Owen Andersonae0a7bc2010-10-13 22:00:45 +000075INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
76 "Deduce function attributes", false, false)
77INITIALIZE_AG_DEPENDENCY(CallGraph)
78INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
Owen Andersonce665bd2010-10-07 22:25:06 +000079 "Deduce function attributes", false, false)
Duncan Sands9e89ba32008-12-31 16:14:43 +000080
81Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
82
83
Duncan Sands9e89ba32008-12-31 16:14:43 +000084/// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +000085bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
Chris Lattner98a27ce2009-08-31 04:09:04 +000086 SmallPtrSet<Function*, 8> SCCNodes;
Duncan Sands9e89ba32008-12-31 16:14:43 +000087
88 // Fill SCCNodes with the elements of the SCC. Used for quickly
89 // looking up whether a given CallGraphNode is in this SCC.
Chris Lattner2decb222010-04-16 22:42:17 +000090 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
91 SCCNodes.insert((*I)->getFunction());
Duncan Sands9e89ba32008-12-31 16:14:43 +000092
93 // Check if any of the functions in the SCC read or write memory. If they
94 // write memory then they can't be marked readnone or readonly.
95 bool ReadsMemory = false;
Chris Lattner2decb222010-04-16 22:42:17 +000096 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
97 Function *F = (*I)->getFunction();
Duncan Sands9e89ba32008-12-31 16:14:43 +000098
99 if (F == 0)
100 // External node - may write memory. Just give up.
101 return false;
102
103 if (F->doesNotAccessMemory())
104 // Already perfect!
105 continue;
106
107 // Definitions with weak linkage may be overridden at linktime with
108 // something that writes memory, so treat them like declarations.
109 if (F->isDeclaration() || F->mayBeOverridden()) {
110 if (!F->onlyReadsMemory())
111 // May write memory. Just give up.
112 return false;
113
114 ReadsMemory = true;
115 continue;
116 }
117
118 // Scan the function body for instructions that may read or write memory.
119 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
120 Instruction *I = &*II;
121
122 // Some instructions can be ignored even if they read or write memory.
123 // Detect these now, skipping to the next instruction if one is found.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000124 CallSite CS(cast<Value>(I));
Dan Gohman3c97f7a2010-11-08 16:10:15 +0000125 if (CS) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000126 // Ignore calls to functions in the same SCC.
Dan Gohman3c97f7a2010-11-08 16:10:15 +0000127 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
Duncan Sands9e89ba32008-12-31 16:14:43 +0000128 continue;
Dan Gohman3c97f7a2010-11-08 16:10:15 +0000129 switch (AA->getModRefBehavior(CS)) {
130 case AliasAnalysis::DoesNotAccessMemory:
131 // Ignore calls that don't access memory.
132 continue;
133 case AliasAnalysis::OnlyReadsMemory:
134 // Handle calls that only read from memory.
135 ReadsMemory = true;
136 continue;
137 case AliasAnalysis::AccessesArguments:
138 // Check whether all pointer arguments point to local memory, and
139 // ignore calls that only access local memory.
140 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
141 CI != CE; ++CI) {
142 Value *Arg = *CI;
143 if (Arg->getType()->isPointerTy() &&
Dan Gohmana25e5db2010-11-08 16:45:26 +0000144 !AA->pointsToConstantMemory(Arg, /*OrLocal=*/true))
Dan Gohman3c97f7a2010-11-08 16:10:15 +0000145 // Writes memory. Just give up.
146 return false;
Duncan Sands7c422ac2010-01-06 08:45:52 +0000147 }
Dan Gohman3c97f7a2010-11-08 16:10:15 +0000148 // Only reads and writes local memory.
149 continue;
150 default:
151 // Otherwise, be conservative.
152 break;
153 }
Duncan Sands9e89ba32008-12-31 16:14:43 +0000154 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Duncan Sandsad6f5412010-10-30 12:59:44 +0000155 // Ignore non-volatile loads from local memory.
Duncan Sands391f5bc2010-11-03 14:45:05 +0000156 if (!LI->isVolatile() &&
Dan Gohmana25e5db2010-11-08 16:45:26 +0000157 AA->pointsToConstantMemory(LI->getPointerOperand(),
158 /*OrLocal=*/true))
Duncan Sands9e89ba32008-12-31 16:14:43 +0000159 continue;
160 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Duncan Sandsad6f5412010-10-30 12:59:44 +0000161 // Ignore non-volatile stores to local memory.
Duncan Sands391f5bc2010-11-03 14:45:05 +0000162 if (!SI->isVolatile() &&
Dan Gohmana25e5db2010-11-08 16:45:26 +0000163 AA->pointsToConstantMemory(SI->getPointerOperand(),
164 /*OrLocal=*/true))
Duncan Sands9e89ba32008-12-31 16:14:43 +0000165 continue;
166 }
167
168 // Any remaining instructions need to be taken seriously! Check if they
169 // read or write memory.
170 if (I->mayWriteToMemory())
171 // Writes memory. Just give up.
172 return false;
Duncan Sandscfd0ebe2009-05-06 08:42:00 +0000173
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;
Chris Lattner2decb222010-04-16 22:42:17 +0000182 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
183 Function *F = (*I)->getFunction();
Duncan Sands9e89ba32008-12-31 16:14:43 +0000184
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.
Chris Lattner2decb222010-04-16 22:42:17 +0000211bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000212 bool Changed = false;
213
214 // Check each function in turn, determining which pointer arguments are not
215 // captured.
Chris Lattner2decb222010-04-16 22:42:17 +0000216 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
217 Function *F = (*I)->getFunction();
Duncan Sands9e89ba32008-12-31 16:14:43 +0000218
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 Sands1df98592010-02-16 11:11:14 +0000229 if (A->getType()->isPointerTy() && !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.
Chris Lattner2decb222010-04-16 22:42:17 +0000306bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &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.
Chris Lattner2decb222010-04-16 22:42:17 +0000311 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
312 SCCNodes.insert((*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.
Chris Lattner2decb222010-04-16 22:42:17 +0000316 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
317 Function *F = (*I)->getFunction();
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000318
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.
Duncan Sands1df98592010-02-16 11:11:14 +0000334 if (!F->getReturnType()->isPointerTy())
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000335 continue;
336
337 if (!IsFunctionMallocLike(F, SCCNodes))
338 return false;
339 }
340
341 bool MadeChange = false;
Chris Lattner2decb222010-04-16 22:42:17 +0000342 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
343 Function *F = (*I)->getFunction();
Duncan Sands1df98592010-02-16 11:11:14 +0000344 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000345 continue;
346
347 F->setDoesNotAlias(0);
348 ++NumNoAlias;
349 MadeChange = true;
350 }
351
352 return MadeChange;
353}
354
Chris Lattner2decb222010-04-16 22:42:17 +0000355bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
Dan Gohman3c97f7a2010-11-08 16:10:15 +0000356 AA = &getAnalysis<AliasAnalysis>();
357
Duncan Sands9e89ba32008-12-31 16:14:43 +0000358 bool Changed = AddReadAttrs(SCC);
359 Changed |= AddNoCaptureAttrs(SCC);
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000360 Changed |= AddNoAliasAttrs(SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +0000361 return Changed;
362}