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