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. It does the
13 // same with function arguments independently, marking them readonly/
14 // readnone/nocapture. Finally, well-known library call declarations
15 // are marked with all attributes that are consistent with the
16 // function's standard definition. This pass is implemented as a
17 // bottom-up traversal of the call-graph.
19 //===----------------------------------------------------------------------===//
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/AssumptionCache.h"
28 #include "llvm/Analysis/BasicAliasAnalysis.h"
29 #include "llvm/Analysis/CallGraph.h"
30 #include "llvm/Analysis/CallGraphSCCPass.h"
31 #include "llvm/Analysis/CaptureTracking.h"
32 #include "llvm/Analysis/TargetLibraryInfo.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/InstIterator.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Analysis/TargetLibraryInfo.h"
43 #define DEBUG_TYPE "functionattrs"
45 STATISTIC(NumReadNone, "Number of functions marked readnone");
46 STATISTIC(NumReadOnly, "Number of functions marked readonly");
47 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
48 STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
49 STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
50 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
51 STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
52 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
55 struct FunctionAttrs : public CallGraphSCCPass {
56 static char ID; // Pass identification, replacement for typeid
57 FunctionAttrs() : CallGraphSCCPass(ID) {
58 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
61 // runOnSCC - Analyze the SCC, performing the transformation if possible.
62 bool runOnSCC(CallGraphSCC &SCC) override;
64 // AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
65 bool AddReadAttrs(const CallGraphSCC &SCC);
67 // AddArgumentAttrs - Deduce nocapture attributes for the SCC.
68 bool AddArgumentAttrs(const CallGraphSCC &SCC);
70 // IsFunctionMallocLike - Does this function allocate new memory?
71 bool IsFunctionMallocLike(Function *F, SmallPtrSet<Function *, 8> &) const;
73 // AddNoAliasAttrs - Deduce noalias attributes for the SCC.
74 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
76 /// \brief Does this function return null?
77 bool ReturnsNonNull(Function *F, SmallPtrSet<Function *, 8> &,
78 bool &Speculative) const;
80 /// \brief Deduce nonnull attributes for the SCC.
81 bool AddNonNullAttrs(const CallGraphSCC &SCC);
83 // Utility methods used by inferPrototypeAttributes to add attributes
84 // and maintain annotation statistics.
86 void setDoesNotAccessMemory(Function &F) {
87 if (!F.doesNotAccessMemory()) {
88 F.setDoesNotAccessMemory();
93 void setOnlyReadsMemory(Function &F) {
94 if (!F.onlyReadsMemory()) {
95 F.setOnlyReadsMemory();
100 void setDoesNotThrow(Function &F) {
101 if (!F.doesNotThrow()) {
107 void setDoesNotCapture(Function &F, unsigned n) {
108 if (!F.doesNotCapture(n)) {
109 F.setDoesNotCapture(n);
114 void setOnlyReadsMemory(Function &F, unsigned n) {
115 if (!F.onlyReadsMemory(n)) {
116 F.setOnlyReadsMemory(n);
121 void setDoesNotAlias(Function &F, unsigned n) {
122 if (!F.doesNotAlias(n)) {
123 F.setDoesNotAlias(n);
128 // inferPrototypeAttributes - Analyze the name and prototype of the
129 // given function and set any applicable attributes. Returns true
130 // if any attributes were set and false otherwise.
131 bool inferPrototypeAttributes(Function &F);
133 // annotateLibraryCalls - Adds attributes to well-known standard library
134 // call declarations.
135 bool annotateLibraryCalls(const CallGraphSCC &SCC);
137 void getAnalysisUsage(AnalysisUsage &AU) const override {
138 AU.setPreservesCFG();
139 AU.addRequired<AssumptionCacheTracker>();
140 AU.addRequired<TargetLibraryInfoWrapperPass>();
141 CallGraphSCCPass::getAnalysisUsage(AU);
145 TargetLibraryInfo *TLI;
149 char FunctionAttrs::ID = 0;
150 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
151 "Deduce function attributes", false, false)
152 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
153 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
154 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
155 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
156 "Deduce function attributes", false, false)
158 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
160 /// AddReadAttrs - Deduce readonly/readnone attributes for the SCC.
161 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
162 SmallPtrSet<Function *, 8> SCCNodes;
164 // Fill SCCNodes with the elements of the SCC. Used for quickly
165 // looking up whether a given CallGraphNode is in this SCC.
166 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
167 SCCNodes.insert((*I)->getFunction());
169 // Check if any of the functions in the SCC read or write memory. If they
170 // write memory then they can't be marked readnone or readonly.
171 bool ReadsMemory = false;
172 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
173 Function *F = (*I)->getFunction();
175 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
176 // External node or node we don't want to optimize - assume it may write
177 // memory and give up.
180 // We need to manually construct BasicAA directly in order to disable its
181 // use of other function analyses.
182 BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F));
184 // Construct our own AA results for this function. We do this manually to
185 // work around the limitations of the legacy pass manager.
186 AAResults AAR(createLegacyPMAAResults(*this, *F, BAR));
188 FunctionModRefBehavior MRB = AAR.getModRefBehavior(F);
189 if (MRB == FMRB_DoesNotAccessMemory)
193 // Definitions with weak linkage may be overridden at linktime with
194 // something that writes memory, so treat them like declarations.
195 if (F->isDeclaration() || F->mayBeOverridden()) {
196 if (!AliasAnalysis::onlyReadsMemory(MRB))
197 // May write memory. Just give up.
204 // Scan the function body for instructions that may read or write memory.
205 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
206 Instruction *I = &*II;
208 // Some instructions can be ignored even if they read or write memory.
209 // Detect these now, skipping to the next instruction if one is found.
210 CallSite CS(cast<Value>(I));
212 // Ignore calls to functions in the same SCC.
213 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
215 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
216 // If the call doesn't access arbitrary memory, we may be able to
217 // figure out something.
218 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
219 // If the call does access argument pointees, check each argument.
220 if (AliasAnalysis::doesAccessArgPointees(MRB))
221 // Check whether all pointer arguments point to local memory, and
222 // ignore calls that only access local memory.
223 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
226 if (Arg->getType()->isPointerTy()) {
228 I->getAAMetadata(AAInfo);
230 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
231 if (!AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
233 // Writes non-local memory. Give up.
236 // Ok, it reads non-local memory.
243 // The call could access any memory. If that includes writes, give up.
246 // If it reads, note it.
250 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
251 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
252 if (!LI->isVolatile()) {
253 MemoryLocation Loc = MemoryLocation::get(LI);
254 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
257 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
258 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
259 if (!SI->isVolatile()) {
260 MemoryLocation Loc = MemoryLocation::get(SI);
261 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
264 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
265 // Ignore vaargs on local memory.
266 MemoryLocation Loc = MemoryLocation::get(VI);
267 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
271 // Any remaining instructions need to be taken seriously! Check if they
272 // read or write memory.
273 if (I->mayWriteToMemory())
274 // Writes memory. Just give up.
277 // If this instruction may read memory, remember that.
278 ReadsMemory |= I->mayReadFromMemory();
282 // Success! Functions in this SCC do not access memory, or only read memory.
283 // Give them the appropriate attribute.
284 bool MadeChange = false;
285 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
286 Function *F = (*I)->getFunction();
288 if (F->doesNotAccessMemory())
292 if (F->onlyReadsMemory() && ReadsMemory)
298 // Clear out any existing attributes.
300 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
302 AttributeSet::FunctionIndex,
303 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
305 // Add in the new attribute.
306 F->addAttribute(AttributeSet::FunctionIndex,
307 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
319 // For a given pointer Argument, this retains a list of Arguments of functions
320 // in the same SCC that the pointer data flows into. We use this to build an
321 // SCC of the arguments.
322 struct ArgumentGraphNode {
323 Argument *Definition;
324 SmallVector<ArgumentGraphNode *, 4> Uses;
327 class ArgumentGraph {
328 // We store pointers to ArgumentGraphNode objects, so it's important that
329 // that they not move around upon insert.
330 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
332 ArgumentMapTy ArgumentMap;
334 // There is no root node for the argument graph, in fact:
335 // void f(int *x, int *y) { if (...) f(x, y); }
336 // is an example where the graph is disconnected. The SCCIterator requires a
337 // single entry point, so we maintain a fake ("synthetic") root node that
338 // uses every node. Because the graph is directed and nothing points into
339 // the root, it will not participate in any SCCs (except for its own).
340 ArgumentGraphNode SyntheticRoot;
343 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
345 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
347 iterator begin() { return SyntheticRoot.Uses.begin(); }
348 iterator end() { return SyntheticRoot.Uses.end(); }
349 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
351 ArgumentGraphNode *operator[](Argument *A) {
352 ArgumentGraphNode &Node = ArgumentMap[A];
354 SyntheticRoot.Uses.push_back(&Node);
359 // This tracker checks whether callees are in the SCC, and if so it does not
360 // consider that a capture, instead adding it to the "Uses" list and
361 // continuing with the analysis.
362 struct ArgumentUsesTracker : public CaptureTracker {
363 ArgumentUsesTracker(const SmallPtrSet<Function *, 8> &SCCNodes)
364 : Captured(false), SCCNodes(SCCNodes) {}
366 void tooManyUses() override { Captured = true; }
368 bool captured(const Use *U) override {
369 CallSite CS(U->getUser());
370 if (!CS.getInstruction()) {
375 Function *F = CS.getCalledFunction();
376 if (!F || !SCCNodes.count(F)) {
382 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
383 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
384 PI != PE; ++PI, ++AI) {
386 assert(F->isVarArg() && "More params than args in non-varargs call");
396 assert(Found && "Capturing call-site captured nothing?");
401 bool Captured; // True only if certainly captured (used outside our SCC).
402 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
404 const SmallPtrSet<Function *, 8> &SCCNodes;
409 template <> struct GraphTraits<ArgumentGraphNode *> {
410 typedef ArgumentGraphNode NodeType;
411 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
413 static inline NodeType *getEntryNode(NodeType *A) { return A; }
414 static inline ChildIteratorType child_begin(NodeType *N) {
415 return N->Uses.begin();
417 static inline ChildIteratorType child_end(NodeType *N) {
418 return N->Uses.end();
422 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
423 static NodeType *getEntryNode(ArgumentGraph *AG) {
424 return AG->getEntryNode();
426 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
429 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
433 // Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
434 static Attribute::AttrKind
435 determinePointerReadAttrs(Argument *A,
436 const SmallPtrSet<Argument *, 8> &SCCNodes) {
438 SmallVector<Use *, 32> Worklist;
439 SmallSet<Use *, 32> Visited;
441 // inalloca arguments are always clobbered by the call.
442 if (A->hasInAllocaAttr())
443 return Attribute::None;
446 // We don't need to track IsWritten. If A is written to, return immediately.
448 for (Use &U : A->uses()) {
450 Worklist.push_back(&U);
453 while (!Worklist.empty()) {
454 Use *U = Worklist.pop_back_val();
455 Instruction *I = cast<Instruction>(U->getUser());
458 switch (I->getOpcode()) {
459 case Instruction::BitCast:
460 case Instruction::GetElementPtr:
461 case Instruction::PHI:
462 case Instruction::Select:
463 case Instruction::AddrSpaceCast:
464 // The original value is not read/written via this if the new value isn't.
465 for (Use &UU : I->uses())
466 if (Visited.insert(&UU).second)
467 Worklist.push_back(&UU);
470 case Instruction::Call:
471 case Instruction::Invoke: {
472 bool Captures = true;
474 if (I->getType()->isVoidTy())
477 auto AddUsersToWorklistIfCapturing = [&] {
479 for (Use &UU : I->uses())
480 if (Visited.insert(&UU).second)
481 Worklist.push_back(&UU);
485 if (CS.doesNotAccessMemory()) {
486 AddUsersToWorklistIfCapturing();
490 Function *F = CS.getCalledFunction();
492 if (CS.onlyReadsMemory()) {
494 AddUsersToWorklistIfCapturing();
497 return Attribute::None;
500 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
501 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
502 for (CallSite::arg_iterator A = B; A != E; ++A, ++AI) {
505 assert(F->isVarArg() &&
506 "More params than args in non-varargs call.");
507 return Attribute::None;
509 Captures &= !CS.doesNotCapture(A - B);
510 if (SCCNodes.count(AI))
512 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
513 return Attribute::None;
514 if (!CS.doesNotAccessMemory(A - B))
518 AddUsersToWorklistIfCapturing();
522 case Instruction::Load:
526 case Instruction::ICmp:
527 case Instruction::Ret:
531 return Attribute::None;
535 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
538 /// AddArgumentAttrs - Deduce nocapture attributes for the SCC.
539 bool FunctionAttrs::AddArgumentAttrs(const CallGraphSCC &SCC) {
540 bool Changed = false;
542 SmallPtrSet<Function *, 8> SCCNodes;
544 // Fill SCCNodes with the elements of the SCC. Used for quickly
545 // looking up whether a given CallGraphNode is in this SCC.
546 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
547 Function *F = (*I)->getFunction();
548 if (F && !F->isDeclaration() && !F->mayBeOverridden() &&
549 !F->hasFnAttribute(Attribute::OptimizeNone))
556 B.addAttribute(Attribute::NoCapture);
558 // Check each function in turn, determining which pointer arguments are not
560 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
561 Function *F = (*I)->getFunction();
563 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
564 // External node or function we're trying not to optimize - only a problem
565 // for arguments that we pass to it.
568 // Definitions with weak linkage may be overridden at linktime with
569 // something that captures pointers, so treat them like declarations.
570 if (F->isDeclaration() || F->mayBeOverridden())
573 // Functions that are readonly (or readnone) and nounwind and don't return
574 // a value can't capture arguments. Don't analyze them.
575 if (F->onlyReadsMemory() && F->doesNotThrow() &&
576 F->getReturnType()->isVoidTy()) {
577 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
579 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
580 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
588 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
590 if (!A->getType()->isPointerTy())
592 bool HasNonLocalUses = false;
593 if (!A->hasNoCaptureAttr()) {
594 ArgumentUsesTracker Tracker(SCCNodes);
595 PointerMayBeCaptured(A, &Tracker);
596 if (!Tracker.Captured) {
597 if (Tracker.Uses.empty()) {
598 // If it's trivially not captured, mark it nocapture now.
600 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
604 // If it's not trivially captured and not trivially not captured,
605 // then it must be calling into another function in our SCC. Save
606 // its particulars for Argument-SCC analysis later.
607 ArgumentGraphNode *Node = AG[A];
608 for (SmallVectorImpl<Argument *>::iterator
609 UI = Tracker.Uses.begin(),
610 UE = Tracker.Uses.end();
612 Node->Uses.push_back(AG[*UI]);
614 HasNonLocalUses = true;
618 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
620 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
621 // Can we determine that it's readonly/readnone without doing an SCC?
622 // Note that we don't allow any calls at all here, or else our result
623 // will be dependent on the iteration order through the functions in the
625 SmallPtrSet<Argument *, 8> Self;
627 Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
628 if (R != Attribute::None) {
631 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
633 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
639 // The graph we've collected is partial because we stopped scanning for
640 // argument uses once we solved the argument trivially. These partial nodes
641 // show up as ArgumentGraphNode objects with an empty Uses list, and for
642 // these nodes the final decision about whether they capture has already been
643 // made. If the definition doesn't have a 'nocapture' attribute by now, it
646 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
647 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
648 if (ArgumentSCC.size() == 1) {
649 if (!ArgumentSCC[0]->Definition)
650 continue; // synthetic root node
652 // eg. "void f(int* x) { if (...) f(x); }"
653 if (ArgumentSCC[0]->Uses.size() == 1 &&
654 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
655 Argument *A = ArgumentSCC[0]->Definition;
656 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
663 bool SCCCaptured = false;
664 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
665 I != E && !SCCCaptured; ++I) {
666 ArgumentGraphNode *Node = *I;
667 if (Node->Uses.empty()) {
668 if (!Node->Definition->hasNoCaptureAttr())
675 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
676 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
677 // quickly looking up whether a given Argument is in this ArgumentSCC.
678 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
679 ArgumentSCCNodes.insert((*I)->Definition);
682 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
683 I != E && !SCCCaptured; ++I) {
684 ArgumentGraphNode *N = *I;
685 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
688 Argument *A = (*UI)->Definition;
689 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
698 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
699 Argument *A = ArgumentSCC[i]->Definition;
700 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
705 // We also want to compute readonly/readnone. With a small number of false
706 // negatives, we can assume that any pointer which is captured isn't going
707 // to be provably readonly or readnone, since by definition we can't
708 // analyze all uses of a captured pointer.
710 // The false negatives happen when the pointer is captured by a function
711 // that promises readonly/readnone behaviour on the pointer, then the
712 // pointer's lifetime ends before anything that writes to arbitrary memory.
713 // Also, a readonly/readnone pointer may be returned, but returning a
714 // pointer is capturing it.
716 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
717 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
718 Argument *A = ArgumentSCC[i]->Definition;
719 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
720 if (K == Attribute::ReadNone)
722 if (K == Attribute::ReadOnly) {
723 ReadAttr = Attribute::ReadOnly;
730 if (ReadAttr != Attribute::None) {
732 B.addAttribute(ReadAttr);
733 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
734 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
735 Argument *A = ArgumentSCC[i]->Definition;
736 // Clear out existing readonly/readnone attributes
737 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
738 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
739 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
748 /// IsFunctionMallocLike - A function is malloc-like if it returns either null
749 /// or a pointer that doesn't alias any other pointer visible to the caller.
750 bool FunctionAttrs::IsFunctionMallocLike(
751 Function *F, SmallPtrSet<Function *, 8> &SCCNodes) const {
752 SmallSetVector<Value *, 8> FlowsToReturn;
753 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
754 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
755 FlowsToReturn.insert(Ret->getReturnValue());
757 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
758 Value *RetVal = FlowsToReturn[i];
760 if (Constant *C = dyn_cast<Constant>(RetVal)) {
761 if (!C->isNullValue() && !isa<UndefValue>(C))
767 if (isa<Argument>(RetVal))
770 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
771 switch (RVI->getOpcode()) {
772 // Extend the analysis by looking upwards.
773 case Instruction::BitCast:
774 case Instruction::GetElementPtr:
775 case Instruction::AddrSpaceCast:
776 FlowsToReturn.insert(RVI->getOperand(0));
778 case Instruction::Select: {
779 SelectInst *SI = cast<SelectInst>(RVI);
780 FlowsToReturn.insert(SI->getTrueValue());
781 FlowsToReturn.insert(SI->getFalseValue());
784 case Instruction::PHI: {
785 PHINode *PN = cast<PHINode>(RVI);
786 for (Value *IncValue : PN->incoming_values())
787 FlowsToReturn.insert(IncValue);
791 // Check whether the pointer came from an allocation.
792 case Instruction::Alloca:
794 case Instruction::Call:
795 case Instruction::Invoke: {
797 if (CS.paramHasAttr(0, Attribute::NoAlias))
799 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
803 return false; // Did not come from an allocation.
806 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
813 /// AddNoAliasAttrs - Deduce noalias attributes for the SCC.
814 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
815 SmallPtrSet<Function *, 8> SCCNodes;
817 // Fill SCCNodes with the elements of the SCC. Used for quickly
818 // looking up whether a given CallGraphNode is in this SCC.
819 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
820 SCCNodes.insert((*I)->getFunction());
822 // Check each function in turn, determining which functions return noalias
824 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
825 Function *F = (*I)->getFunction();
827 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
828 // External node or node we don't want to optimize - skip it;
832 if (F->doesNotAlias(0))
835 // Definitions with weak linkage may be overridden at linktime, so
836 // treat them like declarations.
837 if (F->isDeclaration() || F->mayBeOverridden())
840 // We annotate noalias return values, which are only applicable to
842 if (!F->getReturnType()->isPointerTy())
845 if (!IsFunctionMallocLike(F, SCCNodes))
849 bool MadeChange = false;
850 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
851 Function *F = (*I)->getFunction();
852 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
855 F->setDoesNotAlias(0);
863 bool FunctionAttrs::ReturnsNonNull(Function *F,
864 SmallPtrSet<Function *, 8> &SCCNodes,
865 bool &Speculative) const {
866 assert(F->getReturnType()->isPointerTy() &&
867 "nonnull only meaningful on pointer types");
870 SmallSetVector<Value *, 8> FlowsToReturn;
871 for (BasicBlock &BB : *F)
872 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
873 FlowsToReturn.insert(Ret->getReturnValue());
875 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
876 Value *RetVal = FlowsToReturn[i];
878 // If this value is locally known to be non-null, we're good
879 if (isKnownNonNull(RetVal, TLI))
882 // Otherwise, we need to look upwards since we can't make any local
884 Instruction *RVI = dyn_cast<Instruction>(RetVal);
887 switch (RVI->getOpcode()) {
888 // Extend the analysis by looking upwards.
889 case Instruction::BitCast:
890 case Instruction::GetElementPtr:
891 case Instruction::AddrSpaceCast:
892 FlowsToReturn.insert(RVI->getOperand(0));
894 case Instruction::Select: {
895 SelectInst *SI = cast<SelectInst>(RVI);
896 FlowsToReturn.insert(SI->getTrueValue());
897 FlowsToReturn.insert(SI->getFalseValue());
900 case Instruction::PHI: {
901 PHINode *PN = cast<PHINode>(RVI);
902 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
903 FlowsToReturn.insert(PN->getIncomingValue(i));
906 case Instruction::Call:
907 case Instruction::Invoke: {
909 Function *Callee = CS.getCalledFunction();
910 // A call to a node within the SCC is assumed to return null until
912 if (Callee && SCCNodes.count(Callee)) {
919 return false; // Unknown source, may be null
921 llvm_unreachable("should have either continued or returned");
927 bool FunctionAttrs::AddNonNullAttrs(const CallGraphSCC &SCC) {
928 SmallPtrSet<Function *, 8> SCCNodes;
930 // Fill SCCNodes with the elements of the SCC. Used for quickly
931 // looking up whether a given CallGraphNode is in this SCC.
932 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
933 SCCNodes.insert((*I)->getFunction());
935 // Speculative that all functions in the SCC return only nonnull
936 // pointers. We may refute this as we analyze functions.
937 bool SCCReturnsNonNull = true;
939 bool MadeChange = false;
941 // Check each function in turn, determining which functions return nonnull
943 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
944 Function *F = (*I)->getFunction();
946 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
947 // External node or node we don't want to optimize - skip it;
951 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
955 // Definitions with weak linkage may be overridden at linktime, so
956 // treat them like declarations.
957 if (F->isDeclaration() || F->mayBeOverridden())
960 // We annotate nonnull return values, which are only applicable to
962 if (!F->getReturnType()->isPointerTy())
965 bool Speculative = false;
966 if (ReturnsNonNull(F, SCCNodes, Speculative)) {
968 // Mark the function eagerly since we may discover a function
969 // which prevents us from speculating about the entire SCC
970 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
971 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
977 // At least one function returns something which could be null, can't
978 // speculate any more.
979 SCCReturnsNonNull = false;
982 if (SCCReturnsNonNull) {
983 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
984 Function *F = (*I)->getFunction();
985 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
986 Attribute::NonNull) ||
987 !F->getReturnType()->isPointerTy())
990 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
991 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
1000 /// inferPrototypeAttributes - Analyze the name and prototype of the
1001 /// given function and set any applicable attributes. Returns true
1002 /// if any attributes were set and false otherwise.
1003 bool FunctionAttrs::inferPrototypeAttributes(Function &F) {
1004 if (F.hasFnAttribute(Attribute::OptimizeNone))
1007 FunctionType *FTy = F.getFunctionType();
1008 LibFunc::Func TheLibFunc;
1009 if (!(TLI->getLibFunc(F.getName(), TheLibFunc) && TLI->has(TheLibFunc)))
1012 switch (TheLibFunc) {
1013 case LibFunc::strlen:
1014 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1016 setOnlyReadsMemory(F);
1018 setDoesNotCapture(F, 1);
1020 case LibFunc::strchr:
1021 case LibFunc::strrchr:
1022 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1023 !FTy->getParamType(1)->isIntegerTy())
1025 setOnlyReadsMemory(F);
1028 case LibFunc::strtol:
1029 case LibFunc::strtod:
1030 case LibFunc::strtof:
1031 case LibFunc::strtoul:
1032 case LibFunc::strtoll:
1033 case LibFunc::strtold:
1034 case LibFunc::strtoull:
1035 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1038 setDoesNotCapture(F, 2);
1039 setOnlyReadsMemory(F, 1);
1041 case LibFunc::strcpy:
1042 case LibFunc::stpcpy:
1043 case LibFunc::strcat:
1044 case LibFunc::strncat:
1045 case LibFunc::strncpy:
1046 case LibFunc::stpncpy:
1047 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1050 setDoesNotCapture(F, 2);
1051 setOnlyReadsMemory(F, 2);
1053 case LibFunc::strxfrm:
1054 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1055 !FTy->getParamType(1)->isPointerTy())
1058 setDoesNotCapture(F, 1);
1059 setDoesNotCapture(F, 2);
1060 setOnlyReadsMemory(F, 2);
1062 case LibFunc::strcmp: // 0,1
1063 case LibFunc::strspn: // 0,1
1064 case LibFunc::strncmp: // 0,1
1065 case LibFunc::strcspn: // 0,1
1066 case LibFunc::strcoll: // 0,1
1067 case LibFunc::strcasecmp: // 0,1
1068 case LibFunc::strncasecmp: //
1069 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1070 !FTy->getParamType(1)->isPointerTy())
1072 setOnlyReadsMemory(F);
1074 setDoesNotCapture(F, 1);
1075 setDoesNotCapture(F, 2);
1077 case LibFunc::strstr:
1078 case LibFunc::strpbrk:
1079 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1081 setOnlyReadsMemory(F);
1083 setDoesNotCapture(F, 2);
1085 case LibFunc::strtok:
1086 case LibFunc::strtok_r:
1087 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1090 setDoesNotCapture(F, 2);
1091 setOnlyReadsMemory(F, 2);
1093 case LibFunc::scanf:
1094 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1097 setDoesNotCapture(F, 1);
1098 setOnlyReadsMemory(F, 1);
1100 case LibFunc::setbuf:
1101 case LibFunc::setvbuf:
1102 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1105 setDoesNotCapture(F, 1);
1107 case LibFunc::strdup:
1108 case LibFunc::strndup:
1109 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1110 !FTy->getParamType(0)->isPointerTy())
1113 setDoesNotAlias(F, 0);
1114 setDoesNotCapture(F, 1);
1115 setOnlyReadsMemory(F, 1);
1118 case LibFunc::statvfs:
1119 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1120 !FTy->getParamType(1)->isPointerTy())
1123 setDoesNotCapture(F, 1);
1124 setDoesNotCapture(F, 2);
1125 setOnlyReadsMemory(F, 1);
1127 case LibFunc::sscanf:
1128 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1129 !FTy->getParamType(1)->isPointerTy())
1132 setDoesNotCapture(F, 1);
1133 setDoesNotCapture(F, 2);
1134 setOnlyReadsMemory(F, 1);
1135 setOnlyReadsMemory(F, 2);
1137 case LibFunc::sprintf:
1138 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1139 !FTy->getParamType(1)->isPointerTy())
1142 setDoesNotCapture(F, 1);
1143 setDoesNotCapture(F, 2);
1144 setOnlyReadsMemory(F, 2);
1146 case LibFunc::snprintf:
1147 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1148 !FTy->getParamType(2)->isPointerTy())
1151 setDoesNotCapture(F, 1);
1152 setDoesNotCapture(F, 3);
1153 setOnlyReadsMemory(F, 3);
1155 case LibFunc::setitimer:
1156 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1157 !FTy->getParamType(2)->isPointerTy())
1160 setDoesNotCapture(F, 2);
1161 setDoesNotCapture(F, 3);
1162 setOnlyReadsMemory(F, 2);
1164 case LibFunc::system:
1165 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1167 // May throw; "system" is a valid pthread cancellation point.
1168 setDoesNotCapture(F, 1);
1169 setOnlyReadsMemory(F, 1);
1171 case LibFunc::malloc:
1172 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy())
1175 setDoesNotAlias(F, 0);
1177 case LibFunc::memcmp:
1178 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1179 !FTy->getParamType(1)->isPointerTy())
1181 setOnlyReadsMemory(F);
1183 setDoesNotCapture(F, 1);
1184 setDoesNotCapture(F, 2);
1186 case LibFunc::memchr:
1187 case LibFunc::memrchr:
1188 if (FTy->getNumParams() != 3)
1190 setOnlyReadsMemory(F);
1194 case LibFunc::modff:
1195 case LibFunc::modfl:
1196 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1199 setDoesNotCapture(F, 2);
1201 case LibFunc::memcpy:
1202 case LibFunc::memccpy:
1203 case LibFunc::memmove:
1204 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1207 setDoesNotCapture(F, 2);
1208 setOnlyReadsMemory(F, 2);
1210 case LibFunc::memalign:
1211 if (!FTy->getReturnType()->isPointerTy())
1213 setDoesNotAlias(F, 0);
1215 case LibFunc::mkdir:
1216 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1219 setDoesNotCapture(F, 1);
1220 setOnlyReadsMemory(F, 1);
1222 case LibFunc::mktime:
1223 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1226 setDoesNotCapture(F, 1);
1228 case LibFunc::realloc:
1229 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1230 !FTy->getReturnType()->isPointerTy())
1233 setDoesNotAlias(F, 0);
1234 setDoesNotCapture(F, 1);
1237 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1239 // May throw; "read" is a valid pthread cancellation point.
1240 setDoesNotCapture(F, 2);
1242 case LibFunc::rewind:
1243 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1246 setDoesNotCapture(F, 1);
1248 case LibFunc::rmdir:
1249 case LibFunc::remove:
1250 case LibFunc::realpath:
1251 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1254 setDoesNotCapture(F, 1);
1255 setOnlyReadsMemory(F, 1);
1257 case LibFunc::rename:
1258 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1259 !FTy->getParamType(1)->isPointerTy())
1262 setDoesNotCapture(F, 1);
1263 setDoesNotCapture(F, 2);
1264 setOnlyReadsMemory(F, 1);
1265 setOnlyReadsMemory(F, 2);
1267 case LibFunc::readlink:
1268 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1269 !FTy->getParamType(1)->isPointerTy())
1272 setDoesNotCapture(F, 1);
1273 setDoesNotCapture(F, 2);
1274 setOnlyReadsMemory(F, 1);
1276 case LibFunc::write:
1277 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1279 // May throw; "write" is a valid pthread cancellation point.
1280 setDoesNotCapture(F, 2);
1281 setOnlyReadsMemory(F, 2);
1283 case LibFunc::bcopy:
1284 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1285 !FTy->getParamType(1)->isPointerTy())
1288 setDoesNotCapture(F, 1);
1289 setDoesNotCapture(F, 2);
1290 setOnlyReadsMemory(F, 1);
1293 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1294 !FTy->getParamType(1)->isPointerTy())
1297 setOnlyReadsMemory(F);
1298 setDoesNotCapture(F, 1);
1299 setDoesNotCapture(F, 2);
1301 case LibFunc::bzero:
1302 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1305 setDoesNotCapture(F, 1);
1307 case LibFunc::calloc:
1308 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy())
1311 setDoesNotAlias(F, 0);
1313 case LibFunc::chmod:
1314 case LibFunc::chown:
1315 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1318 setDoesNotCapture(F, 1);
1319 setOnlyReadsMemory(F, 1);
1321 case LibFunc::ctermid:
1322 case LibFunc::clearerr:
1323 case LibFunc::closedir:
1324 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1327 setDoesNotCapture(F, 1);
1332 case LibFunc::atoll:
1333 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1336 setOnlyReadsMemory(F);
1337 setDoesNotCapture(F, 1);
1339 case LibFunc::access:
1340 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1343 setDoesNotCapture(F, 1);
1344 setOnlyReadsMemory(F, 1);
1346 case LibFunc::fopen:
1347 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1348 !FTy->getParamType(0)->isPointerTy() ||
1349 !FTy->getParamType(1)->isPointerTy())
1352 setDoesNotAlias(F, 0);
1353 setDoesNotCapture(F, 1);
1354 setDoesNotCapture(F, 2);
1355 setOnlyReadsMemory(F, 1);
1356 setOnlyReadsMemory(F, 2);
1358 case LibFunc::fdopen:
1359 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1360 !FTy->getParamType(1)->isPointerTy())
1363 setDoesNotAlias(F, 0);
1364 setDoesNotCapture(F, 2);
1365 setOnlyReadsMemory(F, 2);
1369 case LibFunc::fseek:
1370 case LibFunc::ftell:
1371 case LibFunc::fgetc:
1372 case LibFunc::fseeko:
1373 case LibFunc::ftello:
1374 case LibFunc::fileno:
1375 case LibFunc::fflush:
1376 case LibFunc::fclose:
1377 case LibFunc::fsetpos:
1378 case LibFunc::flockfile:
1379 case LibFunc::funlockfile:
1380 case LibFunc::ftrylockfile:
1381 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1384 setDoesNotCapture(F, 1);
1386 case LibFunc::ferror:
1387 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1390 setDoesNotCapture(F, 1);
1391 setOnlyReadsMemory(F);
1393 case LibFunc::fputc:
1394 case LibFunc::fstat:
1395 case LibFunc::frexp:
1396 case LibFunc::frexpf:
1397 case LibFunc::frexpl:
1398 case LibFunc::fstatvfs:
1399 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1402 setDoesNotCapture(F, 2);
1404 case LibFunc::fgets:
1405 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1406 !FTy->getParamType(2)->isPointerTy())
1409 setDoesNotCapture(F, 3);
1411 case LibFunc::fread:
1412 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1413 !FTy->getParamType(3)->isPointerTy())
1416 setDoesNotCapture(F, 1);
1417 setDoesNotCapture(F, 4);
1419 case LibFunc::fwrite:
1420 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1421 !FTy->getParamType(3)->isPointerTy())
1424 setDoesNotCapture(F, 1);
1425 setDoesNotCapture(F, 4);
1427 case LibFunc::fputs:
1428 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1429 !FTy->getParamType(1)->isPointerTy())
1432 setDoesNotCapture(F, 1);
1433 setDoesNotCapture(F, 2);
1434 setOnlyReadsMemory(F, 1);
1436 case LibFunc::fscanf:
1437 case LibFunc::fprintf:
1438 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1439 !FTy->getParamType(1)->isPointerTy())
1442 setDoesNotCapture(F, 1);
1443 setDoesNotCapture(F, 2);
1444 setOnlyReadsMemory(F, 2);
1446 case LibFunc::fgetpos:
1447 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1448 !FTy->getParamType(1)->isPointerTy())
1451 setDoesNotCapture(F, 1);
1452 setDoesNotCapture(F, 2);
1455 case LibFunc::getlogin_r:
1456 case LibFunc::getc_unlocked:
1457 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1460 setDoesNotCapture(F, 1);
1462 case LibFunc::getenv:
1463 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1466 setOnlyReadsMemory(F);
1467 setDoesNotCapture(F, 1);
1470 case LibFunc::getchar:
1473 case LibFunc::getitimer:
1474 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1477 setDoesNotCapture(F, 2);
1479 case LibFunc::getpwnam:
1480 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1483 setDoesNotCapture(F, 1);
1484 setOnlyReadsMemory(F, 1);
1486 case LibFunc::ungetc:
1487 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1490 setDoesNotCapture(F, 2);
1492 case LibFunc::uname:
1493 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1496 setDoesNotCapture(F, 1);
1498 case LibFunc::unlink:
1499 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1502 setDoesNotCapture(F, 1);
1503 setOnlyReadsMemory(F, 1);
1505 case LibFunc::unsetenv:
1506 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1509 setDoesNotCapture(F, 1);
1510 setOnlyReadsMemory(F, 1);
1512 case LibFunc::utime:
1513 case LibFunc::utimes:
1514 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1515 !FTy->getParamType(1)->isPointerTy())
1518 setDoesNotCapture(F, 1);
1519 setDoesNotCapture(F, 2);
1520 setOnlyReadsMemory(F, 1);
1521 setOnlyReadsMemory(F, 2);
1524 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1527 setDoesNotCapture(F, 2);
1530 case LibFunc::printf:
1531 case LibFunc::perror:
1532 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1535 setDoesNotCapture(F, 1);
1536 setOnlyReadsMemory(F, 1);
1538 case LibFunc::pread:
1539 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1541 // May throw; "pread" is a valid pthread cancellation point.
1542 setDoesNotCapture(F, 2);
1544 case LibFunc::pwrite:
1545 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1547 // May throw; "pwrite" is a valid pthread cancellation point.
1548 setDoesNotCapture(F, 2);
1549 setOnlyReadsMemory(F, 2);
1551 case LibFunc::putchar:
1554 case LibFunc::popen:
1555 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1556 !FTy->getParamType(0)->isPointerTy() ||
1557 !FTy->getParamType(1)->isPointerTy())
1560 setDoesNotAlias(F, 0);
1561 setDoesNotCapture(F, 1);
1562 setDoesNotCapture(F, 2);
1563 setOnlyReadsMemory(F, 1);
1564 setOnlyReadsMemory(F, 2);
1566 case LibFunc::pclose:
1567 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1570 setDoesNotCapture(F, 1);
1572 case LibFunc::vscanf:
1573 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1576 setDoesNotCapture(F, 1);
1577 setOnlyReadsMemory(F, 1);
1579 case LibFunc::vsscanf:
1580 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1581 !FTy->getParamType(2)->isPointerTy())
1584 setDoesNotCapture(F, 1);
1585 setDoesNotCapture(F, 2);
1586 setOnlyReadsMemory(F, 1);
1587 setOnlyReadsMemory(F, 2);
1589 case LibFunc::vfscanf:
1590 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1591 !FTy->getParamType(2)->isPointerTy())
1594 setDoesNotCapture(F, 1);
1595 setDoesNotCapture(F, 2);
1596 setOnlyReadsMemory(F, 2);
1598 case LibFunc::valloc:
1599 if (!FTy->getReturnType()->isPointerTy())
1602 setDoesNotAlias(F, 0);
1604 case LibFunc::vprintf:
1605 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1608 setDoesNotCapture(F, 1);
1609 setOnlyReadsMemory(F, 1);
1611 case LibFunc::vfprintf:
1612 case LibFunc::vsprintf:
1613 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1614 !FTy->getParamType(1)->isPointerTy())
1617 setDoesNotCapture(F, 1);
1618 setDoesNotCapture(F, 2);
1619 setOnlyReadsMemory(F, 2);
1621 case LibFunc::vsnprintf:
1622 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1623 !FTy->getParamType(2)->isPointerTy())
1626 setDoesNotCapture(F, 1);
1627 setDoesNotCapture(F, 3);
1628 setOnlyReadsMemory(F, 3);
1631 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1633 // May throw; "open" is a valid pthread cancellation point.
1634 setDoesNotCapture(F, 1);
1635 setOnlyReadsMemory(F, 1);
1637 case LibFunc::opendir:
1638 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy() ||
1639 !FTy->getParamType(0)->isPointerTy())
1642 setDoesNotAlias(F, 0);
1643 setDoesNotCapture(F, 1);
1644 setOnlyReadsMemory(F, 1);
1646 case LibFunc::tmpfile:
1647 if (!FTy->getReturnType()->isPointerTy())
1650 setDoesNotAlias(F, 0);
1652 case LibFunc::times:
1653 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1656 setDoesNotCapture(F, 1);
1658 case LibFunc::htonl:
1659 case LibFunc::htons:
1660 case LibFunc::ntohl:
1661 case LibFunc::ntohs:
1663 setDoesNotAccessMemory(F);
1665 case LibFunc::lstat:
1666 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1667 !FTy->getParamType(1)->isPointerTy())
1670 setDoesNotCapture(F, 1);
1671 setDoesNotCapture(F, 2);
1672 setOnlyReadsMemory(F, 1);
1674 case LibFunc::lchown:
1675 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1678 setDoesNotCapture(F, 1);
1679 setOnlyReadsMemory(F, 1);
1681 case LibFunc::qsort:
1682 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1684 // May throw; places call through function pointer.
1685 setDoesNotCapture(F, 4);
1687 case LibFunc::dunder_strdup:
1688 case LibFunc::dunder_strndup:
1689 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1690 !FTy->getParamType(0)->isPointerTy())
1693 setDoesNotAlias(F, 0);
1694 setDoesNotCapture(F, 1);
1695 setOnlyReadsMemory(F, 1);
1697 case LibFunc::dunder_strtok_r:
1698 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1701 setDoesNotCapture(F, 2);
1702 setOnlyReadsMemory(F, 2);
1704 case LibFunc::under_IO_getc:
1705 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1708 setDoesNotCapture(F, 1);
1710 case LibFunc::under_IO_putc:
1711 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1714 setDoesNotCapture(F, 2);
1716 case LibFunc::dunder_isoc99_scanf:
1717 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1720 setDoesNotCapture(F, 1);
1721 setOnlyReadsMemory(F, 1);
1723 case LibFunc::stat64:
1724 case LibFunc::lstat64:
1725 case LibFunc::statvfs64:
1726 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1727 !FTy->getParamType(1)->isPointerTy())
1730 setDoesNotCapture(F, 1);
1731 setDoesNotCapture(F, 2);
1732 setOnlyReadsMemory(F, 1);
1734 case LibFunc::dunder_isoc99_sscanf:
1735 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1736 !FTy->getParamType(1)->isPointerTy())
1739 setDoesNotCapture(F, 1);
1740 setDoesNotCapture(F, 2);
1741 setOnlyReadsMemory(F, 1);
1742 setOnlyReadsMemory(F, 2);
1744 case LibFunc::fopen64:
1745 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1746 !FTy->getParamType(0)->isPointerTy() ||
1747 !FTy->getParamType(1)->isPointerTy())
1750 setDoesNotAlias(F, 0);
1751 setDoesNotCapture(F, 1);
1752 setDoesNotCapture(F, 2);
1753 setOnlyReadsMemory(F, 1);
1754 setOnlyReadsMemory(F, 2);
1756 case LibFunc::fseeko64:
1757 case LibFunc::ftello64:
1758 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1761 setDoesNotCapture(F, 1);
1763 case LibFunc::tmpfile64:
1764 if (!FTy->getReturnType()->isPointerTy())
1767 setDoesNotAlias(F, 0);
1769 case LibFunc::fstat64:
1770 case LibFunc::fstatvfs64:
1771 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1774 setDoesNotCapture(F, 2);
1776 case LibFunc::open64:
1777 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1779 // May throw; "open" is a valid pthread cancellation point.
1780 setDoesNotCapture(F, 1);
1781 setOnlyReadsMemory(F, 1);
1783 case LibFunc::gettimeofday:
1784 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1785 !FTy->getParamType(1)->isPointerTy())
1787 // Currently some platforms have the restrict keyword on the arguments to
1788 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1791 setDoesNotCapture(F, 1);
1792 setDoesNotCapture(F, 2);
1795 // Didn't mark any attributes.
1802 /// annotateLibraryCalls - Adds attributes to well-known standard library
1803 /// call declarations.
1804 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1805 bool MadeChange = false;
1807 // Check each function in turn annotating well-known library function
1808 // declarations with attributes.
1809 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1810 Function *F = (*I)->getFunction();
1812 if (F && F->isDeclaration())
1813 MadeChange |= inferPrototypeAttributes(*F);
1819 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1820 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1822 bool Changed = annotateLibraryCalls(SCC);
1823 Changed |= AddReadAttrs(SCC);
1824 Changed |= AddArgumentAttrs(SCC);
1825 Changed |= AddNoAliasAttrs(SCC);
1826 Changed |= AddNonNullAttrs(SCC);