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/Analysis/MemoryBuiltins.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/UniqueVector.h"
33 #include "llvm/Support/InstIterator.h"
36 STATISTIC(NumReadNone, "Number of functions marked readnone");
37 STATISTIC(NumReadOnly, "Number of functions marked readonly");
38 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
39 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
42 struct FunctionAttrs : public CallGraphSCCPass {
43 static char ID; // Pass identification, replacement for typeid
44 FunctionAttrs() : CallGraphSCCPass(&ID) {}
46 // runOnSCC - Analyze the SCC, performing the transformation if possible.
47 bool runOnSCC(std::vector<CallGraphNode *> &SCC);
49 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
50 bool AddReadAttrs(const std::vector<CallGraphNode *> &SCC);
52 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
53 bool AddNoCaptureAttrs(const std::vector<CallGraphNode *> &SCC);
55 // IsFunctionMallocLike - Does this function allocate new memory?
56 bool IsFunctionMallocLike(Function *F,
57 SmallPtrSet<Function*, 8> &) const;
59 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
60 bool AddNoAliasAttrs(const std::vector<CallGraphNode *> &SCC);
62 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 CallGraphSCCPass::getAnalysisUsage(AU);
67 bool PointsToLocalMemory(Value *V);
71 char FunctionAttrs::ID = 0;
72 static RegisterPass<FunctionAttrs>
73 X("functionattrs", "Deduce function attributes");
75 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
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.
81 bool FunctionAttrs::PointsToLocalMemory(Value *V) {
82 V = V->getUnderlyingObject();
83 // An alloca instruction defines local memory.
84 if (isa<AllocaInst>(V))
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.
94 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
95 bool FunctionAttrs::AddReadAttrs(const std::vector<CallGraphNode *> &SCC) {
96 SmallPtrSet<Function*, 8> SCCNodes;
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)
101 SCCNodes.insert(SCC[i]->getFunction());
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();
110 // External node - may write memory. Just give up.
113 if (F->doesNotAccessMemory())
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.
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;
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);
135 if (CS.getInstruction() && CS.getCalledFunction()) {
136 // Ignore calls to functions in the same SCC.
137 if (SCCNodes.count(CS.getCalledFunction()))
139 // 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();
147 if (isa<PointerType>(Arg->getType()) && !PointsToLocalMemory(Arg))
148 // Writes memory. Just give up.
151 // Only reads and writes local memory.
154 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
155 // Ignore loads from local memory.
156 if (PointsToLocalMemory(LI->getPointerOperand()))
158 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
159 // Ignore stores to local memory.
160 if (PointsToLocalMemory(SI->getPointerOperand()))
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.
171 // malloc claims not to write memory! PR3754.
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 (unsigned i = 0, e = SCC.size(); i != e; ++i) {
183 Function *F = SCC[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 std::vector<CallGraphNode *> &SCC) {
212 bool Changed = false;
214 // Check each function in turn, determining which pointer arguments are not
216 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
217 Function *F = SCC[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 (isa<PointerType>(A->getType()) && !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 std::vector<CallGraphNode *> &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 (unsigned i = 0, e = SCC.size(); i != e; ++i)
312 SCCNodes.insert(SCC[i]->getFunction());
314 // Check each function in turn, determining which functions return noalias
316 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
317 Function *F = SCC[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 (!isa<PointerType>(F->getReturnType()))
337 if (!IsFunctionMallocLike(F, SCCNodes))
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()))
347 F->setDoesNotAlias(0);
355 bool FunctionAttrs::runOnSCC(std::vector<CallGraphNode *> &SCC) {
356 bool Changed = AddReadAttrs(SCC);
357 Changed |= AddNoCaptureAttrs(SCC);
358 Changed |= AddNoAliasAttrs(SCC);