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;
79 char FunctionAttrs::ID = 0;
80 INITIALIZE_PASS_BEGIN(FunctionAttrs, "functionattrs",
81 "Deduce function attributes", false, false)
82 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
83 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
84 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
85 INITIALIZE_PASS_END(FunctionAttrs, "functionattrs",
86 "Deduce function attributes", false, false)
88 Pass *llvm::createFunctionAttrsPass() { return new FunctionAttrs(); }
91 /// The three kinds of memory access relevant to 'readonly' and
92 /// 'readnone' attributes.
93 enum MemoryAccessKind {
100 static MemoryAccessKind checkFunctionMemoryAccess(Function &F, AAResults &AAR,
101 const SCCNodeSet &SCCNodes) {
102 FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
103 if (MRB == FMRB_DoesNotAccessMemory)
107 // Definitions with weak linkage may be overridden at linktime with
108 // something that writes memory, so treat them like declarations.
109 if (F.isDeclaration() || F.mayBeOverridden()) {
110 if (AliasAnalysis::onlyReadsMemory(MRB))
113 // Conservatively assume it writes to memory.
117 // Scan the function body for instructions that may read or write memory.
118 bool ReadsMemory = false;
119 for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
120 Instruction *I = &*II;
122 // Some instructions can be ignored even if they read or write memory.
123 // Detect these now, skipping to the next instruction if one is found.
124 CallSite CS(cast<Value>(I));
126 // Ignore calls to functions in the same SCC.
127 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
129 FunctionModRefBehavior MRB = AAR.getModRefBehavior(CS);
131 // If the call doesn't access memory, we're done.
132 if (!(MRB & MRI_ModRef))
135 if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
136 // The call could access any memory. If that includes writes, give up.
139 // If it reads, note it.
145 // Check whether all pointer arguments point to local memory, and
146 // ignore calls that only access local memory.
147 for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
150 if (!Arg->getType()->isPointerTy())
154 I->getAAMetadata(AAInfo);
155 MemoryLocation Loc(Arg, MemoryLocation::UnknownSize, AAInfo);
157 // Skip accesses to local or constant memory as they don't impact the
158 // externally visible mod/ref behavior.
159 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
163 // Writes non-local memory. Give up.
166 // Ok, it reads non-local memory.
170 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
171 // Ignore non-volatile loads from local memory. (Atomic is okay here.)
172 if (!LI->isVolatile()) {
173 MemoryLocation Loc = MemoryLocation::get(LI);
174 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
177 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
178 // Ignore non-volatile stores to local memory. (Atomic is okay here.)
179 if (!SI->isVolatile()) {
180 MemoryLocation Loc = MemoryLocation::get(SI);
181 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
184 } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
185 // Ignore vaargs on local memory.
186 MemoryLocation Loc = MemoryLocation::get(VI);
187 if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
191 // Any remaining instructions need to be taken seriously! Check if they
192 // read or write memory.
193 if (I->mayWriteToMemory())
194 // Writes memory. Just give up.
197 // If this instruction may read memory, remember that.
198 ReadsMemory |= I->mayReadFromMemory();
201 return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
204 /// Deduce readonly/readnone attributes for the SCC.
205 template <typename AARGetterT>
206 static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT AARGetter) {
207 // Check if any of the functions in the SCC read or write memory. If they
208 // write memory then they can't be marked readnone or readonly.
209 bool ReadsMemory = false;
210 for (Function *F : SCCNodes) {
211 // Call the callable parameter to look up AA results for this function.
212 AAResults &AAR = AARGetter(*F);
214 switch (checkFunctionMemoryAccess(*F, AAR, SCCNodes)) {
226 // Success! Functions in this SCC do not access memory, or only read memory.
227 // Give them the appropriate attribute.
228 bool MadeChange = false;
229 for (Function *F : SCCNodes) {
230 if (F->doesNotAccessMemory())
234 if (F->onlyReadsMemory() && ReadsMemory)
240 // Clear out any existing attributes.
242 B.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
244 AttributeSet::FunctionIndex,
245 AttributeSet::get(F->getContext(), AttributeSet::FunctionIndex, B));
247 // Add in the new attribute.
248 F->addAttribute(AttributeSet::FunctionIndex,
249 ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
261 /// For a given pointer Argument, this retains a list of Arguments of functions
262 /// in the same SCC that the pointer data flows into. We use this to build an
263 /// SCC of the arguments.
264 struct ArgumentGraphNode {
265 Argument *Definition;
266 SmallVector<ArgumentGraphNode *, 4> Uses;
269 class ArgumentGraph {
270 // We store pointers to ArgumentGraphNode objects, so it's important that
271 // that they not move around upon insert.
272 typedef std::map<Argument *, ArgumentGraphNode> ArgumentMapTy;
274 ArgumentMapTy ArgumentMap;
276 // There is no root node for the argument graph, in fact:
277 // void f(int *x, int *y) { if (...) f(x, y); }
278 // is an example where the graph is disconnected. The SCCIterator requires a
279 // single entry point, so we maintain a fake ("synthetic") root node that
280 // uses every node. Because the graph is directed and nothing points into
281 // the root, it will not participate in any SCCs (except for its own).
282 ArgumentGraphNode SyntheticRoot;
285 ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
287 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator iterator;
289 iterator begin() { return SyntheticRoot.Uses.begin(); }
290 iterator end() { return SyntheticRoot.Uses.end(); }
291 ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
293 ArgumentGraphNode *operator[](Argument *A) {
294 ArgumentGraphNode &Node = ArgumentMap[A];
296 SyntheticRoot.Uses.push_back(&Node);
301 /// This tracker checks whether callees are in the SCC, and if so it does not
302 /// consider that a capture, instead adding it to the "Uses" list and
303 /// continuing with the analysis.
304 struct ArgumentUsesTracker : public CaptureTracker {
305 ArgumentUsesTracker(const SCCNodeSet &SCCNodes)
306 : Captured(false), SCCNodes(SCCNodes) {}
308 void tooManyUses() override { Captured = true; }
310 bool captured(const Use *U) override {
311 CallSite CS(U->getUser());
312 if (!CS.getInstruction()) {
317 Function *F = CS.getCalledFunction();
318 if (!F || F->isDeclaration() || F->mayBeOverridden() ||
319 !SCCNodes.count(F)) {
324 // Note: the callee and the two successor blocks *follow* the argument
325 // operands. This means there is no need to adjust UseIndex to account for
329 std::distance(const_cast<const Use *>(CS.arg_begin()), U);
331 assert(UseIndex < CS.arg_size() && "Non-argument use?");
332 if (UseIndex >= F->arg_size()) {
333 assert(F->isVarArg() && "More params than args in non-varargs call");
338 Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
342 bool Captured; // True only if certainly captured (used outside our SCC).
343 SmallVector<Argument *, 4> Uses; // Uses within our SCC.
345 const SCCNodeSet &SCCNodes;
350 template <> struct GraphTraits<ArgumentGraphNode *> {
351 typedef ArgumentGraphNode NodeType;
352 typedef SmallVectorImpl<ArgumentGraphNode *>::iterator ChildIteratorType;
354 static inline NodeType *getEntryNode(NodeType *A) { return A; }
355 static inline ChildIteratorType child_begin(NodeType *N) {
356 return N->Uses.begin();
358 static inline ChildIteratorType child_end(NodeType *N) {
359 return N->Uses.end();
363 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
364 static NodeType *getEntryNode(ArgumentGraph *AG) {
365 return AG->getEntryNode();
367 static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
370 static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
374 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
375 static Attribute::AttrKind
376 determinePointerReadAttrs(Argument *A,
377 const SmallPtrSet<Argument *, 8> &SCCNodes) {
379 SmallVector<Use *, 32> Worklist;
380 SmallSet<Use *, 32> Visited;
382 // inalloca arguments are always clobbered by the call.
383 if (A->hasInAllocaAttr())
384 return Attribute::None;
387 // We don't need to track IsWritten. If A is written to, return immediately.
389 for (Use &U : A->uses()) {
391 Worklist.push_back(&U);
394 while (!Worklist.empty()) {
395 Use *U = Worklist.pop_back_val();
396 Instruction *I = cast<Instruction>(U->getUser());
398 switch (I->getOpcode()) {
399 case Instruction::BitCast:
400 case Instruction::GetElementPtr:
401 case Instruction::PHI:
402 case Instruction::Select:
403 case Instruction::AddrSpaceCast:
404 // The original value is not read/written via this if the new value isn't.
405 for (Use &UU : I->uses())
406 if (Visited.insert(&UU).second)
407 Worklist.push_back(&UU);
410 case Instruction::Call:
411 case Instruction::Invoke: {
412 bool Captures = true;
414 if (I->getType()->isVoidTy())
417 auto AddUsersToWorklistIfCapturing = [&] {
419 for (Use &UU : I->uses())
420 if (Visited.insert(&UU).second)
421 Worklist.push_back(&UU);
425 if (CS.doesNotAccessMemory()) {
426 AddUsersToWorklistIfCapturing();
430 Function *F = CS.getCalledFunction();
432 if (CS.onlyReadsMemory()) {
434 AddUsersToWorklistIfCapturing();
437 return Attribute::None;
440 // Note: the callee and the two successor blocks *follow* the argument
441 // operands. This means there is no need to adjust UseIndex to account
444 unsigned UseIndex = std::distance(CS.arg_begin(), U);
446 assert(UseIndex < CS.arg_size() && "Non-argument use?");
447 if (UseIndex >= F->arg_size()) {
448 assert(F->isVarArg() && "More params than args in non-varargs call");
449 return Attribute::None;
452 Captures &= !CS.doesNotCapture(UseIndex);
453 if (!SCCNodes.count(std::next(F->arg_begin(), UseIndex))) {
454 if (!CS.onlyReadsMemory() && !CS.onlyReadsMemory(UseIndex))
455 return Attribute::None;
456 if (!CS.doesNotAccessMemory(UseIndex))
460 AddUsersToWorklistIfCapturing();
464 case Instruction::Load:
468 case Instruction::ICmp:
469 case Instruction::Ret:
473 return Attribute::None;
477 return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
480 /// Deduce nocapture attributes for the SCC.
481 static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
482 bool Changed = false;
487 B.addAttribute(Attribute::NoCapture);
489 // Check each function in turn, determining which pointer arguments are not
491 for (Function *F : SCCNodes) {
492 // Definitions with weak linkage may be overridden at linktime with
493 // something that captures pointers, so treat them like declarations.
494 if (F->isDeclaration() || F->mayBeOverridden())
497 // Functions that are readonly (or readnone) and nounwind and don't return
498 // a value can't capture arguments. Don't analyze them.
499 if (F->onlyReadsMemory() && F->doesNotThrow() &&
500 F->getReturnType()->isVoidTy()) {
501 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
503 if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
504 A->addAttr(AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
512 for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
514 if (!A->getType()->isPointerTy())
516 bool HasNonLocalUses = false;
517 if (!A->hasNoCaptureAttr()) {
518 ArgumentUsesTracker Tracker(SCCNodes);
519 PointerMayBeCaptured(&*A, &Tracker);
520 if (!Tracker.Captured) {
521 if (Tracker.Uses.empty()) {
522 // If it's trivially not captured, mark it nocapture now.
524 AttributeSet::get(F->getContext(), A->getArgNo() + 1, B));
528 // If it's not trivially captured and not trivially not captured,
529 // then it must be calling into another function in our SCC. Save
530 // its particulars for Argument-SCC analysis later.
531 ArgumentGraphNode *Node = AG[&*A];
532 for (SmallVectorImpl<Argument *>::iterator
533 UI = Tracker.Uses.begin(),
534 UE = Tracker.Uses.end();
536 Node->Uses.push_back(AG[*UI]);
538 HasNonLocalUses = true;
542 // Otherwise, it's captured. Don't bother doing SCC analysis on it.
544 if (!HasNonLocalUses && !A->onlyReadsMemory()) {
545 // Can we determine that it's readonly/readnone without doing an SCC?
546 // Note that we don't allow any calls at all here, or else our result
547 // will be dependent on the iteration order through the functions in the
549 SmallPtrSet<Argument *, 8> Self;
551 Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
552 if (R != Attribute::None) {
555 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
557 R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
563 // The graph we've collected is partial because we stopped scanning for
564 // argument uses once we solved the argument trivially. These partial nodes
565 // show up as ArgumentGraphNode objects with an empty Uses list, and for
566 // these nodes the final decision about whether they capture has already been
567 // made. If the definition doesn't have a 'nocapture' attribute by now, it
570 for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
571 const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
572 if (ArgumentSCC.size() == 1) {
573 if (!ArgumentSCC[0]->Definition)
574 continue; // synthetic root node
576 // eg. "void f(int* x) { if (...) f(x); }"
577 if (ArgumentSCC[0]->Uses.size() == 1 &&
578 ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
579 Argument *A = ArgumentSCC[0]->Definition;
580 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
587 bool SCCCaptured = false;
588 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
589 I != E && !SCCCaptured; ++I) {
590 ArgumentGraphNode *Node = *I;
591 if (Node->Uses.empty()) {
592 if (!Node->Definition->hasNoCaptureAttr())
599 SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
600 // Fill ArgumentSCCNodes with the elements of the ArgumentSCC. Used for
601 // quickly looking up whether a given Argument is in this ArgumentSCC.
602 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end(); I != E; ++I) {
603 ArgumentSCCNodes.insert((*I)->Definition);
606 for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
607 I != E && !SCCCaptured; ++I) {
608 ArgumentGraphNode *N = *I;
609 for (SmallVectorImpl<ArgumentGraphNode *>::iterator UI = N->Uses.begin(),
612 Argument *A = (*UI)->Definition;
613 if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
622 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
623 Argument *A = ArgumentSCC[i]->Definition;
624 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
629 // We also want to compute readonly/readnone. With a small number of false
630 // negatives, we can assume that any pointer which is captured isn't going
631 // to be provably readonly or readnone, since by definition we can't
632 // analyze all uses of a captured pointer.
634 // The false negatives happen when the pointer is captured by a function
635 // that promises readonly/readnone behaviour on the pointer, then the
636 // pointer's lifetime ends before anything that writes to arbitrary memory.
637 // Also, a readonly/readnone pointer may be returned, but returning a
638 // pointer is capturing it.
640 Attribute::AttrKind ReadAttr = Attribute::ReadNone;
641 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
642 Argument *A = ArgumentSCC[i]->Definition;
643 Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
644 if (K == Attribute::ReadNone)
646 if (K == Attribute::ReadOnly) {
647 ReadAttr = Attribute::ReadOnly;
654 if (ReadAttr != Attribute::None) {
656 B.addAttribute(ReadAttr);
657 R.addAttribute(Attribute::ReadOnly).addAttribute(Attribute::ReadNone);
658 for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
659 Argument *A = ArgumentSCC[i]->Definition;
660 // Clear out existing readonly/readnone attributes
661 A->removeAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, R));
662 A->addAttr(AttributeSet::get(A->getContext(), A->getArgNo() + 1, B));
663 ReadAttr == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
672 /// Tests whether a function is "malloc-like".
674 /// A function is "malloc-like" if it returns either null or a pointer that
675 /// doesn't alias any other pointer visible to the caller.
676 static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
677 SmallSetVector<Value *, 8> FlowsToReturn;
678 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
679 if (ReturnInst *Ret = dyn_cast<ReturnInst>(I->getTerminator()))
680 FlowsToReturn.insert(Ret->getReturnValue());
682 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
683 Value *RetVal = FlowsToReturn[i];
685 if (Constant *C = dyn_cast<Constant>(RetVal)) {
686 if (!C->isNullValue() && !isa<UndefValue>(C))
692 if (isa<Argument>(RetVal))
695 if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
696 switch (RVI->getOpcode()) {
697 // Extend the analysis by looking upwards.
698 case Instruction::BitCast:
699 case Instruction::GetElementPtr:
700 case Instruction::AddrSpaceCast:
701 FlowsToReturn.insert(RVI->getOperand(0));
703 case Instruction::Select: {
704 SelectInst *SI = cast<SelectInst>(RVI);
705 FlowsToReturn.insert(SI->getTrueValue());
706 FlowsToReturn.insert(SI->getFalseValue());
709 case Instruction::PHI: {
710 PHINode *PN = cast<PHINode>(RVI);
711 for (Value *IncValue : PN->incoming_values())
712 FlowsToReturn.insert(IncValue);
716 // Check whether the pointer came from an allocation.
717 case Instruction::Alloca:
719 case Instruction::Call:
720 case Instruction::Invoke: {
722 if (CS.paramHasAttr(0, Attribute::NoAlias))
724 if (CS.getCalledFunction() && SCCNodes.count(CS.getCalledFunction()))
728 return false; // Did not come from an allocation.
731 if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
738 /// Deduce noalias attributes for the SCC.
739 static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
740 // Check each function in turn, determining which functions return noalias
742 for (Function *F : SCCNodes) {
744 if (F->doesNotAlias(0))
747 // Definitions with weak linkage may be overridden at linktime, so
748 // treat them like declarations.
749 if (F->isDeclaration() || F->mayBeOverridden())
752 // We annotate noalias return values, which are only applicable to
754 if (!F->getReturnType()->isPointerTy())
757 if (!isFunctionMallocLike(F, SCCNodes))
761 bool MadeChange = false;
762 for (Function *F : SCCNodes) {
763 if (F->doesNotAlias(0) || !F->getReturnType()->isPointerTy())
766 F->setDoesNotAlias(0);
774 /// Tests whether this function is known to not return null.
776 /// Requires that the function returns a pointer.
778 /// Returns true if it believes the function will not return a null, and sets
779 /// \p Speculative based on whether the returned conclusion is a speculative
780 /// conclusion due to SCC calls.
781 static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
782 const TargetLibraryInfo &TLI, bool &Speculative) {
783 assert(F->getReturnType()->isPointerTy() &&
784 "nonnull only meaningful on pointer types");
787 SmallSetVector<Value *, 8> FlowsToReturn;
788 for (BasicBlock &BB : *F)
789 if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
790 FlowsToReturn.insert(Ret->getReturnValue());
792 for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
793 Value *RetVal = FlowsToReturn[i];
795 // If this value is locally known to be non-null, we're good
796 if (isKnownNonNull(RetVal, &TLI))
799 // Otherwise, we need to look upwards since we can't make any local
801 Instruction *RVI = dyn_cast<Instruction>(RetVal);
804 switch (RVI->getOpcode()) {
805 // Extend the analysis by looking upwards.
806 case Instruction::BitCast:
807 case Instruction::GetElementPtr:
808 case Instruction::AddrSpaceCast:
809 FlowsToReturn.insert(RVI->getOperand(0));
811 case Instruction::Select: {
812 SelectInst *SI = cast<SelectInst>(RVI);
813 FlowsToReturn.insert(SI->getTrueValue());
814 FlowsToReturn.insert(SI->getFalseValue());
817 case Instruction::PHI: {
818 PHINode *PN = cast<PHINode>(RVI);
819 for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
820 FlowsToReturn.insert(PN->getIncomingValue(i));
823 case Instruction::Call:
824 case Instruction::Invoke: {
826 Function *Callee = CS.getCalledFunction();
827 // A call to a node within the SCC is assumed to return null until
829 if (Callee && SCCNodes.count(Callee)) {
836 return false; // Unknown source, may be null
838 llvm_unreachable("should have either continued or returned");
844 /// Deduce nonnull attributes for the SCC.
845 static bool addNonNullAttrs(const SCCNodeSet &SCCNodes,
846 const TargetLibraryInfo &TLI) {
847 // Speculative that all functions in the SCC return only nonnull
848 // pointers. We may refute this as we analyze functions.
849 bool SCCReturnsNonNull = true;
851 bool MadeChange = false;
853 // Check each function in turn, determining which functions return nonnull
855 for (Function *F : SCCNodes) {
857 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
861 // Definitions with weak linkage may be overridden at linktime, so
862 // treat them like declarations.
863 if (F->isDeclaration() || F->mayBeOverridden())
866 // We annotate nonnull return values, which are only applicable to
868 if (!F->getReturnType()->isPointerTy())
871 bool Speculative = false;
872 if (isReturnNonNull(F, SCCNodes, TLI, Speculative)) {
874 // Mark the function eagerly since we may discover a function
875 // which prevents us from speculating about the entire SCC
876 DEBUG(dbgs() << "Eagerly marking " << F->getName() << " as nonnull\n");
877 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
883 // At least one function returns something which could be null, can't
884 // speculate any more.
885 SCCReturnsNonNull = false;
888 if (SCCReturnsNonNull) {
889 for (Function *F : SCCNodes) {
890 if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
891 Attribute::NonNull) ||
892 !F->getReturnType()->isPointerTy())
895 DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
896 F->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
905 static void setDoesNotAccessMemory(Function &F) {
906 if (!F.doesNotAccessMemory()) {
907 F.setDoesNotAccessMemory();
912 static void setOnlyReadsMemory(Function &F) {
913 if (!F.onlyReadsMemory()) {
914 F.setOnlyReadsMemory();
919 static void setDoesNotThrow(Function &F) {
920 if (!F.doesNotThrow()) {
926 static void setDoesNotCapture(Function &F, unsigned n) {
927 if (!F.doesNotCapture(n)) {
928 F.setDoesNotCapture(n);
933 static void setOnlyReadsMemory(Function &F, unsigned n) {
934 if (!F.onlyReadsMemory(n)) {
935 F.setOnlyReadsMemory(n);
940 static void setDoesNotAlias(Function &F, unsigned n) {
941 if (!F.doesNotAlias(n)) {
942 F.setDoesNotAlias(n);
947 /// Analyze the name and prototype of the given function and set any applicable
950 /// Returns true if any attributes were set and false otherwise.
951 static bool inferPrototypeAttributes(Function &F, const TargetLibraryInfo &TLI) {
952 if (F.hasFnAttribute(Attribute::OptimizeNone))
955 FunctionType *FTy = F.getFunctionType();
956 LibFunc::Func TheLibFunc;
957 if (!(TLI.getLibFunc(F.getName(), TheLibFunc) && TLI.has(TheLibFunc)))
960 switch (TheLibFunc) {
961 case LibFunc::strlen:
962 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
964 setOnlyReadsMemory(F);
966 setDoesNotCapture(F, 1);
968 case LibFunc::strchr:
969 case LibFunc::strrchr:
970 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
971 !FTy->getParamType(1)->isIntegerTy())
973 setOnlyReadsMemory(F);
976 case LibFunc::strtol:
977 case LibFunc::strtod:
978 case LibFunc::strtof:
979 case LibFunc::strtoul:
980 case LibFunc::strtoll:
981 case LibFunc::strtold:
982 case LibFunc::strtoull:
983 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
986 setDoesNotCapture(F, 2);
987 setOnlyReadsMemory(F, 1);
989 case LibFunc::strcpy:
990 case LibFunc::stpcpy:
991 case LibFunc::strcat:
992 case LibFunc::strncat:
993 case LibFunc::strncpy:
994 case LibFunc::stpncpy:
995 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
998 setDoesNotCapture(F, 2);
999 setOnlyReadsMemory(F, 2);
1001 case LibFunc::strxfrm:
1002 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1003 !FTy->getParamType(1)->isPointerTy())
1006 setDoesNotCapture(F, 1);
1007 setDoesNotCapture(F, 2);
1008 setOnlyReadsMemory(F, 2);
1010 case LibFunc::strcmp: // 0,1
1011 case LibFunc::strspn: // 0,1
1012 case LibFunc::strncmp: // 0,1
1013 case LibFunc::strcspn: // 0,1
1014 case LibFunc::strcoll: // 0,1
1015 case LibFunc::strcasecmp: // 0,1
1016 case LibFunc::strncasecmp: //
1017 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1018 !FTy->getParamType(1)->isPointerTy())
1020 setOnlyReadsMemory(F);
1022 setDoesNotCapture(F, 1);
1023 setDoesNotCapture(F, 2);
1025 case LibFunc::strstr:
1026 case LibFunc::strpbrk:
1027 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1029 setOnlyReadsMemory(F);
1031 setDoesNotCapture(F, 2);
1033 case LibFunc::strtok:
1034 case LibFunc::strtok_r:
1035 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1038 setDoesNotCapture(F, 2);
1039 setOnlyReadsMemory(F, 2);
1041 case LibFunc::scanf:
1042 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1045 setDoesNotCapture(F, 1);
1046 setOnlyReadsMemory(F, 1);
1048 case LibFunc::setbuf:
1049 case LibFunc::setvbuf:
1050 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1053 setDoesNotCapture(F, 1);
1055 case LibFunc::strdup:
1056 case LibFunc::strndup:
1057 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1058 !FTy->getParamType(0)->isPointerTy())
1061 setDoesNotAlias(F, 0);
1062 setDoesNotCapture(F, 1);
1063 setOnlyReadsMemory(F, 1);
1066 case LibFunc::statvfs:
1067 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1068 !FTy->getParamType(1)->isPointerTy())
1071 setDoesNotCapture(F, 1);
1072 setDoesNotCapture(F, 2);
1073 setOnlyReadsMemory(F, 1);
1075 case LibFunc::sscanf:
1076 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1077 !FTy->getParamType(1)->isPointerTy())
1080 setDoesNotCapture(F, 1);
1081 setDoesNotCapture(F, 2);
1082 setOnlyReadsMemory(F, 1);
1083 setOnlyReadsMemory(F, 2);
1085 case LibFunc::sprintf:
1086 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1087 !FTy->getParamType(1)->isPointerTy())
1090 setDoesNotCapture(F, 1);
1091 setDoesNotCapture(F, 2);
1092 setOnlyReadsMemory(F, 2);
1094 case LibFunc::snprintf:
1095 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1096 !FTy->getParamType(2)->isPointerTy())
1099 setDoesNotCapture(F, 1);
1100 setDoesNotCapture(F, 3);
1101 setOnlyReadsMemory(F, 3);
1103 case LibFunc::setitimer:
1104 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1105 !FTy->getParamType(2)->isPointerTy())
1108 setDoesNotCapture(F, 2);
1109 setDoesNotCapture(F, 3);
1110 setOnlyReadsMemory(F, 2);
1112 case LibFunc::system:
1113 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1115 // May throw; "system" is a valid pthread cancellation point.
1116 setDoesNotCapture(F, 1);
1117 setOnlyReadsMemory(F, 1);
1119 case LibFunc::malloc:
1120 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy())
1123 setDoesNotAlias(F, 0);
1125 case LibFunc::memcmp:
1126 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1127 !FTy->getParamType(1)->isPointerTy())
1129 setOnlyReadsMemory(F);
1131 setDoesNotCapture(F, 1);
1132 setDoesNotCapture(F, 2);
1134 case LibFunc::memchr:
1135 case LibFunc::memrchr:
1136 if (FTy->getNumParams() != 3)
1138 setOnlyReadsMemory(F);
1142 case LibFunc::modff:
1143 case LibFunc::modfl:
1144 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1147 setDoesNotCapture(F, 2);
1149 case LibFunc::memcpy:
1150 case LibFunc::memccpy:
1151 case LibFunc::memmove:
1152 if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1155 setDoesNotCapture(F, 2);
1156 setOnlyReadsMemory(F, 2);
1158 case LibFunc::memalign:
1159 if (!FTy->getReturnType()->isPointerTy())
1161 setDoesNotAlias(F, 0);
1163 case LibFunc::mkdir:
1164 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1167 setDoesNotCapture(F, 1);
1168 setOnlyReadsMemory(F, 1);
1170 case LibFunc::mktime:
1171 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1174 setDoesNotCapture(F, 1);
1176 case LibFunc::realloc:
1177 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1178 !FTy->getReturnType()->isPointerTy())
1181 setDoesNotAlias(F, 0);
1182 setDoesNotCapture(F, 1);
1185 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1187 // May throw; "read" is a valid pthread cancellation point.
1188 setDoesNotCapture(F, 2);
1190 case LibFunc::rewind:
1191 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1194 setDoesNotCapture(F, 1);
1196 case LibFunc::rmdir:
1197 case LibFunc::remove:
1198 case LibFunc::realpath:
1199 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1202 setDoesNotCapture(F, 1);
1203 setOnlyReadsMemory(F, 1);
1205 case LibFunc::rename:
1206 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1207 !FTy->getParamType(1)->isPointerTy())
1210 setDoesNotCapture(F, 1);
1211 setDoesNotCapture(F, 2);
1212 setOnlyReadsMemory(F, 1);
1213 setOnlyReadsMemory(F, 2);
1215 case LibFunc::readlink:
1216 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1217 !FTy->getParamType(1)->isPointerTy())
1220 setDoesNotCapture(F, 1);
1221 setDoesNotCapture(F, 2);
1222 setOnlyReadsMemory(F, 1);
1224 case LibFunc::write:
1225 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1227 // May throw; "write" is a valid pthread cancellation point.
1228 setDoesNotCapture(F, 2);
1229 setOnlyReadsMemory(F, 2);
1231 case LibFunc::bcopy:
1232 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1233 !FTy->getParamType(1)->isPointerTy())
1236 setDoesNotCapture(F, 1);
1237 setDoesNotCapture(F, 2);
1238 setOnlyReadsMemory(F, 1);
1241 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1242 !FTy->getParamType(1)->isPointerTy())
1245 setOnlyReadsMemory(F);
1246 setDoesNotCapture(F, 1);
1247 setDoesNotCapture(F, 2);
1249 case LibFunc::bzero:
1250 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1253 setDoesNotCapture(F, 1);
1255 case LibFunc::calloc:
1256 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy())
1259 setDoesNotAlias(F, 0);
1261 case LibFunc::chmod:
1262 case LibFunc::chown:
1263 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1266 setDoesNotCapture(F, 1);
1267 setOnlyReadsMemory(F, 1);
1269 case LibFunc::ctermid:
1270 case LibFunc::clearerr:
1271 case LibFunc::closedir:
1272 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1275 setDoesNotCapture(F, 1);
1280 case LibFunc::atoll:
1281 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1284 setOnlyReadsMemory(F);
1285 setDoesNotCapture(F, 1);
1287 case LibFunc::access:
1288 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1291 setDoesNotCapture(F, 1);
1292 setOnlyReadsMemory(F, 1);
1294 case LibFunc::fopen:
1295 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1296 !FTy->getParamType(0)->isPointerTy() ||
1297 !FTy->getParamType(1)->isPointerTy())
1300 setDoesNotAlias(F, 0);
1301 setDoesNotCapture(F, 1);
1302 setDoesNotCapture(F, 2);
1303 setOnlyReadsMemory(F, 1);
1304 setOnlyReadsMemory(F, 2);
1306 case LibFunc::fdopen:
1307 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1308 !FTy->getParamType(1)->isPointerTy())
1311 setDoesNotAlias(F, 0);
1312 setDoesNotCapture(F, 2);
1313 setOnlyReadsMemory(F, 2);
1317 case LibFunc::fseek:
1318 case LibFunc::ftell:
1319 case LibFunc::fgetc:
1320 case LibFunc::fseeko:
1321 case LibFunc::ftello:
1322 case LibFunc::fileno:
1323 case LibFunc::fflush:
1324 case LibFunc::fclose:
1325 case LibFunc::fsetpos:
1326 case LibFunc::flockfile:
1327 case LibFunc::funlockfile:
1328 case LibFunc::ftrylockfile:
1329 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1332 setDoesNotCapture(F, 1);
1334 case LibFunc::ferror:
1335 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1338 setDoesNotCapture(F, 1);
1339 setOnlyReadsMemory(F);
1341 case LibFunc::fputc:
1342 case LibFunc::fstat:
1343 case LibFunc::frexp:
1344 case LibFunc::frexpf:
1345 case LibFunc::frexpl:
1346 case LibFunc::fstatvfs:
1347 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1350 setDoesNotCapture(F, 2);
1352 case LibFunc::fgets:
1353 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1354 !FTy->getParamType(2)->isPointerTy())
1357 setDoesNotCapture(F, 3);
1359 case LibFunc::fread:
1360 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1361 !FTy->getParamType(3)->isPointerTy())
1364 setDoesNotCapture(F, 1);
1365 setDoesNotCapture(F, 4);
1367 case LibFunc::fwrite:
1368 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1369 !FTy->getParamType(3)->isPointerTy())
1372 setDoesNotCapture(F, 1);
1373 setDoesNotCapture(F, 4);
1375 case LibFunc::fputs:
1376 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1377 !FTy->getParamType(1)->isPointerTy())
1380 setDoesNotCapture(F, 1);
1381 setDoesNotCapture(F, 2);
1382 setOnlyReadsMemory(F, 1);
1384 case LibFunc::fscanf:
1385 case LibFunc::fprintf:
1386 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1387 !FTy->getParamType(1)->isPointerTy())
1390 setDoesNotCapture(F, 1);
1391 setDoesNotCapture(F, 2);
1392 setOnlyReadsMemory(F, 2);
1394 case LibFunc::fgetpos:
1395 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy() ||
1396 !FTy->getParamType(1)->isPointerTy())
1399 setDoesNotCapture(F, 1);
1400 setDoesNotCapture(F, 2);
1403 case LibFunc::getlogin_r:
1404 case LibFunc::getc_unlocked:
1405 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1408 setDoesNotCapture(F, 1);
1410 case LibFunc::getenv:
1411 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1414 setOnlyReadsMemory(F);
1415 setDoesNotCapture(F, 1);
1418 case LibFunc::getchar:
1421 case LibFunc::getitimer:
1422 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1425 setDoesNotCapture(F, 2);
1427 case LibFunc::getpwnam:
1428 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1431 setDoesNotCapture(F, 1);
1432 setOnlyReadsMemory(F, 1);
1434 case LibFunc::ungetc:
1435 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1438 setDoesNotCapture(F, 2);
1440 case LibFunc::uname:
1441 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1444 setDoesNotCapture(F, 1);
1446 case LibFunc::unlink:
1447 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1450 setDoesNotCapture(F, 1);
1451 setOnlyReadsMemory(F, 1);
1453 case LibFunc::unsetenv:
1454 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1457 setDoesNotCapture(F, 1);
1458 setOnlyReadsMemory(F, 1);
1460 case LibFunc::utime:
1461 case LibFunc::utimes:
1462 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1463 !FTy->getParamType(1)->isPointerTy())
1466 setDoesNotCapture(F, 1);
1467 setDoesNotCapture(F, 2);
1468 setOnlyReadsMemory(F, 1);
1469 setOnlyReadsMemory(F, 2);
1472 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1475 setDoesNotCapture(F, 2);
1478 case LibFunc::printf:
1479 case LibFunc::perror:
1480 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1483 setDoesNotCapture(F, 1);
1484 setOnlyReadsMemory(F, 1);
1486 case LibFunc::pread:
1487 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1489 // May throw; "pread" is a valid pthread cancellation point.
1490 setDoesNotCapture(F, 2);
1492 case LibFunc::pwrite:
1493 if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1495 // May throw; "pwrite" is a valid pthread cancellation point.
1496 setDoesNotCapture(F, 2);
1497 setOnlyReadsMemory(F, 2);
1499 case LibFunc::putchar:
1502 case LibFunc::popen:
1503 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1504 !FTy->getParamType(0)->isPointerTy() ||
1505 !FTy->getParamType(1)->isPointerTy())
1508 setDoesNotAlias(F, 0);
1509 setDoesNotCapture(F, 1);
1510 setDoesNotCapture(F, 2);
1511 setOnlyReadsMemory(F, 1);
1512 setOnlyReadsMemory(F, 2);
1514 case LibFunc::pclose:
1515 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1518 setDoesNotCapture(F, 1);
1520 case LibFunc::vscanf:
1521 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1524 setDoesNotCapture(F, 1);
1525 setOnlyReadsMemory(F, 1);
1527 case LibFunc::vsscanf:
1528 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1529 !FTy->getParamType(2)->isPointerTy())
1532 setDoesNotCapture(F, 1);
1533 setDoesNotCapture(F, 2);
1534 setOnlyReadsMemory(F, 1);
1535 setOnlyReadsMemory(F, 2);
1537 case LibFunc::vfscanf:
1538 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy() ||
1539 !FTy->getParamType(2)->isPointerTy())
1542 setDoesNotCapture(F, 1);
1543 setDoesNotCapture(F, 2);
1544 setOnlyReadsMemory(F, 2);
1546 case LibFunc::valloc:
1547 if (!FTy->getReturnType()->isPointerTy())
1550 setDoesNotAlias(F, 0);
1552 case LibFunc::vprintf:
1553 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1556 setDoesNotCapture(F, 1);
1557 setOnlyReadsMemory(F, 1);
1559 case LibFunc::vfprintf:
1560 case LibFunc::vsprintf:
1561 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy() ||
1562 !FTy->getParamType(1)->isPointerTy())
1565 setDoesNotCapture(F, 1);
1566 setDoesNotCapture(F, 2);
1567 setOnlyReadsMemory(F, 2);
1569 case LibFunc::vsnprintf:
1570 if (FTy->getNumParams() != 4 || !FTy->getParamType(0)->isPointerTy() ||
1571 !FTy->getParamType(2)->isPointerTy())
1574 setDoesNotCapture(F, 1);
1575 setDoesNotCapture(F, 3);
1576 setOnlyReadsMemory(F, 3);
1579 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1581 // May throw; "open" is a valid pthread cancellation point.
1582 setDoesNotCapture(F, 1);
1583 setOnlyReadsMemory(F, 1);
1585 case LibFunc::opendir:
1586 if (FTy->getNumParams() != 1 || !FTy->getReturnType()->isPointerTy() ||
1587 !FTy->getParamType(0)->isPointerTy())
1590 setDoesNotAlias(F, 0);
1591 setDoesNotCapture(F, 1);
1592 setOnlyReadsMemory(F, 1);
1594 case LibFunc::tmpfile:
1595 if (!FTy->getReturnType()->isPointerTy())
1598 setDoesNotAlias(F, 0);
1600 case LibFunc::times:
1601 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1604 setDoesNotCapture(F, 1);
1606 case LibFunc::htonl:
1607 case LibFunc::htons:
1608 case LibFunc::ntohl:
1609 case LibFunc::ntohs:
1611 setDoesNotAccessMemory(F);
1613 case LibFunc::lstat:
1614 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1615 !FTy->getParamType(1)->isPointerTy())
1618 setDoesNotCapture(F, 1);
1619 setDoesNotCapture(F, 2);
1620 setOnlyReadsMemory(F, 1);
1622 case LibFunc::lchown:
1623 if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1626 setDoesNotCapture(F, 1);
1627 setOnlyReadsMemory(F, 1);
1629 case LibFunc::qsort:
1630 if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1632 // May throw; places call through function pointer.
1633 setDoesNotCapture(F, 4);
1635 case LibFunc::dunder_strdup:
1636 case LibFunc::dunder_strndup:
1637 if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1638 !FTy->getParamType(0)->isPointerTy())
1641 setDoesNotAlias(F, 0);
1642 setDoesNotCapture(F, 1);
1643 setOnlyReadsMemory(F, 1);
1645 case LibFunc::dunder_strtok_r:
1646 if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1649 setDoesNotCapture(F, 2);
1650 setOnlyReadsMemory(F, 2);
1652 case LibFunc::under_IO_getc:
1653 if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1656 setDoesNotCapture(F, 1);
1658 case LibFunc::under_IO_putc:
1659 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1662 setDoesNotCapture(F, 2);
1664 case LibFunc::dunder_isoc99_scanf:
1665 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1668 setDoesNotCapture(F, 1);
1669 setOnlyReadsMemory(F, 1);
1671 case LibFunc::stat64:
1672 case LibFunc::lstat64:
1673 case LibFunc::statvfs64:
1674 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1675 !FTy->getParamType(1)->isPointerTy())
1678 setDoesNotCapture(F, 1);
1679 setDoesNotCapture(F, 2);
1680 setOnlyReadsMemory(F, 1);
1682 case LibFunc::dunder_isoc99_sscanf:
1683 if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy() ||
1684 !FTy->getParamType(1)->isPointerTy())
1687 setDoesNotCapture(F, 1);
1688 setDoesNotCapture(F, 2);
1689 setOnlyReadsMemory(F, 1);
1690 setOnlyReadsMemory(F, 2);
1692 case LibFunc::fopen64:
1693 if (FTy->getNumParams() != 2 || !FTy->getReturnType()->isPointerTy() ||
1694 !FTy->getParamType(0)->isPointerTy() ||
1695 !FTy->getParamType(1)->isPointerTy())
1698 setDoesNotAlias(F, 0);
1699 setDoesNotCapture(F, 1);
1700 setDoesNotCapture(F, 2);
1701 setOnlyReadsMemory(F, 1);
1702 setOnlyReadsMemory(F, 2);
1704 case LibFunc::fseeko64:
1705 case LibFunc::ftello64:
1706 if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1709 setDoesNotCapture(F, 1);
1711 case LibFunc::tmpfile64:
1712 if (!FTy->getReturnType()->isPointerTy())
1715 setDoesNotAlias(F, 0);
1717 case LibFunc::fstat64:
1718 case LibFunc::fstatvfs64:
1719 if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1722 setDoesNotCapture(F, 2);
1724 case LibFunc::open64:
1725 if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1727 // May throw; "open" is a valid pthread cancellation point.
1728 setDoesNotCapture(F, 1);
1729 setOnlyReadsMemory(F, 1);
1731 case LibFunc::gettimeofday:
1732 if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy() ||
1733 !FTy->getParamType(1)->isPointerTy())
1735 // Currently some platforms have the restrict keyword on the arguments to
1736 // gettimeofday. To be conservative, do not add noalias to gettimeofday's
1739 setDoesNotCapture(F, 1);
1740 setDoesNotCapture(F, 2);
1743 // Didn't mark any attributes.
1750 bool FunctionAttrs::runOnSCC(CallGraphSCC &SCC) {
1751 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
1752 bool Changed = false;
1754 // We compute dedicated AA results for each function in the SCC as needed. We
1755 // use a lambda referencing external objects so that they live long enough to
1756 // be queried, but we re-use them each time.
1757 Optional<BasicAAResult> BAR;
1758 Optional<AAResults> AAR;
1759 auto AARGetter = [&](Function &F) -> AAResults & {
1760 BAR.emplace(createLegacyPMBasicAAResult(*this, F));
1761 AAR.emplace(createLegacyPMAAResults(*this, F, *BAR));
1765 // Fill SCCNodes with the elements of the SCC. Used for quickly looking up
1766 // whether a given CallGraphNode is in this SCC. Also track whether there are
1767 // any external or opt-none nodes that will prevent us from optimizing any
1769 SCCNodeSet SCCNodes;
1770 bool ExternalNode = false;
1771 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
1772 Function *F = (*I)->getFunction();
1773 if (!F || F->hasFnAttribute(Attribute::OptimizeNone)) {
1774 // External node or function we're trying not to optimize - we both avoid
1775 // transform them and avoid leveraging information they provide.
1776 ExternalNode = true;
1780 // When initially processing functions, also infer their prototype
1781 // attributes if they are declarations.
1782 if (F->isDeclaration())
1783 Changed |= inferPrototypeAttributes(*F, *TLI);
1788 Changed |= addReadAttrs(SCCNodes, AARGetter);
1789 Changed |= addArgumentAttrs(SCCNodes);
1791 // If we have no external nodes participating in the SCC, we can infer some
1792 // more precise attributes as well.
1793 if (!ExternalNode) {
1794 Changed |= addNoAliasAttrs(SCCNodes);
1795 Changed |= addNonNullAttrs(SCCNodes, *TLI);