1 //===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
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 // Finally, well-known library call declarations are marked with all
18 // attributes that are consistent with the function's standard definition.
19 // This pass is implemented as a bottom-up traversal of the call-graph.
21 //===----------------------------------------------------------------------===//
23 #define DEBUG_TYPE "functionattrs"
24 #include "llvm/Transforms/IPO.h"
25 #include "llvm/ADT/SCCIterator.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/CallGraph.h"
31 #include "llvm/Analysis/CallGraphSCCPass.h"
32 #include "llvm/Analysis/CaptureTracking.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/IR/IntrinsicInst.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/Support/InstIterator.h"
37 #include "llvm/Target/TargetLibraryInfo.h"
40 STATISTIC(NumReadNone, "Number of functions marked readnone");
41 STATISTIC(NumReadOnly, "Number of functions marked readonly");
42 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
43 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
44 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
47 struct FunctionAttrs : public CallGraphSCCPass {
48 static char ID; // Pass identification, replacement for typeid
49 FunctionAttrs() : CallGraphSCCPass(ID), AA(0) {
50 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
53 // runOnSCC - Analyze the SCC, performing the transformation if possible.
54 bool runOnSCC(CallGraphSCC &SCC);
56 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
57 bool AddReadAttrs(const CallGraphSCC &SCC);
59 // AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
60 bool AddNoCaptureAttrs(const CallGraphSCC &SCC);
62 // IsFunctionMallocLike - Does this function allocate new memory?
63 bool IsFunctionMallocLike(Function *F,
64 SmallPtrSet<Function*, 8> &) const;
66 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
67 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
69 // Utility methods used by inferPrototypeAttributes to add attributes
70 // and maintain annotation statistics.
72 void setDoesNotAccessMemory(Function &F) {
73 if (!F.doesNotAccessMemory()) {
74 F.setDoesNotAccessMemory();
79 void setOnlyReadsMemory(Function &F) {
80 if (!F.onlyReadsMemory()) {
81 F.setOnlyReadsMemory();
86 void setDoesNotThrow(Function &F) {
87 if (!F.doesNotThrow()) {
93 void setDoesNotCapture(Function &F, unsigned n) {
94 if (!F.doesNotCapture(n)) {
95 F.setDoesNotCapture(n);
100 void setDoesNotAlias(Function &F, unsigned n) {
101 if (!F.doesNotAlias(n)) {
102 F.setDoesNotAlias(n);
107 // inferPrototypeAttributes - Analyze the name and prototype of the
108 // given function and set any applicable attributes. Returns true
109 // if any attributes were set and false otherwise.
110 bool inferPrototypeAttributes(Function &F);
112 // annotateLibraryCalls - Adds attributes to well-known standard library
113 // call declarations.
114 bool annotateLibraryCalls(const CallGraphSCC &SCC);
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117 AU.setPreservesCFG();
118 AU.addRequired<AliasAnalysis>();
119 AU.addRequired<TargetLibraryInfo>();
120 CallGraphSCCPass::getAnalysisUsage(AU);
125 TargetLibraryInfo *TLI;
129 char FunctionAttrs::ID = 0;
130 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
131 "Deduce function attributes", false, false)
132 INITIALIZE_AG_DEPENDENCY(CallGraph)
133 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
134 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
135 "Deduce function attributes", false, false)
137 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
140 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
141 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
142 SmallPtrSet<Function*, 8> SCCNodes;
144 // Fill SCCNodes with the elements of the SCC. Used for quickly
145 // looking up whether a given CallGraphNode is in this SCC.
146 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
147 SCCNodes.insert((*I)->getFunction());
149 // Check if any of the functions in the SCC read or write memory. If they
150 // write memory then they can't be marked readnone or readonly.
151 bool ReadsMemory = false;
152 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
153 Function *F = (*I)->getFunction();
156 // External node - may write memory. Just give up.
159 AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(F);
160 if (MRB == AliasAnalysis::DoesNotAccessMemory)
164 // Definitions with weak linkage may be overridden at linktime with
165 // something that writes memory, so treat them like declarations.
166 if (F->isDeclaration() || F->mayBeOverridden()) {
167 if (!AliasAnalysis::onlyReadsMemory(MRB))
168 // May write memory. Just give up.
175 // Scan the function body for instructions that may read or write memory.
176 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
177 Instruction *I = &*II;
179 // Some instructions can be ignored even if they read or write memory.
180 // Detect these now, skipping to the next instruction if one is found.
181 CallSite CS(cast<Value>(I));
183 // Ignore calls to functions in the same SCC.
184 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
186 AliasAnalysis::ModRefBehavior MRB = AA->getModRefBehavior(CS);
187 // If the call doesn't access arbitrary memory, we may be able to
188 // figure out something.
189 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
190 // If the call does access argument pointees, check each argument.
191 if (AliasAnalysis::doesAccessArgPointees(MRB))
192 // Check whether all pointer arguments point to local memory, and
193 // ignore calls that only access local memory.
194 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
197 if (Arg->getType()->isPointerTy()) {
198 AliasAnalysis::Location Loc(Arg,
199 AliasAnalysis::UnknownSize,
200 I->getMetadata(LLVMContext::MD_tbaa));
201 if (!AA->pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
202 if (MRB & AliasAnalysis::Mod)
203 // Writes non-local memory. Give up.
205 if (MRB & AliasAnalysis::Ref)
206 // Ok, it reads non-local memory.
213 // The call could access any memory. If that includes writes, give up.
214 if (MRB & AliasAnalysis::Mod)
216 // If it reads, note it.
217 if (MRB & AliasAnalysis::Ref)
220 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
221 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
222 if (!LI->isVolatile()) {
223 AliasAnalysis::Location Loc = AA->getLocation(LI);
224 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
227 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
228 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
229 if (!SI->isVolatile()) {
230 AliasAnalysis::Location Loc = AA->getLocation(SI);
231 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
234 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
235 // Ignore vaargs on local memory.
236 AliasAnalysis::Location Loc = AA->getLocation(VI);
237 if (AA->pointsToConstantMemory(Loc, /*OrLocal=*/true))
241 // Any remaining instructions need to be taken seriously! Check if they
242 // read or write memory.
243 if (I->mayWriteToMemory())
244 // Writes memory. Just give up.
247 // If this instruction may read memory, remember that.
248 ReadsMemory |= I->mayReadFromMemory();
252 // Success! Functions in this SCC do not access memory, or only read memory.
253 // Give them the appropriate attribute.
254 bool MadeChange = false;
255 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
256 Function *F = (*I)->getFunction();
258 if (F->doesNotAccessMemory())
262 if (F->onlyReadsMemory() && ReadsMemory)
268 // Clear out any existing attributes.
270 B.addAttribute(Attribute::ReadOnly)
271 .addAttribute(Attribute::ReadNone);
272 F->removeAttributes(AttributeSet::FunctionIndex,
273 AttributeSet::get(F->getContext(),
274 AttributeSet::FunctionIndex, B));
276 // Add in the new attribute.
277 F->addAttribute(AttributeSet::FunctionIndex,
278 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
290 // For a given pointer Argument, this retains a list of Arguments of functions
291 // in the same SCC that the pointer data flows into. We use this to build an
292 // SCC of the arguments.
293 struct ArgumentGraphNode {
294 Argument *Definition;
295 SmallVector<ArgumentGraphNode*, 4> Uses;
298 class ArgumentGraph {
299 // We store pointers to ArgumentGraphNode objects, so it's important that
300 // that they not move around upon insert.
301 typedef std::map<Argument*, ArgumentGraphNode> ArgumentMapTy;
303 ArgumentMapTy ArgumentMap;
305 // There is no root node for the argument graph, in fact:
306 // void f(int *x, int *y) { if (...) f(x, y); }
307 // is an example where the graph is disconnected. The SCCIterator requires a
308 // single entry point, so we maintain a fake ("synthetic") root node that
309 // uses every node. Because the graph is directed and nothing points into
310 // the root, it will not participate in any SCCs (except for its own).
311 ArgumentGraphNode SyntheticRoot;
314 ArgumentGraph() { SyntheticRoot.Definition = 0; }
316 typedef SmallVectorImpl<ArgumentGraphNode*>::iterator iterator;
318 iterator begin() { return SyntheticRoot.Uses.begin(); }
319 iterator end() { return SyntheticRoot.Uses.end(); }
320 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
322 ArgumentGraphNode *operator[](Argument *A) {
323 ArgumentGraphNode &Node = ArgumentMap[A];
325 SyntheticRoot.Uses.push_back(&Node);
330 // This tracker checks whether callees are in the SCC, and if so it does not
331 // consider that a capture, instead adding it to the "Uses" list and
332 // continuing with the analysis.
333 struct ArgumentUsesTracker : public CaptureTracker {
334 ArgumentUsesTracker(const SmallPtrSet<Function*, 8> &SCCNodes)
335 : Captured(false), SCCNodes(SCCNodes) {}
337 void tooManyUses() { Captured = true; }
339 bool captured(Use *U) {
340 CallSite CS(U->getUser());
341 if (!CS.getInstruction()) { Captured = true; return true; }
343 Function *F = CS.getCalledFunction();
344 if (!F || !SCCNodes.count(F)) { Captured = true; return true; }
346 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
347 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
348 PI != PE; ++PI, ++AI) {
350 assert(F->isVarArg() && "More params than args in non-varargs call");
359 assert(!Uses.empty() && "Capturing call-site captured nothing?");
363 bool Captured; // True only if certainly captured (used outside our SCC).
364 SmallVector<Argument*, 4> Uses; // Uses within our SCC.
366 const SmallPtrSet<Function*, 8> &SCCNodes;
371 template<> struct GraphTraits<ArgumentGraphNode*> {
372 typedef ArgumentGraphNode NodeType;
373 typedef SmallVectorImpl<ArgumentGraphNode*>::iterator ChildIteratorType;
375 static inline NodeType *getEntryNode(NodeType *A) { return A; }
376 static inline ChildIteratorType child_begin(NodeType *N) {
377 return N->Uses.begin();
379 static inline ChildIteratorType child_end(NodeType *N) {
380 return N->Uses.end();
383 template<> struct GraphTraits<ArgumentGraph*>
384 : public GraphTraits<ArgumentGraphNode*> {
385 static NodeType *getEntryNode(ArgumentGraph *AG) {
386 return AG->getEntryNode();
388 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
391 static ChildIteratorType nodes_end(ArgumentGraph *AG) {
397 /// AddNoCaptureAttrs - Deduce nocapture attributes for the SCC.
398 bool FunctionAttrs::AddNoCaptureAttrs(const CallGraphSCC &SCC) {
399 bool Changed = false;
401 SmallPtrSet<Function*, 8> SCCNodes;
403 // Fill SCCNodes with the elements of the SCC. Used for quickly
404 // looking up whether a given CallGraphNode is in this SCC.
405 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
406 Function *F = (*I)->getFunction();
407 if (F && !F->isDeclaration() && !F->mayBeOverridden())
414 B.addAttribute(Attribute::NoCapture);
416 // Check each function in turn, determining which pointer arguments are not
418 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
419 Function *F = (*I)->getFunction();
422 // External node - only a problem for arguments that we pass to it.
425 // Definitions with weak linkage may be overridden at linktime with
426 // something that captures pointers, so treat them like declarations.
427 if (F->isDeclaration() || F->mayBeOverridden())
430 // Functions that are readonly (or readnone) and nounwind and don't return
431 // a value can't capture arguments. Don't analyze them.
432 if (F->onlyReadsMemory() && F->doesNotThrow() &&
433 F->getReturnType()->isVoidTy()) {
434 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end();
436 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
437 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
445 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A!=E; ++A)
446 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
447 ArgumentUsesTracker Tracker(SCCNodes);
448 PointerMayBeCaptured(A, &Tracker);
449 if (!Tracker.Captured) {
450 if (Tracker.Uses.empty()) {
451 // If it's trivially not captured, mark it nocapture now.
452 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo()+1, B));
456 // If it's not trivially captured and not trivially not captured,
457 // then it must be calling into another function in our SCC. Save
458 // its particulars for Argument-SCC analysis later.
459 ArgumentGraphNode *Node = AG[A];
460 for (SmallVectorImpl<Argument*>::iterator UI = Tracker.Uses.begin(),
461 UE = Tracker.Uses.end(); UI != UE; ++UI)
462 Node->Uses.push_back(AG[*UI]);
465 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
469 // The graph we've collected is partial because we stopped scanning for
470 // argument uses once we solved the argument trivially. These partial nodes
471 // show up as ArgumentGraphNode objects with an empty Uses list, and for
472 // these nodes the final decision about whether they capture has already been
473 // made. If the definition doesn't have a 'nocapture' attribute by now, it
476 for (scc_iterator<ArgumentGraph*> I = scc_begin(&AG), E = scc_end(&AG);
478 std::vector<ArgumentGraphNode*> &ArgumentSCC = *I;
479 if (ArgumentSCC.size() == 1) {
480 if (!ArgumentSCC[0]->Definition) continue; // synthetic root node
482 // eg. "void f(int* x) { if (...) f(x); }"
483 if (ArgumentSCC[0]->Uses.size() == 1 &&
484 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
487 addAttr(AttributeSet::get(ArgumentSCC[0]->Definition->getContext(),
488 ArgumentSCC[0]->Definition->getArgNo() + 1,
496 bool SCCCaptured = false;
497 for (std::vector<ArgumentGraphNode*>::iterator I = ArgumentSCC.begin(),
498 E = ArgumentSCC.end(); I != E && !SCCCaptured; ++I) {
499 ArgumentGraphNode *Node = *I;
500 if (Node->Uses.empty()) {
501 if (!Node->Definition->hasNoCaptureAttr())
505 if (SCCCaptured) continue;
507 SmallPtrSet<Argument*, 8> ArgumentSCCNodes;
508 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
509 // quickly looking up whether a given Argument is in this ArgumentSCC.
510 for (std::vector<ArgumentGraphNode*>::iterator I = ArgumentSCC.begin(),
511 E = ArgumentSCC.end(); I != E; ++I) {
512 ArgumentSCCNodes.insert((*I)->Definition);
515 for (std::vector<ArgumentGraphNode*>::iterator I = ArgumentSCC.begin(),
516 E = ArgumentSCC.end(); I != E && !SCCCaptured; ++I) {
517 ArgumentGraphNode *N = *I;
518 for (SmallVectorImpl<ArgumentGraphNode*>::iterator UI = N->Uses.begin(),
519 UE = N->Uses.end(); UI != UE; ++UI) {
520 Argument *A = (*UI)->Definition;
521 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
527 if (SCCCaptured) continue;
529 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
530 Argument *A = ArgumentSCC[i]->Definition;
531 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
540 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
541 /// or a pointer that doesn't alias any other pointer visible to the caller.
542 bool FunctionAttrs::IsFunctionMallocLike(Function *F,
543 SmallPtrSet<Function*, 8> &SCCNodes) const {
544 SmallSetVector<Value *, 8> FlowsToReturn;
545 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
546 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
547 FlowsToReturn.insert(Ret->getReturnValue());
549 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
550 Value *RetVal = FlowsToReturn[i];
552 if (Constant *C = dyn_cast<Constant>(RetVal)) {
553 if (!C->isNullValue() && !isa<UndefValue>(C))
559 if (isa<Argument>(RetVal))
562 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
563 switch (RVI->getOpcode()) {
564 // Extend the analysis by looking upwards.
565 case Instruction::BitCast:
566 case Instruction::GetElementPtr:
567 FlowsToReturn.insert(RVI->getOperand(0));
569 case Instruction::Select: {
570 SelectInst *SI = cast<SelectInst>(RVI);
571 FlowsToReturn.insert(SI->getTrueValue());
572 FlowsToReturn.insert(SI->getFalseValue());
575 case Instruction::PHI: {
576 PHINode *PN = cast<PHINode>(RVI);
577 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
578 FlowsToReturn.insert(PN->getIncomingValue(i));
582 // Check whether the pointer came from an allocation.
583 case Instruction::Alloca:
585 case Instruction::Call:
586 case Instruction::Invoke: {
588 if (CS.paramHasAttr(0, Attribute::NoAlias))
590 if (CS.getCalledFunction() &&
591 SCCNodes.count(CS.getCalledFunction()))
595 return false; // Did not come from an allocation.
598 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
605 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
606 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
607 SmallPtrSet<Function*, 8> SCCNodes;
609 // Fill SCCNodes with the elements of the SCC. Used for quickly
610 // looking up whether a given CallGraphNode is in this SCC.
611 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
612 SCCNodes.insert((*I)->getFunction());
614 // Check each function in turn, determining which functions return noalias
616 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
617 Function *F = (*I)->getFunction();
620 // External node - skip it;
624 if (F->doesNotAlias(0))
627 // Definitions with weak linkage may be overridden at linktime, so
628 // treat them like declarations.
629 if (F->isDeclaration() || F->mayBeOverridden())
632 // We annotate noalias return values, which are only applicable to
634 if (!F->getReturnType()->isPointerTy())
637 if (!IsFunctionMallocLike(F, SCCNodes))
641 bool MadeChange = false;
642 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
643 Function *F = (*I)->getFunction();
644 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
647 F->setDoesNotAlias(0);
655 /// inferPrototypeAttributes - Analyze the name and prototype of the
656 /// given function and set any applicable attributes. Returns true
657 /// if any attributes were set and false otherwise.
658 bool FunctionAttrs::inferPrototypeAttributes(Function &F) {
659 FunctionType *FTy = F.getFunctionType();
660 LibFunc::Func TheLibFunc;
661 if (!(TLI->getLibFunc(F.getName(), TheLibFunc) && TLI->has(TheLibFunc)))
664 switch (TheLibFunc) {
665 case LibFunc::strlen:
666 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
668 setOnlyReadsMemory(F);
670 setDoesNotCapture(F, 1);
672 case LibFunc::strchr:
673 case LibFunc::strrchr:
674 if (FTy->getNumParams() != 2 ||
675 !FTy->getParamType(0)->isPointerTy() ||
676 !FTy->getParamType(1)->isIntegerTy())
678 setOnlyReadsMemory(F);
681 case LibFunc::strcpy:
682 case LibFunc::stpcpy:
683 case LibFunc::strcat:
684 case LibFunc::strtol:
685 case LibFunc::strtod:
686 case LibFunc::strtof:
687 case LibFunc::strtoul:
688 case LibFunc::strtoll:
689 case LibFunc::strtold:
690 case LibFunc::strncat:
691 case LibFunc::strncpy:
692 case LibFunc::stpncpy:
693 case LibFunc::strtoull:
694 if (FTy->getNumParams() < 2 ||
695 !FTy->getParamType(1)->isPointerTy())
698 setDoesNotCapture(F, 2);
700 case LibFunc::strxfrm:
701 if (FTy->getNumParams() != 3 ||
702 !FTy->getParamType(0)->isPointerTy() ||
703 !FTy->getParamType(1)->isPointerTy())
706 setDoesNotCapture(F, 1);
707 setDoesNotCapture(F, 2);
709 case LibFunc::strcmp:
710 case LibFunc::strspn:
711 case LibFunc::strncmp:
712 case LibFunc::strcspn:
713 case LibFunc::strcoll:
714 case LibFunc::strcasecmp:
715 case LibFunc::strncasecmp:
716 if (FTy->getNumParams() < 2 ||
717 !FTy->getParamType(0)->isPointerTy() ||
718 !FTy->getParamType(1)->isPointerTy())
720 setOnlyReadsMemory(F);
722 setDoesNotCapture(F, 1);
723 setDoesNotCapture(F, 2);
725 case LibFunc::strstr:
726 case LibFunc::strpbrk:
727 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
729 setOnlyReadsMemory(F);
731 setDoesNotCapture(F, 2);
733 case LibFunc::strtok:
734 case LibFunc::strtok_r:
735 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
738 setDoesNotCapture(F, 2);
741 case LibFunc::setbuf:
742 case LibFunc::setvbuf:
743 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
746 setDoesNotCapture(F, 1);
748 case LibFunc::strdup:
749 case LibFunc::strndup:
750 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
751 !FTy->getParamType(0)->isPointerTy())
754 setDoesNotAlias(F, 0);
755 setDoesNotCapture(F, 1);
758 case LibFunc::sscanf:
759 case LibFunc::sprintf:
760 case LibFunc::statvfs:
761 if (FTy->getNumParams() < 2 ||
762 !FTy->getParamType(0)->isPointerTy() ||
763 !FTy->getParamType(1)->isPointerTy())
766 setDoesNotCapture(F, 1);
767 setDoesNotCapture(F, 2);
769 case LibFunc::snprintf:
770 if (FTy->getNumParams() != 3 ||
771 !FTy->getParamType(0)->isPointerTy() ||
772 !FTy->getParamType(2)->isPointerTy())
775 setDoesNotCapture(F, 1);
776 setDoesNotCapture(F, 3);
778 case LibFunc::setitimer:
779 if (FTy->getNumParams() != 3 ||
780 !FTy->getParamType(1)->isPointerTy() ||
781 !FTy->getParamType(2)->isPointerTy())
784 setDoesNotCapture(F, 2);
785 setDoesNotCapture(F, 3);
787 case LibFunc::system:
788 if (FTy->getNumParams() != 1 ||
789 !FTy->getParamType(0)->isPointerTy())
791 // May throw; "system" is a valid pthread cancellation point.
792 setDoesNotCapture(F, 1);
794 case LibFunc::malloc:
795 if (FTy->getNumParams() != 1 ||
796 !FTy->getReturnType()->isPointerTy())
799 setDoesNotAlias(F, 0);
801 case LibFunc::memcmp:
802 if (FTy->getNumParams() != 3 ||
803 !FTy->getParamType(0)->isPointerTy() ||
804 !FTy->getParamType(1)->isPointerTy())
806 setOnlyReadsMemory(F);
808 setDoesNotCapture(F, 1);
809 setDoesNotCapture(F, 2);
811 case LibFunc::memchr:
812 case LibFunc::memrchr:
813 if (FTy->getNumParams() != 3)
815 setOnlyReadsMemory(F);
821 case LibFunc::memcpy:
822 case LibFunc::memccpy:
823 case LibFunc::memmove:
824 if (FTy->getNumParams() < 2 ||
825 !FTy->getParamType(1)->isPointerTy())
828 setDoesNotCapture(F, 2);
830 case LibFunc::memalign:
831 if (!FTy->getReturnType()->isPointerTy())
833 setDoesNotAlias(F, 0);
836 case LibFunc::mktime:
837 if (FTy->getNumParams() == 0 ||
838 !FTy->getParamType(0)->isPointerTy())
841 setDoesNotCapture(F, 1);
843 case LibFunc::realloc:
844 if (FTy->getNumParams() != 2 ||
845 !FTy->getParamType(0)->isPointerTy() ||
846 !FTy->getReturnType()->isPointerTy())
849 setDoesNotAlias(F, 0);
850 setDoesNotCapture(F, 1);
853 if (FTy->getNumParams() != 3 ||
854 !FTy->getParamType(1)->isPointerTy())
856 // May throw; "read" is a valid pthread cancellation point.
857 setDoesNotCapture(F, 2);
860 case LibFunc::rewind:
861 case LibFunc::remove:
862 case LibFunc::realpath:
863 if (FTy->getNumParams() < 1 ||
864 !FTy->getParamType(0)->isPointerTy())
867 setDoesNotCapture(F, 1);
869 case LibFunc::rename:
870 case LibFunc::readlink:
871 if (FTy->getNumParams() < 2 ||
872 !FTy->getParamType(0)->isPointerTy() ||
873 !FTy->getParamType(1)->isPointerTy())
876 setDoesNotCapture(F, 1);
877 setDoesNotCapture(F, 2);
880 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
882 // May throw; "write" is a valid pthread cancellation point.
883 setDoesNotCapture(F, 2);
886 if (FTy->getNumParams() != 3 ||
887 !FTy->getParamType(0)->isPointerTy() ||
888 !FTy->getParamType(1)->isPointerTy())
891 setDoesNotCapture(F, 1);
892 setDoesNotCapture(F, 2);
895 if (FTy->getNumParams() != 3 ||
896 !FTy->getParamType(0)->isPointerTy() ||
897 !FTy->getParamType(1)->isPointerTy())
900 setOnlyReadsMemory(F);
901 setDoesNotCapture(F, 1);
902 setDoesNotCapture(F, 2);
905 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
908 setDoesNotCapture(F, 1);
910 case LibFunc::calloc:
911 if (FTy->getNumParams() != 2 ||
912 !FTy->getReturnType()->isPointerTy())
915 setDoesNotAlias(F, 0);
919 case LibFunc::ctermid:
920 case LibFunc::clearerr:
921 case LibFunc::closedir:
922 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
925 setDoesNotCapture(F, 1);
931 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
934 setOnlyReadsMemory(F);
935 setDoesNotCapture(F, 1);
937 case LibFunc::access:
938 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
941 setDoesNotCapture(F, 1);
944 if (FTy->getNumParams() != 2 ||
945 !FTy->getReturnType()->isPointerTy() ||
946 !FTy->getParamType(0)->isPointerTy() ||
947 !FTy->getParamType(1)->isPointerTy())
950 setDoesNotAlias(F, 0);
951 setDoesNotCapture(F, 1);
952 setDoesNotCapture(F, 2);
954 case LibFunc::fdopen:
955 if (FTy->getNumParams() != 2 ||
956 !FTy->getReturnType()->isPointerTy() ||
957 !FTy->getParamType(1)->isPointerTy())
960 setDoesNotAlias(F, 0);
961 setDoesNotCapture(F, 2);
968 case LibFunc::fseeko:
969 case LibFunc::ftello:
970 case LibFunc::fileno:
971 case LibFunc::fflush:
972 case LibFunc::fclose:
973 case LibFunc::fsetpos:
974 case LibFunc::flockfile:
975 case LibFunc::funlockfile:
976 case LibFunc::ftrylockfile:
977 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
980 setDoesNotCapture(F, 1);
982 case LibFunc::ferror:
983 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
986 setDoesNotCapture(F, 1);
987 setOnlyReadsMemory(F);
992 case LibFunc::frexpf:
993 case LibFunc::frexpl:
994 case LibFunc::fstatvfs:
995 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
998 setDoesNotCapture(F, 2);
1000 case LibFunc::fgets:
1001 if (FTy->getNumParams() != 3 ||
1002 !FTy->getParamType(0)->isPointerTy() ||
1003 !FTy->getParamType(2)->isPointerTy())
1006 setDoesNotCapture(F, 3);
1008 case LibFunc::fread:
1009 case LibFunc::fwrite:
1010 if (FTy->getNumParams() != 4 ||
1011 !FTy->getParamType(0)->isPointerTy() ||
1012 !FTy->getParamType(3)->isPointerTy())
1015 setDoesNotCapture(F, 1);
1016 setDoesNotCapture(F, 4);
1018 case LibFunc::fputs:
1019 case LibFunc::fscanf:
1020 case LibFunc::fprintf:
1021 case LibFunc::fgetpos:
1022 if (FTy->getNumParams() < 2 ||
1023 !FTy->getParamType(0)->isPointerTy() ||
1024 !FTy->getParamType(1)->isPointerTy())
1027 setDoesNotCapture(F, 1);
1028 setDoesNotCapture(F, 2);
1031 case LibFunc::getlogin_r:
1032 case LibFunc::getc_unlocked:
1033 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1036 setDoesNotCapture(F, 1);
1038 case LibFunc::getenv:
1039 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1042 setOnlyReadsMemory(F);
1043 setDoesNotCapture(F, 1);
1046 case LibFunc::getchar:
1049 case LibFunc::getitimer:
1050 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1053 setDoesNotCapture(F, 2);
1055 case LibFunc::getpwnam:
1056 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1059 setDoesNotCapture(F, 1);
1061 case LibFunc::ungetc:
1062 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1065 setDoesNotCapture(F, 2);
1067 case LibFunc::uname:
1068 case LibFunc::unlink:
1069 case LibFunc::unsetenv:
1070 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1073 setDoesNotCapture(F, 1);
1075 case LibFunc::utime:
1076 case LibFunc::utimes:
1077 if (FTy->getNumParams() != 2 ||
1078 !FTy->getParamType(0)->isPointerTy() ||
1079 !FTy->getParamType(1)->isPointerTy())
1082 setDoesNotCapture(F, 1);
1083 setDoesNotCapture(F, 2);
1086 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1089 setDoesNotCapture(F, 2);
1092 case LibFunc::printf:
1093 case LibFunc::perror:
1094 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1097 setDoesNotCapture(F, 1);
1099 case LibFunc::pread:
1100 case LibFunc::pwrite:
1101 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1103 // May throw; these are valid pthread cancellation points.
1104 setDoesNotCapture(F, 2);
1106 case LibFunc::putchar:
1109 case LibFunc::popen:
1110 if (FTy->getNumParams() != 2 ||
1111 !FTy->getReturnType()->isPointerTy() ||
1112 !FTy->getParamType(0)->isPointerTy() ||
1113 !FTy->getParamType(1)->isPointerTy())
1116 setDoesNotAlias(F, 0);
1117 setDoesNotCapture(F, 1);
1118 setDoesNotCapture(F, 2);
1120 case LibFunc::pclose:
1121 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1124 setDoesNotCapture(F, 1);
1126 case LibFunc::vscanf:
1127 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1130 setDoesNotCapture(F, 1);
1132 case LibFunc::vsscanf:
1133 case LibFunc::vfscanf:
1134 if (FTy->getNumParams() != 3 ||
1135 !FTy->getParamType(1)->isPointerTy() ||
1136 !FTy->getParamType(2)->isPointerTy())
1139 setDoesNotCapture(F, 1);
1140 setDoesNotCapture(F, 2);
1142 case LibFunc::valloc:
1143 if (!FTy->getReturnType()->isPointerTy())
1146 setDoesNotAlias(F, 0);
1148 case LibFunc::vprintf:
1149 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1152 setDoesNotCapture(F, 1);
1154 case LibFunc::vfprintf:
1155 case LibFunc::vsprintf:
1156 if (FTy->getNumParams() != 3 ||
1157 !FTy->getParamType(0)->isPointerTy() ||
1158 !FTy->getParamType(1)->isPointerTy())
1161 setDoesNotCapture(F, 1);
1162 setDoesNotCapture(F, 2);
1164 case LibFunc::vsnprintf:
1165 if (FTy->getNumParams() != 4 ||
1166 !FTy->getParamType(0)->isPointerTy() ||
1167 !FTy->getParamType(2)->isPointerTy())
1170 setDoesNotCapture(F, 1);
1171 setDoesNotCapture(F, 3);
1174 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1176 // May throw; "open" is a valid pthread cancellation point.
1177 setDoesNotCapture(F, 1);
1179 case LibFunc::opendir:
1180 if (FTy->getNumParams() != 1 ||
1181 !FTy->getReturnType()->isPointerTy() ||
1182 !FTy->getParamType(0)->isPointerTy())
1185 setDoesNotAlias(F, 0);
1186 setDoesNotCapture(F, 1);
1188 case LibFunc::tmpfile:
1189 if (!FTy->getReturnType()->isPointerTy())
1192 setDoesNotAlias(F, 0);
1194 case LibFunc::times:
1195 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1198 setDoesNotCapture(F, 1);
1200 case LibFunc::htonl:
1201 case LibFunc::htons:
1202 case LibFunc::ntohl:
1203 case LibFunc::ntohs:
1205 setDoesNotAccessMemory(F);
1207 case LibFunc::lstat:
1208 if (FTy->getNumParams() != 2 ||
1209 !FTy->getParamType(0)->isPointerTy() ||
1210 !FTy->getParamType(1)->isPointerTy())
1213 setDoesNotCapture(F, 1);
1214 setDoesNotCapture(F, 2);
1216 case LibFunc::lchown:
1217 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1220 setDoesNotCapture(F, 1);
1222 case LibFunc::qsort:
1223 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1225 // May throw; places call through function pointer.
1226 setDoesNotCapture(F, 4);
1228 case LibFunc::dunder_strdup:
1229 case LibFunc::dunder_strndup:
1230 if (FTy->getNumParams() < 1 ||
1231 !FTy->getReturnType()->isPointerTy() ||
1232 !FTy->getParamType(0)->isPointerTy())
1235 setDoesNotAlias(F, 0);
1236 setDoesNotCapture(F, 1);
1238 case LibFunc::dunder_strtok_r:
1239 if (FTy->getNumParams() != 3 ||
1240 !FTy->getParamType(1)->isPointerTy())
1243 setDoesNotCapture(F, 2);
1245 case LibFunc::under_IO_getc:
1246 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1249 setDoesNotCapture(F, 1);
1251 case LibFunc::under_IO_putc:
1252 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1255 setDoesNotCapture(F, 2);
1257 case LibFunc::dunder_isoc99_scanf:
1258 if (FTy->getNumParams() < 1 ||
1259 !FTy->getParamType(0)->isPointerTy())
1262 setDoesNotCapture(F, 1);
1264 case LibFunc::stat64:
1265 case LibFunc::lstat64:
1266 case LibFunc::statvfs64:
1267 case LibFunc::dunder_isoc99_sscanf:
1268 if (FTy->getNumParams() < 1 ||
1269 !FTy->getParamType(0)->isPointerTy() ||
1270 !FTy->getParamType(1)->isPointerTy())
1273 setDoesNotCapture(F, 1);
1274 setDoesNotCapture(F, 2);
1276 case LibFunc::fopen64:
1277 if (FTy->getNumParams() != 2 ||
1278 !FTy->getReturnType()->isPointerTy() ||
1279 !FTy->getParamType(0)->isPointerTy() ||
1280 !FTy->getParamType(1)->isPointerTy())
1283 setDoesNotAlias(F, 0);
1284 setDoesNotCapture(F, 1);
1285 setDoesNotCapture(F, 2);
1287 case LibFunc::fseeko64:
1288 case LibFunc::ftello64:
1289 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1292 setDoesNotCapture(F, 1);
1294 case LibFunc::tmpfile64:
1295 if (!FTy->getReturnType()->isPointerTy())
1298 setDoesNotAlias(F, 0);
1300 case LibFunc::fstat64:
1301 case LibFunc::fstatvfs64:
1302 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1305 setDoesNotCapture(F, 2);
1307 case LibFunc::open64:
1308 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1310 // May throw; "open" is a valid pthread cancellation point.
1311 setDoesNotCapture(F, 1);
1313 case LibFunc::gettimeofday:
1314 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1315 !FTy->getParamType(1)->isPointerTy())
1317 // Currently some platforms have the restrict keyword on the arguments to
1318 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1321 setDoesNotCapture(F, 1);
1322 setDoesNotCapture(F, 2);
1324 // Didn't mark any attributes.
1331 /// annotateLibraryCalls - Adds attributes to well-known standard library
1332 /// call declarations.
1333 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1334 bool MadeChange = false;
1336 // Check each function in turn annotating well-known library function
1337 // declarations with attributes.
1338 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1339 Function *F = (*I)->getFunction();
1341 if (F != 0 && F->isDeclaration())
1342 MadeChange |= inferPrototypeAttributes(*F);
1348 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1349 AA = &getAnalysis<AliasAnalysis>();
1350 TLI = &getAnalysis<TargetLibraryInfo>();
1352 bool Changed = annotateLibraryCalls(SCC);
1353 Changed |= AddReadAttrs(SCC);
1354 Changed |= AddNoCaptureAttrs(SCC);
1355 Changed |= AddNoAliasAttrs(SCC);