blob: d464e2ee8259482cfb1d5e4f00bbe872c01efe3f [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
Owen Anderson081c34b2010-10-19 17:21:58 +000043 FunctionAttrs() : CallGraphSCCPass(ID) {
44 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();
65 CallGraphSCCPass::getAnalysisUsage(AU);
66 }
67
Duncan Sands391f5bc2010-11-03 14:45:05 +000068 bool PointsToLocalOrConstantMemory(Value *V);
Duncan Sands9e89ba32008-12-31 16:14:43 +000069 };
70}
71
72char FunctionAttrs::ID = 0;
Owen Andersonae0a7bc2010-10-13 22:00:45 +000073INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
74 "Deduce function attributes", false, false)
75INITIALIZE_AG_DEPENDENCY(CallGraph)
76INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
Owen Andersonce665bd2010-10-07 22:25:06 +000077 "Deduce function attributes", false, false)
Duncan Sands9e89ba32008-12-31 16:14:43 +000078
79Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
80
81
Duncan Sands391f5bc2010-11-03 14:45:05 +000082/// PointsToLocalOrConstantMemory - Returns whether the given pointer value
83/// points to memory that is local to the function, with global constants being
84/// considered local to all functions.
85bool FunctionAttrs::PointsToLocalOrConstantMemory(Value *V) {
Duncan Sands5d8ea112010-01-07 05:48:42 +000086 SmallVector<Value*, 16> Worklist;
87 unsigned MaxLookup = 8;
Duncan Sandse10920d2010-01-06 15:37:47 +000088
89 Worklist.push_back(V);
90
91 do {
92 V = Worklist.pop_back_val()->getUnderlyingObject();
93
94 // An alloca instruction defines local memory.
95 if (isa<AllocaInst>(V))
96 continue;
97
98 // A global constant counts as local memory for our purposes.
99 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
100 if (!GV->isConstant())
101 return false;
102 continue;
103 }
104
105 // If both select values point to local memory, then so does the select.
106 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
107 Worklist.push_back(SI->getTrueValue());
108 Worklist.push_back(SI->getFalseValue());
109 continue;
110 }
111
112 // If all values incoming to a phi node point to local memory, then so does
113 // the phi.
114 if (PHINode *PN = dyn_cast<PHINode>(V)) {
115 // Don't bother inspecting phi nodes with many operands.
116 if (PN->getNumIncomingValues() > MaxLookup)
117 return false;
118 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
119 Worklist.push_back(PN->getIncomingValue(i));
120 continue;
121 }
122
123 return false;
124 } while (!Worklist.empty() && --MaxLookup);
125
126 return Worklist.empty();
Duncan Sands9e89ba32008-12-31 16:14:43 +0000127}
128
129/// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +0000130bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
Chris Lattner98a27ce2009-08-31 04:09:04 +0000131 SmallPtrSet<Function*, 8> SCCNodes;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000132
133 // Fill SCCNodes with the elements of the SCC. Used for quickly
134 // looking up whether a given CallGraphNode is in this SCC.
Chris Lattner2decb222010-04-16 22:42:17 +0000135 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
136 SCCNodes.insert((*I)->getFunction());
Duncan Sands9e89ba32008-12-31 16:14:43 +0000137
138 // Check if any of the functions in the SCC read or write memory. If they
139 // write memory then they can't be marked readnone or readonly.
140 bool ReadsMemory = false;
Chris Lattner2decb222010-04-16 22:42:17 +0000141 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
142 Function *F = (*I)->getFunction();
Duncan Sands9e89ba32008-12-31 16:14:43 +0000143
144 if (F == 0)
145 // External node - may write memory. Just give up.
146 return false;
147
148 if (F->doesNotAccessMemory())
149 // Already perfect!
150 continue;
151
152 // Definitions with weak linkage may be overridden at linktime with
153 // something that writes memory, so treat them like declarations.
154 if (F->isDeclaration() || F->mayBeOverridden()) {
155 if (!F->onlyReadsMemory())
156 // May write memory. Just give up.
157 return false;
158
159 ReadsMemory = true;
160 continue;
161 }
162
163 // Scan the function body for instructions that may read or write memory.
164 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
165 Instruction *I = &*II;
166
167 // Some instructions can be ignored even if they read or write memory.
168 // Detect these now, skipping to the next instruction if one is found.
Gabor Greif7d3056b2010-07-28 22:50:26 +0000169 CallSite CS(cast<Value>(I));
170 if (CS && CS.getCalledFunction()) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000171 // Ignore calls to functions in the same SCC.
Chris Lattner98a27ce2009-08-31 04:09:04 +0000172 if (SCCNodes.count(CS.getCalledFunction()))
Duncan Sands9e89ba32008-12-31 16:14:43 +0000173 continue;
Duncan Sands7c422ac2010-01-06 08:45:52 +0000174 // Ignore intrinsics that only access local memory.
175 if (unsigned id = CS.getCalledFunction()->getIntrinsicID())
Dan Gohman79fca6f2010-08-03 21:48:53 +0000176 if (AliasAnalysis::getIntrinsicModRefBehavior(id) ==
Duncan Sands7c422ac2010-01-06 08:45:52 +0000177 AliasAnalysis::AccessesArguments) {
178 // Check that all pointer arguments point to local memory.
179 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
180 CI != CE; ++CI) {
181 Value *Arg = *CI;
Duncan Sands391f5bc2010-11-03 14:45:05 +0000182 if (Arg->getType()->isPointerTy() &&
183 !PointsToLocalOrConstantMemory(Arg))
Duncan Sands7c422ac2010-01-06 08:45:52 +0000184 // Writes memory. Just give up.
185 return false;
186 }
187 // Only reads and writes local memory.
188 continue;
189 }
Duncan Sands9e89ba32008-12-31 16:14:43 +0000190 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Duncan Sandsad6f5412010-10-30 12:59:44 +0000191 // Ignore non-volatile loads from local memory.
Duncan Sands391f5bc2010-11-03 14:45:05 +0000192 if (!LI->isVolatile() &&
193 PointsToLocalOrConstantMemory(LI->getPointerOperand()))
Duncan Sands9e89ba32008-12-31 16:14:43 +0000194 continue;
195 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Duncan Sandsad6f5412010-10-30 12:59:44 +0000196 // Ignore non-volatile stores to local memory.
Duncan Sands391f5bc2010-11-03 14:45:05 +0000197 if (!SI->isVolatile() &&
198 PointsToLocalOrConstantMemory(SI->getPointerOperand()))
Duncan Sands9e89ba32008-12-31 16:14:43 +0000199 continue;
200 }
201
202 // Any remaining instructions need to be taken seriously! Check if they
203 // read or write memory.
204 if (I->mayWriteToMemory())
205 // Writes memory. Just give up.
206 return false;
Duncan Sandscfd0ebe2009-05-06 08:42:00 +0000207
Duncan Sands9e89ba32008-12-31 16:14:43 +0000208 // If this instruction may read memory, remember that.
209 ReadsMemory |= I->mayReadFromMemory();
210 }
211 }
212
213 // Success! Functions in this SCC do not access memory, or only read memory.
214 // Give them the appropriate attribute.
215 bool MadeChange = false;
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->doesNotAccessMemory())
220 // Already perfect!
221 continue;
222
223 if (F->onlyReadsMemory() && ReadsMemory)
224 // No change.
225 continue;
226
227 MadeChange = true;
228
229 // Clear out any existing attributes.
230 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
231
232 // Add in the new attribute.
233 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
234
235 if (ReadsMemory)
Duncan Sandsb2f22792009-01-02 11:46:24 +0000236 ++NumReadOnly;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000237 else
Duncan Sandsb2f22792009-01-02 11:46:24 +0000238 ++NumReadNone;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000239 }
240
241 return MadeChange;
242}
243
Duncan Sands9e89ba32008-12-31 16:14:43 +0000244/// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +0000245bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000246 bool Changed = false;
247
248 // Check each function in turn, determining which pointer arguments are not
249 // captured.
Chris Lattner2decb222010-04-16 22:42:17 +0000250 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
251 Function *F = (*I)->getFunction();
Duncan Sands9e89ba32008-12-31 16:14:43 +0000252
253 if (F == 0)
254 // External node - skip it;
255 continue;
256
257 // Definitions with weak linkage may be overridden at linktime with
258 // something that writes memory, so treat them like declarations.
259 if (F->isDeclaration() || F->mayBeOverridden())
260 continue;
261
262 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
Duncan Sands1df98592010-02-16 11:11:14 +0000263 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000264 !PointerMayBeCaptured(A, true, /*StoreCaptures=*/false)) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000265 A->addAttr(Attribute::NoCapture);
Nick Lewycky6b056862009-01-02 03:46:56 +0000266 ++NumNoCapture;
Duncan Sands9e89ba32008-12-31 16:14:43 +0000267 Changed = true;
268 }
269 }
270
271 return Changed;
272}
273
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000274/// IsFunctionMallocLike - A function is malloc-like if it returns either null
Nick Lewycky4bfba9d2009-03-08 17:08:09 +0000275/// or a pointer that doesn't alias any other pointer visible to the caller.
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000276bool FunctionAttrs::IsFunctionMallocLike(Function *F,
Chris Lattner98a27ce2009-08-31 04:09:04 +0000277 SmallPtrSet<Function*, 8> &SCCNodes) const {
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000278 UniqueVector<Value *> FlowsToReturn;
279 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
280 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
281 FlowsToReturn.insert(Ret->getReturnValue());
282
283 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
284 Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
285
286 if (Constant *C = dyn_cast<Constant>(RetVal)) {
287 if (!C->isNullValue() && !isa<UndefValue>(C))
288 return false;
289
290 continue;
291 }
292
293 if (isa<Argument>(RetVal))
294 return false;
295
296 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
297 switch (RVI->getOpcode()) {
298 // Extend the analysis by looking upwards.
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000299 case Instruction::BitCast:
Victor Hernandez83d63912009-09-18 22:35:49 +0000300 case Instruction::GetElementPtr:
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000301 FlowsToReturn.insert(RVI->getOperand(0));
302 continue;
303 case Instruction::Select: {
304 SelectInst *SI = cast<SelectInst>(RVI);
305 FlowsToReturn.insert(SI->getTrueValue());
306 FlowsToReturn.insert(SI->getFalseValue());
Chris Lattner439044f2009-09-27 21:29:28 +0000307 continue;
308 }
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000309 case Instruction::PHI: {
310 PHINode *PN = cast<PHINode>(RVI);
311 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
312 FlowsToReturn.insert(PN->getIncomingValue(i));
Chris Lattner439044f2009-09-27 21:29:28 +0000313 continue;
314 }
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000315
316 // Check whether the pointer came from an allocation.
317 case Instruction::Alloca:
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000318 break;
319 case Instruction::Call:
320 case Instruction::Invoke: {
321 CallSite CS(RVI);
322 if (CS.paramHasAttr(0, Attribute::NoAlias))
323 break;
324 if (CS.getCalledFunction() &&
Chris Lattner98a27ce2009-08-31 04:09:04 +0000325 SCCNodes.count(CS.getCalledFunction()))
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000326 break;
327 } // fall-through
328 default:
329 return false; // Did not come from an allocation.
330 }
331
Dan Gohmanf94b5ed2009-11-19 21:57:48 +0000332 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000333 return false;
334 }
335
336 return true;
337}
338
339/// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
Chris Lattner2decb222010-04-16 22:42:17 +0000340bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
Chris Lattner98a27ce2009-08-31 04:09:04 +0000341 SmallPtrSet<Function*, 8> SCCNodes;
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000342
343 // Fill SCCNodes with the elements of the SCC. Used for quickly
344 // looking up whether a given CallGraphNode is in this SCC.
Chris Lattner2decb222010-04-16 22:42:17 +0000345 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
346 SCCNodes.insert((*I)->getFunction());
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000347
Nick Lewycky4bfba9d2009-03-08 17:08:09 +0000348 // Check each function in turn, determining which functions return noalias
349 // pointers.
Chris Lattner2decb222010-04-16 22:42:17 +0000350 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
351 Function *F = (*I)->getFunction();
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000352
353 if (F == 0)
354 // External node - skip it;
355 return false;
356
357 // Already noalias.
358 if (F->doesNotAlias(0))
359 continue;
360
361 // Definitions with weak linkage may be overridden at linktime, so
362 // treat them like declarations.
363 if (F->isDeclaration() || F->mayBeOverridden())
364 return false;
365
366 // We annotate noalias return values, which are only applicable to
367 // pointer types.
Duncan Sands1df98592010-02-16 11:11:14 +0000368 if (!F->getReturnType()->isPointerTy())
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000369 continue;
370
371 if (!IsFunctionMallocLike(F, SCCNodes))
372 return false;
373 }
374
375 bool MadeChange = false;
Chris Lattner2decb222010-04-16 22:42:17 +0000376 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
377 Function *F = (*I)->getFunction();
Duncan Sands1df98592010-02-16 11:11:14 +0000378 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000379 continue;
380
381 F->setDoesNotAlias(0);
382 ++NumNoAlias;
383 MadeChange = true;
384 }
385
386 return MadeChange;
387}
388
Chris Lattner2decb222010-04-16 22:42:17 +0000389bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
Duncan Sands9e89ba32008-12-31 16:14:43 +0000390 bool Changed = AddReadAttrs(SCC);
391 Changed |= AddNoCaptureAttrs(SCC);
Nick Lewycky199aa3c2009-03-08 06:20:47 +0000392 Changed |= AddNoAliasAttrs(SCC);
Duncan Sands9e89ba32008-12-31 16:14:43 +0000393 return Changed;
394}