xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/IPO/FunctionAttrs.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
1 //===- FunctionAttrs.cpp - Pass which marks functions attributes ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This file implements interprocedural passes which walk the
11 /// call-graph deducing and/or propagating function attributes.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/IPO/FunctionAttrs.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/SCCIterator.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AssumptionCache.h"
24 #include "llvm/Analysis/BasicAliasAnalysis.h"
25 #include "llvm/Analysis/CFG.h"
26 #include "llvm/Analysis/CGSCCPassManager.h"
27 #include "llvm/Analysis/CallGraph.h"
28 #include "llvm/Analysis/CallGraphSCCPass.h"
29 #include "llvm/Analysis/CaptureTracking.h"
30 #include "llvm/Analysis/LazyCallGraph.h"
31 #include "llvm/Analysis/MemoryBuiltins.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/IR/Argument.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/Constant.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/InstIterator.h"
41 #include "llvm/IR/InstrTypes.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Metadata.h"
46 #include "llvm/IR/PassManager.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/IR/Use.h"
49 #include "llvm/IR/User.h"
50 #include "llvm/IR/Value.h"
51 #include "llvm/InitializePasses.h"
52 #include "llvm/Pass.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Transforms/IPO.h"
60 #include <cassert>
61 #include <iterator>
62 #include <map>
63 #include <vector>
64 
65 using namespace llvm;
66 
67 #define DEBUG_TYPE "function-attrs"
68 
69 STATISTIC(NumReadNone, "Number of functions marked readnone");
70 STATISTIC(NumReadOnly, "Number of functions marked readonly");
71 STATISTIC(NumWriteOnly, "Number of functions marked writeonly");
72 STATISTIC(NumNoCapture, "Number of arguments marked nocapture");
73 STATISTIC(NumReturned, "Number of arguments marked returned");
74 STATISTIC(NumReadNoneArg, "Number of arguments marked readnone");
75 STATISTIC(NumReadOnlyArg, "Number of arguments marked readonly");
76 STATISTIC(NumNoAlias, "Number of function returns marked noalias");
77 STATISTIC(NumNonNullReturn, "Number of function returns marked nonnull");
78 STATISTIC(NumNoRecurse, "Number of functions marked as norecurse");
79 STATISTIC(NumNoUnwind, "Number of functions marked as nounwind");
80 STATISTIC(NumNoFree, "Number of functions marked as nofree");
81 STATISTIC(NumWillReturn, "Number of functions marked as willreturn");
82 
83 static cl::opt<bool> EnableNonnullArgPropagation(
84     "enable-nonnull-arg-prop", cl::init(true), cl::Hidden,
85     cl::desc("Try to propagate nonnull argument attributes from callsites to "
86              "caller functions."));
87 
88 static cl::opt<bool> DisableNoUnwindInference(
89     "disable-nounwind-inference", cl::Hidden,
90     cl::desc("Stop inferring nounwind attribute during function-attrs pass"));
91 
92 static cl::opt<bool> DisableNoFreeInference(
93     "disable-nofree-inference", cl::Hidden,
94     cl::desc("Stop inferring nofree attribute during function-attrs pass"));
95 
96 namespace {
97 
98 using SCCNodeSet = SmallSetVector<Function *, 8>;
99 
100 } // end anonymous namespace
101 
102 /// Returns the memory access attribute for function F using AAR for AA results,
103 /// where SCCNodes is the current SCC.
104 ///
105 /// If ThisBody is true, this function may examine the function body and will
106 /// return a result pertaining to this copy of the function. If it is false, the
107 /// result will be based only on AA results for the function declaration; it
108 /// will be assumed that some other (perhaps less optimized) version of the
109 /// function may be selected at link time.
110 static MemoryAccessKind checkFunctionMemoryAccess(Function &F, bool ThisBody,
111                                                   AAResults &AAR,
112                                                   const SCCNodeSet &SCCNodes) {
113   FunctionModRefBehavior MRB = AAR.getModRefBehavior(&F);
114   if (MRB == FMRB_DoesNotAccessMemory)
115     // Already perfect!
116     return MAK_ReadNone;
117 
118   if (!ThisBody) {
119     if (AliasAnalysis::onlyReadsMemory(MRB))
120       return MAK_ReadOnly;
121 
122     if (AliasAnalysis::doesNotReadMemory(MRB))
123       return MAK_WriteOnly;
124 
125     // Conservatively assume it reads and writes to memory.
126     return MAK_MayWrite;
127   }
128 
129   // Scan the function body for instructions that may read or write memory.
130   bool ReadsMemory = false;
131   bool WritesMemory = false;
132   for (inst_iterator II = inst_begin(F), E = inst_end(F); II != E; ++II) {
133     Instruction *I = &*II;
134 
135     // Some instructions can be ignored even if they read or write memory.
136     // Detect these now, skipping to the next instruction if one is found.
137     if (auto *Call = dyn_cast<CallBase>(I)) {
138       // Ignore calls to functions in the same SCC, as long as the call sites
139       // don't have operand bundles.  Calls with operand bundles are allowed to
140       // have memory effects not described by the memory effects of the call
141       // target.
142       if (!Call->hasOperandBundles() && Call->getCalledFunction() &&
143           SCCNodes.count(Call->getCalledFunction()))
144         continue;
145       FunctionModRefBehavior MRB = AAR.getModRefBehavior(Call);
146       ModRefInfo MRI = createModRefInfo(MRB);
147 
148       // If the call doesn't access memory, we're done.
149       if (isNoModRef(MRI))
150         continue;
151 
152       if (!AliasAnalysis::onlyAccessesArgPointees(MRB)) {
153         // The call could access any memory. If that includes writes, note it.
154         if (isModSet(MRI))
155           WritesMemory = true;
156         // If it reads, note it.
157         if (isRefSet(MRI))
158           ReadsMemory = true;
159         continue;
160       }
161 
162       // Check whether all pointer arguments point to local memory, and
163       // ignore calls that only access local memory.
164       for (auto CI = Call->arg_begin(), CE = Call->arg_end(); CI != CE; ++CI) {
165         Value *Arg = *CI;
166         if (!Arg->getType()->isPtrOrPtrVectorTy())
167           continue;
168 
169         AAMDNodes AAInfo;
170         I->getAAMetadata(AAInfo);
171         MemoryLocation Loc = MemoryLocation::getBeforeOrAfter(Arg, AAInfo);
172 
173         // Skip accesses to local or constant memory as they don't impact the
174         // externally visible mod/ref behavior.
175         if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
176           continue;
177 
178         if (isModSet(MRI))
179           // Writes non-local memory.
180           WritesMemory = true;
181         if (isRefSet(MRI))
182           // Ok, it reads non-local memory.
183           ReadsMemory = true;
184       }
185       continue;
186     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
187       // Ignore non-volatile loads from local memory. (Atomic is okay here.)
188       if (!LI->isVolatile()) {
189         MemoryLocation Loc = MemoryLocation::get(LI);
190         if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
191           continue;
192       }
193     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
194       // Ignore non-volatile stores to local memory. (Atomic is okay here.)
195       if (!SI->isVolatile()) {
196         MemoryLocation Loc = MemoryLocation::get(SI);
197         if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
198           continue;
199       }
200     } else if (VAArgInst *VI = dyn_cast<VAArgInst>(I)) {
201       // Ignore vaargs on local memory.
202       MemoryLocation Loc = MemoryLocation::get(VI);
203       if (AAR.pointsToConstantMemory(Loc, /*OrLocal=*/true))
204         continue;
205     }
206 
207     // Any remaining instructions need to be taken seriously!  Check if they
208     // read or write memory.
209     //
210     // Writes memory, remember that.
211     WritesMemory |= I->mayWriteToMemory();
212 
213     // If this instruction may read memory, remember that.
214     ReadsMemory |= I->mayReadFromMemory();
215   }
216 
217   if (WritesMemory) {
218     if (!ReadsMemory)
219       return MAK_WriteOnly;
220     else
221       return MAK_MayWrite;
222   }
223 
224   return ReadsMemory ? MAK_ReadOnly : MAK_ReadNone;
225 }
226 
227 MemoryAccessKind llvm::computeFunctionBodyMemoryAccess(Function &F,
228                                                        AAResults &AAR) {
229   return checkFunctionMemoryAccess(F, /*ThisBody=*/true, AAR, {});
230 }
231 
232 /// Deduce readonly/readnone attributes for the SCC.
233 template <typename AARGetterT>
234 static bool addReadAttrs(const SCCNodeSet &SCCNodes, AARGetterT &&AARGetter) {
235   // Check if any of the functions in the SCC read or write memory.  If they
236   // write memory then they can't be marked readnone or readonly.
237   bool ReadsMemory = false;
238   bool WritesMemory = false;
239   for (Function *F : SCCNodes) {
240     // Call the callable parameter to look up AA results for this function.
241     AAResults &AAR = AARGetter(*F);
242 
243     // Non-exact function definitions may not be selected at link time, and an
244     // alternative version that writes to memory may be selected.  See the
245     // comment on GlobalValue::isDefinitionExact for more details.
246     switch (checkFunctionMemoryAccess(*F, F->hasExactDefinition(),
247                                       AAR, SCCNodes)) {
248     case MAK_MayWrite:
249       return false;
250     case MAK_ReadOnly:
251       ReadsMemory = true;
252       break;
253     case MAK_WriteOnly:
254       WritesMemory = true;
255       break;
256     case MAK_ReadNone:
257       // Nothing to do!
258       break;
259     }
260   }
261 
262   // If the SCC contains both functions that read and functions that write, then
263   // we cannot add readonly attributes.
264   if (ReadsMemory && WritesMemory)
265     return false;
266 
267   // Success!  Functions in this SCC do not access memory, or only read memory.
268   // Give them the appropriate attribute.
269   bool MadeChange = false;
270 
271   for (Function *F : SCCNodes) {
272     if (F->doesNotAccessMemory())
273       // Already perfect!
274       continue;
275 
276     if (F->onlyReadsMemory() && ReadsMemory)
277       // No change.
278       continue;
279 
280     if (F->doesNotReadMemory() && WritesMemory)
281       continue;
282 
283     MadeChange = true;
284 
285     // Clear out any existing attributes.
286     AttrBuilder AttrsToRemove;
287     AttrsToRemove.addAttribute(Attribute::ReadOnly);
288     AttrsToRemove.addAttribute(Attribute::ReadNone);
289     AttrsToRemove.addAttribute(Attribute::WriteOnly);
290 
291     if (!WritesMemory && !ReadsMemory) {
292       // Clear out any "access range attributes" if readnone was deduced.
293       AttrsToRemove.addAttribute(Attribute::ArgMemOnly);
294       AttrsToRemove.addAttribute(Attribute::InaccessibleMemOnly);
295       AttrsToRemove.addAttribute(Attribute::InaccessibleMemOrArgMemOnly);
296     }
297     F->removeAttributes(AttributeList::FunctionIndex, AttrsToRemove);
298 
299     // Add in the new attribute.
300     if (WritesMemory && !ReadsMemory)
301       F->addFnAttr(Attribute::WriteOnly);
302     else
303       F->addFnAttr(ReadsMemory ? Attribute::ReadOnly : Attribute::ReadNone);
304 
305     if (WritesMemory && !ReadsMemory)
306       ++NumWriteOnly;
307     else if (ReadsMemory)
308       ++NumReadOnly;
309     else
310       ++NumReadNone;
311   }
312 
313   return MadeChange;
314 }
315 
316 namespace {
317 
318 /// For a given pointer Argument, this retains a list of Arguments of functions
319 /// in the same SCC that the pointer data flows into. We use this to build an
320 /// SCC of the arguments.
321 struct ArgumentGraphNode {
322   Argument *Definition;
323   SmallVector<ArgumentGraphNode *, 4> Uses;
324 };
325 
326 class ArgumentGraph {
327   // We store pointers to ArgumentGraphNode objects, so it's important that
328   // that they not move around upon insert.
329   using ArgumentMapTy = std::map<Argument *, ArgumentGraphNode>;
330 
331   ArgumentMapTy ArgumentMap;
332 
333   // There is no root node for the argument graph, in fact:
334   //   void f(int *x, int *y) { if (...) f(x, y); }
335   // is an example where the graph is disconnected. The SCCIterator requires a
336   // single entry point, so we maintain a fake ("synthetic") root node that
337   // uses every node. Because the graph is directed and nothing points into
338   // the root, it will not participate in any SCCs (except for its own).
339   ArgumentGraphNode SyntheticRoot;
340 
341 public:
342   ArgumentGraph() { SyntheticRoot.Definition = nullptr; }
343 
344   using iterator = SmallVectorImpl<ArgumentGraphNode *>::iterator;
345 
346   iterator begin() { return SyntheticRoot.Uses.begin(); }
347   iterator end() { return SyntheticRoot.Uses.end(); }
348   ArgumentGraphNode *getEntryNode() { return &SyntheticRoot; }
349 
350   ArgumentGraphNode *operator[](Argument *A) {
351     ArgumentGraphNode &Node = ArgumentMap[A];
352     Node.Definition = A;
353     SyntheticRoot.Uses.push_back(&Node);
354     return &Node;
355   }
356 };
357 
358 /// This tracker checks whether callees are in the SCC, and if so it does not
359 /// consider that a capture, instead adding it to the "Uses" list and
360 /// continuing with the analysis.
361 struct ArgumentUsesTracker : public CaptureTracker {
362   ArgumentUsesTracker(const SCCNodeSet &SCCNodes) : SCCNodes(SCCNodes) {}
363 
364   void tooManyUses() override { Captured = true; }
365 
366   bool captured(const Use *U) override {
367     CallBase *CB = dyn_cast<CallBase>(U->getUser());
368     if (!CB) {
369       Captured = true;
370       return true;
371     }
372 
373     Function *F = CB->getCalledFunction();
374     if (!F || !F->hasExactDefinition() || !SCCNodes.count(F)) {
375       Captured = true;
376       return true;
377     }
378 
379     // Note: the callee and the two successor blocks *follow* the argument
380     // operands.  This means there is no need to adjust UseIndex to account for
381     // these.
382 
383     unsigned UseIndex =
384         std::distance(const_cast<const Use *>(CB->arg_begin()), U);
385 
386     assert(UseIndex < CB->data_operands_size() &&
387            "Indirect function calls should have been filtered above!");
388 
389     if (UseIndex >= CB->getNumArgOperands()) {
390       // Data operand, but not a argument operand -- must be a bundle operand
391       assert(CB->hasOperandBundles() && "Must be!");
392 
393       // CaptureTracking told us that we're being captured by an operand bundle
394       // use.  In this case it does not matter if the callee is within our SCC
395       // or not -- we've been captured in some unknown way, and we have to be
396       // conservative.
397       Captured = true;
398       return true;
399     }
400 
401     if (UseIndex >= F->arg_size()) {
402       assert(F->isVarArg() && "More params than args in non-varargs call");
403       Captured = true;
404       return true;
405     }
406 
407     Uses.push_back(&*std::next(F->arg_begin(), UseIndex));
408     return false;
409   }
410 
411   // True only if certainly captured (used outside our SCC).
412   bool Captured = false;
413 
414   // Uses within our SCC.
415   SmallVector<Argument *, 4> Uses;
416 
417   const SCCNodeSet &SCCNodes;
418 };
419 
420 } // end anonymous namespace
421 
422 namespace llvm {
423 
424 template <> struct GraphTraits<ArgumentGraphNode *> {
425   using NodeRef = ArgumentGraphNode *;
426   using ChildIteratorType = SmallVectorImpl<ArgumentGraphNode *>::iterator;
427 
428   static NodeRef getEntryNode(NodeRef A) { return A; }
429   static ChildIteratorType child_begin(NodeRef N) { return N->Uses.begin(); }
430   static ChildIteratorType child_end(NodeRef N) { return N->Uses.end(); }
431 };
432 
433 template <>
434 struct GraphTraits<ArgumentGraph *> : public GraphTraits<ArgumentGraphNode *> {
435   static NodeRef getEntryNode(ArgumentGraph *AG) { return AG->getEntryNode(); }
436 
437   static ChildIteratorType nodes_begin(ArgumentGraph *AG) {
438     return AG->begin();
439   }
440 
441   static ChildIteratorType nodes_end(ArgumentGraph *AG) { return AG->end(); }
442 };
443 
444 } // end namespace llvm
445 
446 /// Returns Attribute::None, Attribute::ReadOnly or Attribute::ReadNone.
447 static Attribute::AttrKind
448 determinePointerReadAttrs(Argument *A,
449                           const SmallPtrSet<Argument *, 8> &SCCNodes) {
450   SmallVector<Use *, 32> Worklist;
451   SmallPtrSet<Use *, 32> Visited;
452 
453   // inalloca arguments are always clobbered by the call.
454   if (A->hasInAllocaAttr() || A->hasPreallocatedAttr())
455     return Attribute::None;
456 
457   bool IsRead = false;
458   // We don't need to track IsWritten. If A is written to, return immediately.
459 
460   for (Use &U : A->uses()) {
461     Visited.insert(&U);
462     Worklist.push_back(&U);
463   }
464 
465   while (!Worklist.empty()) {
466     Use *U = Worklist.pop_back_val();
467     Instruction *I = cast<Instruction>(U->getUser());
468 
469     switch (I->getOpcode()) {
470     case Instruction::BitCast:
471     case Instruction::GetElementPtr:
472     case Instruction::PHI:
473     case Instruction::Select:
474     case Instruction::AddrSpaceCast:
475       // The original value is not read/written via this if the new value isn't.
476       for (Use &UU : I->uses())
477         if (Visited.insert(&UU).second)
478           Worklist.push_back(&UU);
479       break;
480 
481     case Instruction::Call:
482     case Instruction::Invoke: {
483       bool Captures = true;
484 
485       if (I->getType()->isVoidTy())
486         Captures = false;
487 
488       auto AddUsersToWorklistIfCapturing = [&] {
489         if (Captures)
490           for (Use &UU : I->uses())
491             if (Visited.insert(&UU).second)
492               Worklist.push_back(&UU);
493       };
494 
495       CallBase &CB = cast<CallBase>(*I);
496       if (CB.doesNotAccessMemory()) {
497         AddUsersToWorklistIfCapturing();
498         continue;
499       }
500 
501       Function *F = CB.getCalledFunction();
502       if (!F) {
503         if (CB.onlyReadsMemory()) {
504           IsRead = true;
505           AddUsersToWorklistIfCapturing();
506           continue;
507         }
508         return Attribute::None;
509       }
510 
511       // Note: the callee and the two successor blocks *follow* the argument
512       // operands.  This means there is no need to adjust UseIndex to account
513       // for these.
514 
515       unsigned UseIndex = std::distance(CB.arg_begin(), U);
516 
517       // U cannot be the callee operand use: since we're exploring the
518       // transitive uses of an Argument, having such a use be a callee would
519       // imply the call site is an indirect call or invoke; and we'd take the
520       // early exit above.
521       assert(UseIndex < CB.data_operands_size() &&
522              "Data operand use expected!");
523 
524       bool IsOperandBundleUse = UseIndex >= CB.getNumArgOperands();
525 
526       if (UseIndex >= F->arg_size() && !IsOperandBundleUse) {
527         assert(F->isVarArg() && "More params than args in non-varargs call");
528         return Attribute::None;
529       }
530 
531       Captures &= !CB.doesNotCapture(UseIndex);
532 
533       // Since the optimizer (by design) cannot see the data flow corresponding
534       // to a operand bundle use, these cannot participate in the optimistic SCC
535       // analysis.  Instead, we model the operand bundle uses as arguments in
536       // call to a function external to the SCC.
537       if (IsOperandBundleUse ||
538           !SCCNodes.count(&*std::next(F->arg_begin(), UseIndex))) {
539 
540         // The accessors used on call site here do the right thing for calls and
541         // invokes with operand bundles.
542 
543         if (!CB.onlyReadsMemory() && !CB.onlyReadsMemory(UseIndex))
544           return Attribute::None;
545         if (!CB.doesNotAccessMemory(UseIndex))
546           IsRead = true;
547       }
548 
549       AddUsersToWorklistIfCapturing();
550       break;
551     }
552 
553     case Instruction::Load:
554       // A volatile load has side effects beyond what readonly can be relied
555       // upon.
556       if (cast<LoadInst>(I)->isVolatile())
557         return Attribute::None;
558 
559       IsRead = true;
560       break;
561 
562     case Instruction::ICmp:
563     case Instruction::Ret:
564       break;
565 
566     default:
567       return Attribute::None;
568     }
569   }
570 
571   return IsRead ? Attribute::ReadOnly : Attribute::ReadNone;
572 }
573 
574 /// Deduce returned attributes for the SCC.
575 static bool addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes) {
576   bool Changed = false;
577 
578   // Check each function in turn, determining if an argument is always returned.
579   for (Function *F : SCCNodes) {
580     // We can infer and propagate function attributes only when we know that the
581     // definition we'll get at link time is *exactly* the definition we see now.
582     // For more details, see GlobalValue::mayBeDerefined.
583     if (!F->hasExactDefinition())
584       continue;
585 
586     if (F->getReturnType()->isVoidTy())
587       continue;
588 
589     // There is nothing to do if an argument is already marked as 'returned'.
590     if (llvm::any_of(F->args(),
591                      [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
592       continue;
593 
594     auto FindRetArg = [&]() -> Value * {
595       Value *RetArg = nullptr;
596       for (BasicBlock &BB : *F)
597         if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
598           // Note that stripPointerCasts should look through functions with
599           // returned arguments.
600           Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
601           if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
602             return nullptr;
603 
604           if (!RetArg)
605             RetArg = RetVal;
606           else if (RetArg != RetVal)
607             return nullptr;
608         }
609 
610       return RetArg;
611     };
612 
613     if (Value *RetArg = FindRetArg()) {
614       auto *A = cast<Argument>(RetArg);
615       A->addAttr(Attribute::Returned);
616       ++NumReturned;
617       Changed = true;
618     }
619   }
620 
621   return Changed;
622 }
623 
624 /// If a callsite has arguments that are also arguments to the parent function,
625 /// try to propagate attributes from the callsite's arguments to the parent's
626 /// arguments. This may be important because inlining can cause information loss
627 /// when attribute knowledge disappears with the inlined call.
628 static bool addArgumentAttrsFromCallsites(Function &F) {
629   if (!EnableNonnullArgPropagation)
630     return false;
631 
632   bool Changed = false;
633 
634   // For an argument attribute to transfer from a callsite to the parent, the
635   // call must be guaranteed to execute every time the parent is called.
636   // Conservatively, just check for calls in the entry block that are guaranteed
637   // to execute.
638   // TODO: This could be enhanced by testing if the callsite post-dominates the
639   // entry block or by doing simple forward walks or backward walks to the
640   // callsite.
641   BasicBlock &Entry = F.getEntryBlock();
642   for (Instruction &I : Entry) {
643     if (auto *CB = dyn_cast<CallBase>(&I)) {
644       if (auto *CalledFunc = CB->getCalledFunction()) {
645         for (auto &CSArg : CalledFunc->args()) {
646           if (!CSArg.hasNonNullAttr(/* AllowUndefOrPoison */ false))
647             continue;
648 
649           // If the non-null callsite argument operand is an argument to 'F'
650           // (the caller) and the call is guaranteed to execute, then the value
651           // must be non-null throughout 'F'.
652           auto *FArg = dyn_cast<Argument>(CB->getArgOperand(CSArg.getArgNo()));
653           if (FArg && !FArg->hasNonNullAttr()) {
654             FArg->addAttr(Attribute::NonNull);
655             Changed = true;
656           }
657         }
658       }
659     }
660     if (!isGuaranteedToTransferExecutionToSuccessor(&I))
661       break;
662   }
663 
664   return Changed;
665 }
666 
667 static bool addReadAttr(Argument *A, Attribute::AttrKind R) {
668   assert((R == Attribute::ReadOnly || R == Attribute::ReadNone)
669          && "Must be a Read attribute.");
670   assert(A && "Argument must not be null.");
671 
672   // If the argument already has the attribute, nothing needs to be done.
673   if (A->hasAttribute(R))
674       return false;
675 
676   // Otherwise, remove potentially conflicting attribute, add the new one,
677   // and update statistics.
678   A->removeAttr(Attribute::WriteOnly);
679   A->removeAttr(Attribute::ReadOnly);
680   A->removeAttr(Attribute::ReadNone);
681   A->addAttr(R);
682   R == Attribute::ReadOnly ? ++NumReadOnlyArg : ++NumReadNoneArg;
683   return true;
684 }
685 
686 /// Deduce nocapture attributes for the SCC.
687 static bool addArgumentAttrs(const SCCNodeSet &SCCNodes) {
688   bool Changed = false;
689 
690   ArgumentGraph AG;
691 
692   // Check each function in turn, determining which pointer arguments are not
693   // captured.
694   for (Function *F : SCCNodes) {
695     // We can infer and propagate function attributes only when we know that the
696     // definition we'll get at link time is *exactly* the definition we see now.
697     // For more details, see GlobalValue::mayBeDerefined.
698     if (!F->hasExactDefinition())
699       continue;
700 
701     Changed |= addArgumentAttrsFromCallsites(*F);
702 
703     // Functions that are readonly (or readnone) and nounwind and don't return
704     // a value can't capture arguments. Don't analyze them.
705     if (F->onlyReadsMemory() && F->doesNotThrow() &&
706         F->getReturnType()->isVoidTy()) {
707       for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
708            ++A) {
709         if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
710           A->addAttr(Attribute::NoCapture);
711           ++NumNoCapture;
712           Changed = true;
713         }
714       }
715       continue;
716     }
717 
718     for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
719          ++A) {
720       if (!A->getType()->isPointerTy())
721         continue;
722       bool HasNonLocalUses = false;
723       if (!A->hasNoCaptureAttr()) {
724         ArgumentUsesTracker Tracker(SCCNodes);
725         PointerMayBeCaptured(&*A, &Tracker);
726         if (!Tracker.Captured) {
727           if (Tracker.Uses.empty()) {
728             // If it's trivially not captured, mark it nocapture now.
729             A->addAttr(Attribute::NoCapture);
730             ++NumNoCapture;
731             Changed = true;
732           } else {
733             // If it's not trivially captured and not trivially not captured,
734             // then it must be calling into another function in our SCC. Save
735             // its particulars for Argument-SCC analysis later.
736             ArgumentGraphNode *Node = AG[&*A];
737             for (Argument *Use : Tracker.Uses) {
738               Node->Uses.push_back(AG[Use]);
739               if (Use != &*A)
740                 HasNonLocalUses = true;
741             }
742           }
743         }
744         // Otherwise, it's captured. Don't bother doing SCC analysis on it.
745       }
746       if (!HasNonLocalUses && !A->onlyReadsMemory()) {
747         // Can we determine that it's readonly/readnone without doing an SCC?
748         // Note that we don't allow any calls at all here, or else our result
749         // will be dependent on the iteration order through the functions in the
750         // SCC.
751         SmallPtrSet<Argument *, 8> Self;
752         Self.insert(&*A);
753         Attribute::AttrKind R = determinePointerReadAttrs(&*A, Self);
754         if (R != Attribute::None)
755           Changed = addReadAttr(A, R);
756       }
757     }
758   }
759 
760   // The graph we've collected is partial because we stopped scanning for
761   // argument uses once we solved the argument trivially. These partial nodes
762   // show up as ArgumentGraphNode objects with an empty Uses list, and for
763   // these nodes the final decision about whether they capture has already been
764   // made.  If the definition doesn't have a 'nocapture' attribute by now, it
765   // captures.
766 
767   for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
768     const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
769     if (ArgumentSCC.size() == 1) {
770       if (!ArgumentSCC[0]->Definition)
771         continue; // synthetic root node
772 
773       // eg. "void f(int* x) { if (...) f(x); }"
774       if (ArgumentSCC[0]->Uses.size() == 1 &&
775           ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
776         Argument *A = ArgumentSCC[0]->Definition;
777         A->addAttr(Attribute::NoCapture);
778         ++NumNoCapture;
779         Changed = true;
780       }
781       continue;
782     }
783 
784     bool SCCCaptured = false;
785     for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
786          I != E && !SCCCaptured; ++I) {
787       ArgumentGraphNode *Node = *I;
788       if (Node->Uses.empty()) {
789         if (!Node->Definition->hasNoCaptureAttr())
790           SCCCaptured = true;
791       }
792     }
793     if (SCCCaptured)
794       continue;
795 
796     SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
797     // Fill ArgumentSCCNodes with the elements of the ArgumentSCC.  Used for
798     // quickly looking up whether a given Argument is in this ArgumentSCC.
799     for (ArgumentGraphNode *I : ArgumentSCC) {
800       ArgumentSCCNodes.insert(I->Definition);
801     }
802 
803     for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
804          I != E && !SCCCaptured; ++I) {
805       ArgumentGraphNode *N = *I;
806       for (ArgumentGraphNode *Use : N->Uses) {
807         Argument *A = Use->Definition;
808         if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
809           continue;
810         SCCCaptured = true;
811         break;
812       }
813     }
814     if (SCCCaptured)
815       continue;
816 
817     for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
818       Argument *A = ArgumentSCC[i]->Definition;
819       A->addAttr(Attribute::NoCapture);
820       ++NumNoCapture;
821       Changed = true;
822     }
823 
824     // We also want to compute readonly/readnone. With a small number of false
825     // negatives, we can assume that any pointer which is captured isn't going
826     // to be provably readonly or readnone, since by definition we can't
827     // analyze all uses of a captured pointer.
828     //
829     // The false negatives happen when the pointer is captured by a function
830     // that promises readonly/readnone behaviour on the pointer, then the
831     // pointer's lifetime ends before anything that writes to arbitrary memory.
832     // Also, a readonly/readnone pointer may be returned, but returning a
833     // pointer is capturing it.
834 
835     Attribute::AttrKind ReadAttr = Attribute::ReadNone;
836     for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
837       Argument *A = ArgumentSCC[i]->Definition;
838       Attribute::AttrKind K = determinePointerReadAttrs(A, ArgumentSCCNodes);
839       if (K == Attribute::ReadNone)
840         continue;
841       if (K == Attribute::ReadOnly) {
842         ReadAttr = Attribute::ReadOnly;
843         continue;
844       }
845       ReadAttr = K;
846       break;
847     }
848 
849     if (ReadAttr != Attribute::None) {
850       for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
851         Argument *A = ArgumentSCC[i]->Definition;
852         Changed = addReadAttr(A, ReadAttr);
853       }
854     }
855   }
856 
857   return Changed;
858 }
859 
860 /// Tests whether a function is "malloc-like".
861 ///
862 /// A function is "malloc-like" if it returns either null or a pointer that
863 /// doesn't alias any other pointer visible to the caller.
864 static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
865   SmallSetVector<Value *, 8> FlowsToReturn;
866   for (BasicBlock &BB : *F)
867     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
868       FlowsToReturn.insert(Ret->getReturnValue());
869 
870   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
871     Value *RetVal = FlowsToReturn[i];
872 
873     if (Constant *C = dyn_cast<Constant>(RetVal)) {
874       if (!C->isNullValue() && !isa<UndefValue>(C))
875         return false;
876 
877       continue;
878     }
879 
880     if (isa<Argument>(RetVal))
881       return false;
882 
883     if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
884       switch (RVI->getOpcode()) {
885       // Extend the analysis by looking upwards.
886       case Instruction::BitCast:
887       case Instruction::GetElementPtr:
888       case Instruction::AddrSpaceCast:
889         FlowsToReturn.insert(RVI->getOperand(0));
890         continue;
891       case Instruction::Select: {
892         SelectInst *SI = cast<SelectInst>(RVI);
893         FlowsToReturn.insert(SI->getTrueValue());
894         FlowsToReturn.insert(SI->getFalseValue());
895         continue;
896       }
897       case Instruction::PHI: {
898         PHINode *PN = cast<PHINode>(RVI);
899         for (Value *IncValue : PN->incoming_values())
900           FlowsToReturn.insert(IncValue);
901         continue;
902       }
903 
904       // Check whether the pointer came from an allocation.
905       case Instruction::Alloca:
906         break;
907       case Instruction::Call:
908       case Instruction::Invoke: {
909         CallBase &CB = cast<CallBase>(*RVI);
910         if (CB.hasRetAttr(Attribute::NoAlias))
911           break;
912         if (CB.getCalledFunction() && SCCNodes.count(CB.getCalledFunction()))
913           break;
914         LLVM_FALLTHROUGH;
915       }
916       default:
917         return false; // Did not come from an allocation.
918       }
919 
920     if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
921       return false;
922   }
923 
924   return true;
925 }
926 
927 /// Deduce noalias attributes for the SCC.
928 static bool addNoAliasAttrs(const SCCNodeSet &SCCNodes) {
929   // Check each function in turn, determining which functions return noalias
930   // pointers.
931   for (Function *F : SCCNodes) {
932     // Already noalias.
933     if (F->returnDoesNotAlias())
934       continue;
935 
936     // We can infer and propagate function attributes only when we know that the
937     // definition we'll get at link time is *exactly* the definition we see now.
938     // For more details, see GlobalValue::mayBeDerefined.
939     if (!F->hasExactDefinition())
940       return false;
941 
942     // We annotate noalias return values, which are only applicable to
943     // pointer types.
944     if (!F->getReturnType()->isPointerTy())
945       continue;
946 
947     if (!isFunctionMallocLike(F, SCCNodes))
948       return false;
949   }
950 
951   bool MadeChange = false;
952   for (Function *F : SCCNodes) {
953     if (F->returnDoesNotAlias() ||
954         !F->getReturnType()->isPointerTy())
955       continue;
956 
957     F->setReturnDoesNotAlias();
958     ++NumNoAlias;
959     MadeChange = true;
960   }
961 
962   return MadeChange;
963 }
964 
965 /// Tests whether this function is known to not return null.
966 ///
967 /// Requires that the function returns a pointer.
968 ///
969 /// Returns true if it believes the function will not return a null, and sets
970 /// \p Speculative based on whether the returned conclusion is a speculative
971 /// conclusion due to SCC calls.
972 static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
973                             bool &Speculative) {
974   assert(F->getReturnType()->isPointerTy() &&
975          "nonnull only meaningful on pointer types");
976   Speculative = false;
977 
978   SmallSetVector<Value *, 8> FlowsToReturn;
979   for (BasicBlock &BB : *F)
980     if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
981       FlowsToReturn.insert(Ret->getReturnValue());
982 
983   auto &DL = F->getParent()->getDataLayout();
984 
985   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
986     Value *RetVal = FlowsToReturn[i];
987 
988     // If this value is locally known to be non-null, we're good
989     if (isKnownNonZero(RetVal, DL))
990       continue;
991 
992     // Otherwise, we need to look upwards since we can't make any local
993     // conclusions.
994     Instruction *RVI = dyn_cast<Instruction>(RetVal);
995     if (!RVI)
996       return false;
997     switch (RVI->getOpcode()) {
998     // Extend the analysis by looking upwards.
999     case Instruction::BitCast:
1000     case Instruction::GetElementPtr:
1001     case Instruction::AddrSpaceCast:
1002       FlowsToReturn.insert(RVI->getOperand(0));
1003       continue;
1004     case Instruction::Select: {
1005       SelectInst *SI = cast<SelectInst>(RVI);
1006       FlowsToReturn.insert(SI->getTrueValue());
1007       FlowsToReturn.insert(SI->getFalseValue());
1008       continue;
1009     }
1010     case Instruction::PHI: {
1011       PHINode *PN = cast<PHINode>(RVI);
1012       for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1013         FlowsToReturn.insert(PN->getIncomingValue(i));
1014       continue;
1015     }
1016     case Instruction::Call:
1017     case Instruction::Invoke: {
1018       CallBase &CB = cast<CallBase>(*RVI);
1019       Function *Callee = CB.getCalledFunction();
1020       // A call to a node within the SCC is assumed to return null until
1021       // proven otherwise
1022       if (Callee && SCCNodes.count(Callee)) {
1023         Speculative = true;
1024         continue;
1025       }
1026       return false;
1027     }
1028     default:
1029       return false; // Unknown source, may be null
1030     };
1031     llvm_unreachable("should have either continued or returned");
1032   }
1033 
1034   return true;
1035 }
1036 
1037 /// Deduce nonnull attributes for the SCC.
1038 static bool addNonNullAttrs(const SCCNodeSet &SCCNodes) {
1039   // Speculative that all functions in the SCC return only nonnull
1040   // pointers.  We may refute this as we analyze functions.
1041   bool SCCReturnsNonNull = true;
1042 
1043   bool MadeChange = false;
1044 
1045   // Check each function in turn, determining which functions return nonnull
1046   // pointers.
1047   for (Function *F : SCCNodes) {
1048     // Already nonnull.
1049     if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1050                                         Attribute::NonNull))
1051       continue;
1052 
1053     // We can infer and propagate function attributes only when we know that the
1054     // definition we'll get at link time is *exactly* the definition we see now.
1055     // For more details, see GlobalValue::mayBeDerefined.
1056     if (!F->hasExactDefinition())
1057       return false;
1058 
1059     // We annotate nonnull return values, which are only applicable to
1060     // pointer types.
1061     if (!F->getReturnType()->isPointerTy())
1062       continue;
1063 
1064     bool Speculative = false;
1065     if (isReturnNonNull(F, SCCNodes, Speculative)) {
1066       if (!Speculative) {
1067         // Mark the function eagerly since we may discover a function
1068         // which prevents us from speculating about the entire SCC
1069         LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1070                           << " as nonnull\n");
1071         F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
1072         ++NumNonNullReturn;
1073         MadeChange = true;
1074       }
1075       continue;
1076     }
1077     // At least one function returns something which could be null, can't
1078     // speculate any more.
1079     SCCReturnsNonNull = false;
1080   }
1081 
1082   if (SCCReturnsNonNull) {
1083     for (Function *F : SCCNodes) {
1084       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1085                                           Attribute::NonNull) ||
1086           !F->getReturnType()->isPointerTy())
1087         continue;
1088 
1089       LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
1090       F->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
1091       ++NumNonNullReturn;
1092       MadeChange = true;
1093     }
1094   }
1095 
1096   return MadeChange;
1097 }
1098 
1099 namespace {
1100 
1101 /// Collects a set of attribute inference requests and performs them all in one
1102 /// go on a single SCC Node. Inference involves scanning function bodies
1103 /// looking for instructions that violate attribute assumptions.
1104 /// As soon as all the bodies are fine we are free to set the attribute.
1105 /// Customization of inference for individual attributes is performed by
1106 /// providing a handful of predicates for each attribute.
1107 class AttributeInferer {
1108 public:
1109   /// Describes a request for inference of a single attribute.
1110   struct InferenceDescriptor {
1111 
1112     /// Returns true if this function does not have to be handled.
1113     /// General intent for this predicate is to provide an optimization
1114     /// for functions that do not need this attribute inference at all
1115     /// (say, for functions that already have the attribute).
1116     std::function<bool(const Function &)> SkipFunction;
1117 
1118     /// Returns true if this instruction violates attribute assumptions.
1119     std::function<bool(Instruction &)> InstrBreaksAttribute;
1120 
1121     /// Sets the inferred attribute for this function.
1122     std::function<void(Function &)> SetAttribute;
1123 
1124     /// Attribute we derive.
1125     Attribute::AttrKind AKind;
1126 
1127     /// If true, only "exact" definitions can be used to infer this attribute.
1128     /// See GlobalValue::isDefinitionExact.
1129     bool RequiresExactDefinition;
1130 
1131     InferenceDescriptor(Attribute::AttrKind AK,
1132                         std::function<bool(const Function &)> SkipFunc,
1133                         std::function<bool(Instruction &)> InstrScan,
1134                         std::function<void(Function &)> SetAttr,
1135                         bool ReqExactDef)
1136         : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1137           SetAttribute(SetAttr), AKind(AK),
1138           RequiresExactDefinition(ReqExactDef) {}
1139   };
1140 
1141 private:
1142   SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1143 
1144 public:
1145   void registerAttrInference(InferenceDescriptor AttrInference) {
1146     InferenceDescriptors.push_back(AttrInference);
1147   }
1148 
1149   bool run(const SCCNodeSet &SCCNodes);
1150 };
1151 
1152 /// Perform all the requested attribute inference actions according to the
1153 /// attribute predicates stored before.
1154 bool AttributeInferer::run(const SCCNodeSet &SCCNodes) {
1155   SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1156   // Go through all the functions in SCC and check corresponding attribute
1157   // assumptions for each of them. Attributes that are invalid for this SCC
1158   // will be removed from InferInSCC.
1159   for (Function *F : SCCNodes) {
1160 
1161     // No attributes whose assumptions are still valid - done.
1162     if (InferInSCC.empty())
1163       return false;
1164 
1165     // Check if our attributes ever need scanning/can be scanned.
1166     llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1167       if (ID.SkipFunction(*F))
1168         return false;
1169 
1170       // Remove from further inference (invalidate) when visiting a function
1171       // that has no instructions to scan/has an unsuitable definition.
1172       return F->isDeclaration() ||
1173              (ID.RequiresExactDefinition && !F->hasExactDefinition());
1174     });
1175 
1176     // For each attribute still in InferInSCC that doesn't explicitly skip F,
1177     // set up the F instructions scan to verify assumptions of the attribute.
1178     SmallVector<InferenceDescriptor, 4> InferInThisFunc;
1179     llvm::copy_if(
1180         InferInSCC, std::back_inserter(InferInThisFunc),
1181         [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1182 
1183     if (InferInThisFunc.empty())
1184       continue;
1185 
1186     // Start instruction scan.
1187     for (Instruction &I : instructions(*F)) {
1188       llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1189         if (!ID.InstrBreaksAttribute(I))
1190           return false;
1191         // Remove attribute from further inference on any other functions
1192         // because attribute assumptions have just been violated.
1193         llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1194           return D.AKind == ID.AKind;
1195         });
1196         // Remove attribute from the rest of current instruction scan.
1197         return true;
1198       });
1199 
1200       if (InferInThisFunc.empty())
1201         break;
1202     }
1203   }
1204 
1205   if (InferInSCC.empty())
1206     return false;
1207 
1208   bool Changed = false;
1209   for (Function *F : SCCNodes)
1210     // At this point InferInSCC contains only functions that were either:
1211     //   - explicitly skipped from scan/inference, or
1212     //   - verified to have no instructions that break attribute assumptions.
1213     // Hence we just go and force the attribute for all non-skipped functions.
1214     for (auto &ID : InferInSCC) {
1215       if (ID.SkipFunction(*F))
1216         continue;
1217       Changed = true;
1218       ID.SetAttribute(*F);
1219     }
1220   return Changed;
1221 }
1222 
1223 struct SCCNodesResult {
1224   SCCNodeSet SCCNodes;
1225   bool HasUnknownCall;
1226 };
1227 
1228 } // end anonymous namespace
1229 
1230 /// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1231 static bool InstrBreaksNonConvergent(Instruction &I,
1232                                      const SCCNodeSet &SCCNodes) {
1233   const CallBase *CB = dyn_cast<CallBase>(&I);
1234   // Breaks non-convergent assumption if CS is a convergent call to a function
1235   // not in the SCC.
1236   return CB && CB->isConvergent() &&
1237          SCCNodes.count(CB->getCalledFunction()) == 0;
1238 }
1239 
1240 /// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1241 static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1242   if (!I.mayThrow())
1243     return false;
1244   if (const auto *CI = dyn_cast<CallInst>(&I)) {
1245     if (Function *Callee = CI->getCalledFunction()) {
1246       // I is a may-throw call to a function inside our SCC. This doesn't
1247       // invalidate our current working assumption that the SCC is no-throw; we
1248       // just have to scan that other function.
1249       if (SCCNodes.contains(Callee))
1250         return false;
1251     }
1252   }
1253   return true;
1254 }
1255 
1256 /// Helper for NoFree inference predicate InstrBreaksAttribute.
1257 static bool InstrBreaksNoFree(Instruction &I, const SCCNodeSet &SCCNodes) {
1258   CallBase *CB = dyn_cast<CallBase>(&I);
1259   if (!CB)
1260     return false;
1261 
1262   Function *Callee = CB->getCalledFunction();
1263   if (!Callee)
1264     return true;
1265 
1266   if (Callee->doesNotFreeMemory())
1267     return false;
1268 
1269   if (SCCNodes.contains(Callee))
1270     return false;
1271 
1272   return true;
1273 }
1274 
1275 /// Attempt to remove convergent function attribute when possible.
1276 ///
1277 /// Returns true if any changes to function attributes were made.
1278 static bool inferConvergent(const SCCNodeSet &SCCNodes) {
1279   AttributeInferer AI;
1280 
1281   // Request to remove the convergent attribute from all functions in the SCC
1282   // if every callsite within the SCC is not convergent (except for calls
1283   // to functions within the SCC).
1284   // Note: Removal of the attr from the callsites will happen in
1285   // InstCombineCalls separately.
1286   AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1287       Attribute::Convergent,
1288       // Skip non-convergent functions.
1289       [](const Function &F) { return !F.isConvergent(); },
1290       // Instructions that break non-convergent assumption.
1291       [SCCNodes](Instruction &I) {
1292         return InstrBreaksNonConvergent(I, SCCNodes);
1293       },
1294       [](Function &F) {
1295         LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1296                           << "\n");
1297         F.setNotConvergent();
1298       },
1299       /* RequiresExactDefinition= */ false});
1300   // Perform all the requested attribute inference actions.
1301   return AI.run(SCCNodes);
1302 }
1303 
1304 /// Infer attributes from all functions in the SCC by scanning every
1305 /// instruction for compliance to the attribute assumptions. Currently it
1306 /// does:
1307 ///   - addition of NoUnwind attribute
1308 ///
1309 /// Returns true if any changes to function attributes were made.
1310 static bool inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes) {
1311   AttributeInferer AI;
1312 
1313   if (!DisableNoUnwindInference)
1314     // Request to infer nounwind attribute for all the functions in the SCC if
1315     // every callsite within the SCC is not throwing (except for calls to
1316     // functions within the SCC). Note that nounwind attribute suffers from
1317     // derefinement - results may change depending on how functions are
1318     // optimized. Thus it can be inferred only from exact definitions.
1319     AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1320         Attribute::NoUnwind,
1321         // Skip non-throwing functions.
1322         [](const Function &F) { return F.doesNotThrow(); },
1323         // Instructions that break non-throwing assumption.
1324         [&SCCNodes](Instruction &I) {
1325           return InstrBreaksNonThrowing(I, SCCNodes);
1326         },
1327         [](Function &F) {
1328           LLVM_DEBUG(dbgs()
1329                      << "Adding nounwind attr to fn " << F.getName() << "\n");
1330           F.setDoesNotThrow();
1331           ++NumNoUnwind;
1332         },
1333         /* RequiresExactDefinition= */ true});
1334 
1335   if (!DisableNoFreeInference)
1336     // Request to infer nofree attribute for all the functions in the SCC if
1337     // every callsite within the SCC does not directly or indirectly free
1338     // memory (except for calls to functions within the SCC). Note that nofree
1339     // attribute suffers from derefinement - results may change depending on
1340     // how functions are optimized. Thus it can be inferred only from exact
1341     // definitions.
1342     AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1343         Attribute::NoFree,
1344         // Skip functions known not to free memory.
1345         [](const Function &F) { return F.doesNotFreeMemory(); },
1346         // Instructions that break non-deallocating assumption.
1347         [&SCCNodes](Instruction &I) {
1348           return InstrBreaksNoFree(I, SCCNodes);
1349         },
1350         [](Function &F) {
1351           LLVM_DEBUG(dbgs()
1352                      << "Adding nofree attr to fn " << F.getName() << "\n");
1353           F.setDoesNotFreeMemory();
1354           ++NumNoFree;
1355         },
1356         /* RequiresExactDefinition= */ true});
1357 
1358   // Perform all the requested attribute inference actions.
1359   return AI.run(SCCNodes);
1360 }
1361 
1362 static bool addNoRecurseAttrs(const SCCNodeSet &SCCNodes) {
1363   // Try and identify functions that do not recurse.
1364 
1365   // If the SCC contains multiple nodes we know for sure there is recursion.
1366   if (SCCNodes.size() != 1)
1367     return false;
1368 
1369   Function *F = *SCCNodes.begin();
1370   if (!F || !F->hasExactDefinition() || F->doesNotRecurse())
1371     return false;
1372 
1373   // If all of the calls in F are identifiable and are to norecurse functions, F
1374   // is norecurse. This check also detects self-recursion as F is not currently
1375   // marked norecurse, so any called from F to F will not be marked norecurse.
1376   for (auto &BB : *F)
1377     for (auto &I : BB.instructionsWithoutDebug())
1378       if (auto *CB = dyn_cast<CallBase>(&I)) {
1379         Function *Callee = CB->getCalledFunction();
1380         if (!Callee || Callee == F || !Callee->doesNotRecurse())
1381           // Function calls a potentially recursive function.
1382           return false;
1383       }
1384 
1385   // Every call was to a non-recursive function other than this function, and
1386   // we have no indirect recursion as the SCC size is one. This function cannot
1387   // recurse.
1388   F->setDoesNotRecurse();
1389   ++NumNoRecurse;
1390   return true;
1391 }
1392 
1393 static bool instructionDoesNotReturn(Instruction &I) {
1394   if (auto *CB = dyn_cast<CallBase>(&I)) {
1395     Function *Callee = CB->getCalledFunction();
1396     return Callee && Callee->doesNotReturn();
1397   }
1398   return false;
1399 }
1400 
1401 // A basic block can only return if it terminates with a ReturnInst and does not
1402 // contain calls to noreturn functions.
1403 static bool basicBlockCanReturn(BasicBlock &BB) {
1404   if (!isa<ReturnInst>(BB.getTerminator()))
1405     return false;
1406   return none_of(BB, instructionDoesNotReturn);
1407 }
1408 
1409 // Set the noreturn function attribute if possible.
1410 static bool addNoReturnAttrs(const SCCNodeSet &SCCNodes) {
1411   bool Changed = false;
1412 
1413   for (Function *F : SCCNodes) {
1414     if (!F || !F->hasExactDefinition() || F->hasFnAttribute(Attribute::Naked) ||
1415         F->doesNotReturn())
1416       continue;
1417 
1418     // The function can return if any basic blocks can return.
1419     // FIXME: this doesn't handle recursion or unreachable blocks.
1420     if (none_of(*F, basicBlockCanReturn)) {
1421       F->setDoesNotReturn();
1422       Changed = true;
1423     }
1424   }
1425 
1426   return Changed;
1427 }
1428 
1429 static bool functionWillReturn(const Function &F) {
1430   // Must-progress function without side-effects must return.
1431   if (F.mustProgress() && F.onlyReadsMemory())
1432     return true;
1433 
1434   // Can only analyze functions with a definition.
1435   if (F.isDeclaration())
1436     return false;
1437 
1438   // Functions with loops require more sophisticated analysis, as the loop
1439   // may be infinite. For now, don't try to handle them.
1440   SmallVector<std::pair<const BasicBlock *, const BasicBlock *>> Backedges;
1441   FindFunctionBackedges(F, Backedges);
1442   if (!Backedges.empty())
1443     return false;
1444 
1445   // If there are no loops, then the function is willreturn if all calls in
1446   // it are willreturn.
1447   return all_of(instructions(F), [](const Instruction &I) {
1448     const auto *CB = dyn_cast<CallBase>(&I);
1449     return !CB || CB->hasFnAttr(Attribute::WillReturn);
1450   });
1451 }
1452 
1453 // Set the willreturn function attribute if possible.
1454 static bool addWillReturn(const SCCNodeSet &SCCNodes) {
1455   bool Changed = false;
1456 
1457   for (Function *F : SCCNodes) {
1458     if (!F || F->willReturn() || !functionWillReturn(*F))
1459       continue;
1460 
1461     F->setWillReturn();
1462     NumWillReturn++;
1463     Changed = true;
1464   }
1465 
1466   return Changed;
1467 }
1468 
1469 static SCCNodesResult createSCCNodeSet(ArrayRef<Function *> Functions) {
1470   SCCNodesResult Res;
1471   Res.HasUnknownCall = false;
1472   for (Function *F : Functions) {
1473     if (!F || F->hasOptNone() || F->hasFnAttribute(Attribute::Naked)) {
1474       // Treat any function we're trying not to optimize as if it were an
1475       // indirect call and omit it from the node set used below.
1476       Res.HasUnknownCall = true;
1477       continue;
1478     }
1479     // Track whether any functions in this SCC have an unknown call edge.
1480     // Note: if this is ever a performance hit, we can common it with
1481     // subsequent routines which also do scans over the instructions of the
1482     // function.
1483     if (!Res.HasUnknownCall) {
1484       for (Instruction &I : instructions(*F)) {
1485         if (auto *CB = dyn_cast<CallBase>(&I)) {
1486           if (!CB->getCalledFunction()) {
1487             Res.HasUnknownCall = true;
1488             break;
1489           }
1490         }
1491       }
1492     }
1493     Res.SCCNodes.insert(F);
1494   }
1495   return Res;
1496 }
1497 
1498 template <typename AARGetterT>
1499 static bool deriveAttrsInPostOrder(ArrayRef<Function *> Functions,
1500                                    AARGetterT &&AARGetter) {
1501   SCCNodesResult Nodes = createSCCNodeSet(Functions);
1502   bool Changed = false;
1503 
1504   // Bail if the SCC only contains optnone functions.
1505   if (Nodes.SCCNodes.empty())
1506     return Changed;
1507 
1508   Changed |= addArgumentReturnedAttrs(Nodes.SCCNodes);
1509   Changed |= addReadAttrs(Nodes.SCCNodes, AARGetter);
1510   Changed |= addArgumentAttrs(Nodes.SCCNodes);
1511   Changed |= inferConvergent(Nodes.SCCNodes);
1512   Changed |= addNoReturnAttrs(Nodes.SCCNodes);
1513   Changed |= addWillReturn(Nodes.SCCNodes);
1514 
1515   // If we have no external nodes participating in the SCC, we can deduce some
1516   // more precise attributes as well.
1517   if (!Nodes.HasUnknownCall) {
1518     Changed |= addNoAliasAttrs(Nodes.SCCNodes);
1519     Changed |= addNonNullAttrs(Nodes.SCCNodes);
1520     Changed |= inferAttrsFromFunctionBodies(Nodes.SCCNodes);
1521     Changed |= addNoRecurseAttrs(Nodes.SCCNodes);
1522   }
1523 
1524   return Changed;
1525 }
1526 
1527 PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
1528                                                   CGSCCAnalysisManager &AM,
1529                                                   LazyCallGraph &CG,
1530                                                   CGSCCUpdateResult &) {
1531   FunctionAnalysisManager &FAM =
1532       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
1533 
1534   // We pass a lambda into functions to wire them up to the analysis manager
1535   // for getting function analyses.
1536   auto AARGetter = [&](Function &F) -> AAResults & {
1537     return FAM.getResult<AAManager>(F);
1538   };
1539 
1540   SmallVector<Function *, 8> Functions;
1541   for (LazyCallGraph::Node &N : C) {
1542     Functions.push_back(&N.getFunction());
1543   }
1544 
1545   if (deriveAttrsInPostOrder(Functions, AARGetter))
1546     return PreservedAnalyses::none();
1547 
1548   return PreservedAnalyses::all();
1549 }
1550 
1551 namespace {
1552 
1553 struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
1554   // Pass identification, replacement for typeid
1555   static char ID;
1556 
1557   PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
1558     initializePostOrderFunctionAttrsLegacyPassPass(
1559         *PassRegistry::getPassRegistry());
1560   }
1561 
1562   bool runOnSCC(CallGraphSCC &SCC) override;
1563 
1564   void getAnalysisUsage(AnalysisUsage &AU) const override {
1565     AU.setPreservesCFG();
1566     AU.addRequired<AssumptionCacheTracker>();
1567     getAAResultsAnalysisUsage(AU);
1568     CallGraphSCCPass::getAnalysisUsage(AU);
1569   }
1570 };
1571 
1572 } // end anonymous namespace
1573 
1574 char PostOrderFunctionAttrsLegacyPass::ID = 0;
1575 INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "function-attrs",
1576                       "Deduce function attributes", false, false)
1577 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1578 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1579 INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "function-attrs",
1580                     "Deduce function attributes", false, false)
1581 
1582 Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1583   return new PostOrderFunctionAttrsLegacyPass();
1584 }
1585 
1586 template <typename AARGetterT>
1587 static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
1588   SmallVector<Function *, 8> Functions;
1589   for (CallGraphNode *I : SCC) {
1590     Functions.push_back(I->getFunction());
1591   }
1592 
1593   return deriveAttrsInPostOrder(Functions, AARGetter);
1594 }
1595 
1596 bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1597   if (skipSCC(SCC))
1598     return false;
1599   return runImpl(SCC, LegacyAARGetter(*this));
1600 }
1601 
1602 namespace {
1603 
1604 struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
1605   // Pass identification, replacement for typeid
1606   static char ID;
1607 
1608   ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
1609     initializeReversePostOrderFunctionAttrsLegacyPassPass(
1610         *PassRegistry::getPassRegistry());
1611   }
1612 
1613   bool runOnModule(Module &M) override;
1614 
1615   void getAnalysisUsage(AnalysisUsage &AU) const override {
1616     AU.setPreservesCFG();
1617     AU.addRequired<CallGraphWrapperPass>();
1618     AU.addPreserved<CallGraphWrapperPass>();
1619   }
1620 };
1621 
1622 } // end anonymous namespace
1623 
1624 char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
1625 
1626 INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass,
1627                       "rpo-function-attrs", "Deduce function attributes in RPO",
1628                       false, false)
1629 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1630 INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass,
1631                     "rpo-function-attrs", "Deduce function attributes in RPO",
1632                     false, false)
1633 
1634 Pass *llvm::createReversePostOrderFunctionAttrsPass() {
1635   return new ReversePostOrderFunctionAttrsLegacyPass();
1636 }
1637 
1638 static bool addNoRecurseAttrsTopDown(Function &F) {
1639   // We check the preconditions for the function prior to calling this to avoid
1640   // the cost of building up a reversible post-order list. We assert them here
1641   // to make sure none of the invariants this relies on were violated.
1642   assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1643   assert(!F.doesNotRecurse() &&
1644          "This function has already been deduced as norecurs!");
1645   assert(F.hasInternalLinkage() &&
1646          "Can only do top-down deduction for internal linkage functions!");
1647 
1648   // If F is internal and all of its uses are calls from a non-recursive
1649   // functions, then none of its calls could in fact recurse without going
1650   // through a function marked norecurse, and so we can mark this function too
1651   // as norecurse. Note that the uses must actually be calls -- otherwise
1652   // a pointer to this function could be returned from a norecurse function but
1653   // this function could be recursively (indirectly) called. Note that this
1654   // also detects if F is directly recursive as F is not yet marked as
1655   // a norecurse function.
1656   for (auto *U : F.users()) {
1657     auto *I = dyn_cast<Instruction>(U);
1658     if (!I)
1659       return false;
1660     CallBase *CB = dyn_cast<CallBase>(I);
1661     if (!CB || !CB->getParent()->getParent()->doesNotRecurse())
1662       return false;
1663   }
1664   F.setDoesNotRecurse();
1665   ++NumNoRecurse;
1666   return true;
1667 }
1668 
1669 static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
1670   // We only have a post-order SCC traversal (because SCCs are inherently
1671   // discovered in post-order), so we accumulate them in a vector and then walk
1672   // it in reverse. This is simpler than using the RPO iterator infrastructure
1673   // because we need to combine SCC detection and the PO walk of the call
1674   // graph. We can also cheat egregiously because we're primarily interested in
1675   // synthesizing norecurse and so we can only save the singular SCCs as SCCs
1676   // with multiple functions in them will clearly be recursive.
1677   SmallVector<Function *, 16> Worklist;
1678   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
1679     if (I->size() != 1)
1680       continue;
1681 
1682     Function *F = I->front()->getFunction();
1683     if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
1684         F->hasInternalLinkage())
1685       Worklist.push_back(F);
1686   }
1687 
1688   bool Changed = false;
1689   for (auto *F : llvm::reverse(Worklist))
1690     Changed |= addNoRecurseAttrsTopDown(*F);
1691 
1692   return Changed;
1693 }
1694 
1695 bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
1696   if (skipModule(M))
1697     return false;
1698 
1699   auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
1700 
1701   return deduceFunctionAttributeInRPO(M, CG);
1702 }
1703 
1704 PreservedAnalyses
1705 ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
1706   auto &CG = AM.getResult<CallGraphAnalysis>(M);
1707 
1708   if (!deduceFunctionAttributeInRPO(M, CG))
1709     return PreservedAnalyses::all();
1710 
1711   PreservedAnalyses PA;
1712   PA.preserve<CallGraphAnalysis>();
1713   return PA;
1714 }
1715