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 bool runOnSCC(CallGraphSCC &SCC) override;
63 void getAnalysisUsage(AnalysisUsage &AU) const override {
65 AU.addRequired<AssumptionCacheTracker>();
66 AU.addRequired<TargetLibraryInfoWrapperPass>();
67 CallGraphSCCPass::getAnalysisUsage(AU);
71 TargetLibraryInfo *TLI;
73 bool AddReadAttrs(const CallGraphSCC &SCC);
74 bool AddArgumentAttrs(const CallGraphSCC &SCC);
75 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
76 bool AddNonNullAttrs(const CallGraphSCC &SCC);
77 bool annotateLibraryCalls(const CallGraphSCC &SCC);
81 char FunctionAttrs::ID = 0;
82 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
83 "Deduce function attributes", false, false)
84 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
85 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
86 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
87 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
88 "Deduce function attributes", false, false)
90 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
92 /// Deduce readonly/readnone attributes for the SCC.
93 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
94 SmallPtrSet<Function *, 8> SCCNodes;
96 // Fill SCCNodes with the elements of the SCC. Used for quickly
97 // looking up whether a given CallGraphNode is in this SCC.
98 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
99 SCCNodes.insert((*I)->getFunction());
101 // Check if any of the functions in the SCC read or write memory. If they
102 // write memory then they can't be marked readnone or readonly.
103 bool ReadsMemory = false;
104 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
105 Function *F = (*I)->getFunction();
107 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
108 // External node or node we don't want to optimize - assume it may write
109 // memory and give up.
112 // We need to manually construct BasicAA directly in order to disable its
113 // use of other function analyses.
114 BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F));
116 // Construct our own AA results for this function. We do this manually to
117 // work around the limitations of the legacy pass manager.
118 AAResults AAR(createLegacyPMAAResults(*this, *F, BAR));
120 FunctionModRefBehavior MRB = AAR.getModRefBehavior(F);
121 if (MRB == FMRB_DoesNotAccessMemory)
125 // Definitions with weak linkage may be overridden at linktime with
126 // something that writes memory, so treat them like declarations.
127 if (F->isDeclaration() || F->mayBeOverridden()) {
128 if (!AliasAnalysis::onlyReadsMemory(MRB))
129 // May write memory. Just give up.
136 // Scan the function body for instructions that may read or write memory.
137 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
138 Instruction *I = &*II;
140 // Some instructions can be ignored even if they read or write memory.
141 // Detect these now, skipping to the next instruction if one is found.
142 CallSite CS(cast<Value>(I));
144 // Ignore calls to functions in the same SCC.
145 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
147 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
148 // If the call doesn't access arbitrary memory, we may be able to
149 // figure out something.
150 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
151 // If the call does access argument pointees, check each argument.
152 if (AliasAnalysis::doesAccessArgPointees(MRB))
153 // Check whether all pointer arguments point to local memory, and
154 // ignore calls that only access local memory.
155 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
158 if (Arg->getType()->isPointerTy()) {
160 I->getAAMetadata(AAInfo);
162 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
163 if (!AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
165 // Writes non-local memory. Give up.
168 // Ok, it reads non-local memory.
175 // The call could access any memory. If that includes writes, give up.
178 // If it reads, note it.
182 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
183 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
184 if (!LI->isVolatile()) {
185 MemoryLocation Loc = MemoryLocation::get(LI);
186 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
189 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
190 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
191 if (!SI->isVolatile()) {
192 MemoryLocation Loc = MemoryLocation::get(SI);
193 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
196 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
197 // Ignore vaargs on local memory.
198 MemoryLocation Loc = MemoryLocation::get(VI);
199 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
203 // Any remaining instructions need to be taken seriously! Check if they
204 // read or write memory.
205 if (I->mayWriteToMemory())
206 // Writes memory. Just give up.
209 // If this instruction may read memory, remember that.
210 ReadsMemory |= I->mayReadFromMemory();
214 // Success! Functions in this SCC do not access memory, or only read memory.
215 // Give them the appropriate attribute.
216 bool MadeChange = false;
217 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
218 Function *F = (*I)->getFunction();
220 if (F->doesNotAccessMemory())
224 if (F->onlyReadsMemory() && ReadsMemory)
230 // Clear out any existing attributes.
232 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
234 AttributeSet::FunctionIndex,
235 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
237 // Add in the new attribute.
238 F->addAttribute(AttributeSet::FunctionIndex,
239 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
251 /// For a given pointer Argument, this retains a list of Arguments of functions
252 /// in the same SCC that the pointer data flows into. We use this to build an
253 /// SCC of the arguments.
254 struct ArgumentGraphNode {
255 Argument *Definition;
256 SmallVector<ArgumentGraphNode *, 4> Uses;
259 class ArgumentGraph {
260 // We store pointers to ArgumentGraphNode objects, so it's important that
261 // that they not move around upon insert.
262 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
264 ArgumentMapTy ArgumentMap;
266 // There is no root node for the argument graph, in fact:
267 // void f(int *x, int *y) { if (...) f(x, y); }
268 // is an example where the graph is disconnected. The SCCIterator requires a
269 // single entry point, so we maintain a fake ("synthetic") root node that
270 // uses every node. Because the graph is directed and nothing points into
271 // the root, it will not participate in any SCCs (except for its own).
272 ArgumentGraphNode SyntheticRoot;
275 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
277 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
279 iterator begin() { return SyntheticRoot.Uses.begin(); }
280 iterator end() { return SyntheticRoot.Uses.end(); }
281 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
283 ArgumentGraphNode *operator[](Argument *A) {
284 ArgumentGraphNode &Node = ArgumentMap[A];
286 SyntheticRoot.Uses.push_back(&Node);
291 /// This tracker checks whether callees are in the SCC, and if so it does not
292 /// consider that a capture, instead adding it to the "Uses" list and
293 /// continuing with the analysis.
294 struct ArgumentUsesTracker : public CaptureTracker {
295 ArgumentUsesTracker(const SmallPtrSet<Function *, 8> &SCCNodes)
296 : Captured(false), SCCNodes(SCCNodes) {}
298 void tooManyUses() override { Captured = true; }
300 bool captured(const Use *U) override {
301 CallSite CS(U->getUser());
302 if (!CS.getInstruction()) {
307 Function *F = CS.getCalledFunction();
308 if (!F || !SCCNodes.count(F)) {
314 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
315 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
316 PI != PE; ++PI, ++AI) {
318 assert(F->isVarArg() && "More params than args in non-varargs call");
328 assert(Found && "Capturing call-site captured nothing?");
333 bool Captured; // True only if certainly captured (used outside our SCC).
334 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
336 const SmallPtrSet<Function *, 8> &SCCNodes;
341 template <> struct GraphTraits<ArgumentGraphNode *> {
342 typedef ArgumentGraphNode NodeType;
343 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
345 static inline NodeType *getEntryNode(NodeType *A) { return A; }
346 static inline ChildIteratorType child_begin(NodeType *N) {
347 return N->Uses.begin();
349 static inline ChildIteratorType child_end(NodeType *N) {
350 return N->Uses.end();
354 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
355 static NodeType *getEntryNode(ArgumentGraph *AG) {
356 return AG->getEntryNode();
358 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
361 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
365 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
366 static Attribute::AttrKind
367 determinePointerReadAttrs(Argument *A,
368 const SmallPtrSet<Argument *, 8> &SCCNodes) {
370 SmallVector<Use *, 32> Worklist;
371 SmallSet<Use *, 32> Visited;
373 // inalloca arguments are always clobbered by the call.
374 if (A->hasInAllocaAttr())
375 return Attribute::None;
378 // We don't need to track IsWritten. If A is written to, return immediately.
380 for (Use &U : A->uses()) {
382 Worklist.push_back(&U);
385 while (!Worklist.empty()) {
386 Use *U = Worklist.pop_back_val();
387 Instruction *I = cast<Instruction>(U->getUser());
390 switch (I->getOpcode()) {
391 case Instruction::BitCast:
392 case Instruction::GetElementPtr:
393 case Instruction::PHI:
394 case Instruction::Select:
395 case Instruction::AddrSpaceCast:
396 // The original value is not read/written via this if the new value isn't.
397 for (Use &UU : I->uses())
398 if (Visited.insert(&UU).second)
399 Worklist.push_back(&UU);
402 case Instruction::Call:
403 case Instruction::Invoke: {
404 bool Captures = true;
406 if (I->getType()->isVoidTy())
409 auto AddUsersToWorklistIfCapturing = [&] {
411 for (Use &UU : I->uses())
412 if (Visited.insert(&UU).second)
413 Worklist.push_back(&UU);
417 if (CS.doesNotAccessMemory()) {
418 AddUsersToWorklistIfCapturing();
422 Function *F = CS.getCalledFunction();
424 if (CS.onlyReadsMemory()) {
426 AddUsersToWorklistIfCapturing();
429 return Attribute::None;
432 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
433 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
434 for (CallSite::arg_iterator A = B; A != E; ++A, ++AI) {
437 assert(F->isVarArg() &&
438 "More params than args in non-varargs call.");
439 return Attribute::None;
441 Captures &= !CS.doesNotCapture(A - B);
442 if (SCCNodes.count(AI))
444 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
445 return Attribute::None;
446 if (!CS.doesNotAccessMemory(A - B))
450 AddUsersToWorklistIfCapturing();
454 case Instruction::Load:
458 case Instruction::ICmp:
459 case Instruction::Ret:
463 return Attribute::None;
467 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
470 /// Deduce nocapture attributes for the SCC.
471 bool FunctionAttrs::AddArgumentAttrs(const CallGraphSCC &SCC) {
472 bool Changed = false;
474 SmallPtrSet<Function *, 8> SCCNodes;
476 // Fill SCCNodes with the elements of the SCC. Used for quickly
477 // looking up whether a given CallGraphNode is in this SCC.
478 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
479 Function *F = (*I)->getFunction();
480 if (F && !F->isDeclaration() && !F->mayBeOverridden() &&
481 !F->hasFnAttribute(Attribute::OptimizeNone))
488 B.addAttribute(Attribute::NoCapture);
490 // Check each function in turn, determining which pointer arguments are not
492 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
493 Function *F = (*I)->getFunction();
495 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
496 // External node or function we're trying not to optimize - only a problem
497 // for arguments that we pass to it.
500 // Definitions with weak linkage may be overridden at linktime with
501 // something that captures pointers, so treat them like declarations.
502 if (F->isDeclaration() || F->mayBeOverridden())
505 // Functions that are readonly (or readnone) and nounwind and don't return
506 // a value can't capture arguments. Don't analyze them.
507 if (F->onlyReadsMemory() && F->doesNotThrow() &&
508 F->getReturnType()->isVoidTy()) {
509 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
511 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
512 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
520 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
522 if (!A->getType()->isPointerTy())
524 bool HasNonLocalUses = false;
525 if (!A->hasNoCaptureAttr()) {
526 ArgumentUsesTracker Tracker(SCCNodes);
527 PointerMayBeCaptured(A, &Tracker);
528 if (!Tracker.Captured) {
529 if (Tracker.Uses.empty()) {
530 // If it's trivially not captured, mark it nocapture now.
532 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
536 // If it's not trivially captured and not trivially not captured,
537 // then it must be calling into another function in our SCC. Save
538 // its particulars for Argument-SCC analysis later.
539 ArgumentGraphNode *Node = AG[A];
540 for (SmallVectorImpl<Argument *>::iterator
541 UI = Tracker.Uses.begin(),
542 UE = Tracker.Uses.end();
544 Node->Uses.push_back(AG[*UI]);
546 HasNonLocalUses = true;
550 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
552 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
553 // Can we determine that it's readonly/readnone without doing an SCC?
554 // Note that we don't allow any calls at all here, or else our result
555 // will be dependent on the iteration order through the functions in the
557 SmallPtrSet<Argument *, 8> Self;
559 Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
560 if (R != Attribute::None) {
563 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
565 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
571 // The graph we've collected is partial because we stopped scanning for
572 // argument uses once we solved the argument trivially. These partial nodes
573 // show up as ArgumentGraphNode objects with an empty Uses list, and for
574 // these nodes the final decision about whether they capture has already been
575 // made. If the definition doesn't have a 'nocapture' attribute by now, it
578 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
579 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
580 if (ArgumentSCC.size() == 1) {
581 if (!ArgumentSCC[0]->Definition)
582 continue; // synthetic root node
584 // eg. "void f(int* x) { if (...) f(x); }"
585 if (ArgumentSCC[0]->Uses.size() == 1 &&
586 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
587 Argument *A = ArgumentSCC[0]->Definition;
588 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
595 bool SCCCaptured = false;
596 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
597 I != E && !SCCCaptured; ++I) {
598 ArgumentGraphNode *Node = *I;
599 if (Node->Uses.empty()) {
600 if (!Node->Definition->hasNoCaptureAttr())
607 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
608 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
609 // quickly looking up whether a given Argument is in this ArgumentSCC.
610 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
611 ArgumentSCCNodes.insert((*I)->Definition);
614 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
615 I != E && !SCCCaptured; ++I) {
616 ArgumentGraphNode *N = *I;
617 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
620 Argument *A = (*UI)->Definition;
621 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
630 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
631 Argument *A = ArgumentSCC[i]->Definition;
632 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
637 // We also want to compute readonly/readnone. With a small number of false
638 // negatives, we can assume that any pointer which is captured isn't going
639 // to be provably readonly or readnone, since by definition we can't
640 // analyze all uses of a captured pointer.
642 // The false negatives happen when the pointer is captured by a function
643 // that promises readonly/readnone behaviour on the pointer, then the
644 // pointer's lifetime ends before anything that writes to arbitrary memory.
645 // Also, a readonly/readnone pointer may be returned, but returning a
646 // pointer is capturing it.
648 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
649 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
650 Argument *A = ArgumentSCC[i]->Definition;
651 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
652 if (K == Attribute::ReadNone)
654 if (K == Attribute::ReadOnly) {
655 ReadAttr = Attribute::ReadOnly;
662 if (ReadAttr != Attribute::None) {
664 B.addAttribute(ReadAttr);
665 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
666 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
667 Argument *A = ArgumentSCC[i]->Definition;
668 // Clear out existing readonly/readnone attributes
669 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
670 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
671 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
680 /// Tests whether a function is "malloc-like".
682 /// A function is "malloc-like" if it returns either null or a pointer that
683 /// doesn't alias any other pointer visible to the caller.
684 static bool isFunctionMallocLike(Function *F,
685 SmallPtrSet<Function *, 8> &SCCNodes) {
686 SmallSetVector<Value *, 8> FlowsToReturn;
687 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
688 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
689 FlowsToReturn.insert(Ret->getReturnValue());
691 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
692 Value *RetVal = FlowsToReturn[i];
694 if (Constant *C = dyn_cast<Constant>(RetVal)) {
695 if (!C->isNullValue() && !isa<UndefValue>(C))
701 if (isa<Argument>(RetVal))
704 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
705 switch (RVI->getOpcode()) {
706 // Extend the analysis by looking upwards.
707 case Instruction::BitCast:
708 case Instruction::GetElementPtr:
709 case Instruction::AddrSpaceCast:
710 FlowsToReturn.insert(RVI->getOperand(0));
712 case Instruction::Select: {
713 SelectInst *SI = cast<SelectInst>(RVI);
714 FlowsToReturn.insert(SI->getTrueValue());
715 FlowsToReturn.insert(SI->getFalseValue());
718 case Instruction::PHI: {
719 PHINode *PN = cast<PHINode>(RVI);
720 for (Value *IncValue : PN->incoming_values())
721 FlowsToReturn.insert(IncValue);
725 // Check whether the pointer came from an allocation.
726 case Instruction::Alloca:
728 case Instruction::Call:
729 case Instruction::Invoke: {
731 if (CS.paramHasAttr(0, Attribute::NoAlias))
733 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
737 return false; // Did not come from an allocation.
740 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
747 /// Deduce noalias attributes for the SCC.
748 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
749 SmallPtrSet<Function *, 8> SCCNodes;
751 // Fill SCCNodes with the elements of the SCC. Used for quickly
752 // looking up whether a given CallGraphNode is in this SCC.
753 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
754 SCCNodes.insert((*I)->getFunction());
756 // Check each function in turn, determining which functions return noalias
758 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
759 Function *F = (*I)->getFunction();
761 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
762 // External node or node we don't want to optimize - skip it;
766 if (F->doesNotAlias(0))
769 // Definitions with weak linkage may be overridden at linktime, so
770 // treat them like declarations.
771 if (F->isDeclaration() || F->mayBeOverridden())
774 // We annotate noalias return values, which are only applicable to
776 if (!F->getReturnType()->isPointerTy())
779 if (!isFunctionMallocLike(F, SCCNodes))
783 bool MadeChange = false;
784 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
785 Function *F = (*I)->getFunction();
786 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
789 F->setDoesNotAlias(0);
797 /// Tests whether this function is known to not return null.
799 /// Requires that the function returns a pointer.
801 /// Returns true if it believes the function will not return a null, and sets
802 /// \p Speculative based on whether the returned conclusion is a speculative
803 /// conclusion due to SCC calls.
804 static bool isReturnNonNull(Function *F, SmallPtrSet<Function *, 8> &SCCNodes,
805 const TargetLibraryInfo &TLI, bool &Speculative) {
806 assert(F->getReturnType()->isPointerTy() &&
807 "nonnull only meaningful on pointer types");
810 SmallSetVector<Value *, 8> FlowsToReturn;
811 for (BasicBlock &BB : *F)
812 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
813 FlowsToReturn.insert(Ret->getReturnValue());
815 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
816 Value *RetVal = FlowsToReturn[i];
818 // If this value is locally known to be non-null, we're good
819 if (isKnownNonNull(RetVal, &TLI))
822 // Otherwise, we need to look upwards since we can't make any local
824 Instruction *RVI = dyn_cast<Instruction>(RetVal);
827 switch (RVI->getOpcode()) {
828 // Extend the analysis by looking upwards.
829 case Instruction::BitCast:
830 case Instruction::GetElementPtr:
831 case Instruction::AddrSpaceCast:
832 FlowsToReturn.insert(RVI->getOperand(0));
834 case Instruction::Select: {
835 SelectInst *SI = cast<SelectInst>(RVI);
836 FlowsToReturn.insert(SI->getTrueValue());
837 FlowsToReturn.insert(SI->getFalseValue());
840 case Instruction::PHI: {
841 PHINode *PN = cast<PHINode>(RVI);
842 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
843 FlowsToReturn.insert(PN->getIncomingValue(i));
846 case Instruction::Call:
847 case Instruction::Invoke: {
849 Function *Callee = CS.getCalledFunction();
850 // A call to a node within the SCC is assumed to return null until
852 if (Callee && SCCNodes.count(Callee)) {
859 return false; // Unknown source, may be null
861 llvm_unreachable("should have either continued or returned");
867 /// Deduce nonnull attributes for the SCC.
868 bool FunctionAttrs::AddNonNullAttrs(const CallGraphSCC &SCC) {
869 SmallPtrSet<Function *, 8> SCCNodes;
871 // Fill SCCNodes with the elements of the SCC. Used for quickly
872 // looking up whether a given CallGraphNode is in this SCC.
873 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
874 SCCNodes.insert((*I)->getFunction());
876 // Speculative that all functions in the SCC return only nonnull
877 // pointers. We may refute this as we analyze functions.
878 bool SCCReturnsNonNull = true;
880 bool MadeChange = false;
882 // Check each function in turn, determining which functions return nonnull
884 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
885 Function *F = (*I)->getFunction();
887 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
888 // External node or node we don't want to optimize - skip it;
892 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
896 // Definitions with weak linkage may be overridden at linktime, so
897 // treat them like declarations.
898 if (F->isDeclaration() || F->mayBeOverridden())
901 // We annotate nonnull return values, which are only applicable to
903 if (!F->getReturnType()->isPointerTy())
906 bool Speculative = false;
907 if (isReturnNonNull(F, SCCNodes, *TLI, Speculative)) {
909 // Mark the function eagerly since we may discover a function
910 // which prevents us from speculating about the entire SCC
911 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
912 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
918 // At least one function returns something which could be null, can't
919 // speculate any more.
920 SCCReturnsNonNull = false;
923 if (SCCReturnsNonNull) {
924 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
925 Function *F = (*I)->getFunction();
926 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
927 Attribute::NonNull) ||
928 !F->getReturnType()->isPointerTy())
931 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
932 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
941 static void setDoesNotAccessMemory(Function &F) {
942 if (!F.doesNotAccessMemory()) {
943 F.setDoesNotAccessMemory();
948 static void setOnlyReadsMemory(Function &F) {
949 if (!F.onlyReadsMemory()) {
950 F.setOnlyReadsMemory();
955 static void setDoesNotThrow(Function &F) {
956 if (!F.doesNotThrow()) {
962 static void setDoesNotCapture(Function &F, unsigned n) {
963 if (!F.doesNotCapture(n)) {
964 F.setDoesNotCapture(n);
969 static void setOnlyReadsMemory(Function &F, unsigned n) {
970 if (!F.onlyReadsMemory(n)) {
971 F.setOnlyReadsMemory(n);
976 static void setDoesNotAlias(Function &F, unsigned n) {
977 if (!F.doesNotAlias(n)) {
978 F.setDoesNotAlias(n);
983 /// Analyze the name and prototype of the given function and set any applicable
986 /// Returns true if any attributes were set and false otherwise.
987 static bool inferPrototypeAttributes(Function &F, const TargetLibraryInfo &TLI) {
988 if (F.hasFnAttribute(Attribute::OptimizeNone))
991 FunctionType *FTy = F.getFunctionType();
992 LibFunc::Func TheLibFunc;
993 if (!(TLI.getLibFunc(F.getName(), TheLibFunc) && TLI.has(TheLibFunc)))
996 switch (TheLibFunc) {
997 case LibFunc::strlen:
998 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1000 setOnlyReadsMemory(F);
1002 setDoesNotCapture(F, 1);
1004 case LibFunc::strchr:
1005 case LibFunc::strrchr:
1006 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1007 !FTy->getParamType(1)->isIntegerTy())
1009 setOnlyReadsMemory(F);
1012 case LibFunc::strtol:
1013 case LibFunc::strtod:
1014 case LibFunc::strtof:
1015 case LibFunc::strtoul:
1016 case LibFunc::strtoll:
1017 case LibFunc::strtold:
1018 case LibFunc::strtoull:
1019 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1022 setDoesNotCapture(F, 2);
1023 setOnlyReadsMemory(F, 1);
1025 case LibFunc::strcpy:
1026 case LibFunc::stpcpy:
1027 case LibFunc::strcat:
1028 case LibFunc::strncat:
1029 case LibFunc::strncpy:
1030 case LibFunc::stpncpy:
1031 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1034 setDoesNotCapture(F, 2);
1035 setOnlyReadsMemory(F, 2);
1037 case LibFunc::strxfrm:
1038 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1039 !FTy->getParamType(1)->isPointerTy())
1042 setDoesNotCapture(F, 1);
1043 setDoesNotCapture(F, 2);
1044 setOnlyReadsMemory(F, 2);
1046 case LibFunc::strcmp: // 0,1
1047 case LibFunc::strspn: // 0,1
1048 case LibFunc::strncmp: // 0,1
1049 case LibFunc::strcspn: // 0,1
1050 case LibFunc::strcoll: // 0,1
1051 case LibFunc::strcasecmp: // 0,1
1052 case LibFunc::strncasecmp: //
1053 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1054 !FTy->getParamType(1)->isPointerTy())
1056 setOnlyReadsMemory(F);
1058 setDoesNotCapture(F, 1);
1059 setDoesNotCapture(F, 2);
1061 case LibFunc::strstr:
1062 case LibFunc::strpbrk:
1063 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1065 setOnlyReadsMemory(F);
1067 setDoesNotCapture(F, 2);
1069 case LibFunc::strtok:
1070 case LibFunc::strtok_r:
1071 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1074 setDoesNotCapture(F, 2);
1075 setOnlyReadsMemory(F, 2);
1077 case LibFunc::scanf:
1078 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1081 setDoesNotCapture(F, 1);
1082 setOnlyReadsMemory(F, 1);
1084 case LibFunc::setbuf:
1085 case LibFunc::setvbuf:
1086 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1089 setDoesNotCapture(F, 1);
1091 case LibFunc::strdup:
1092 case LibFunc::strndup:
1093 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1094 !FTy->getParamType(0)->isPointerTy())
1097 setDoesNotAlias(F, 0);
1098 setDoesNotCapture(F, 1);
1099 setOnlyReadsMemory(F, 1);
1102 case LibFunc::statvfs:
1103 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1104 !FTy->getParamType(1)->isPointerTy())
1107 setDoesNotCapture(F, 1);
1108 setDoesNotCapture(F, 2);
1109 setOnlyReadsMemory(F, 1);
1111 case LibFunc::sscanf:
1112 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1113 !FTy->getParamType(1)->isPointerTy())
1116 setDoesNotCapture(F, 1);
1117 setDoesNotCapture(F, 2);
1118 setOnlyReadsMemory(F, 1);
1119 setOnlyReadsMemory(F, 2);
1121 case LibFunc::sprintf:
1122 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1123 !FTy->getParamType(1)->isPointerTy())
1126 setDoesNotCapture(F, 1);
1127 setDoesNotCapture(F, 2);
1128 setOnlyReadsMemory(F, 2);
1130 case LibFunc::snprintf:
1131 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1132 !FTy->getParamType(2)->isPointerTy())
1135 setDoesNotCapture(F, 1);
1136 setDoesNotCapture(F, 3);
1137 setOnlyReadsMemory(F, 3);
1139 case LibFunc::setitimer:
1140 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1141 !FTy->getParamType(2)->isPointerTy())
1144 setDoesNotCapture(F, 2);
1145 setDoesNotCapture(F, 3);
1146 setOnlyReadsMemory(F, 2);
1148 case LibFunc::system:
1149 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1151 // May throw; "system" is a valid pthread cancellation point.
1152 setDoesNotCapture(F, 1);
1153 setOnlyReadsMemory(F, 1);
1155 case LibFunc::malloc:
1156 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy())
1159 setDoesNotAlias(F, 0);
1161 case LibFunc::memcmp:
1162 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1163 !FTy->getParamType(1)->isPointerTy())
1165 setOnlyReadsMemory(F);
1167 setDoesNotCapture(F, 1);
1168 setDoesNotCapture(F, 2);
1170 case LibFunc::memchr:
1171 case LibFunc::memrchr:
1172 if (FTy->getNumParams() != 3)
1174 setOnlyReadsMemory(F);
1178 case LibFunc::modff:
1179 case LibFunc::modfl:
1180 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1183 setDoesNotCapture(F, 2);
1185 case LibFunc::memcpy:
1186 case LibFunc::memccpy:
1187 case LibFunc::memmove:
1188 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1191 setDoesNotCapture(F, 2);
1192 setOnlyReadsMemory(F, 2);
1194 case LibFunc::memalign:
1195 if (!FTy->getReturnType()->isPointerTy())
1197 setDoesNotAlias(F, 0);
1199 case LibFunc::mkdir:
1200 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1203 setDoesNotCapture(F, 1);
1204 setOnlyReadsMemory(F, 1);
1206 case LibFunc::mktime:
1207 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1210 setDoesNotCapture(F, 1);
1212 case LibFunc::realloc:
1213 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1214 !FTy->getReturnType()->isPointerTy())
1217 setDoesNotAlias(F, 0);
1218 setDoesNotCapture(F, 1);
1221 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1223 // May throw; "read" is a valid pthread cancellation point.
1224 setDoesNotCapture(F, 2);
1226 case LibFunc::rewind:
1227 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1230 setDoesNotCapture(F, 1);
1232 case LibFunc::rmdir:
1233 case LibFunc::remove:
1234 case LibFunc::realpath:
1235 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1238 setDoesNotCapture(F, 1);
1239 setOnlyReadsMemory(F, 1);
1241 case LibFunc::rename:
1242 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1243 !FTy->getParamType(1)->isPointerTy())
1246 setDoesNotCapture(F, 1);
1247 setDoesNotCapture(F, 2);
1248 setOnlyReadsMemory(F, 1);
1249 setOnlyReadsMemory(F, 2);
1251 case LibFunc::readlink:
1252 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1253 !FTy->getParamType(1)->isPointerTy())
1256 setDoesNotCapture(F, 1);
1257 setDoesNotCapture(F, 2);
1258 setOnlyReadsMemory(F, 1);
1260 case LibFunc::write:
1261 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1263 // May throw; "write" is a valid pthread cancellation point.
1264 setDoesNotCapture(F, 2);
1265 setOnlyReadsMemory(F, 2);
1267 case LibFunc::bcopy:
1268 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1269 !FTy->getParamType(1)->isPointerTy())
1272 setDoesNotCapture(F, 1);
1273 setDoesNotCapture(F, 2);
1274 setOnlyReadsMemory(F, 1);
1277 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1278 !FTy->getParamType(1)->isPointerTy())
1281 setOnlyReadsMemory(F);
1282 setDoesNotCapture(F, 1);
1283 setDoesNotCapture(F, 2);
1285 case LibFunc::bzero:
1286 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1289 setDoesNotCapture(F, 1);
1291 case LibFunc::calloc:
1292 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy())
1295 setDoesNotAlias(F, 0);
1297 case LibFunc::chmod:
1298 case LibFunc::chown:
1299 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1302 setDoesNotCapture(F, 1);
1303 setOnlyReadsMemory(F, 1);
1305 case LibFunc::ctermid:
1306 case LibFunc::clearerr:
1307 case LibFunc::closedir:
1308 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1311 setDoesNotCapture(F, 1);
1316 case LibFunc::atoll:
1317 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1320 setOnlyReadsMemory(F);
1321 setDoesNotCapture(F, 1);
1323 case LibFunc::access:
1324 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1327 setDoesNotCapture(F, 1);
1328 setOnlyReadsMemory(F, 1);
1330 case LibFunc::fopen:
1331 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1332 !FTy->getParamType(0)->isPointerTy() ||
1333 !FTy->getParamType(1)->isPointerTy())
1336 setDoesNotAlias(F, 0);
1337 setDoesNotCapture(F, 1);
1338 setDoesNotCapture(F, 2);
1339 setOnlyReadsMemory(F, 1);
1340 setOnlyReadsMemory(F, 2);
1342 case LibFunc::fdopen:
1343 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1344 !FTy->getParamType(1)->isPointerTy())
1347 setDoesNotAlias(F, 0);
1348 setDoesNotCapture(F, 2);
1349 setOnlyReadsMemory(F, 2);
1353 case LibFunc::fseek:
1354 case LibFunc::ftell:
1355 case LibFunc::fgetc:
1356 case LibFunc::fseeko:
1357 case LibFunc::ftello:
1358 case LibFunc::fileno:
1359 case LibFunc::fflush:
1360 case LibFunc::fclose:
1361 case LibFunc::fsetpos:
1362 case LibFunc::flockfile:
1363 case LibFunc::funlockfile:
1364 case LibFunc::ftrylockfile:
1365 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1368 setDoesNotCapture(F, 1);
1370 case LibFunc::ferror:
1371 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1374 setDoesNotCapture(F, 1);
1375 setOnlyReadsMemory(F);
1377 case LibFunc::fputc:
1378 case LibFunc::fstat:
1379 case LibFunc::frexp:
1380 case LibFunc::frexpf:
1381 case LibFunc::frexpl:
1382 case LibFunc::fstatvfs:
1383 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1386 setDoesNotCapture(F, 2);
1388 case LibFunc::fgets:
1389 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1390 !FTy->getParamType(2)->isPointerTy())
1393 setDoesNotCapture(F, 3);
1395 case LibFunc::fread:
1396 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1397 !FTy->getParamType(3)->isPointerTy())
1400 setDoesNotCapture(F, 1);
1401 setDoesNotCapture(F, 4);
1403 case LibFunc::fwrite:
1404 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1405 !FTy->getParamType(3)->isPointerTy())
1408 setDoesNotCapture(F, 1);
1409 setDoesNotCapture(F, 4);
1411 case LibFunc::fputs:
1412 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1413 !FTy->getParamType(1)->isPointerTy())
1416 setDoesNotCapture(F, 1);
1417 setDoesNotCapture(F, 2);
1418 setOnlyReadsMemory(F, 1);
1420 case LibFunc::fscanf:
1421 case LibFunc::fprintf:
1422 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1423 !FTy->getParamType(1)->isPointerTy())
1426 setDoesNotCapture(F, 1);
1427 setDoesNotCapture(F, 2);
1428 setOnlyReadsMemory(F, 2);
1430 case LibFunc::fgetpos:
1431 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1432 !FTy->getParamType(1)->isPointerTy())
1435 setDoesNotCapture(F, 1);
1436 setDoesNotCapture(F, 2);
1439 case LibFunc::getlogin_r:
1440 case LibFunc::getc_unlocked:
1441 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1444 setDoesNotCapture(F, 1);
1446 case LibFunc::getenv:
1447 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1450 setOnlyReadsMemory(F);
1451 setDoesNotCapture(F, 1);
1454 case LibFunc::getchar:
1457 case LibFunc::getitimer:
1458 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1461 setDoesNotCapture(F, 2);
1463 case LibFunc::getpwnam:
1464 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1467 setDoesNotCapture(F, 1);
1468 setOnlyReadsMemory(F, 1);
1470 case LibFunc::ungetc:
1471 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1474 setDoesNotCapture(F, 2);
1476 case LibFunc::uname:
1477 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1480 setDoesNotCapture(F, 1);
1482 case LibFunc::unlink:
1483 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1486 setDoesNotCapture(F, 1);
1487 setOnlyReadsMemory(F, 1);
1489 case LibFunc::unsetenv:
1490 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1493 setDoesNotCapture(F, 1);
1494 setOnlyReadsMemory(F, 1);
1496 case LibFunc::utime:
1497 case LibFunc::utimes:
1498 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1499 !FTy->getParamType(1)->isPointerTy())
1502 setDoesNotCapture(F, 1);
1503 setDoesNotCapture(F, 2);
1504 setOnlyReadsMemory(F, 1);
1505 setOnlyReadsMemory(F, 2);
1508 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1511 setDoesNotCapture(F, 2);
1514 case LibFunc::printf:
1515 case LibFunc::perror:
1516 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1519 setDoesNotCapture(F, 1);
1520 setOnlyReadsMemory(F, 1);
1522 case LibFunc::pread:
1523 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1525 // May throw; "pread" is a valid pthread cancellation point.
1526 setDoesNotCapture(F, 2);
1528 case LibFunc::pwrite:
1529 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1531 // May throw; "pwrite" is a valid pthread cancellation point.
1532 setDoesNotCapture(F, 2);
1533 setOnlyReadsMemory(F, 2);
1535 case LibFunc::putchar:
1538 case LibFunc::popen:
1539 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1540 !FTy->getParamType(0)->isPointerTy() ||
1541 !FTy->getParamType(1)->isPointerTy())
1544 setDoesNotAlias(F, 0);
1545 setDoesNotCapture(F, 1);
1546 setDoesNotCapture(F, 2);
1547 setOnlyReadsMemory(F, 1);
1548 setOnlyReadsMemory(F, 2);
1550 case LibFunc::pclose:
1551 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1554 setDoesNotCapture(F, 1);
1556 case LibFunc::vscanf:
1557 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1560 setDoesNotCapture(F, 1);
1561 setOnlyReadsMemory(F, 1);
1563 case LibFunc::vsscanf:
1564 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1565 !FTy->getParamType(2)->isPointerTy())
1568 setDoesNotCapture(F, 1);
1569 setDoesNotCapture(F, 2);
1570 setOnlyReadsMemory(F, 1);
1571 setOnlyReadsMemory(F, 2);
1573 case LibFunc::vfscanf:
1574 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1575 !FTy->getParamType(2)->isPointerTy())
1578 setDoesNotCapture(F, 1);
1579 setDoesNotCapture(F, 2);
1580 setOnlyReadsMemory(F, 2);
1582 case LibFunc::valloc:
1583 if (!FTy->getReturnType()->isPointerTy())
1586 setDoesNotAlias(F, 0);
1588 case LibFunc::vprintf:
1589 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1592 setDoesNotCapture(F, 1);
1593 setOnlyReadsMemory(F, 1);
1595 case LibFunc::vfprintf:
1596 case LibFunc::vsprintf:
1597 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1598 !FTy->getParamType(1)->isPointerTy())
1601 setDoesNotCapture(F, 1);
1602 setDoesNotCapture(F, 2);
1603 setOnlyReadsMemory(F, 2);
1605 case LibFunc::vsnprintf:
1606 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1607 !FTy->getParamType(2)->isPointerTy())
1610 setDoesNotCapture(F, 1);
1611 setDoesNotCapture(F, 3);
1612 setOnlyReadsMemory(F, 3);
1615 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1617 // May throw; "open" is a valid pthread cancellation point.
1618 setDoesNotCapture(F, 1);
1619 setOnlyReadsMemory(F, 1);
1621 case LibFunc::opendir:
1622 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy() ||
1623 !FTy->getParamType(0)->isPointerTy())
1626 setDoesNotAlias(F, 0);
1627 setDoesNotCapture(F, 1);
1628 setOnlyReadsMemory(F, 1);
1630 case LibFunc::tmpfile:
1631 if (!FTy->getReturnType()->isPointerTy())
1634 setDoesNotAlias(F, 0);
1636 case LibFunc::times:
1637 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1640 setDoesNotCapture(F, 1);
1642 case LibFunc::htonl:
1643 case LibFunc::htons:
1644 case LibFunc::ntohl:
1645 case LibFunc::ntohs:
1647 setDoesNotAccessMemory(F);
1649 case LibFunc::lstat:
1650 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1651 !FTy->getParamType(1)->isPointerTy())
1654 setDoesNotCapture(F, 1);
1655 setDoesNotCapture(F, 2);
1656 setOnlyReadsMemory(F, 1);
1658 case LibFunc::lchown:
1659 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1662 setDoesNotCapture(F, 1);
1663 setOnlyReadsMemory(F, 1);
1665 case LibFunc::qsort:
1666 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1668 // May throw; places call through function pointer.
1669 setDoesNotCapture(F, 4);
1671 case LibFunc::dunder_strdup:
1672 case LibFunc::dunder_strndup:
1673 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1674 !FTy->getParamType(0)->isPointerTy())
1677 setDoesNotAlias(F, 0);
1678 setDoesNotCapture(F, 1);
1679 setOnlyReadsMemory(F, 1);
1681 case LibFunc::dunder_strtok_r:
1682 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1685 setDoesNotCapture(F, 2);
1686 setOnlyReadsMemory(F, 2);
1688 case LibFunc::under_IO_getc:
1689 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1692 setDoesNotCapture(F, 1);
1694 case LibFunc::under_IO_putc:
1695 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1698 setDoesNotCapture(F, 2);
1700 case LibFunc::dunder_isoc99_scanf:
1701 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1704 setDoesNotCapture(F, 1);
1705 setOnlyReadsMemory(F, 1);
1707 case LibFunc::stat64:
1708 case LibFunc::lstat64:
1709 case LibFunc::statvfs64:
1710 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1711 !FTy->getParamType(1)->isPointerTy())
1714 setDoesNotCapture(F, 1);
1715 setDoesNotCapture(F, 2);
1716 setOnlyReadsMemory(F, 1);
1718 case LibFunc::dunder_isoc99_sscanf:
1719 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1720 !FTy->getParamType(1)->isPointerTy())
1723 setDoesNotCapture(F, 1);
1724 setDoesNotCapture(F, 2);
1725 setOnlyReadsMemory(F, 1);
1726 setOnlyReadsMemory(F, 2);
1728 case LibFunc::fopen64:
1729 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1730 !FTy->getParamType(0)->isPointerTy() ||
1731 !FTy->getParamType(1)->isPointerTy())
1734 setDoesNotAlias(F, 0);
1735 setDoesNotCapture(F, 1);
1736 setDoesNotCapture(F, 2);
1737 setOnlyReadsMemory(F, 1);
1738 setOnlyReadsMemory(F, 2);
1740 case LibFunc::fseeko64:
1741 case LibFunc::ftello64:
1742 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1745 setDoesNotCapture(F, 1);
1747 case LibFunc::tmpfile64:
1748 if (!FTy->getReturnType()->isPointerTy())
1751 setDoesNotAlias(F, 0);
1753 case LibFunc::fstat64:
1754 case LibFunc::fstatvfs64:
1755 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1758 setDoesNotCapture(F, 2);
1760 case LibFunc::open64:
1761 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1763 // May throw; "open" is a valid pthread cancellation point.
1764 setDoesNotCapture(F, 1);
1765 setOnlyReadsMemory(F, 1);
1767 case LibFunc::gettimeofday:
1768 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1769 !FTy->getParamType(1)->isPointerTy())
1771 // Currently some platforms have the restrict keyword on the arguments to
1772 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1775 setDoesNotCapture(F, 1);
1776 setDoesNotCapture(F, 2);
1779 // Didn't mark any attributes.
1786 /// Adds attributes to well-known standard library call declarations.
1787 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1788 bool MadeChange = false;
1790 // Check each function in turn annotating well-known library function
1791 // declarations with attributes.
1792 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1793 Function *F = (*I)->getFunction();
1795 if (F && F->isDeclaration())
1796 MadeChange |= inferPrototypeAttributes(*F, *TLI);
1802 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1803 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1805 bool Changed = annotateLibraryCalls(SCC);
1806 Changed |= AddReadAttrs(SCC);
1807 Changed |= AddArgumentAttrs(SCC);
1808 Changed |= AddNoAliasAttrs(SCC);
1809 Changed |= AddNonNullAttrs(SCC);