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) {
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 CallGraphSCCPass::getAnalysisUsage(AU);
68 bool PointsToLocalOrConstantMemory(Value *V);
72 char FunctionAttrs::ID = 0;
73 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
74 "Deduce function attributes", false, false)
75 INITIALIZE_AG_DEPENDENCY(CallGraph)
76 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
77 "Deduce function attributes", false, false)
79 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
82 /// 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.
85 bool FunctionAttrs::PointsToLocalOrConstantMemory(Value *V) {
86 SmallVector<Value*, 16> Worklist;
87 unsigned MaxLookup = 8;
89 Worklist.push_back(V);
92 V = Worklist.pop_back_val()->getUnderlyingObject();
94 // An alloca instruction defines local memory.
95 if (isa<AllocaInst>(V))
98 // A global constant counts as local memory for our purposes.
99 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
100 if (!GV->isConstant())
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());
112 // If all values incoming to a phi node point to local memory, then so does
114 if (PHINode *PN = dyn_cast<PHINode>(V)) {
115 // Don't bother inspecting phi nodes with many operands.
116 if (PN->getNumIncomingValues() > MaxLookup)
118 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
119 Worklist.push_back(PN->getIncomingValue(i));
124 } while (!Worklist.empty() && --MaxLookup);
126 return Worklist.empty();
129 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
130 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
131 SmallPtrSet<Function*, 8> SCCNodes;
133 // Fill SCCNodes with the elements of the SCC. Used for quickly
134 // looking up whether a given CallGraphNode is in this SCC.
135 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
136 SCCNodes.insert((*I)->getFunction());
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;
141 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
142 Function *F = (*I)->getFunction();
145 // External node - may write memory. Just give up.
148 if (F->doesNotAccessMemory())
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.
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;
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.
169 CallSite CS(cast<Value>(I));
170 if (CS && CS.getCalledFunction()) {
171 // Ignore calls to functions in the same SCC.
172 if (SCCNodes.count(CS.getCalledFunction()))
174 // Ignore intrinsics that only access local memory.
175 if (unsigned id = CS.getCalledFunction()->getIntrinsicID())
176 if (AliasAnalysis::getIntrinsicModRefBehavior(id) ==
177 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();
182 if (Arg->getType()->isPointerTy() &&
183 !PointsToLocalOrConstantMemory(Arg))
184 // Writes memory. Just give up.
187 // Only reads and writes local memory.
190 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
191 // Ignore non-volatile loads from local memory.
192 if (!LI->isVolatile() &&
193 PointsToLocalOrConstantMemory(LI->getPointerOperand()))
195 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
196 // Ignore non-volatile stores to local memory.
197 if (!SI->isVolatile() &&
198 PointsToLocalOrConstantMemory(SI->getPointerOperand()))
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.
208 // If this instruction may read memory, remember that.
209 ReadsMemory |= I->mayReadFromMemory();
213 // Success! Functions in this SCC do not access memory, or only read memory.
214 // Give them the appropriate attribute.
215 bool MadeChange = false;
216 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
217 Function *F = (*I)->getFunction();
219 if (F->doesNotAccessMemory())
223 if (F->onlyReadsMemory() && ReadsMemory)
229 // Clear out any existing attributes.
230 F->removeAttribute(~0, Attribute::ReadOnly | Attribute::ReadNone);
232 // Add in the new attribute.
233 F->addAttribute(~0, ReadsMemory? Attribute::ReadOnly : Attribute::ReadNone);
244 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
245 bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
246 bool Changed = false;
248 // Check each function in turn, determining which pointer arguments are not
250 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
251 Function *F = (*I)->getFunction();
254 // External node - skip it;
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())
262 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
263 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&
264 !PointerMayBeCaptured(A, true, /*StoreCaptures=*/false)) {
265 A->addAttr(Attribute::NoCapture);
274 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
275 /// or a pointer that doesn't alias any other pointer visible to the caller.
276 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
277 SmallPtrSet<Function*, 8> &SCCNodes) const {
278 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());
283 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
284 Value *RetVal = FlowsToReturn[i+1]; // UniqueVector[0] is reserved.
286 if (Constant *C = dyn_cast<Constant>(RetVal)) {
287 if (!C->isNullValue() && !isa<UndefValue>(C))
293 if (isa<Argument>(RetVal))
296 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
297 switch (RVI->getOpcode()) {
298 // Extend the analysis by looking upwards.
299 case Instruction::BitCast:
300 case Instruction::GetElementPtr:
301 FlowsToReturn.insert(RVI->getOperand(0));
303 case Instruction::Select: {
304 SelectInst *SI = cast<SelectInst>(RVI);
305 FlowsToReturn.insert(SI->getTrueValue());
306 FlowsToReturn.insert(SI->getFalseValue());
309 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));
316 // Check whether the pointer came from an allocation.
317 case Instruction::Alloca:
319 case Instruction::Call:
320 case Instruction::Invoke: {
322 if (CS.paramHasAttr(0, Attribute::NoAlias))
324 if (CS.getCalledFunction() &&
325 SCCNodes.count(CS.getCalledFunction()))
329 return false; // Did not come from an allocation.
332 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
339 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
340 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
341 SmallPtrSet<Function*, 8> SCCNodes;
343 // Fill SCCNodes with the elements of the SCC. Used for quickly
344 // looking up whether a given CallGraphNode is in this SCC.
345 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
346 SCCNodes.insert((*I)->getFunction());
348 // Check each function in turn, determining which functions return noalias
350 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
351 Function *F = (*I)->getFunction();
354 // External node - skip it;
358 if (F->doesNotAlias(0))
361 // Definitions with weak linkage may be overridden at linktime, so
362 // treat them like declarations.
363 if (F->isDeclaration() || F->mayBeOverridden())
366 // We annotate noalias return values, which are only applicable to
368 if (!F->getReturnType()->isPointerTy())
371 if (!IsFunctionMallocLike(F, SCCNodes))
375 bool MadeChange = false;
376 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
377 Function *F = (*I)->getFunction();
378 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
381 F->setDoesNotAlias(0);
389 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
390 bool Changed = AddReadAttrs(SCC);
391 Changed |= AddNoCaptureAttrs(SCC);
392 Changed |= AddNoAliasAttrs(SCC);