FunctionAttrs.cpp revision a14b31ab8d5ca36fdd0cb4569b728c37e97478e7
1//===- 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
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.
18//
19//===----------------------------------------------------------------------===//
20
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"
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");
38STATISTIC(NumNoAlias, "Number of function returns marked noalias");
39
40namespace {
41  struct FunctionAttrs : public CallGraphSCCPass {
42    static char ID; // Pass identification, replacement for typeid
43    FunctionAttrs() : CallGraphSCCPass(ID), AA(0) {
44      initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
45    }
46
47    // runOnSCC - Analyze the SCC, performing the transformation if possible.
48    bool runOnSCC(CallGraphSCC &SCC);
49
50    // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
51    bool AddReadAttrs(const CallGraphSCC &SCC);
52
53    // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
54    bool AddNoCaptureAttrs(const CallGraphSCC &SCC);
55
56    // IsFunctionMallocLike - Does this function allocate new memory?
57    bool IsFunctionMallocLike(Function *F,
58                              SmallPtrSet<Function*, 8> &) const;
59
60    // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
61    bool AddNoAliasAttrs(const CallGraphSCC &SCC);
62
63    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64      AU.setPreservesCFG();
65      AU.addRequired<AliasAnalysis>();
66      CallGraphSCCPass::getAnalysisUsage(AU);
67    }
68
69  private:
70    AliasAnalysis *AA;
71  };
72}
73
74char FunctionAttrs::ID = 0;
75INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
76                "Deduce function attributes", false, false)
77INITIALIZE_AG_DEPENDENCY(CallGraph)
78INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
79                "Deduce function attributes", false, false)
80
81Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
82
83
84/// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
85bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
86  SmallPtrSet<Function*, 8> SCCNodes;
87
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());
92
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();
98
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.
124      CallSite CS(cast<Value>(I));
125      if (CS) {
126        // Ignore calls to functions in the same SCC.
127        if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
128          continue;
129        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() &&
144                !AA->pointsToConstantMemory(Arg, /*OrLocal=*/true))
145              // Writes memory.  Just give up.
146              return false;
147          }
148          // Only reads and writes local memory.
149          continue;
150        default:
151          // Otherwise, be conservative.
152          break;
153        }
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(),
158                                       /*OrLocal=*/true))
159          continue;
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(),
164                                       /*OrLocal=*/true))
165          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;
173
174      // 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;
182  for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
183    Function *F = (*I)->getFunction();
184
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)
202      ++NumReadOnly;
203    else
204      ++NumReadNone;
205  }
206
207  return MadeChange;
208}
209
210/// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
211bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
212  bool Changed = false;
213
214  // Check each function in turn, determining which pointer arguments are not
215  // captured.
216  for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
217    Function *F = (*I)->getFunction();
218
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)
229      if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr() &&
230          !PointerMayBeCaptured(A, true, /*StoreCaptures=*/false)) {
231        A->addAttr(Attribute::NoCapture);
232        ++NumNoCapture;
233        Changed = true;
234      }
235  }
236
237  return Changed;
238}
239
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.
242bool 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());
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.
265        case Instruction::BitCast:
266        case Instruction::GetElementPtr:
267          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());
273          continue;
274        }
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));
279          continue;
280        }
281
282        // Check whether the pointer came from an allocation.
283        case Instruction::Alloca:
284          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() &&
291              SCCNodes.count(CS.getCalledFunction()))
292            break;
293        } // fall-through
294        default:
295          return false;  // Did not come from an allocation.
296      }
297
298    if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
299      return false;
300  }
301
302  return true;
303}
304
305/// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
306bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
307  SmallPtrSet<Function*, 8> SCCNodes;
308
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());
313
314  // Check each function in turn, determining which functions return noalias
315  // pointers.
316  for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
317    Function *F = (*I)->getFunction();
318
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.
334    if (!F->getReturnType()->isPointerTy())
335      continue;
336
337    if (!IsFunctionMallocLike(F, SCCNodes))
338      return false;
339  }
340
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())
345      continue;
346
347    F->setDoesNotAlias(0);
348    ++NumNoAlias;
349    MadeChange = true;
350  }
351
352  return MadeChange;
353}
354
355bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
356  AA = &getAnalysis<AliasAnalysis>();
357
358  bool Changed = AddReadAttrs(SCC);
359  Changed |= AddNoCaptureAttrs(SCC);
360  Changed |= AddNoAliasAttrs(SCC);
361  return Changed;
362}
363