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/IntrinsicInst.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/CallGraph.h"
28 #include "llvm/Analysis/CaptureTracking.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/UniqueVector.h"
32 #include "llvm/Support/InstIterator.h"
35 STATISTIC(NumReadNone, "Number of functions marked readnone");
36 STATISTIC(NumReadOnly, "Number of functions marked readonly");
37 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
38 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
41 struct FunctionAttrs : public CallGraphSCCPass {
42 static char ID; // Pass identification, replacement for typeid
43 FunctionAttrs() : CallGraphSCCPass(ID), AA(0) {
44 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
47 // runOnSCC - Analyze the SCC, performing the transformation if possible.
48 bool runOnSCC(CallGraphSCC &SCC);
50 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
51 bool AddReadAttrs(const CallGraphSCC &SCC);
53 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
54 bool AddNoCaptureAttrs(const CallGraphSCC &SCC);
56 // IsFunctionMallocLike - Does this function allocate new memory?
57 bool IsFunctionMallocLike(Function *F,
58 SmallPtrSet<Function*, 8> &) const;
60 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
61 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
63 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired<AliasAnalysis>();
66 CallGraphSCCPass::getAnalysisUsage(AU);
74 char FunctionAttrs::ID = 0;
75 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
76 "Deduce function attributes", false, false)
77 INITIALIZE_AG_DEPENDENCY(CallGraph)
78 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
79 "Deduce function attributes", false, false)
81 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
84 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
85 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
86 SmallPtrSet<Function*, 8> SCCNodes;
88 // Fill SCCNodes with the elements of the SCC. Used for quickly
89 // looking up whether a given CallGraphNode is in this SCC.
90 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
91 SCCNodes.insert((*I)->getFunction());
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;
96 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
97 Function *F = (*I)->getFunction();
100 // External node - may write memory. Just give up.
103 if (F->doesNotAccessMemory())
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.
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;
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.
124 CallSite CS(cast<Value>(I));
126 // Ignore calls to functions in the same SCC.
127 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
129 switch (AA->getModRefBehavior(CS)) {
130 case AliasAnalysis::DoesNotAccessMemory:
131 // Ignore calls that don't access memory.
133 case AliasAnalysis::OnlyReadsMemory:
134 // Handle calls that only read from memory.
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();
143 if (Arg->getType()->isPointerTy() &&
144 !AA->pointsToConstantMemory(Arg, /*OrLocal=*/true))
145 // Writes memory. Just give up.
148 // Only reads and writes local memory.
151 // Otherwise, be conservative.
154 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
155 // Ignore non-volatile loads from local memory.
156 if (!LI->isVolatile() &&
157 AA->pointsToConstantMemory(LI->getPointerOperand(),
160 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
161 // Ignore non-volatile stores to local memory.
162 if (!SI->isVolatile() &&
163 AA->pointsToConstantMemory(SI->getPointerOperand(),
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.
174 // If this instruction may read memory, remember that.
175 ReadsMemory |= I->mayReadFromMemory();
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 (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
183 Function *F = (*I)->getFunction();
185 if (F->doesNotAccessMemory())
189 if (F->onlyReadsMemory() && ReadsMemory)
195 // Clear out any existing attributes.
196 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
198 // Add in the new attribute.
199 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
210 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
211 bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
212 bool Changed = false;
214 // Check each function in turn, determining which pointer arguments are not
216 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
217 Function *F = (*I)->getFunction();
220 // External node - skip it;
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())
228 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
229 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&
230 !PointerMayBeCaptured(A, true, /*StoreCaptures=*/false)) {
231 A->addAttr(Attribute::NoCapture);
240 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
241 /// or a pointer that doesn't alias any other pointer visible to the caller.
242 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
243 SmallPtrSet<Function*, 8> &SCCNodes) const {
244 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());
249 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
250 Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
252 if (Constant *C = dyn_cast<Constant>(RetVal)) {
253 if (!C->isNullValue() && !isa<UndefValue>(C))
259 if (isa<Argument>(RetVal))
262 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
263 switch (RVI->getOpcode()) {
264 // Extend the analysis by looking upwards.
265 case Instruction::BitCast:
266 case Instruction::GetElementPtr:
267 FlowsToReturn.insert(RVI->getOperand(0));
269 case Instruction::Select: {
270 SelectInst *SI = cast<SelectInst>(RVI);
271 FlowsToReturn.insert(SI->getTrueValue());
272 FlowsToReturn.insert(SI->getFalseValue());
275 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));
282 // Check whether the pointer came from an allocation.
283 case Instruction::Alloca:
285 case Instruction::Call:
286 case Instruction::Invoke: {
288 if (CS.paramHasAttr(0, Attribute::NoAlias))
290 if (CS.getCalledFunction() &&
291 SCCNodes.count(CS.getCalledFunction()))
295 return false; // Did not come from an allocation.
298 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
305 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
306 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
307 SmallPtrSet<Function*, 8> SCCNodes;
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 (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
312 SCCNodes.insert((*I)->getFunction());
314 // Check each function in turn, determining which functions return noalias
316 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
317 Function *F = (*I)->getFunction();
320 // External node - skip it;
324 if (F->doesNotAlias(0))
327 // Definitions with weak linkage may be overridden at linktime, so
328 // treat them like declarations.
329 if (F->isDeclaration() || F->mayBeOverridden())
332 // We annotate noalias return values, which are only applicable to
334 if (!F->getReturnType()->isPointerTy())
337 if (!IsFunctionMallocLike(F, SCCNodes))
341 bool MadeChange = false;
342 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
343 Function *F = (*I)->getFunction();
344 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
347 F->setDoesNotAlias(0);
355 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
356 AA = &getAnalysis<AliasAnalysis>();
358 bool Changed = AddReadAttrs(SCC);
359 Changed |= AddNoCaptureAttrs(SCC);
360 Changed |= AddNoAliasAttrs(SCC);