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 typedef SmallSetVector<Function *, 8> SCCNodeSet;
59 struct FunctionAttrs : public CallGraphSCCPass {
60 static char ID; // Pass identification, replacement for typeid
61 FunctionAttrs() : CallGraphSCCPass(ID) {
62 initializeFunctionAttrsPass(*PassRegistry::getPassRegistry());
65 bool runOnSCC(CallGraphSCC &SCC) override;
67 void getAnalysisUsage(AnalysisUsage &AU) const override {
69 AU.addRequired<AssumptionCacheTracker>();
70 AU.addRequired<TargetLibraryInfoWrapperPass>();
71 CallGraphSCCPass::getAnalysisUsage(AU);
75 TargetLibraryInfo *TLI;
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(); }
93 /// The three kinds of memory access relevant to 'readonly' and
94 /// 'readnone' attributes.
95 enum MemoryAccessKind {
102 static MemoryAccessKind checkFunctionMemoryAccess(Function &F, AAResults &AAR,
103 const SCCNodeSet &SCCNodes) {
104 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
105 if (MRB == FMRB_DoesNotAccessMemory)
109 // Definitions with weak linkage may be overridden at linktime with
110 // something that writes memory, so treat them like declarations.
111 if (F.isDeclaration() || F.mayBeOverridden()) {
112 if (AliasAnalysis::onlyReadsMemory(MRB))
115 // Conservatively assume it writes to memory.
119 // Scan the function body for instructions that may read or write memory.
120 bool ReadsMemory = false;
121 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
122 Instruction *I = &*II;
124 // Some instructions can be ignored even if they read or write memory.
125 // Detect these now, skipping to the next instruction if one is found.
126 CallSite CS(cast<Value>(I));
128 // Ignore calls to functions in the same SCC.
129 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
131 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
133 // If the call doesn't access memory, we're done.
134 if (!(MRB & MRI_ModRef))
137 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
138 // The call could access any memory. If that includes writes, give up.
141 // If it reads, note it.
147 // Check whether all pointer arguments point to local memory, and
148 // ignore calls that only access local memory.
149 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
152 if (!Arg->getType()->isPointerTy())
156 I->getAAMetadata(AAInfo);
157 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
159 // Skip accesses to local or constant memory as they don't impact the
160 // externally visible mod/ref behavior.
161 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
165 // Writes non-local memory. Give up.
168 // Ok, it reads non-local memory.
172 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
173 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
174 if (!LI->isVolatile()) {
175 MemoryLocation Loc = MemoryLocation::get(LI);
176 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
179 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
180 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
181 if (!SI->isVolatile()) {
182 MemoryLocation Loc = MemoryLocation::get(SI);
183 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
186 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
187 // Ignore vaargs on local memory.
188 MemoryLocation Loc = MemoryLocation::get(VI);
189 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
193 // Any remaining instructions need to be taken seriously! Check if they
194 // read or write memory.
195 if (I->mayWriteToMemory())
196 // Writes memory. Just give up.
199 // If this instruction may read memory, remember that.
200 ReadsMemory |= I->mayReadFromMemory();
203 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
206 /// Deduce readonly/readnone attributes for the SCC.
207 template <typename AARGetterT>
208 static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT AARGetter) {
209 // Check if any of the functions in the SCC read or write memory. If they
210 // write memory then they can't be marked readnone or readonly.
211 bool ReadsMemory = false;
212 for (Function *F : SCCNodes) {
213 // Call the callable parameter to look up AA results for this function.
214 AAResults &AAR = AARGetter(*F);
216 switch (checkFunctionMemoryAccess(*F, AAR, SCCNodes)) {
228 // Success! Functions in this SCC do not access memory, or only read memory.
229 // Give them the appropriate attribute.
230 bool MadeChange = false;
231 for (Function *F : SCCNodes) {
232 if (F->doesNotAccessMemory())
236 if (F->onlyReadsMemory() && ReadsMemory)
242 // Clear out any existing attributes.
244 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
246 AttributeSet::FunctionIndex,
247 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
249 // Add in the new attribute.
250 F->addAttribute(AttributeSet::FunctionIndex,
251 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
263 /// For a given pointer Argument, this retains a list of Arguments of functions
264 /// in the same SCC that the pointer data flows into. We use this to build an
265 /// SCC of the arguments.
266 struct ArgumentGraphNode {
267 Argument *Definition;
268 SmallVector<ArgumentGraphNode *, 4> Uses;
271 class ArgumentGraph {
272 // We store pointers to ArgumentGraphNode objects, so it's important that
273 // that they not move around upon insert.
274 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
276 ArgumentMapTy ArgumentMap;
278 // There is no root node for the argument graph, in fact:
279 // void f(int *x, int *y) { if (...) f(x, y); }
280 // is an example where the graph is disconnected. The SCCIterator requires a
281 // single entry point, so we maintain a fake ("synthetic") root node that
282 // uses every node. Because the graph is directed and nothing points into
283 // the root, it will not participate in any SCCs (except for its own).
284 ArgumentGraphNode SyntheticRoot;
287 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
289 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
291 iterator begin() { return SyntheticRoot.Uses.begin(); }
292 iterator end() { return SyntheticRoot.Uses.end(); }
293 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
295 ArgumentGraphNode *operator[](Argument *A) {
296 ArgumentGraphNode &Node = ArgumentMap[A];
298 SyntheticRoot.Uses.push_back(&Node);
303 /// This tracker checks whether callees are in the SCC, and if so it does not
304 /// consider that a capture, instead adding it to the "Uses" list and
305 /// continuing with the analysis.
306 struct ArgumentUsesTracker : public CaptureTracker {
307 ArgumentUsesTracker(const SCCNodeSet &SCCNodes)
308 : Captured(false), SCCNodes(SCCNodes) {}
310 void tooManyUses() override { Captured = true; }
312 bool captured(const Use *U) override {
313 CallSite CS(U->getUser());
314 if (!CS.getInstruction()) {
319 Function *F = CS.getCalledFunction();
320 if (!F || F->isDeclaration() || F->mayBeOverridden() ||
321 !SCCNodes.count(F)) {
327 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
328 for (CallSite::arg_iterator PI = CS.arg_begin(), PE = CS.arg_end();
329 PI != PE; ++PI, ++AI) {
331 assert(F->isVarArg() && "More params than args in non-varargs call");
336 Uses.push_back(&*AI);
341 assert(Found && "Capturing call-site captured nothing?");
346 bool Captured; // True only if certainly captured (used outside our SCC).
347 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
349 const SCCNodeSet &SCCNodes;
354 template <> struct GraphTraits<ArgumentGraphNode *> {
355 typedef ArgumentGraphNode NodeType;
356 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
358 static inline NodeType *getEntryNode(NodeType *A) { return A; }
359 static inline ChildIteratorType child_begin(NodeType *N) {
360 return N->Uses.begin();
362 static inline ChildIteratorType child_end(NodeType *N) {
363 return N->Uses.end();
367 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
368 static NodeType *getEntryNode(ArgumentGraph *AG) {
369 return AG->getEntryNode();
371 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
374 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
378 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
379 static Attribute::AttrKind
380 determinePointerReadAttrs(Argument *A,
381 const SmallPtrSet<Argument *, 8> &SCCNodes) {
383 SmallVector<Use *, 32> Worklist;
384 SmallSet<Use *, 32> Visited;
386 // inalloca arguments are always clobbered by the call.
387 if (A->hasInAllocaAttr())
388 return Attribute::None;
391 // We don't need to track IsWritten. If A is written to, return immediately.
393 for (Use &U : A->uses()) {
395 Worklist.push_back(&U);
398 while (!Worklist.empty()) {
399 Use *U = Worklist.pop_back_val();
400 Instruction *I = cast<Instruction>(U->getUser());
403 switch (I->getOpcode()) {
404 case Instruction::BitCast:
405 case Instruction::GetElementPtr:
406 case Instruction::PHI:
407 case Instruction::Select:
408 case Instruction::AddrSpaceCast:
409 // The original value is not read/written via this if the new value isn't.
410 for (Use &UU : I->uses())
411 if (Visited.insert(&UU).second)
412 Worklist.push_back(&UU);
415 case Instruction::Call:
416 case Instruction::Invoke: {
417 bool Captures = true;
419 if (I->getType()->isVoidTy())
422 auto AddUsersToWorklistIfCapturing = [&] {
424 for (Use &UU : I->uses())
425 if (Visited.insert(&UU).second)
426 Worklist.push_back(&UU);
430 if (CS.doesNotAccessMemory()) {
431 AddUsersToWorklistIfCapturing();
435 Function *F = CS.getCalledFunction();
437 if (CS.onlyReadsMemory()) {
439 AddUsersToWorklistIfCapturing();
442 return Attribute::None;
445 Function::arg_iterator AI = F->arg_begin(), AE = F->arg_end();
446 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
447 for (CallSite::arg_iterator A = B; A != E; ++A, ++AI) {
450 assert(F->isVarArg() &&
451 "More params than args in non-varargs call.");
452 return Attribute::None;
454 Captures &= !CS.doesNotCapture(A - B);
455 if (SCCNodes.count(&*AI))
457 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(A - B))
458 return Attribute::None;
459 if (!CS.doesNotAccessMemory(A - B))
463 AddUsersToWorklistIfCapturing();
467 case Instruction::Load:
471 case Instruction::ICmp:
472 case Instruction::Ret:
476 return Attribute::None;
480 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
483 /// Deduce nocapture attributes for the SCC.
484 static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
485 bool Changed = false;
490 B.addAttribute(Attribute::NoCapture);
492 // Check each function in turn, determining which pointer arguments are not
494 for (Function *F : SCCNodes) {
495 // Definitions with weak linkage may be overridden at linktime with
496 // something that captures pointers, so treat them like declarations.
497 if (F->isDeclaration() || F->mayBeOverridden())
500 // Functions that are readonly (or readnone) and nounwind and don't return
501 // a value can't capture arguments. Don't analyze them.
502 if (F->onlyReadsMemory() && F->doesNotThrow() &&
503 F->getReturnType()->isVoidTy()) {
504 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
506 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
507 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
515 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
517 if (!A->getType()->isPointerTy())
519 bool HasNonLocalUses = false;
520 if (!A->hasNoCaptureAttr()) {
521 ArgumentUsesTracker Tracker(SCCNodes);
522 PointerMayBeCaptured(&*A, &Tracker);
523 if (!Tracker.Captured) {
524 if (Tracker.Uses.empty()) {
525 // If it's trivially not captured, mark it nocapture now.
527 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
531 // If it's not trivially captured and not trivially not captured,
532 // then it must be calling into another function in our SCC. Save
533 // its particulars for Argument-SCC analysis later.
534 ArgumentGraphNode *Node = AG[&*A];
535 for (SmallVectorImpl<Argument *>::iterator
536 UI = Tracker.Uses.begin(),
537 UE = Tracker.Uses.end();
539 Node->Uses.push_back(AG[*UI]);
541 HasNonLocalUses = true;
545 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
547 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
548 // Can we determine that it's readonly/readnone without doing an SCC?
549 // Note that we don't allow any calls at all here, or else our result
550 // will be dependent on the iteration order through the functions in the
552 SmallPtrSet<Argument *, 8> Self;
554 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
555 if (R != Attribute::None) {
558 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
560 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
566 // The graph we've collected is partial because we stopped scanning for
567 // argument uses once we solved the argument trivially. These partial nodes
568 // show up as ArgumentGraphNode objects with an empty Uses list, and for
569 // these nodes the final decision about whether they capture has already been
570 // made. If the definition doesn't have a 'nocapture' attribute by now, it
573 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
574 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
575 if (ArgumentSCC.size() == 1) {
576 if (!ArgumentSCC[0]->Definition)
577 continue; // synthetic root node
579 // eg. "void f(int* x) { if (...) f(x); }"
580 if (ArgumentSCC[0]->Uses.size() == 1 &&
581 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
582 Argument *A = ArgumentSCC[0]->Definition;
583 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
590 bool SCCCaptured = false;
591 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
592 I != E && !SCCCaptured; ++I) {
593 ArgumentGraphNode *Node = *I;
594 if (Node->Uses.empty()) {
595 if (!Node->Definition->hasNoCaptureAttr())
602 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
603 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
604 // quickly looking up whether a given Argument is in this ArgumentSCC.
605 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
606 ArgumentSCCNodes.insert((*I)->Definition);
609 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
610 I != E && !SCCCaptured; ++I) {
611 ArgumentGraphNode *N = *I;
612 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
615 Argument *A = (*UI)->Definition;
616 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
625 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
626 Argument *A = ArgumentSCC[i]->Definition;
627 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
632 // We also want to compute readonly/readnone. With a small number of false
633 // negatives, we can assume that any pointer which is captured isn't going
634 // to be provably readonly or readnone, since by definition we can't
635 // analyze all uses of a captured pointer.
637 // The false negatives happen when the pointer is captured by a function
638 // that promises readonly/readnone behaviour on the pointer, then the
639 // pointer's lifetime ends before anything that writes to arbitrary memory.
640 // Also, a readonly/readnone pointer may be returned, but returning a
641 // pointer is capturing it.
643 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
644 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
645 Argument *A = ArgumentSCC[i]->Definition;
646 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
647 if (K == Attribute::ReadNone)
649 if (K == Attribute::ReadOnly) {
650 ReadAttr = Attribute::ReadOnly;
657 if (ReadAttr != Attribute::None) {
659 B.addAttribute(ReadAttr);
660 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
661 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
662 Argument *A = ArgumentSCC[i]->Definition;
663 // Clear out existing readonly/readnone attributes
664 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
665 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
666 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
675 /// Tests whether a function is "malloc-like".
677 /// A function is "malloc-like" if it returns either null or a pointer that
678 /// doesn't alias any other pointer visible to the caller.
679 static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
680 SmallSetVector<Value *, 8> FlowsToReturn;
681 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
682 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
683 FlowsToReturn.insert(Ret->getReturnValue());
685 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
686 Value *RetVal = FlowsToReturn[i];
688 if (Constant *C = dyn_cast<Constant>(RetVal)) {
689 if (!C->isNullValue() && !isa<UndefValue>(C))
695 if (isa<Argument>(RetVal))
698 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
699 switch (RVI->getOpcode()) {
700 // Extend the analysis by looking upwards.
701 case Instruction::BitCast:
702 case Instruction::GetElementPtr:
703 case Instruction::AddrSpaceCast:
704 FlowsToReturn.insert(RVI->getOperand(0));
706 case Instruction::Select: {
707 SelectInst *SI = cast<SelectInst>(RVI);
708 FlowsToReturn.insert(SI->getTrueValue());
709 FlowsToReturn.insert(SI->getFalseValue());
712 case Instruction::PHI: {
713 PHINode *PN = cast<PHINode>(RVI);
714 for (Value *IncValue : PN->incoming_values())
715 FlowsToReturn.insert(IncValue);
719 // Check whether the pointer came from an allocation.
720 case Instruction::Alloca:
722 case Instruction::Call:
723 case Instruction::Invoke: {
725 if (CS.paramHasAttr(0, Attribute::NoAlias))
727 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
731 return false; // Did not come from an allocation.
734 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
741 /// Deduce noalias attributes for the SCC.
742 static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
743 // Check each function in turn, determining which functions return noalias
745 for (Function *F : SCCNodes) {
747 if (F->doesNotAlias(0))
750 // Definitions with weak linkage may be overridden at linktime, so
751 // treat them like declarations.
752 if (F->isDeclaration() || F->mayBeOverridden())
755 // We annotate noalias return values, which are only applicable to
757 if (!F->getReturnType()->isPointerTy())
760 if (!isFunctionMallocLike(F, SCCNodes))
764 bool MadeChange = false;
765 for (Function *F : SCCNodes) {
766 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
769 F->setDoesNotAlias(0);
777 /// Tests whether this function is known to not return null.
779 /// Requires that the function returns a pointer.
781 /// Returns true if it believes the function will not return a null, and sets
782 /// \p Speculative based on whether the returned conclusion is a speculative
783 /// conclusion due to SCC calls.
784 static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
785 const TargetLibraryInfo &TLI, bool &Speculative) {
786 assert(F->getReturnType()->isPointerTy() &&
787 "nonnull only meaningful on pointer types");
790 SmallSetVector<Value *, 8> FlowsToReturn;
791 for (BasicBlock &BB : *F)
792 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
793 FlowsToReturn.insert(Ret->getReturnValue());
795 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
796 Value *RetVal = FlowsToReturn[i];
798 // If this value is locally known to be non-null, we're good
799 if (isKnownNonNull(RetVal, &TLI))
802 // Otherwise, we need to look upwards since we can't make any local
804 Instruction *RVI = dyn_cast<Instruction>(RetVal);
807 switch (RVI->getOpcode()) {
808 // Extend the analysis by looking upwards.
809 case Instruction::BitCast:
810 case Instruction::GetElementPtr:
811 case Instruction::AddrSpaceCast:
812 FlowsToReturn.insert(RVI->getOperand(0));
814 case Instruction::Select: {
815 SelectInst *SI = cast<SelectInst>(RVI);
816 FlowsToReturn.insert(SI->getTrueValue());
817 FlowsToReturn.insert(SI->getFalseValue());
820 case Instruction::PHI: {
821 PHINode *PN = cast<PHINode>(RVI);
822 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
823 FlowsToReturn.insert(PN->getIncomingValue(i));
826 case Instruction::Call:
827 case Instruction::Invoke: {
829 Function *Callee = CS.getCalledFunction();
830 // A call to a node within the SCC is assumed to return null until
832 if (Callee && SCCNodes.count(Callee)) {
839 return false; // Unknown source, may be null
841 llvm_unreachable("should have either continued or returned");
847 /// Deduce nonnull attributes for the SCC.
848 static bool addNonNullAttrs(const SCCNodeSet &SCCNodes,
849 const TargetLibraryInfo &TLI) {
850 // Speculative that all functions in the SCC return only nonnull
851 // pointers. We may refute this as we analyze functions.
852 bool SCCReturnsNonNull = true;
854 bool MadeChange = false;
856 // Check each function in turn, determining which functions return nonnull
858 for (Function *F : SCCNodes) {
860 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
864 // Definitions with weak linkage may be overridden at linktime, so
865 // treat them like declarations.
866 if (F->isDeclaration() || F->mayBeOverridden())
869 // We annotate nonnull return values, which are only applicable to
871 if (!F->getReturnType()->isPointerTy())
874 bool Speculative = false;
875 if (isReturnNonNull(F, SCCNodes, TLI, Speculative)) {
877 // Mark the function eagerly since we may discover a function
878 // which prevents us from speculating about the entire SCC
879 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
880 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
886 // At least one function returns something which could be null, can't
887 // speculate any more.
888 SCCReturnsNonNull = false;
891 if (SCCReturnsNonNull) {
892 for (Function *F : SCCNodes) {
893 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
894 Attribute::NonNull) ||
895 !F->getReturnType()->isPointerTy())
898 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
899 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
908 static void setDoesNotAccessMemory(Function &F) {
909 if (!F.doesNotAccessMemory()) {
910 F.setDoesNotAccessMemory();
915 static void setOnlyReadsMemory(Function &F) {
916 if (!F.onlyReadsMemory()) {
917 F.setOnlyReadsMemory();
922 static void setDoesNotThrow(Function &F) {
923 if (!F.doesNotThrow()) {
929 static void setDoesNotCapture(Function &F, unsigned n) {
930 if (!F.doesNotCapture(n)) {
931 F.setDoesNotCapture(n);
936 static void setOnlyReadsMemory(Function &F, unsigned n) {
937 if (!F.onlyReadsMemory(n)) {
938 F.setOnlyReadsMemory(n);
943 static void setDoesNotAlias(Function &F, unsigned n) {
944 if (!F.doesNotAlias(n)) {
945 F.setDoesNotAlias(n);
950 /// Analyze the name and prototype of the given function and set any applicable
953 /// Returns true if any attributes were set and false otherwise.
954 static bool inferPrototypeAttributes(Function &F, const TargetLibraryInfo &TLI) {
955 if (F.hasFnAttribute(Attribute::OptimizeNone))
958 FunctionType *FTy = F.getFunctionType();
959 LibFunc::Func TheLibFunc;
960 if (!(TLI.getLibFunc(F.getName(), TheLibFunc) && TLI.has(TheLibFunc)))
963 switch (TheLibFunc) {
964 case LibFunc::strlen:
965 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
967 setOnlyReadsMemory(F);
969 setDoesNotCapture(F, 1);
971 case LibFunc::strchr:
972 case LibFunc::strrchr:
973 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
974 !FTy->getParamType(1)->isIntegerTy())
976 setOnlyReadsMemory(F);
979 case LibFunc::strtol:
980 case LibFunc::strtod:
981 case LibFunc::strtof:
982 case LibFunc::strtoul:
983 case LibFunc::strtoll:
984 case LibFunc::strtold:
985 case LibFunc::strtoull:
986 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
989 setDoesNotCapture(F, 2);
990 setOnlyReadsMemory(F, 1);
992 case LibFunc::strcpy:
993 case LibFunc::stpcpy:
994 case LibFunc::strcat:
995 case LibFunc::strncat:
996 case LibFunc::strncpy:
997 case LibFunc::stpncpy:
998 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1001 setDoesNotCapture(F, 2);
1002 setOnlyReadsMemory(F, 2);
1004 case LibFunc::strxfrm:
1005 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1006 !FTy->getParamType(1)->isPointerTy())
1009 setDoesNotCapture(F, 1);
1010 setDoesNotCapture(F, 2);
1011 setOnlyReadsMemory(F, 2);
1013 case LibFunc::strcmp: // 0,1
1014 case LibFunc::strspn: // 0,1
1015 case LibFunc::strncmp: // 0,1
1016 case LibFunc::strcspn: // 0,1
1017 case LibFunc::strcoll: // 0,1
1018 case LibFunc::strcasecmp: // 0,1
1019 case LibFunc::strncasecmp: //
1020 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1021 !FTy->getParamType(1)->isPointerTy())
1023 setOnlyReadsMemory(F);
1025 setDoesNotCapture(F, 1);
1026 setDoesNotCapture(F, 2);
1028 case LibFunc::strstr:
1029 case LibFunc::strpbrk:
1030 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1032 setOnlyReadsMemory(F);
1034 setDoesNotCapture(F, 2);
1036 case LibFunc::strtok:
1037 case LibFunc::strtok_r:
1038 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1041 setDoesNotCapture(F, 2);
1042 setOnlyReadsMemory(F, 2);
1044 case LibFunc::scanf:
1045 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1048 setDoesNotCapture(F, 1);
1049 setOnlyReadsMemory(F, 1);
1051 case LibFunc::setbuf:
1052 case LibFunc::setvbuf:
1053 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1056 setDoesNotCapture(F, 1);
1058 case LibFunc::strdup:
1059 case LibFunc::strndup:
1060 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1061 !FTy->getParamType(0)->isPointerTy())
1064 setDoesNotAlias(F, 0);
1065 setDoesNotCapture(F, 1);
1066 setOnlyReadsMemory(F, 1);
1069 case LibFunc::statvfs:
1070 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1071 !FTy->getParamType(1)->isPointerTy())
1074 setDoesNotCapture(F, 1);
1075 setDoesNotCapture(F, 2);
1076 setOnlyReadsMemory(F, 1);
1078 case LibFunc::sscanf:
1079 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1080 !FTy->getParamType(1)->isPointerTy())
1083 setDoesNotCapture(F, 1);
1084 setDoesNotCapture(F, 2);
1085 setOnlyReadsMemory(F, 1);
1086 setOnlyReadsMemory(F, 2);
1088 case LibFunc::sprintf:
1089 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1090 !FTy->getParamType(1)->isPointerTy())
1093 setDoesNotCapture(F, 1);
1094 setDoesNotCapture(F, 2);
1095 setOnlyReadsMemory(F, 2);
1097 case LibFunc::snprintf:
1098 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1099 !FTy->getParamType(2)->isPointerTy())
1102 setDoesNotCapture(F, 1);
1103 setDoesNotCapture(F, 3);
1104 setOnlyReadsMemory(F, 3);
1106 case LibFunc::setitimer:
1107 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1108 !FTy->getParamType(2)->isPointerTy())
1111 setDoesNotCapture(F, 2);
1112 setDoesNotCapture(F, 3);
1113 setOnlyReadsMemory(F, 2);
1115 case LibFunc::system:
1116 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1118 // May throw; "system" is a valid pthread cancellation point.
1119 setDoesNotCapture(F, 1);
1120 setOnlyReadsMemory(F, 1);
1122 case LibFunc::malloc:
1123 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy())
1126 setDoesNotAlias(F, 0);
1128 case LibFunc::memcmp:
1129 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1130 !FTy->getParamType(1)->isPointerTy())
1132 setOnlyReadsMemory(F);
1134 setDoesNotCapture(F, 1);
1135 setDoesNotCapture(F, 2);
1137 case LibFunc::memchr:
1138 case LibFunc::memrchr:
1139 if (FTy->getNumParams() != 3)
1141 setOnlyReadsMemory(F);
1145 case LibFunc::modff:
1146 case LibFunc::modfl:
1147 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1150 setDoesNotCapture(F, 2);
1152 case LibFunc::memcpy:
1153 case LibFunc::memccpy:
1154 case LibFunc::memmove:
1155 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1158 setDoesNotCapture(F, 2);
1159 setOnlyReadsMemory(F, 2);
1161 case LibFunc::memalign:
1162 if (!FTy->getReturnType()->isPointerTy())
1164 setDoesNotAlias(F, 0);
1166 case LibFunc::mkdir:
1167 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1170 setDoesNotCapture(F, 1);
1171 setOnlyReadsMemory(F, 1);
1173 case LibFunc::mktime:
1174 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1177 setDoesNotCapture(F, 1);
1179 case LibFunc::realloc:
1180 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1181 !FTy->getReturnType()->isPointerTy())
1184 setDoesNotAlias(F, 0);
1185 setDoesNotCapture(F, 1);
1188 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1190 // May throw; "read" is a valid pthread cancellation point.
1191 setDoesNotCapture(F, 2);
1193 case LibFunc::rewind:
1194 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1197 setDoesNotCapture(F, 1);
1199 case LibFunc::rmdir:
1200 case LibFunc::remove:
1201 case LibFunc::realpath:
1202 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1205 setDoesNotCapture(F, 1);
1206 setOnlyReadsMemory(F, 1);
1208 case LibFunc::rename:
1209 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1210 !FTy->getParamType(1)->isPointerTy())
1213 setDoesNotCapture(F, 1);
1214 setDoesNotCapture(F, 2);
1215 setOnlyReadsMemory(F, 1);
1216 setOnlyReadsMemory(F, 2);
1218 case LibFunc::readlink:
1219 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1220 !FTy->getParamType(1)->isPointerTy())
1223 setDoesNotCapture(F, 1);
1224 setDoesNotCapture(F, 2);
1225 setOnlyReadsMemory(F, 1);
1227 case LibFunc::write:
1228 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1230 // May throw; "write" is a valid pthread cancellation point.
1231 setDoesNotCapture(F, 2);
1232 setOnlyReadsMemory(F, 2);
1234 case LibFunc::bcopy:
1235 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1236 !FTy->getParamType(1)->isPointerTy())
1239 setDoesNotCapture(F, 1);
1240 setDoesNotCapture(F, 2);
1241 setOnlyReadsMemory(F, 1);
1244 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1245 !FTy->getParamType(1)->isPointerTy())
1248 setOnlyReadsMemory(F);
1249 setDoesNotCapture(F, 1);
1250 setDoesNotCapture(F, 2);
1252 case LibFunc::bzero:
1253 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1256 setDoesNotCapture(F, 1);
1258 case LibFunc::calloc:
1259 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy())
1262 setDoesNotAlias(F, 0);
1264 case LibFunc::chmod:
1265 case LibFunc::chown:
1266 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1269 setDoesNotCapture(F, 1);
1270 setOnlyReadsMemory(F, 1);
1272 case LibFunc::ctermid:
1273 case LibFunc::clearerr:
1274 case LibFunc::closedir:
1275 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1278 setDoesNotCapture(F, 1);
1283 case LibFunc::atoll:
1284 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1287 setOnlyReadsMemory(F);
1288 setDoesNotCapture(F, 1);
1290 case LibFunc::access:
1291 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1294 setDoesNotCapture(F, 1);
1295 setOnlyReadsMemory(F, 1);
1297 case LibFunc::fopen:
1298 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1299 !FTy->getParamType(0)->isPointerTy() ||
1300 !FTy->getParamType(1)->isPointerTy())
1303 setDoesNotAlias(F, 0);
1304 setDoesNotCapture(F, 1);
1305 setDoesNotCapture(F, 2);
1306 setOnlyReadsMemory(F, 1);
1307 setOnlyReadsMemory(F, 2);
1309 case LibFunc::fdopen:
1310 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1311 !FTy->getParamType(1)->isPointerTy())
1314 setDoesNotAlias(F, 0);
1315 setDoesNotCapture(F, 2);
1316 setOnlyReadsMemory(F, 2);
1320 case LibFunc::fseek:
1321 case LibFunc::ftell:
1322 case LibFunc::fgetc:
1323 case LibFunc::fseeko:
1324 case LibFunc::ftello:
1325 case LibFunc::fileno:
1326 case LibFunc::fflush:
1327 case LibFunc::fclose:
1328 case LibFunc::fsetpos:
1329 case LibFunc::flockfile:
1330 case LibFunc::funlockfile:
1331 case LibFunc::ftrylockfile:
1332 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1335 setDoesNotCapture(F, 1);
1337 case LibFunc::ferror:
1338 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1341 setDoesNotCapture(F, 1);
1342 setOnlyReadsMemory(F);
1344 case LibFunc::fputc:
1345 case LibFunc::fstat:
1346 case LibFunc::frexp:
1347 case LibFunc::frexpf:
1348 case LibFunc::frexpl:
1349 case LibFunc::fstatvfs:
1350 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1353 setDoesNotCapture(F, 2);
1355 case LibFunc::fgets:
1356 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1357 !FTy->getParamType(2)->isPointerTy())
1360 setDoesNotCapture(F, 3);
1362 case LibFunc::fread:
1363 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1364 !FTy->getParamType(3)->isPointerTy())
1367 setDoesNotCapture(F, 1);
1368 setDoesNotCapture(F, 4);
1370 case LibFunc::fwrite:
1371 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1372 !FTy->getParamType(3)->isPointerTy())
1375 setDoesNotCapture(F, 1);
1376 setDoesNotCapture(F, 4);
1378 case LibFunc::fputs:
1379 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1380 !FTy->getParamType(1)->isPointerTy())
1383 setDoesNotCapture(F, 1);
1384 setDoesNotCapture(F, 2);
1385 setOnlyReadsMemory(F, 1);
1387 case LibFunc::fscanf:
1388 case LibFunc::fprintf:
1389 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1390 !FTy->getParamType(1)->isPointerTy())
1393 setDoesNotCapture(F, 1);
1394 setDoesNotCapture(F, 2);
1395 setOnlyReadsMemory(F, 2);
1397 case LibFunc::fgetpos:
1398 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1399 !FTy->getParamType(1)->isPointerTy())
1402 setDoesNotCapture(F, 1);
1403 setDoesNotCapture(F, 2);
1406 case LibFunc::getlogin_r:
1407 case LibFunc::getc_unlocked:
1408 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1411 setDoesNotCapture(F, 1);
1413 case LibFunc::getenv:
1414 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1417 setOnlyReadsMemory(F);
1418 setDoesNotCapture(F, 1);
1421 case LibFunc::getchar:
1424 case LibFunc::getitimer:
1425 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1428 setDoesNotCapture(F, 2);
1430 case LibFunc::getpwnam:
1431 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1434 setDoesNotCapture(F, 1);
1435 setOnlyReadsMemory(F, 1);
1437 case LibFunc::ungetc:
1438 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1441 setDoesNotCapture(F, 2);
1443 case LibFunc::uname:
1444 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1447 setDoesNotCapture(F, 1);
1449 case LibFunc::unlink:
1450 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1453 setDoesNotCapture(F, 1);
1454 setOnlyReadsMemory(F, 1);
1456 case LibFunc::unsetenv:
1457 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1460 setDoesNotCapture(F, 1);
1461 setOnlyReadsMemory(F, 1);
1463 case LibFunc::utime:
1464 case LibFunc::utimes:
1465 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1466 !FTy->getParamType(1)->isPointerTy())
1469 setDoesNotCapture(F, 1);
1470 setDoesNotCapture(F, 2);
1471 setOnlyReadsMemory(F, 1);
1472 setOnlyReadsMemory(F, 2);
1475 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1478 setDoesNotCapture(F, 2);
1481 case LibFunc::printf:
1482 case LibFunc::perror:
1483 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1486 setDoesNotCapture(F, 1);
1487 setOnlyReadsMemory(F, 1);
1489 case LibFunc::pread:
1490 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1492 // May throw; "pread" is a valid pthread cancellation point.
1493 setDoesNotCapture(F, 2);
1495 case LibFunc::pwrite:
1496 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1498 // May throw; "pwrite" is a valid pthread cancellation point.
1499 setDoesNotCapture(F, 2);
1500 setOnlyReadsMemory(F, 2);
1502 case LibFunc::putchar:
1505 case LibFunc::popen:
1506 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1507 !FTy->getParamType(0)->isPointerTy() ||
1508 !FTy->getParamType(1)->isPointerTy())
1511 setDoesNotAlias(F, 0);
1512 setDoesNotCapture(F, 1);
1513 setDoesNotCapture(F, 2);
1514 setOnlyReadsMemory(F, 1);
1515 setOnlyReadsMemory(F, 2);
1517 case LibFunc::pclose:
1518 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1521 setDoesNotCapture(F, 1);
1523 case LibFunc::vscanf:
1524 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1527 setDoesNotCapture(F, 1);
1528 setOnlyReadsMemory(F, 1);
1530 case LibFunc::vsscanf:
1531 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1532 !FTy->getParamType(2)->isPointerTy())
1535 setDoesNotCapture(F, 1);
1536 setDoesNotCapture(F, 2);
1537 setOnlyReadsMemory(F, 1);
1538 setOnlyReadsMemory(F, 2);
1540 case LibFunc::vfscanf:
1541 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1542 !FTy->getParamType(2)->isPointerTy())
1545 setDoesNotCapture(F, 1);
1546 setDoesNotCapture(F, 2);
1547 setOnlyReadsMemory(F, 2);
1549 case LibFunc::valloc:
1550 if (!FTy->getReturnType()->isPointerTy())
1553 setDoesNotAlias(F, 0);
1555 case LibFunc::vprintf:
1556 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1559 setDoesNotCapture(F, 1);
1560 setOnlyReadsMemory(F, 1);
1562 case LibFunc::vfprintf:
1563 case LibFunc::vsprintf:
1564 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1565 !FTy->getParamType(1)->isPointerTy())
1568 setDoesNotCapture(F, 1);
1569 setDoesNotCapture(F, 2);
1570 setOnlyReadsMemory(F, 2);
1572 case LibFunc::vsnprintf:
1573 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1574 !FTy->getParamType(2)->isPointerTy())
1577 setDoesNotCapture(F, 1);
1578 setDoesNotCapture(F, 3);
1579 setOnlyReadsMemory(F, 3);
1582 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1584 // May throw; "open" is a valid pthread cancellation point.
1585 setDoesNotCapture(F, 1);
1586 setOnlyReadsMemory(F, 1);
1588 case LibFunc::opendir:
1589 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy() ||
1590 !FTy->getParamType(0)->isPointerTy())
1593 setDoesNotAlias(F, 0);
1594 setDoesNotCapture(F, 1);
1595 setOnlyReadsMemory(F, 1);
1597 case LibFunc::tmpfile:
1598 if (!FTy->getReturnType()->isPointerTy())
1601 setDoesNotAlias(F, 0);
1603 case LibFunc::times:
1604 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1607 setDoesNotCapture(F, 1);
1609 case LibFunc::htonl:
1610 case LibFunc::htons:
1611 case LibFunc::ntohl:
1612 case LibFunc::ntohs:
1614 setDoesNotAccessMemory(F);
1616 case LibFunc::lstat:
1617 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1618 !FTy->getParamType(1)->isPointerTy())
1621 setDoesNotCapture(F, 1);
1622 setDoesNotCapture(F, 2);
1623 setOnlyReadsMemory(F, 1);
1625 case LibFunc::lchown:
1626 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1629 setDoesNotCapture(F, 1);
1630 setOnlyReadsMemory(F, 1);
1632 case LibFunc::qsort:
1633 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1635 // May throw; places call through function pointer.
1636 setDoesNotCapture(F, 4);
1638 case LibFunc::dunder_strdup:
1639 case LibFunc::dunder_strndup:
1640 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1641 !FTy->getParamType(0)->isPointerTy())
1644 setDoesNotAlias(F, 0);
1645 setDoesNotCapture(F, 1);
1646 setOnlyReadsMemory(F, 1);
1648 case LibFunc::dunder_strtok_r:
1649 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1652 setDoesNotCapture(F, 2);
1653 setOnlyReadsMemory(F, 2);
1655 case LibFunc::under_IO_getc:
1656 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1659 setDoesNotCapture(F, 1);
1661 case LibFunc::under_IO_putc:
1662 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1665 setDoesNotCapture(F, 2);
1667 case LibFunc::dunder_isoc99_scanf:
1668 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1671 setDoesNotCapture(F, 1);
1672 setOnlyReadsMemory(F, 1);
1674 case LibFunc::stat64:
1675 case LibFunc::lstat64:
1676 case LibFunc::statvfs64:
1677 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1678 !FTy->getParamType(1)->isPointerTy())
1681 setDoesNotCapture(F, 1);
1682 setDoesNotCapture(F, 2);
1683 setOnlyReadsMemory(F, 1);
1685 case LibFunc::dunder_isoc99_sscanf:
1686 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1687 !FTy->getParamType(1)->isPointerTy())
1690 setDoesNotCapture(F, 1);
1691 setDoesNotCapture(F, 2);
1692 setOnlyReadsMemory(F, 1);
1693 setOnlyReadsMemory(F, 2);
1695 case LibFunc::fopen64:
1696 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1697 !FTy->getParamType(0)->isPointerTy() ||
1698 !FTy->getParamType(1)->isPointerTy())
1701 setDoesNotAlias(F, 0);
1702 setDoesNotCapture(F, 1);
1703 setDoesNotCapture(F, 2);
1704 setOnlyReadsMemory(F, 1);
1705 setOnlyReadsMemory(F, 2);
1707 case LibFunc::fseeko64:
1708 case LibFunc::ftello64:
1709 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1712 setDoesNotCapture(F, 1);
1714 case LibFunc::tmpfile64:
1715 if (!FTy->getReturnType()->isPointerTy())
1718 setDoesNotAlias(F, 0);
1720 case LibFunc::fstat64:
1721 case LibFunc::fstatvfs64:
1722 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1725 setDoesNotCapture(F, 2);
1727 case LibFunc::open64:
1728 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1730 // May throw; "open" is a valid pthread cancellation point.
1731 setDoesNotCapture(F, 1);
1732 setOnlyReadsMemory(F, 1);
1734 case LibFunc::gettimeofday:
1735 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1736 !FTy->getParamType(1)->isPointerTy())
1738 // Currently some platforms have the restrict keyword on the arguments to
1739 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1742 setDoesNotCapture(F, 1);
1743 setDoesNotCapture(F, 2);
1746 // Didn't mark any attributes.
1753 /// Adds attributes to well-known standard library call declarations.
1754 bool FunctionAttrs::annotateLibraryCalls(const CallGraphSCC &SCC) {
1755 bool MadeChange = false;
1757 // Check each function in turn annotating well-known library function
1758 // declarations with attributes.
1759 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1760 Function *F = (*I)->getFunction();
1762 if (F && F->isDeclaration())
1763 MadeChange |= inferPrototypeAttributes(*F, *TLI);
1769 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1770 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1772 // Annotate declarations for which we have special knowledge.
1773 bool Changed = annotateLibraryCalls(SCC);
1775 // We compute dedicated AA results for each function in the SCC as needed. We
1776 // use a lambda referencing external objects so that they live long enough to
1777 // be queried, but we re-use them each time.
1778 Optional<BasicAAResult> BAR;
1779 Optional<AAResults> AAR;
1780 auto AARGetter = [&](Function &F) -> AAResults & {
1781 BAR.emplace(createLegacyPMBasicAAResult(*this, F));
1782 AAR.emplace(createLegacyPMAAResults(*this, F, *BAR));
1786 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1787 // whether a given CallGraphNode is in this SCC. Also track whether there are
1788 // any external or opt-none nodes that will prevent us from optimizing any
1790 SCCNodeSet SCCNodes;
1791 bool ExternalNode = false;
1792 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1793 Function *F = (*I)->getFunction();
1794 if (!F || F->hasFnAttribute(Attribute::OptimizeNone)) {
1795 // External node or function we're trying not to optimize - we both avoid
1796 // transform them and avoid leveraging information they provide.
1797 ExternalNode = true;
1804 Changed |= addReadAttrs(SCCNodes, AARGetter);
1805 Changed |= addArgumentAttrs(SCCNodes);
1807 // If we have no external nodes participating in the SCC, we can infer some
1808 // more precise attributes as well.
1809 if (!ExternalNode) {
1810 Changed |= addNoAliasAttrs(SCCNodes);
1811 Changed |= addNonNullAttrs(SCCNodes, *TLI);