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 IsFunctionMallocLike(Function *F, SmallPtrSet<Function *, 8> &) const;
76 bool AddNoAliasAttrs(const CallGraphSCC &SCC);
77 bool ReturnsNonNull(Function *F, SmallPtrSet<Function *, 8> &,
78 bool &Speculative) const;
79 bool AddNonNullAttrs(const CallGraphSCC &SCC);
80 bool annotateLibraryCalls(const CallGraphSCC &SCC);
84 char FunctionAttrs::ID = 0;
85 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
86 "Deduce function attributes", false, false)
87 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
88 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
89 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
90 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
91 "Deduce function attributes", false, false)
93 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
95 /// Deduce readonly/readnone attributes for the SCC.
96 bool FunctionAttrs::AddReadAttrs(const CallGraphSCC &SCC) {
97 SmallPtrSet<Function *, 8> SCCNodes;
99 // Fill SCCNodes with the elements of the SCC. Used for quickly
100 // looking up whether a given CallGraphNode is in this SCC.
101 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
102 SCCNodes.insert((*I)->getFunction());
104 // Check if any of the functions in the SCC read or write memory. If they
105 // write memory then they can't be marked readnone or readonly.
106 bool ReadsMemory = false;
107 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
108 Function *F = (*I)->getFunction();
110 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
111 // External node or node we don't want to optimize - assume it may write
112 // memory and give up.
115 // We need to manually construct BasicAA directly in order to disable its
116 // use of other function analyses.
117 BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F));
119 // Construct our own AA results for this function. We do this manually to
120 // work around the limitations of the legacy pass manager.
121 AAResults AAR(createLegacyPMAAResults(*this, *F, BAR));
123 FunctionModRefBehavior MRB = AAR.getModRefBehavior(F);
124 if (MRB == FMRB_DoesNotAccessMemory)
128 // Definitions with weak linkage may be overridden at linktime with
129 // something that writes memory, so treat them like declarations.
130 if (F->isDeclaration() || F->mayBeOverridden()) {
131 if (!AliasAnalysis::onlyReadsMemory(MRB))
132 // May write memory. Just give up.
139 // Scan the function body for instructions that may read or write memory.
140 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
141 Instruction *I = &*II;
143 // Some instructions can be ignored even if they read or write memory.
144 // Detect these now, skipping to the next instruction if one is found.
145 CallSite CS(cast<Value>(I));
147 // Ignore calls to functions in the same SCC.
148 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
150 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
151 // If the call doesn't access arbitrary memory, we may be able to
152 // figure out something.
153 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
154 // If the call does access argument pointees, check each argument.
155 if (AliasAnalysis::doesAccessArgPointees(MRB))
156 // Check whether all pointer arguments point to local memory, and
157 // ignore calls that only access local memory.
158 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
161 if (Arg->getType()->isPointerTy()) {
163 I->getAAMetadata(AAInfo);
165 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
166 if (!AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true)) {
168 // Writes non-local memory. Give up.
171 // Ok, it reads non-local memory.
178 // The call could access any memory. If that includes writes, give up.
181 // If it reads, note it.
185 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
186 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
187 if (!LI->isVolatile()) {
188 MemoryLocation Loc = MemoryLocation::get(LI);
189 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
192 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
193 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
194 if (!SI->isVolatile()) {
195 MemoryLocation Loc = MemoryLocation::get(SI);
196 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
199 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
200 // Ignore vaargs on local memory.
201 MemoryLocation Loc = MemoryLocation::get(VI);
202 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
206 // Any remaining instructions need to be taken seriously! Check if they
207 // read or write memory.
208 if (I->mayWriteToMemory())
209 // Writes memory. Just give up.
212 // If this instruction may read memory, remember that.
213 ReadsMemory |= I->mayReadFromMemory();
217 // Success! Functions in this SCC do not access memory, or only read memory.
218 // Give them the appropriate attribute.
219 bool MadeChange = false;
220 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
221 Function *F = (*I)->getFunction();
223 if (F->doesNotAccessMemory())
227 if (F->onlyReadsMemory() && ReadsMemory)
233 // Clear out any existing attributes.
235 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
237 AttributeSet::FunctionIndex,
238 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
240 // Add in the new attribute.
241 F->addAttribute(AttributeSet::FunctionIndex,
242 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
254 /// For a given pointer Argument, this retains a list of Arguments of functions
255 /// in the same SCC that the pointer data flows into. We use this to build an
256 /// SCC of the arguments.
257 struct ArgumentGraphNode {
258 Argument *Definition;
259 SmallVector<ArgumentGraphNode *, 4> Uses;
262 class ArgumentGraph {
263 // We store pointers to ArgumentGraphNode objects, so it's important that
264 // that they not move around upon insert.
265 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
267 ArgumentMapTy ArgumentMap;
269 // There is no root node for the argument graph, in fact:
270 // void f(int *x, int *y) { if (...) f(x, y); }
271 // is an example where the graph is disconnected. The SCCIterator requires a
272 // single entry point, so we maintain a fake ("synthetic") root node that
273 // uses every node. Because the graph is directed and nothing points into
274 // the root, it will not participate in any SCCs (except for its own).
275 ArgumentGraphNode SyntheticRoot;
278 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
280 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
282 iterator begin() { return SyntheticRoot.Uses.begin(); }
283 iterator end() { return SyntheticRoot.Uses.end(); }
284 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
286 ArgumentGraphNode *operator[](Argument *A) {
287 ArgumentGraphNode &Node = ArgumentMap[A];
289 SyntheticRoot.Uses.push_back(&Node);
294 /// This tracker checks whether callees are in the SCC, and if so it does not
295 /// consider that a capture, instead adding it to the "Uses" list and
296 /// continuing with the analysis.
297 struct ArgumentUsesTracker : public CaptureTracker {
298 ArgumentUsesTracker(const SmallPtrSet<Function *, 8> &SCCNodes)
299 : Captured(false), SCCNodes(SCCNodes) {}
301 void tooManyUses() override { Captured = true; }
303 bool captured(const Use *U) override {
304 CallSite CS(U->getUser());
305 if (!CS.getInstruction()) {
310 Function *F = CS.getCalledFunction();
311 if (!F || !SCCNodes.count(F)) {
317 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
318 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
319 PI != PE; ++PI, ++AI) {
321 assert(F->isVarArg() && "More params than args in non-varargs call");
331 assert(Found && "Capturing call-site captured nothing?");
336 bool Captured; // True only if certainly captured (used outside our SCC).
337 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
339 const SmallPtrSet<Function *, 8> &SCCNodes;
344 template <> struct GraphTraits<ArgumentGraphNode *> {
345 typedef ArgumentGraphNode NodeType;
346 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
348 static inline NodeType *getEntryNode(NodeType *A) { return A; }
349 static inline ChildIteratorType child_begin(NodeType *N) {
350 return N->Uses.begin();
352 static inline ChildIteratorType child_end(NodeType *N) {
353 return N->Uses.end();
357 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
358 static NodeType *getEntryNode(ArgumentGraph *AG) {
359 return AG->getEntryNode();
361 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
364 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
368 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
369 static Attribute::AttrKind
370 determinePointerReadAttrs(Argument *A,
371 const SmallPtrSet<Argument *, 8> &SCCNodes) {
373 SmallVector<Use *, 32> Worklist;
374 SmallSet<Use *, 32> Visited;
376 // inalloca arguments are always clobbered by the call.
377 if (A->hasInAllocaAttr())
378 return Attribute::None;
381 // We don't need to track IsWritten. If A is written to, return immediately.
383 for (Use &U : A->uses()) {
385 Worklist.push_back(&U);
388 while (!Worklist.empty()) {
389 Use *U = Worklist.pop_back_val();
390 Instruction *I = cast<Instruction>(U->getUser());
393 switch (I->getOpcode()) {
394 case Instruction::BitCast:
395 case Instruction::GetElementPtr:
396 case Instruction::PHI:
397 case Instruction::Select:
398 case Instruction::AddrSpaceCast:
399 // The original value is not read/written via this if the new value isn't.
400 for (Use &UU : I->uses())
401 if (Visited.insert(&UU).second)
402 Worklist.push_back(&UU);
405 case Instruction::Call:
406 case Instruction::Invoke: {
407 bool Captures = true;
409 if (I->getType()->isVoidTy())
412 auto AddUsersToWorklistIfCapturing = [&] {
414 for (Use &UU : I->uses())
415 if (Visited.insert(&UU).second)
416 Worklist.push_back(&UU);
420 if (CS.doesNotAccessMemory()) {
421 AddUsersToWorklistIfCapturing();
425 Function *F = CS.getCalledFunction();
427 if (CS.onlyReadsMemory()) {
429 AddUsersToWorklistIfCapturing();
432 return Attribute::None;
435 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
436 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
437 for (CallSite::arg_iterator A = B; A != E; ++A, ++AI) {
440 assert(F->isVarArg() &&
441 "More params than args in non-varargs call.");
442 return Attribute::None;
444 Captures &= !CS.doesNotCapture(A - B);
445 if (SCCNodes.count(AI))
447 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
448 return Attribute::None;
449 if (!CS.doesNotAccessMemory(A - B))
453 AddUsersToWorklistIfCapturing();
457 case Instruction::Load:
461 case Instruction::ICmp:
462 case Instruction::Ret:
466 return Attribute::None;
470 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
473 /// Deduce nocapture attributes for the SCC.
474 bool FunctionAttrs::AddArgumentAttrs(const CallGraphSCC &SCC) {
475 bool Changed = false;
477 SmallPtrSet<Function *, 8> SCCNodes;
479 // Fill SCCNodes with the elements of the SCC. Used for quickly
480 // looking up whether a given CallGraphNode is in this SCC.
481 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
482 Function *F = (*I)->getFunction();
483 if (F && !F->isDeclaration() && !F->mayBeOverridden() &&
484 !F->hasFnAttribute(Attribute::OptimizeNone))
491 B.addAttribute(Attribute::NoCapture);
493 // Check each function in turn, determining which pointer arguments are not
495 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
496 Function *F = (*I)->getFunction();
498 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
499 // External node or function we're trying not to optimize - only a problem
500 // for arguments that we pass to it.
503 // Definitions with weak linkage may be overridden at linktime with
504 // something that captures pointers, so treat them like declarations.
505 if (F->isDeclaration() || F->mayBeOverridden())
508 // Functions that are readonly (or readnone) and nounwind and don't return
509 // a value can't capture arguments. Don't analyze them.
510 if (F->onlyReadsMemory() && F->doesNotThrow() &&
511 F->getReturnType()->isVoidTy()) {
512 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
514 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
515 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
523 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
525 if (!A->getType()->isPointerTy())
527 bool HasNonLocalUses = false;
528 if (!A->hasNoCaptureAttr()) {
529 ArgumentUsesTracker Tracker(SCCNodes);
530 PointerMayBeCaptured(A, &Tracker);
531 if (!Tracker.Captured) {
532 if (Tracker.Uses.empty()) {
533 // If it's trivially not captured, mark it nocapture now.
535 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
539 // If it's not trivially captured and not trivially not captured,
540 // then it must be calling into another function in our SCC. Save
541 // its particulars for Argument-SCC analysis later.
542 ArgumentGraphNode *Node = AG[A];
543 for (SmallVectorImpl<Argument *>::iterator
544 UI = Tracker.Uses.begin(),
545 UE = Tracker.Uses.end();
547 Node->Uses.push_back(AG[*UI]);
549 HasNonLocalUses = true;
553 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
555 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
556 // Can we determine that it's readonly/readnone without doing an SCC?
557 // Note that we don't allow any calls at all here, or else our result
558 // will be dependent on the iteration order through the functions in the
560 SmallPtrSet<Argument *, 8> Self;
562 Attribute::AttrKind R = determinePointerReadAttrs(A, Self);
563 if (R != Attribute::None) {
566 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
568 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
574 // The graph we've collected is partial because we stopped scanning for
575 // argument uses once we solved the argument trivially. These partial nodes
576 // show up as ArgumentGraphNode objects with an empty Uses list, and for
577 // these nodes the final decision about whether they capture has already been
578 // made. If the definition doesn't have a 'nocapture' attribute by now, it
581 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
582 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
583 if (ArgumentSCC.size() == 1) {
584 if (!ArgumentSCC[0]->Definition)
585 continue; // synthetic root node
587 // eg. "void f(int* x) { if (...) f(x); }"
588 if (ArgumentSCC[0]->Uses.size() == 1 &&
589 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
590 Argument *A = ArgumentSCC[0]->Definition;
591 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
598 bool SCCCaptured = false;
599 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
600 I != E && !SCCCaptured; ++I) {
601 ArgumentGraphNode *Node = *I;
602 if (Node->Uses.empty()) {
603 if (!Node->Definition->hasNoCaptureAttr())
610 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
611 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
612 // quickly looking up whether a given Argument is in this ArgumentSCC.
613 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
614 ArgumentSCCNodes.insert((*I)->Definition);
617 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
618 I != E && !SCCCaptured; ++I) {
619 ArgumentGraphNode *N = *I;
620 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
623 Argument *A = (*UI)->Definition;
624 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
633 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
634 Argument *A = ArgumentSCC[i]->Definition;
635 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
640 // We also want to compute readonly/readnone. With a small number of false
641 // negatives, we can assume that any pointer which is captured isn't going
642 // to be provably readonly or readnone, since by definition we can't
643 // analyze all uses of a captured pointer.
645 // The false negatives happen when the pointer is captured by a function
646 // that promises readonly/readnone behaviour on the pointer, then the
647 // pointer's lifetime ends before anything that writes to arbitrary memory.
648 // Also, a readonly/readnone pointer may be returned, but returning a
649 // pointer is capturing it.
651 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
652 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
653 Argument *A = ArgumentSCC[i]->Definition;
654 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
655 if (K == Attribute::ReadNone)
657 if (K == Attribute::ReadOnly) {
658 ReadAttr = Attribute::ReadOnly;
665 if (ReadAttr != Attribute::None) {
667 B.addAttribute(ReadAttr);
668 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
669 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
670 Argument *A = ArgumentSCC[i]->Definition;
671 // Clear out existing readonly/readnone attributes
672 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
673 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
674 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
683 /// Tests whether a function is "malloc-like".
685 /// A function is "malloc-like" if it returns either null or a pointer that
686 /// doesn't alias any other pointer visible to the caller.
687 bool FunctionAttrs::IsFunctionMallocLike(
688 Function *F, SmallPtrSet<Function *, 8> &SCCNodes) const {
689 SmallSetVector<Value *, 8> FlowsToReturn;
690 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
691 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
692 FlowsToReturn.insert(Ret->getReturnValue());
694 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
695 Value *RetVal = FlowsToReturn[i];
697 if (Constant *C = dyn_cast<Constant>(RetVal)) {
698 if (!C->isNullValue() && !isa<UndefValue>(C))
704 if (isa<Argument>(RetVal))
707 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
708 switch (RVI->getOpcode()) {
709 // Extend the analysis by looking upwards.
710 case Instruction::BitCast:
711 case Instruction::GetElementPtr:
712 case Instruction::AddrSpaceCast:
713 FlowsToReturn.insert(RVI->getOperand(0));
715 case Instruction::Select: {
716 SelectInst *SI = cast<SelectInst>(RVI);
717 FlowsToReturn.insert(SI->getTrueValue());
718 FlowsToReturn.insert(SI->getFalseValue());
721 case Instruction::PHI: {
722 PHINode *PN = cast<PHINode>(RVI);
723 for (Value *IncValue : PN->incoming_values())
724 FlowsToReturn.insert(IncValue);
728 // Check whether the pointer came from an allocation.
729 case Instruction::Alloca:
731 case Instruction::Call:
732 case Instruction::Invoke: {
734 if (CS.paramHasAttr(0, Attribute::NoAlias))
736 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
740 return false; // Did not come from an allocation.
743 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
750 /// Deduce noalias attributes for the SCC.
751 bool FunctionAttrs::AddNoAliasAttrs(const CallGraphSCC &SCC) {
752 SmallPtrSet<Function *, 8> SCCNodes;
754 // Fill SCCNodes with the elements of the SCC. Used for quickly
755 // looking up whether a given CallGraphNode is in this SCC.
756 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
757 SCCNodes.insert((*I)->getFunction());
759 // Check each function in turn, determining which functions return noalias
761 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
762 Function *F = (*I)->getFunction();
764 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
765 // External node or node we don't want to optimize - skip it;
769 if (F->doesNotAlias(0))
772 // Definitions with weak linkage may be overridden at linktime, so
773 // treat them like declarations.
774 if (F->isDeclaration() || F->mayBeOverridden())
777 // We annotate noalias return values, which are only applicable to
779 if (!F->getReturnType()->isPointerTy())
782 if (!IsFunctionMallocLike(F, SCCNodes))
786 bool MadeChange = false;
787 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
788 Function *F = (*I)->getFunction();
789 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
792 F->setDoesNotAlias(0);
800 /// Tests whether this function is known to not return null.
801 bool FunctionAttrs::ReturnsNonNull(Function *F,
802 SmallPtrSet<Function *, 8> &SCCNodes,
803 bool &Speculative) const {
804 assert(F->getReturnType()->isPointerTy() &&
805 "nonnull only meaningful on pointer types");
808 SmallSetVector<Value *, 8> FlowsToReturn;
809 for (BasicBlock &BB : *F)
810 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
811 FlowsToReturn.insert(Ret->getReturnValue());
813 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
814 Value *RetVal = FlowsToReturn[i];
816 // If this value is locally known to be non-null, we're good
817 if (isKnownNonNull(RetVal, TLI))
820 // Otherwise, we need to look upwards since we can't make any local
822 Instruction *RVI = dyn_cast<Instruction>(RetVal);
825 switch (RVI->getOpcode()) {
826 // Extend the analysis by looking upwards.
827 case Instruction::BitCast:
828 case Instruction::GetElementPtr:
829 case Instruction::AddrSpaceCast:
830 FlowsToReturn.insert(RVI->getOperand(0));
832 case Instruction::Select: {
833 SelectInst *SI = cast<SelectInst>(RVI);
834 FlowsToReturn.insert(SI->getTrueValue());
835 FlowsToReturn.insert(SI->getFalseValue());
838 case Instruction::PHI: {
839 PHINode *PN = cast<PHINode>(RVI);
840 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
841 FlowsToReturn.insert(PN->getIncomingValue(i));
844 case Instruction::Call:
845 case Instruction::Invoke: {
847 Function *Callee = CS.getCalledFunction();
848 // A call to a node within the SCC is assumed to return null until
850 if (Callee && SCCNodes.count(Callee)) {
857 return false; // Unknown source, may be null
859 llvm_unreachable("should have either continued or returned");
865 /// Deduce nonnull attributes for the SCC.
866 bool FunctionAttrs::AddNonNullAttrs(const CallGraphSCC &SCC) {
867 SmallPtrSet<Function *, 8> SCCNodes;
869 // Fill SCCNodes with the elements of the SCC. Used for quickly
870 // looking up whether a given CallGraphNode is in this SCC.
871 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
872 SCCNodes.insert((*I)->getFunction());
874 // Speculative that all functions in the SCC return only nonnull
875 // pointers. We may refute this as we analyze functions.
876 bool SCCReturnsNonNull = true;
878 bool MadeChange = false;
880 // Check each function in turn, determining which functions return nonnull
882 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
883 Function *F = (*I)->getFunction();
885 if (!F || F->hasFnAttribute(Attribute::OptimizeNone))
886 // External node or node we don't want to optimize - skip it;
890 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
894 // Definitions with weak linkage may be overridden at linktime, so
895 // treat them like declarations.
896 if (F->isDeclaration() || F->mayBeOverridden())
899 // We annotate nonnull return values, which are only applicable to
901 if (!F->getReturnType()->isPointerTy())
904 bool Speculative = false;
905 if (ReturnsNonNull(F, SCCNodes, Speculative)) {
907 // Mark the function eagerly since we may discover a function
908 // which prevents us from speculating about the entire SCC
909 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
910 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
916 // At least one function returns something which could be null, can't
917 // speculate any more.
918 SCCReturnsNonNull = false;
921 if (SCCReturnsNonNull) {
922 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
923 Function *F = (*I)->getFunction();
924 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
925 Attribute::NonNull) ||
926 !F->getReturnType()->isPointerTy())
929 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
930 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
939 static void setDoesNotAccessMemory(Function &F) {
940 if (!F.doesNotAccessMemory()) {
941 F.setDoesNotAccessMemory();
946 static void setOnlyReadsMemory(Function &F) {
947 if (!F.onlyReadsMemory()) {
948 F.setOnlyReadsMemory();
953 static void setDoesNotThrow(Function &F) {
954 if (!F.doesNotThrow()) {
960 static void setDoesNotCapture(Function &F, unsigned n) {
961 if (!F.doesNotCapture(n)) {
962 F.setDoesNotCapture(n);
967 static void setOnlyReadsMemory(Function &F, unsigned n) {
968 if (!F.onlyReadsMemory(n)) {
969 F.setOnlyReadsMemory(n);
974 static void setDoesNotAlias(Function &F, unsigned n) {
975 if (!F.doesNotAlias(n)) {
976 F.setDoesNotAlias(n);
981 /// Analyze the name and prototype of the given function and set any applicable
984 /// Returns true if any attributes were set and false otherwise.
985 static bool inferPrototypeAttributes(Function &F, const TargetLibraryInfo &TLI) {
986 if (F.hasFnAttribute(Attribute::OptimizeNone))
989 FunctionType *FTy = F.getFunctionType();
990 LibFunc::Func TheLibFunc;
991 if (!(TLI.getLibFunc(F.getName(), TheLibFunc) && TLI.has(TheLibFunc)))
994 switch (TheLibFunc) {
995 case LibFunc::strlen:
996 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
998 setOnlyReadsMemory(F);
1000 setDoesNotCapture(F, 1);
1002 case LibFunc::strchr:
1003 case LibFunc::strrchr:
1004 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1005 !FTy->getParamType(1)->isIntegerTy())
1007 setOnlyReadsMemory(F);
1010 case LibFunc::strtol:
1011 case LibFunc::strtod:
1012 case LibFunc::strtof:
1013 case LibFunc::strtoul:
1014 case LibFunc::strtoll:
1015 case LibFunc::strtold:
1016 case LibFunc::strtoull:
1017 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1020 setDoesNotCapture(F, 2);
1021 setOnlyReadsMemory(F, 1);
1023 case LibFunc::strcpy:
1024 case LibFunc::stpcpy:
1025 case LibFunc::strcat:
1026 case LibFunc::strncat:
1027 case LibFunc::strncpy:
1028 case LibFunc::stpncpy:
1029 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1032 setDoesNotCapture(F, 2);
1033 setOnlyReadsMemory(F, 2);
1035 case LibFunc::strxfrm:
1036 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1037 !FTy->getParamType(1)->isPointerTy())
1040 setDoesNotCapture(F, 1);
1041 setDoesNotCapture(F, 2);
1042 setOnlyReadsMemory(F, 2);
1044 case LibFunc::strcmp: // 0,1
1045 case LibFunc::strspn: // 0,1
1046 case LibFunc::strncmp: // 0,1
1047 case LibFunc::strcspn: // 0,1
1048 case LibFunc::strcoll: // 0,1
1049 case LibFunc::strcasecmp: // 0,1
1050 case LibFunc::strncasecmp: //
1051 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1052 !FTy->getParamType(1)->isPointerTy())
1054 setOnlyReadsMemory(F);
1056 setDoesNotCapture(F, 1);
1057 setDoesNotCapture(F, 2);
1059 case LibFunc::strstr:
1060 case LibFunc::strpbrk:
1061 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1063 setOnlyReadsMemory(F);
1065 setDoesNotCapture(F, 2);
1067 case LibFunc::strtok:
1068 case LibFunc::strtok_r:
1069 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1072 setDoesNotCapture(F, 2);
1073 setOnlyReadsMemory(F, 2);
1075 case LibFunc::scanf:
1076 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1079 setDoesNotCapture(F, 1);
1080 setOnlyReadsMemory(F, 1);
1082 case LibFunc::setbuf:
1083 case LibFunc::setvbuf:
1084 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1087 setDoesNotCapture(F, 1);
1089 case LibFunc::strdup:
1090 case LibFunc::strndup:
1091 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1092 !FTy->getParamType(0)->isPointerTy())
1095 setDoesNotAlias(F, 0);
1096 setDoesNotCapture(F, 1);
1097 setOnlyReadsMemory(F, 1);
1100 case LibFunc::statvfs:
1101 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1102 !FTy->getParamType(1)->isPointerTy())
1105 setDoesNotCapture(F, 1);
1106 setDoesNotCapture(F, 2);
1107 setOnlyReadsMemory(F, 1);
1109 case LibFunc::sscanf:
1110 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1111 !FTy->getParamType(1)->isPointerTy())
1114 setDoesNotCapture(F, 1);
1115 setDoesNotCapture(F, 2);
1116 setOnlyReadsMemory(F, 1);
1117 setOnlyReadsMemory(F, 2);
1119 case LibFunc::sprintf:
1120 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1121 !FTy->getParamType(1)->isPointerTy())
1124 setDoesNotCapture(F, 1);
1125 setDoesNotCapture(F, 2);
1126 setOnlyReadsMemory(F, 2);
1128 case LibFunc::snprintf:
1129 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1130 !FTy->getParamType(2)->isPointerTy())
1133 setDoesNotCapture(F, 1);
1134 setDoesNotCapture(F, 3);
1135 setOnlyReadsMemory(F, 3);
1137 case LibFunc::setitimer:
1138 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1139 !FTy->getParamType(2)->isPointerTy())
1142 setDoesNotCapture(F, 2);
1143 setDoesNotCapture(F, 3);
1144 setOnlyReadsMemory(F, 2);
1146 case LibFunc::system:
1147 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1149 // May throw; "system" is a valid pthread cancellation point.
1150 setDoesNotCapture(F, 1);
1151 setOnlyReadsMemory(F, 1);
1153 case LibFunc::malloc:
1154 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy())
1157 setDoesNotAlias(F, 0);
1159 case LibFunc::memcmp:
1160 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1161 !FTy->getParamType(1)->isPointerTy())
1163 setOnlyReadsMemory(F);
1165 setDoesNotCapture(F, 1);
1166 setDoesNotCapture(F, 2);
1168 case LibFunc::memchr:
1169 case LibFunc::memrchr:
1170 if (FTy->getNumParams() != 3)
1172 setOnlyReadsMemory(F);
1176 case LibFunc::modff:
1177 case LibFunc::modfl:
1178 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1181 setDoesNotCapture(F, 2);
1183 case LibFunc::memcpy:
1184 case LibFunc::memccpy:
1185 case LibFunc::memmove:
1186 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1189 setDoesNotCapture(F, 2);
1190 setOnlyReadsMemory(F, 2);
1192 case LibFunc::memalign:
1193 if (!FTy->getReturnType()->isPointerTy())
1195 setDoesNotAlias(F, 0);
1197 case LibFunc::mkdir:
1198 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1201 setDoesNotCapture(F, 1);
1202 setOnlyReadsMemory(F, 1);
1204 case LibFunc::mktime:
1205 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1208 setDoesNotCapture(F, 1);
1210 case LibFunc::realloc:
1211 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1212 !FTy->getReturnType()->isPointerTy())
1215 setDoesNotAlias(F, 0);
1216 setDoesNotCapture(F, 1);
1219 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1221 // May throw; "read" is a valid pthread cancellation point.
1222 setDoesNotCapture(F, 2);
1224 case LibFunc::rewind:
1225 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1228 setDoesNotCapture(F, 1);
1230 case LibFunc::rmdir:
1231 case LibFunc::remove:
1232 case LibFunc::realpath:
1233 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1236 setDoesNotCapture(F, 1);
1237 setOnlyReadsMemory(F, 1);
1239 case LibFunc::rename:
1240 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1241 !FTy->getParamType(1)->isPointerTy())
1244 setDoesNotCapture(F, 1);
1245 setDoesNotCapture(F, 2);
1246 setOnlyReadsMemory(F, 1);
1247 setOnlyReadsMemory(F, 2);
1249 case LibFunc::readlink:
1250 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1251 !FTy->getParamType(1)->isPointerTy())
1254 setDoesNotCapture(F, 1);
1255 setDoesNotCapture(F, 2);
1256 setOnlyReadsMemory(F, 1);
1258 case LibFunc::write:
1259 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1261 // May throw; "write" is a valid pthread cancellation point.
1262 setDoesNotCapture(F, 2);
1263 setOnlyReadsMemory(F, 2);
1265 case LibFunc::bcopy:
1266 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1267 !FTy->getParamType(1)->isPointerTy())
1270 setDoesNotCapture(F, 1);
1271 setDoesNotCapture(F, 2);
1272 setOnlyReadsMemory(F, 1);
1275 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1276 !FTy->getParamType(1)->isPointerTy())
1279 setOnlyReadsMemory(F);
1280 setDoesNotCapture(F, 1);
1281 setDoesNotCapture(F, 2);
1283 case LibFunc::bzero:
1284 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1287 setDoesNotCapture(F, 1);
1289 case LibFunc::calloc:
1290 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy())
1293 setDoesNotAlias(F, 0);
1295 case LibFunc::chmod:
1296 case LibFunc::chown:
1297 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1300 setDoesNotCapture(F, 1);
1301 setOnlyReadsMemory(F, 1);
1303 case LibFunc::ctermid:
1304 case LibFunc::clearerr:
1305 case LibFunc::closedir:
1306 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1309 setDoesNotCapture(F, 1);
1314 case LibFunc::atoll:
1315 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1318 setOnlyReadsMemory(F);
1319 setDoesNotCapture(F, 1);
1321 case LibFunc::access:
1322 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1325 setDoesNotCapture(F, 1);
1326 setOnlyReadsMemory(F, 1);
1328 case LibFunc::fopen:
1329 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1330 !FTy->getParamType(0)->isPointerTy() ||
1331 !FTy->getParamType(1)->isPointerTy())
1334 setDoesNotAlias(F, 0);
1335 setDoesNotCapture(F, 1);
1336 setDoesNotCapture(F, 2);
1337 setOnlyReadsMemory(F, 1);
1338 setOnlyReadsMemory(F, 2);
1340 case LibFunc::fdopen:
1341 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1342 !FTy->getParamType(1)->isPointerTy())
1345 setDoesNotAlias(F, 0);
1346 setDoesNotCapture(F, 2);
1347 setOnlyReadsMemory(F, 2);
1351 case LibFunc::fseek:
1352 case LibFunc::ftell:
1353 case LibFunc::fgetc:
1354 case LibFunc::fseeko:
1355 case LibFunc::ftello:
1356 case LibFunc::fileno:
1357 case LibFunc::fflush:
1358 case LibFunc::fclose:
1359 case LibFunc::fsetpos:
1360 case LibFunc::flockfile:
1361 case LibFunc::funlockfile:
1362 case LibFunc::ftrylockfile:
1363 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1366 setDoesNotCapture(F, 1);
1368 case LibFunc::ferror:
1369 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1372 setDoesNotCapture(F, 1);
1373 setOnlyReadsMemory(F);
1375 case LibFunc::fputc:
1376 case LibFunc::fstat:
1377 case LibFunc::frexp:
1378 case LibFunc::frexpf:
1379 case LibFunc::frexpl:
1380 case LibFunc::fstatvfs:
1381 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1384 setDoesNotCapture(F, 2);
1386 case LibFunc::fgets:
1387 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1388 !FTy->getParamType(2)->isPointerTy())
1391 setDoesNotCapture(F, 3);
1393 case LibFunc::fread:
1394 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1395 !FTy->getParamType(3)->isPointerTy())
1398 setDoesNotCapture(F, 1);
1399 setDoesNotCapture(F, 4);
1401 case LibFunc::fwrite:
1402 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1403 !FTy->getParamType(3)->isPointerTy())
1406 setDoesNotCapture(F, 1);
1407 setDoesNotCapture(F, 4);
1409 case LibFunc::fputs:
1410 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1411 !FTy->getParamType(1)->isPointerTy())
1414 setDoesNotCapture(F, 1);
1415 setDoesNotCapture(F, 2);
1416 setOnlyReadsMemory(F, 1);
1418 case LibFunc::fscanf:
1419 case LibFunc::fprintf:
1420 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1421 !FTy->getParamType(1)->isPointerTy())
1424 setDoesNotCapture(F, 1);
1425 setDoesNotCapture(F, 2);
1426 setOnlyReadsMemory(F, 2);
1428 case LibFunc::fgetpos:
1429 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1430 !FTy->getParamType(1)->isPointerTy())
1433 setDoesNotCapture(F, 1);
1434 setDoesNotCapture(F, 2);
1437 case LibFunc::getlogin_r:
1438 case LibFunc::getc_unlocked:
1439 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1442 setDoesNotCapture(F, 1);
1444 case LibFunc::getenv:
1445 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1448 setOnlyReadsMemory(F);
1449 setDoesNotCapture(F, 1);
1452 case LibFunc::getchar:
1455 case LibFunc::getitimer:
1456 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1459 setDoesNotCapture(F, 2);
1461 case LibFunc::getpwnam:
1462 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1465 setDoesNotCapture(F, 1);
1466 setOnlyReadsMemory(F, 1);
1468 case LibFunc::ungetc:
1469 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1472 setDoesNotCapture(F, 2);
1474 case LibFunc::uname:
1475 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1478 setDoesNotCapture(F, 1);
1480 case LibFunc::unlink:
1481 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1484 setDoesNotCapture(F, 1);
1485 setOnlyReadsMemory(F, 1);
1487 case LibFunc::unsetenv:
1488 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1491 setDoesNotCapture(F, 1);
1492 setOnlyReadsMemory(F, 1);
1494 case LibFunc::utime:
1495 case LibFunc::utimes:
1496 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1497 !FTy->getParamType(1)->isPointerTy())
1500 setDoesNotCapture(F, 1);
1501 setDoesNotCapture(F, 2);
1502 setOnlyReadsMemory(F, 1);
1503 setOnlyReadsMemory(F, 2);
1506 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1509 setDoesNotCapture(F, 2);
1512 case LibFunc::printf:
1513 case LibFunc::perror:
1514 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1517 setDoesNotCapture(F, 1);
1518 setOnlyReadsMemory(F, 1);
1520 case LibFunc::pread:
1521 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1523 // May throw; "pread" is a valid pthread cancellation point.
1524 setDoesNotCapture(F, 2);
1526 case LibFunc::pwrite:
1527 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1529 // May throw; "pwrite" is a valid pthread cancellation point.
1530 setDoesNotCapture(F, 2);
1531 setOnlyReadsMemory(F, 2);
1533 case LibFunc::putchar:
1536 case LibFunc::popen:
1537 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1538 !FTy->getParamType(0)->isPointerTy() ||
1539 !FTy->getParamType(1)->isPointerTy())
1542 setDoesNotAlias(F, 0);
1543 setDoesNotCapture(F, 1);
1544 setDoesNotCapture(F, 2);
1545 setOnlyReadsMemory(F, 1);
1546 setOnlyReadsMemory(F, 2);
1548 case LibFunc::pclose:
1549 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1552 setDoesNotCapture(F, 1);
1554 case LibFunc::vscanf:
1555 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1558 setDoesNotCapture(F, 1);
1559 setOnlyReadsMemory(F, 1);
1561 case LibFunc::vsscanf:
1562 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1563 !FTy->getParamType(2)->isPointerTy())
1566 setDoesNotCapture(F, 1);
1567 setDoesNotCapture(F, 2);
1568 setOnlyReadsMemory(F, 1);
1569 setOnlyReadsMemory(F, 2);
1571 case LibFunc::vfscanf:
1572 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1573 !FTy->getParamType(2)->isPointerTy())
1576 setDoesNotCapture(F, 1);
1577 setDoesNotCapture(F, 2);
1578 setOnlyReadsMemory(F, 2);
1580 case LibFunc::valloc:
1581 if (!FTy->getReturnType()->isPointerTy())
1584 setDoesNotAlias(F, 0);
1586 case LibFunc::vprintf:
1587 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1590 setDoesNotCapture(F, 1);
1591 setOnlyReadsMemory(F, 1);
1593 case LibFunc::vfprintf:
1594 case LibFunc::vsprintf:
1595 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1596 !FTy->getParamType(1)->isPointerTy())
1599 setDoesNotCapture(F, 1);
1600 setDoesNotCapture(F, 2);
1601 setOnlyReadsMemory(F, 2);
1603 case LibFunc::vsnprintf:
1604 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1605 !FTy->getParamType(2)->isPointerTy())
1608 setDoesNotCapture(F, 1);
1609 setDoesNotCapture(F, 3);
1610 setOnlyReadsMemory(F, 3);
1613 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1615 // May throw; "open" is a valid pthread cancellation point.
1616 setDoesNotCapture(F, 1);
1617 setOnlyReadsMemory(F, 1);
1619 case LibFunc::opendir:
1620 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy() ||
1621 !FTy->getParamType(0)->isPointerTy())
1624 setDoesNotAlias(F, 0);
1625 setDoesNotCapture(F, 1);
1626 setOnlyReadsMemory(F, 1);
1628 case LibFunc::tmpfile:
1629 if (!FTy->getReturnType()->isPointerTy())
1632 setDoesNotAlias(F, 0);
1634 case LibFunc::times:
1635 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1638 setDoesNotCapture(F, 1);
1640 case LibFunc::htonl:
1641 case LibFunc::htons:
1642 case LibFunc::ntohl:
1643 case LibFunc::ntohs:
1645 setDoesNotAccessMemory(F);
1647 case LibFunc::lstat:
1648 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1649 !FTy->getParamType(1)->isPointerTy())
1652 setDoesNotCapture(F, 1);
1653 setDoesNotCapture(F, 2);
1654 setOnlyReadsMemory(F, 1);
1656 case LibFunc::lchown:
1657 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1660 setDoesNotCapture(F, 1);
1661 setOnlyReadsMemory(F, 1);
1663 case LibFunc::qsort:
1664 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1666 // May throw; places call through function pointer.
1667 setDoesNotCapture(F, 4);
1669 case LibFunc::dunder_strdup:
1670 case LibFunc::dunder_strndup:
1671 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1672 !FTy->getParamType(0)->isPointerTy())
1675 setDoesNotAlias(F, 0);
1676 setDoesNotCapture(F, 1);
1677 setOnlyReadsMemory(F, 1);
1679 case LibFunc::dunder_strtok_r:
1680 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1683 setDoesNotCapture(F, 2);
1684 setOnlyReadsMemory(F, 2);
1686 case LibFunc::under_IO_getc:
1687 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1690 setDoesNotCapture(F, 1);
1692 case LibFunc::under_IO_putc:
1693 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1696 setDoesNotCapture(F, 2);
1698 case LibFunc::dunder_isoc99_scanf:
1699 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1702 setDoesNotCapture(F, 1);
1703 setOnlyReadsMemory(F, 1);
1705 case LibFunc::stat64:
1706 case LibFunc::lstat64:
1707 case LibFunc::statvfs64:
1708 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1709 !FTy->getParamType(1)->isPointerTy())
1712 setDoesNotCapture(F, 1);
1713 setDoesNotCapture(F, 2);
1714 setOnlyReadsMemory(F, 1);
1716 case LibFunc::dunder_isoc99_sscanf:
1717 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1718 !FTy->getParamType(1)->isPointerTy())
1721 setDoesNotCapture(F, 1);
1722 setDoesNotCapture(F, 2);
1723 setOnlyReadsMemory(F, 1);
1724 setOnlyReadsMemory(F, 2);
1726 case LibFunc::fopen64:
1727 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1728 !FTy->getParamType(0)->isPointerTy() ||
1729 !FTy->getParamType(1)->isPointerTy())
1732 setDoesNotAlias(F, 0);
1733 setDoesNotCapture(F, 1);
1734 setDoesNotCapture(F, 2);
1735 setOnlyReadsMemory(F, 1);
1736 setOnlyReadsMemory(F, 2);
1738 case LibFunc::fseeko64:
1739 case LibFunc::ftello64:
1740 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1743 setDoesNotCapture(F, 1);
1745 case LibFunc::tmpfile64:
1746 if (!FTy->getReturnType()->isPointerTy())
1749 setDoesNotAlias(F, 0);
1751 case LibFunc::fstat64:
1752 case LibFunc::fstatvfs64:
1753 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1756 setDoesNotCapture(F, 2);
1758 case LibFunc::open64:
1759 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1761 // May throw; "open" is a valid pthread cancellation point.
1762 setDoesNotCapture(F, 1);
1763 setOnlyReadsMemory(F, 1);
1765 case LibFunc::gettimeofday:
1766 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1767 !FTy->getParamType(1)->isPointerTy())
1769 // Currently some platforms have the restrict keyword on the arguments to
1770 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1773 setDoesNotCapture(F, 1);
1774 setDoesNotCapture(F, 2);
1777 // Didn't mark any attributes.
1784 /// Adds attributes to well-known standard library call declarations.
1785 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1786 bool MadeChange = false;
1788 // Check each function in turn annotating well-known library function
1789 // declarations with attributes.
1790 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1791 Function *F = (*I)->getFunction();
1793 if (F && F->isDeclaration())
1794 MadeChange |= inferPrototypeAttributes(*F, *TLI);
1800 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1801 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1803 bool Changed = annotateLibraryCalls(SCC);
1804 Changed |= AddReadAttrs(SCC);
1805 Changed |= AddArgumentAttrs(SCC);
1806 Changed |= AddNoAliasAttrs(SCC);
1807 Changed |= AddNonNullAttrs(SCC);