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       CallBase &CB = cast<CallBase>(*I);
685       if (CB.isCallee(U)) {
686         IsRead = true;
687         // Note that indirect calls do not capture, see comment in
688         // CaptureTracking for context
689         continue;
690       }
691 
692       // Given we've explictily handled the callee operand above, what's left
693       // must be a data operand (e.g. argument or operand bundle)
694       const unsigned UseIndex = CB.getDataOperandNo(U);
695 
696       if (!CB.doesNotCapture(UseIndex)) {
697         if (!CB.onlyReadsMemory())
698           // If the callee can save a copy into other memory, then simply
699           // scanning uses of the call is insufficient.  We have no way
700           // of tracking copies of the pointer through memory to see
701           // if a reloaded copy is written to, thus we must give up.
702           return Attribute::None;
703         // Push users for processing once we finish this one
704         if (!I->getType()->isVoidTy())
705           for (Use &UU : I->uses())
706             if (Visited.insert(&UU).second)
707               Worklist.push_back(&UU);
708       }
709 
710       if (CB.doesNotAccessMemory())
711         continue;
712 
713       Function *F = CB.getCalledFunction();
714       if (!F) {
715         if (CB.onlyReadsMemory()) {
716           IsRead = true;
717           continue;
718         }
719         return Attribute::None;
720       }
721 
722       if (CB.isArgOperand(U) && UseIndex < F->arg_size() &&
723           SCCNodes.count(F->getArg(UseIndex))) {
724         // This is an argument which is part of the speculative SCC.  Note that
725         // only operands corresponding to formal arguments of the callee can
726         // participate in the speculation.
727         break;
728       }
729 
730       // The accessors used on call site here do the right thing for calls and
731       // invokes with operand bundles.
732       if (!CB.onlyReadsMemory() && !CB.onlyReadsMemory(UseIndex))
733         return Attribute::None;
734       if (!CB.doesNotAccessMemory(UseIndex))
735         IsRead = true;
736       break;
737     }
738 
739     case Instruction::Load:
740       // A volatile load has side effects beyond what readonly can be relied
741       // upon.
742       if (cast<LoadInst>(I)->isVolatile())
743         return Attribute::None;
744 
745       IsRead = true;
746       break;
747 
748     case Instruction::Store:
749       if (cast<StoreInst>(I)->getValueOperand() == *U)
750         // untrackable capture
751         return Attribute::None;
752 
753       // A volatile store has side effects beyond what writeonly can be relied
754       // upon.
755       if (cast<StoreInst>(I)->isVolatile())
756         return Attribute::None;
757 
758       IsWrite = true;
759       break;
760 
761     case Instruction::ICmp:
762     case Instruction::Ret:
763       break;
764 
765     default:
766       return Attribute::None;
767     }
768   }
769 
770   if (IsWrite && IsRead)
771     return Attribute::None;
772   else if (IsRead)
773     return Attribute::ReadOnly;
774   else if (IsWrite)
775     return Attribute::WriteOnly;
776   else
777     return Attribute::ReadNone;
778 }
779 
780 /// Deduce returned attributes for the SCC.
781 static void addArgumentReturnedAttrs(const SCCNodeSet &SCCNodes,
782                                      SmallSet<Function *, 8> &Changed) {
783   // Check each function in turn, determining if an argument is always returned.
784   for (Function *F : SCCNodes) {
785     // We can infer and propagate function attributes only when we know that the
786     // definition we'll get at link time is *exactly* the definition we see now.
787     // For more details, see GlobalValue::mayBeDerefined.
788     if (!F->hasExactDefinition())
789       continue;
790 
791     if (F->getReturnType()->isVoidTy())
792       continue;
793 
794     // There is nothing to do if an argument is already marked as 'returned'.
795     if (llvm::any_of(F->args(),
796                      [](const Argument &Arg) { return Arg.hasReturnedAttr(); }))
797       continue;
798 
799     auto FindRetArg = [&]() -> Value * {
800       Value *RetArg = nullptr;
801       for (BasicBlock &BB : *F)
802         if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator())) {
803           // Note that stripPointerCasts should look through functions with
804           // returned arguments.
805           Value *RetVal = Ret->getReturnValue()->stripPointerCasts();
806           if (!isa<Argument>(RetVal) || RetVal->getType() != F->getReturnType())
807             return nullptr;
808 
809           if (!RetArg)
810             RetArg = RetVal;
811           else if (RetArg != RetVal)
812             return nullptr;
813         }
814 
815       return RetArg;
816     };
817 
818     if (Value *RetArg = FindRetArg()) {
819       auto *A = cast<Argument>(RetArg);
820       A->addAttr(Attribute::Returned);
821       ++NumReturned;
822       Changed.insert(F);
823     }
824   }
825 }
826 
827 /// If a callsite has arguments that are also arguments to the parent function,
828 /// try to propagate attributes from the callsite's arguments to the parent's
829 /// arguments. This may be important because inlining can cause information loss
830 /// when attribute knowledge disappears with the inlined call.
831 static bool addArgumentAttrsFromCallsites(Function &F) {
832   if (!EnableNonnullArgPropagation)
833     return false;
834 
835   bool Changed = false;
836 
837   // For an argument attribute to transfer from a callsite to the parent, the
838   // call must be guaranteed to execute every time the parent is called.
839   // Conservatively, just check for calls in the entry block that are guaranteed
840   // to execute.
841   // TODO: This could be enhanced by testing if the callsite post-dominates the
842   // entry block or by doing simple forward walks or backward walks to the
843   // callsite.
844   BasicBlock &Entry = F.getEntryBlock();
845   for (Instruction &I : Entry) {
846     if (auto *CB = dyn_cast<CallBase>(&I)) {
847       if (auto *CalledFunc = CB->getCalledFunction()) {
848         for (auto &CSArg : CalledFunc->args()) {
849           if (!CSArg.hasNonNullAttr(/* AllowUndefOrPoison */ false))
850             continue;
851 
852           // If the non-null callsite argument operand is an argument to 'F'
853           // (the caller) and the call is guaranteed to execute, then the value
854           // must be non-null throughout 'F'.
855           auto *FArg = dyn_cast<Argument>(CB->getArgOperand(CSArg.getArgNo()));
856           if (FArg && !FArg->hasNonNullAttr()) {
857             FArg->addAttr(Attribute::NonNull);
858             Changed = true;
859           }
860         }
861       }
862     }
863     if (!isGuaranteedToTransferExecutionToSuccessor(&I))
864       break;
865   }
866 
867   return Changed;
868 }
869 
870 static bool addAccessAttr(Argument *A, Attribute::AttrKind R) {
871   assert((R == Attribute::ReadOnly || R == Attribute::ReadNone ||
872           R == Attribute::WriteOnly)
873          && "Must be an access attribute.");
874   assert(A && "Argument must not be null.");
875 
876   // If the argument already has the attribute, nothing needs to be done.
877   if (A->hasAttribute(R))
878       return false;
879 
880   // Otherwise, remove potentially conflicting attribute, add the new one,
881   // and update statistics.
882   A->removeAttr(Attribute::WriteOnly);
883   A->removeAttr(Attribute::ReadOnly);
884   A->removeAttr(Attribute::ReadNone);
885   A->addAttr(R);
886   if (R == Attribute::ReadOnly)
887     ++NumReadOnlyArg;
888   else if (R == Attribute::WriteOnly)
889     ++NumWriteOnlyArg;
890   else
891     ++NumReadNoneArg;
892   return true;
893 }
894 
895 /// Deduce nocapture attributes for the SCC.
896 static void addArgumentAttrs(const SCCNodeSet &SCCNodes,
897                              SmallSet<Function *, 8> &Changed) {
898   ArgumentGraph AG;
899 
900   // Check each function in turn, determining which pointer arguments are not
901   // captured.
902   for (Function *F : SCCNodes) {
903     // We can infer and propagate function attributes only when we know that the
904     // definition we'll get at link time is *exactly* the definition we see now.
905     // For more details, see GlobalValue::mayBeDerefined.
906     if (!F->hasExactDefinition())
907       continue;
908 
909     if (addArgumentAttrsFromCallsites(*F))
910       Changed.insert(F);
911 
912     // Functions that are readonly (or readnone) and nounwind and don't return
913     // a value can't capture arguments. Don't analyze them.
914     if (F->onlyReadsMemory() && F->doesNotThrow() &&
915         F->getReturnType()->isVoidTy()) {
916       for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
917            ++A) {
918         if (A->getType()->isPointerTy() && !A->hasNoCaptureAttr()) {
919           A->addAttr(Attribute::NoCapture);
920           ++NumNoCapture;
921           Changed.insert(F);
922         }
923       }
924       continue;
925     }
926 
927     for (Function::arg_iterator A = F->arg_begin(), E = F->arg_end(); A != E;
928          ++A) {
929       if (!A->getType()->isPointerTy())
930         continue;
931       bool HasNonLocalUses = false;
932       if (!A->hasNoCaptureAttr()) {
933         ArgumentUsesTracker Tracker(SCCNodes);
934         PointerMayBeCaptured(&*A, &Tracker);
935         if (!Tracker.Captured) {
936           if (Tracker.Uses.empty()) {
937             // If it's trivially not captured, mark it nocapture now.
938             A->addAttr(Attribute::NoCapture);
939             ++NumNoCapture;
940             Changed.insert(F);
941           } else {
942             // If it's not trivially captured and not trivially not captured,
943             // then it must be calling into another function in our SCC. Save
944             // its particulars for Argument-SCC analysis later.
945             ArgumentGraphNode *Node = AG[&*A];
946             for (Argument *Use : Tracker.Uses) {
947               Node->Uses.push_back(AG[Use]);
948               if (Use != &*A)
949                 HasNonLocalUses = true;
950             }
951           }
952         }
953         // Otherwise, it's captured. Don't bother doing SCC analysis on it.
954       }
955       if (!HasNonLocalUses && !A->onlyReadsMemory()) {
956         // Can we determine that it's readonly/readnone/writeonly without doing
957         // an SCC? Note that we don't allow any calls at all here, or else our
958         // result will be dependent on the iteration order through the
959         // functions in the SCC.
960         SmallPtrSet<Argument *, 8> Self;
961         Self.insert(&*A);
962         Attribute::AttrKind R = determinePointerAccessAttrs(&*A, Self);
963         if (R != Attribute::None)
964           if (addAccessAttr(A, R))
965             Changed.insert(F);
966       }
967     }
968   }
969 
970   // The graph we've collected is partial because we stopped scanning for
971   // argument uses once we solved the argument trivially. These partial nodes
972   // show up as ArgumentGraphNode objects with an empty Uses list, and for
973   // these nodes the final decision about whether they capture has already been
974   // made.  If the definition doesn't have a 'nocapture' attribute by now, it
975   // captures.
976 
977   for (scc_iterator<ArgumentGraph *> I = scc_begin(&AG); !I.isAtEnd(); ++I) {
978     const std::vector<ArgumentGraphNode *> &ArgumentSCC = *I;
979     if (ArgumentSCC.size() == 1) {
980       if (!ArgumentSCC[0]->Definition)
981         continue; // synthetic root node
982 
983       // eg. "void f(int* x) { if (...) f(x); }"
984       if (ArgumentSCC[0]->Uses.size() == 1 &&
985           ArgumentSCC[0]->Uses[0] == ArgumentSCC[0]) {
986         Argument *A = ArgumentSCC[0]->Definition;
987         A->addAttr(Attribute::NoCapture);
988         ++NumNoCapture;
989         Changed.insert(A->getParent());
990 
991         // Infer the access attributes given the new nocapture one
992         SmallPtrSet<Argument *, 8> Self;
993         Self.insert(&*A);
994         Attribute::AttrKind R = determinePointerAccessAttrs(&*A, Self);
995         if (R != Attribute::None)
996           addAccessAttr(A, R);
997       }
998       continue;
999     }
1000 
1001     bool SCCCaptured = false;
1002     for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
1003          I != E && !SCCCaptured; ++I) {
1004       ArgumentGraphNode *Node = *I;
1005       if (Node->Uses.empty()) {
1006         if (!Node->Definition->hasNoCaptureAttr())
1007           SCCCaptured = true;
1008       }
1009     }
1010     if (SCCCaptured)
1011       continue;
1012 
1013     SmallPtrSet<Argument *, 8> ArgumentSCCNodes;
1014     // Fill ArgumentSCCNodes with the elements of the ArgumentSCC.  Used for
1015     // quickly looking up whether a given Argument is in this ArgumentSCC.
1016     for (ArgumentGraphNode *I : ArgumentSCC) {
1017       ArgumentSCCNodes.insert(I->Definition);
1018     }
1019 
1020     for (auto I = ArgumentSCC.begin(), E = ArgumentSCC.end();
1021          I != E && !SCCCaptured; ++I) {
1022       ArgumentGraphNode *N = *I;
1023       for (ArgumentGraphNode *Use : N->Uses) {
1024         Argument *A = Use->Definition;
1025         if (A->hasNoCaptureAttr() || ArgumentSCCNodes.count(A))
1026           continue;
1027         SCCCaptured = true;
1028         break;
1029       }
1030     }
1031     if (SCCCaptured)
1032       continue;
1033 
1034     for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
1035       Argument *A = ArgumentSCC[i]->Definition;
1036       A->addAttr(Attribute::NoCapture);
1037       ++NumNoCapture;
1038       Changed.insert(A->getParent());
1039     }
1040 
1041     // We also want to compute readonly/readnone/writeonly. With a small number
1042     // of false negatives, we can assume that any pointer which is captured
1043     // isn't going to be provably readonly or readnone, since by definition
1044     // we can't analyze all uses of a captured pointer.
1045     //
1046     // The false negatives happen when the pointer is captured by a function
1047     // that promises readonly/readnone behaviour on the pointer, then the
1048     // pointer's lifetime ends before anything that writes to arbitrary memory.
1049     // Also, a readonly/readnone pointer may be returned, but returning a
1050     // pointer is capturing it.
1051 
1052     auto meetAccessAttr = [](Attribute::AttrKind A, Attribute::AttrKind B) {
1053       if (A == B)
1054         return A;
1055       if (A == Attribute::ReadNone)
1056         return B;
1057       if (B == Attribute::ReadNone)
1058         return A;
1059       return Attribute::None;
1060     };
1061 
1062     Attribute::AttrKind AccessAttr = Attribute::ReadNone;
1063     for (unsigned i = 0, e = ArgumentSCC.size();
1064          i != e && AccessAttr != Attribute::None; ++i) {
1065       Argument *A = ArgumentSCC[i]->Definition;
1066       Attribute::AttrKind K = determinePointerAccessAttrs(A, ArgumentSCCNodes);
1067       AccessAttr = meetAccessAttr(AccessAttr, K);
1068     }
1069 
1070     if (AccessAttr != Attribute::None) {
1071       for (unsigned i = 0, e = ArgumentSCC.size(); i != e; ++i) {
1072         Argument *A = ArgumentSCC[i]->Definition;
1073         if (addAccessAttr(A, AccessAttr))
1074           Changed.insert(A->getParent());
1075       }
1076     }
1077   }
1078 }
1079 
1080 /// Tests whether a function is "malloc-like".
1081 ///
1082 /// A function is "malloc-like" if it returns either null or a pointer that
1083 /// doesn't alias any other pointer visible to the caller.
1084 static bool isFunctionMallocLike(Function *F, const SCCNodeSet &SCCNodes) {
1085   SmallSetVector<Value *, 8> FlowsToReturn;
1086   for (BasicBlock &BB : *F)
1087     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
1088       FlowsToReturn.insert(Ret->getReturnValue());
1089 
1090   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
1091     Value *RetVal = FlowsToReturn[i];
1092 
1093     if (Constant *C = dyn_cast<Constant>(RetVal)) {
1094       if (!C->isNullValue() && !isa<UndefValue>(C))
1095         return false;
1096 
1097       continue;
1098     }
1099 
1100     if (isa<Argument>(RetVal))
1101       return false;
1102 
1103     if (Instruction *RVI = dyn_cast<Instruction>(RetVal))
1104       switch (RVI->getOpcode()) {
1105       // Extend the analysis by looking upwards.
1106       case Instruction::BitCast:
1107       case Instruction::GetElementPtr:
1108       case Instruction::AddrSpaceCast:
1109         FlowsToReturn.insert(RVI->getOperand(0));
1110         continue;
1111       case Instruction::Select: {
1112         SelectInst *SI = cast<SelectInst>(RVI);
1113         FlowsToReturn.insert(SI->getTrueValue());
1114         FlowsToReturn.insert(SI->getFalseValue());
1115         continue;
1116       }
1117       case Instruction::PHI: {
1118         PHINode *PN = cast<PHINode>(RVI);
1119         for (Value *IncValue : PN->incoming_values())
1120           FlowsToReturn.insert(IncValue);
1121         continue;
1122       }
1123 
1124       // Check whether the pointer came from an allocation.
1125       case Instruction::Alloca:
1126         break;
1127       case Instruction::Call:
1128       case Instruction::Invoke: {
1129         CallBase &CB = cast<CallBase>(*RVI);
1130         if (CB.hasRetAttr(Attribute::NoAlias))
1131           break;
1132         if (CB.getCalledFunction() && SCCNodes.count(CB.getCalledFunction()))
1133           break;
1134         LLVM_FALLTHROUGH;
1135       }
1136       default:
1137         return false; // Did not come from an allocation.
1138       }
1139 
1140     if (PointerMayBeCaptured(RetVal, false, /*StoreCaptures=*/false))
1141       return false;
1142   }
1143 
1144   return true;
1145 }
1146 
1147 /// Deduce noalias attributes for the SCC.
1148 static void addNoAliasAttrs(const SCCNodeSet &SCCNodes,
1149                             SmallSet<Function *, 8> &Changed) {
1150   // Check each function in turn, determining which functions return noalias
1151   // pointers.
1152   for (Function *F : SCCNodes) {
1153     // Already noalias.
1154     if (F->returnDoesNotAlias())
1155       continue;
1156 
1157     // We can infer and propagate function attributes only when we know that the
1158     // definition we'll get at link time is *exactly* the definition we see now.
1159     // For more details, see GlobalValue::mayBeDerefined.
1160     if (!F->hasExactDefinition())
1161       return;
1162 
1163     // We annotate noalias return values, which are only applicable to
1164     // pointer types.
1165     if (!F->getReturnType()->isPointerTy())
1166       continue;
1167 
1168     if (!isFunctionMallocLike(F, SCCNodes))
1169       return;
1170   }
1171 
1172   for (Function *F : SCCNodes) {
1173     if (F->returnDoesNotAlias() ||
1174         !F->getReturnType()->isPointerTy())
1175       continue;
1176 
1177     F->setReturnDoesNotAlias();
1178     ++NumNoAlias;
1179     Changed.insert(F);
1180   }
1181 }
1182 
1183 /// Tests whether this function is known to not return null.
1184 ///
1185 /// Requires that the function returns a pointer.
1186 ///
1187 /// Returns true if it believes the function will not return a null, and sets
1188 /// \p Speculative based on whether the returned conclusion is a speculative
1189 /// conclusion due to SCC calls.
1190 static bool isReturnNonNull(Function *F, const SCCNodeSet &SCCNodes,
1191                             bool &Speculative) {
1192   assert(F->getReturnType()->isPointerTy() &&
1193          "nonnull only meaningful on pointer types");
1194   Speculative = false;
1195 
1196   SmallSetVector<Value *, 8> FlowsToReturn;
1197   for (BasicBlock &BB : *F)
1198     if (auto *Ret = dyn_cast<ReturnInst>(BB.getTerminator()))
1199       FlowsToReturn.insert(Ret->getReturnValue());
1200 
1201   auto &DL = F->getParent()->getDataLayout();
1202 
1203   for (unsigned i = 0; i != FlowsToReturn.size(); ++i) {
1204     Value *RetVal = FlowsToReturn[i];
1205 
1206     // If this value is locally known to be non-null, we're good
1207     if (isKnownNonZero(RetVal, DL))
1208       continue;
1209 
1210     // Otherwise, we need to look upwards since we can't make any local
1211     // conclusions.
1212     Instruction *RVI = dyn_cast<Instruction>(RetVal);
1213     if (!RVI)
1214       return false;
1215     switch (RVI->getOpcode()) {
1216     // Extend the analysis by looking upwards.
1217     case Instruction::BitCast:
1218     case Instruction::GetElementPtr:
1219     case Instruction::AddrSpaceCast:
1220       FlowsToReturn.insert(RVI->getOperand(0));
1221       continue;
1222     case Instruction::Select: {
1223       SelectInst *SI = cast<SelectInst>(RVI);
1224       FlowsToReturn.insert(SI->getTrueValue());
1225       FlowsToReturn.insert(SI->getFalseValue());
1226       continue;
1227     }
1228     case Instruction::PHI: {
1229       PHINode *PN = cast<PHINode>(RVI);
1230       for (int i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1231         FlowsToReturn.insert(PN->getIncomingValue(i));
1232       continue;
1233     }
1234     case Instruction::Call:
1235     case Instruction::Invoke: {
1236       CallBase &CB = cast<CallBase>(*RVI);
1237       Function *Callee = CB.getCalledFunction();
1238       // A call to a node within the SCC is assumed to return null until
1239       // proven otherwise
1240       if (Callee && SCCNodes.count(Callee)) {
1241         Speculative = true;
1242         continue;
1243       }
1244       return false;
1245     }
1246     default:
1247       return false; // Unknown source, may be null
1248     };
1249     llvm_unreachable("should have either continued or returned");
1250   }
1251 
1252   return true;
1253 }
1254 
1255 /// Deduce nonnull attributes for the SCC.
1256 static void addNonNullAttrs(const SCCNodeSet &SCCNodes,
1257                             SmallSet<Function *, 8> &Changed) {
1258   // Speculative that all functions in the SCC return only nonnull
1259   // pointers.  We may refute this as we analyze functions.
1260   bool SCCReturnsNonNull = true;
1261 
1262   // Check each function in turn, determining which functions return nonnull
1263   // pointers.
1264   for (Function *F : SCCNodes) {
1265     // Already nonnull.
1266     if (F->getAttributes().hasRetAttr(Attribute::NonNull))
1267       continue;
1268 
1269     // We can infer and propagate function attributes only when we know that the
1270     // definition we'll get at link time is *exactly* the definition we see now.
1271     // For more details, see GlobalValue::mayBeDerefined.
1272     if (!F->hasExactDefinition())
1273       return;
1274 
1275     // We annotate nonnull return values, which are only applicable to
1276     // pointer types.
1277     if (!F->getReturnType()->isPointerTy())
1278       continue;
1279 
1280     bool Speculative = false;
1281     if (isReturnNonNull(F, SCCNodes, Speculative)) {
1282       if (!Speculative) {
1283         // Mark the function eagerly since we may discover a function
1284         // which prevents us from speculating about the entire SCC
1285         LLVM_DEBUG(dbgs() << "Eagerly marking " << F->getName()
1286                           << " as nonnull\n");
1287         F->addRetAttr(Attribute::NonNull);
1288         ++NumNonNullReturn;
1289         Changed.insert(F);
1290       }
1291       continue;
1292     }
1293     // At least one function returns something which could be null, can't
1294     // speculate any more.
1295     SCCReturnsNonNull = false;
1296   }
1297 
1298   if (SCCReturnsNonNull) {
1299     for (Function *F : SCCNodes) {
1300       if (F->getAttributes().hasRetAttr(Attribute::NonNull) ||
1301           !F->getReturnType()->isPointerTy())
1302         continue;
1303 
1304       LLVM_DEBUG(dbgs() << "SCC marking " << F->getName() << " as nonnull\n");
1305       F->addRetAttr(Attribute::NonNull);
1306       ++NumNonNullReturn;
1307       Changed.insert(F);
1308     }
1309   }
1310 }
1311 
1312 namespace {
1313 
1314 /// Collects a set of attribute inference requests and performs them all in one
1315 /// go on a single SCC Node. Inference involves scanning function bodies
1316 /// looking for instructions that violate attribute assumptions.
1317 /// As soon as all the bodies are fine we are free to set the attribute.
1318 /// Customization of inference for individual attributes is performed by
1319 /// providing a handful of predicates for each attribute.
1320 class AttributeInferer {
1321 public:
1322   /// Describes a request for inference of a single attribute.
1323   struct InferenceDescriptor {
1324 
1325     /// Returns true if this function does not have to be handled.
1326     /// General intent for this predicate is to provide an optimization
1327     /// for functions that do not need this attribute inference at all
1328     /// (say, for functions that already have the attribute).
1329     std::function<bool(const Function &)> SkipFunction;
1330 
1331     /// Returns true if this instruction violates attribute assumptions.
1332     std::function<bool(Instruction &)> InstrBreaksAttribute;
1333 
1334     /// Sets the inferred attribute for this function.
1335     std::function<void(Function &)> SetAttribute;
1336 
1337     /// Attribute we derive.
1338     Attribute::AttrKind AKind;
1339 
1340     /// If true, only "exact" definitions can be used to infer this attribute.
1341     /// See GlobalValue::isDefinitionExact.
1342     bool RequiresExactDefinition;
1343 
1344     InferenceDescriptor(Attribute::AttrKind AK,
1345                         std::function<bool(const Function &)> SkipFunc,
1346                         std::function<bool(Instruction &)> InstrScan,
1347                         std::function<void(Function &)> SetAttr,
1348                         bool ReqExactDef)
1349         : SkipFunction(SkipFunc), InstrBreaksAttribute(InstrScan),
1350           SetAttribute(SetAttr), AKind(AK),
1351           RequiresExactDefinition(ReqExactDef) {}
1352   };
1353 
1354 private:
1355   SmallVector<InferenceDescriptor, 4> InferenceDescriptors;
1356 
1357 public:
1358   void registerAttrInference(InferenceDescriptor AttrInference) {
1359     InferenceDescriptors.push_back(AttrInference);
1360   }
1361 
1362   void run(const SCCNodeSet &SCCNodes, SmallSet<Function *, 8> &Changed);
1363 };
1364 
1365 /// Perform all the requested attribute inference actions according to the
1366 /// attribute predicates stored before.
1367 void AttributeInferer::run(const SCCNodeSet &SCCNodes,
1368                            SmallSet<Function *, 8> &Changed) {
1369   SmallVector<InferenceDescriptor, 4> InferInSCC = InferenceDescriptors;
1370   // Go through all the functions in SCC and check corresponding attribute
1371   // assumptions for each of them. Attributes that are invalid for this SCC
1372   // will be removed from InferInSCC.
1373   for (Function *F : SCCNodes) {
1374 
1375     // No attributes whose assumptions are still valid - done.
1376     if (InferInSCC.empty())
1377       return;
1378 
1379     // Check if our attributes ever need scanning/can be scanned.
1380     llvm::erase_if(InferInSCC, [F](const InferenceDescriptor &ID) {
1381       if (ID.SkipFunction(*F))
1382         return false;
1383 
1384       // Remove from further inference (invalidate) when visiting a function
1385       // that has no instructions to scan/has an unsuitable definition.
1386       return F->isDeclaration() ||
1387              (ID.RequiresExactDefinition && !F->hasExactDefinition());
1388     });
1389 
1390     // For each attribute still in InferInSCC that doesn't explicitly skip F,
1391     // set up the F instructions scan to verify assumptions of the attribute.
1392     SmallVector<InferenceDescriptor, 4> InferInThisFunc;
1393     llvm::copy_if(
1394         InferInSCC, std::back_inserter(InferInThisFunc),
1395         [F](const InferenceDescriptor &ID) { return !ID.SkipFunction(*F); });
1396 
1397     if (InferInThisFunc.empty())
1398       continue;
1399 
1400     // Start instruction scan.
1401     for (Instruction &I : instructions(*F)) {
1402       llvm::erase_if(InferInThisFunc, [&](const InferenceDescriptor &ID) {
1403         if (!ID.InstrBreaksAttribute(I))
1404           return false;
1405         // Remove attribute from further inference on any other functions
1406         // because attribute assumptions have just been violated.
1407         llvm::erase_if(InferInSCC, [&ID](const InferenceDescriptor &D) {
1408           return D.AKind == ID.AKind;
1409         });
1410         // Remove attribute from the rest of current instruction scan.
1411         return true;
1412       });
1413 
1414       if (InferInThisFunc.empty())
1415         break;
1416     }
1417   }
1418 
1419   if (InferInSCC.empty())
1420     return;
1421 
1422   for (Function *F : SCCNodes)
1423     // At this point InferInSCC contains only functions that were either:
1424     //   - explicitly skipped from scan/inference, or
1425     //   - verified to have no instructions that break attribute assumptions.
1426     // Hence we just go and force the attribute for all non-skipped functions.
1427     for (auto &ID : InferInSCC) {
1428       if (ID.SkipFunction(*F))
1429         continue;
1430       Changed.insert(F);
1431       ID.SetAttribute(*F);
1432     }
1433 }
1434 
1435 struct SCCNodesResult {
1436   SCCNodeSet SCCNodes;
1437   bool HasUnknownCall;
1438 };
1439 
1440 } // end anonymous namespace
1441 
1442 /// Helper for non-Convergent inference predicate InstrBreaksAttribute.
1443 static bool InstrBreaksNonConvergent(Instruction &I,
1444                                      const SCCNodeSet &SCCNodes) {
1445   const CallBase *CB = dyn_cast<CallBase>(&I);
1446   // Breaks non-convergent assumption if CS is a convergent call to a function
1447   // not in the SCC.
1448   return CB && CB->isConvergent() &&
1449          !SCCNodes.contains(CB->getCalledFunction());
1450 }
1451 
1452 /// Helper for NoUnwind inference predicate InstrBreaksAttribute.
1453 static bool InstrBreaksNonThrowing(Instruction &I, const SCCNodeSet &SCCNodes) {
1454   if (!I.mayThrow())
1455     return false;
1456   if (const auto *CI = dyn_cast<CallInst>(&I)) {
1457     if (Function *Callee = CI->getCalledFunction()) {
1458       // I is a may-throw call to a function inside our SCC. This doesn't
1459       // invalidate our current working assumption that the SCC is no-throw; we
1460       // just have to scan that other function.
1461       if (SCCNodes.contains(Callee))
1462         return false;
1463     }
1464   }
1465   return true;
1466 }
1467 
1468 /// Helper for NoFree inference predicate InstrBreaksAttribute.
1469 static bool InstrBreaksNoFree(Instruction &I, const SCCNodeSet &SCCNodes) {
1470   CallBase *CB = dyn_cast<CallBase>(&I);
1471   if (!CB)
1472     return false;
1473 
1474   if (CB->hasFnAttr(Attribute::NoFree))
1475     return false;
1476 
1477   // Speculatively assume in SCC.
1478   if (Function *Callee = CB->getCalledFunction())
1479     if (SCCNodes.contains(Callee))
1480       return false;
1481 
1482   return true;
1483 }
1484 
1485 /// Attempt to remove convergent function attribute when possible.
1486 ///
1487 /// Returns true if any changes to function attributes were made.
1488 static void inferConvergent(const SCCNodeSet &SCCNodes,
1489                             SmallSet<Function *, 8> &Changed) {
1490   AttributeInferer AI;
1491 
1492   // Request to remove the convergent attribute from all functions in the SCC
1493   // if every callsite within the SCC is not convergent (except for calls
1494   // to functions within the SCC).
1495   // Note: Removal of the attr from the callsites will happen in
1496   // InstCombineCalls separately.
1497   AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1498       Attribute::Convergent,
1499       // Skip non-convergent functions.
1500       [](const Function &F) { return !F.isConvergent(); },
1501       // Instructions that break non-convergent assumption.
1502       [SCCNodes](Instruction &I) {
1503         return InstrBreaksNonConvergent(I, SCCNodes);
1504       },
1505       [](Function &F) {
1506         LLVM_DEBUG(dbgs() << "Removing convergent attr from fn " << F.getName()
1507                           << "\n");
1508         F.setNotConvergent();
1509       },
1510       /* RequiresExactDefinition= */ false});
1511   // Perform all the requested attribute inference actions.
1512   AI.run(SCCNodes, Changed);
1513 }
1514 
1515 /// Infer attributes from all functions in the SCC by scanning every
1516 /// instruction for compliance to the attribute assumptions. Currently it
1517 /// does:
1518 ///   - addition of NoUnwind attribute
1519 ///
1520 /// Returns true if any changes to function attributes were made.
1521 static void inferAttrsFromFunctionBodies(const SCCNodeSet &SCCNodes,
1522                                          SmallSet<Function *, 8> &Changed) {
1523   AttributeInferer AI;
1524 
1525   if (!DisableNoUnwindInference)
1526     // Request to infer nounwind attribute for all the functions in the SCC if
1527     // every callsite within the SCC is not throwing (except for calls to
1528     // functions within the SCC). Note that nounwind attribute suffers from
1529     // derefinement - results may change depending on how functions are
1530     // optimized. Thus it can be inferred only from exact definitions.
1531     AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1532         Attribute::NoUnwind,
1533         // Skip non-throwing functions.
1534         [](const Function &F) { return F.doesNotThrow(); },
1535         // Instructions that break non-throwing assumption.
1536         [&SCCNodes](Instruction &I) {
1537           return InstrBreaksNonThrowing(I, SCCNodes);
1538         },
1539         [](Function &F) {
1540           LLVM_DEBUG(dbgs()
1541                      << "Adding nounwind attr to fn " << F.getName() << "\n");
1542           F.setDoesNotThrow();
1543           ++NumNoUnwind;
1544         },
1545         /* RequiresExactDefinition= */ true});
1546 
1547   if (!DisableNoFreeInference)
1548     // Request to infer nofree attribute for all the functions in the SCC if
1549     // every callsite within the SCC does not directly or indirectly free
1550     // memory (except for calls to functions within the SCC). Note that nofree
1551     // attribute suffers from derefinement - results may change depending on
1552     // how functions are optimized. Thus it can be inferred only from exact
1553     // definitions.
1554     AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1555         Attribute::NoFree,
1556         // Skip functions known not to free memory.
1557         [](const Function &F) { return F.doesNotFreeMemory(); },
1558         // Instructions that break non-deallocating assumption.
1559         [&SCCNodes](Instruction &I) {
1560           return InstrBreaksNoFree(I, SCCNodes);
1561         },
1562         [](Function &F) {
1563           LLVM_DEBUG(dbgs()
1564                      << "Adding nofree attr to fn " << F.getName() << "\n");
1565           F.setDoesNotFreeMemory();
1566           ++NumNoFree;
1567         },
1568         /* RequiresExactDefinition= */ true});
1569 
1570   // Perform all the requested attribute inference actions.
1571   AI.run(SCCNodes, Changed);
1572 }
1573 
1574 static void addNoRecurseAttrs(const SCCNodeSet &SCCNodes,
1575                               SmallSet<Function *, 8> &Changed) {
1576   // Try and identify functions that do not recurse.
1577 
1578   // If the SCC contains multiple nodes we know for sure there is recursion.
1579   if (SCCNodes.size() != 1)
1580     return;
1581 
1582   Function *F = *SCCNodes.begin();
1583   if (!F || !F->hasExactDefinition() || F->doesNotRecurse())
1584     return;
1585 
1586   // If all of the calls in F are identifiable and are to norecurse functions, F
1587   // is norecurse. This check also detects self-recursion as F is not currently
1588   // marked norecurse, so any called from F to F will not be marked norecurse.
1589   for (auto &BB : *F)
1590     for (auto &I : BB.instructionsWithoutDebug())
1591       if (auto *CB = dyn_cast<CallBase>(&I)) {
1592         Function *Callee = CB->getCalledFunction();
1593         if (!Callee || Callee == F || !Callee->doesNotRecurse())
1594           // Function calls a potentially recursive function.
1595           return;
1596       }
1597 
1598   // Every call was to a non-recursive function other than this function, and
1599   // we have no indirect recursion as the SCC size is one. This function cannot
1600   // recurse.
1601   F->setDoesNotRecurse();
1602   ++NumNoRecurse;
1603   Changed.insert(F);
1604 }
1605 
1606 static bool instructionDoesNotReturn(Instruction &I) {
1607   if (auto *CB = dyn_cast<CallBase>(&I))
1608     return CB->hasFnAttr(Attribute::NoReturn);
1609   return false;
1610 }
1611 
1612 // A basic block can only return if it terminates with a ReturnInst and does not
1613 // contain calls to noreturn functions.
1614 static bool basicBlockCanReturn(BasicBlock &BB) {
1615   if (!isa<ReturnInst>(BB.getTerminator()))
1616     return false;
1617   return none_of(BB, instructionDoesNotReturn);
1618 }
1619 
1620 // Set the noreturn function attribute if possible.
1621 static void addNoReturnAttrs(const SCCNodeSet &SCCNodes,
1622                              SmallSet<Function *, 8> &Changed) {
1623   for (Function *F : SCCNodes) {
1624     if (!F || !F->hasExactDefinition() || F->hasFnAttribute(Attribute::Naked) ||
1625         F->doesNotReturn())
1626       continue;
1627 
1628     // The function can return if any basic blocks can return.
1629     // FIXME: this doesn't handle recursion or unreachable blocks.
1630     if (none_of(*F, basicBlockCanReturn)) {
1631       F->setDoesNotReturn();
1632       Changed.insert(F);
1633     }
1634   }
1635 }
1636 
1637 static bool functionWillReturn(const Function &F) {
1638   // We can infer and propagate function attributes only when we know that the
1639   // definition we'll get at link time is *exactly* the definition we see now.
1640   // For more details, see GlobalValue::mayBeDerefined.
1641   if (!F.hasExactDefinition())
1642     return false;
1643 
1644   // Must-progress function without side-effects must return.
1645   if (F.mustProgress() && F.onlyReadsMemory())
1646     return true;
1647 
1648   // Can only analyze functions with a definition.
1649   if (F.isDeclaration())
1650     return false;
1651 
1652   // Functions with loops require more sophisticated analysis, as the loop
1653   // may be infinite. For now, don't try to handle them.
1654   SmallVector<std::pair<const BasicBlock *, const BasicBlock *>> Backedges;
1655   FindFunctionBackedges(F, Backedges);
1656   if (!Backedges.empty())
1657     return false;
1658 
1659   // If there are no loops, then the function is willreturn if all calls in
1660   // it are willreturn.
1661   return all_of(instructions(F), [](const Instruction &I) {
1662     return I.willReturn();
1663   });
1664 }
1665 
1666 // Set the willreturn function attribute if possible.
1667 static void addWillReturn(const SCCNodeSet &SCCNodes,
1668                           SmallSet<Function *, 8> &Changed) {
1669   for (Function *F : SCCNodes) {
1670     if (!F || F->willReturn() || !functionWillReturn(*F))
1671       continue;
1672 
1673     F->setWillReturn();
1674     NumWillReturn++;
1675     Changed.insert(F);
1676   }
1677 }
1678 
1679 // Return true if this is an atomic which has an ordering stronger than
1680 // unordered.  Note that this is different than the predicate we use in
1681 // Attributor.  Here we chose to be conservative and consider monotonic
1682 // operations potentially synchronizing.  We generally don't do much with
1683 // monotonic operations, so this is simply risk reduction.
1684 static bool isOrderedAtomic(Instruction *I) {
1685   if (!I->isAtomic())
1686     return false;
1687 
1688   if (auto *FI = dyn_cast<FenceInst>(I))
1689     // All legal orderings for fence are stronger than monotonic.
1690     return FI->getSyncScopeID() != SyncScope::SingleThread;
1691   else if (isa<AtomicCmpXchgInst>(I) || isa<AtomicRMWInst>(I))
1692     return true;
1693   else if (auto *SI = dyn_cast<StoreInst>(I))
1694     return !SI->isUnordered();
1695   else if (auto *LI = dyn_cast<LoadInst>(I))
1696     return !LI->isUnordered();
1697   else {
1698     llvm_unreachable("unknown atomic instruction?");
1699   }
1700 }
1701 
1702 static bool InstrBreaksNoSync(Instruction &I, const SCCNodeSet &SCCNodes) {
1703   // Volatile may synchronize
1704   if (I.isVolatile())
1705     return true;
1706 
1707   // An ordered atomic may synchronize.  (See comment about on monotonic.)
1708   if (isOrderedAtomic(&I))
1709     return true;
1710 
1711   auto *CB = dyn_cast<CallBase>(&I);
1712   if (!CB)
1713     // Non call site cases covered by the two checks above
1714     return false;
1715 
1716   if (CB->hasFnAttr(Attribute::NoSync))
1717     return false;
1718 
1719   // Non volatile memset/memcpy/memmoves are nosync
1720   // NOTE: Only intrinsics with volatile flags should be handled here.  All
1721   // others should be marked in Intrinsics.td.
1722   if (auto *MI = dyn_cast<MemIntrinsic>(&I))
1723     if (!MI->isVolatile())
1724       return false;
1725 
1726   // Speculatively assume in SCC.
1727   if (Function *Callee = CB->getCalledFunction())
1728     if (SCCNodes.contains(Callee))
1729       return false;
1730 
1731   return true;
1732 }
1733 
1734 // Infer the nosync attribute.
1735 static void addNoSyncAttr(const SCCNodeSet &SCCNodes,
1736                           SmallSet<Function *, 8> &Changed) {
1737   AttributeInferer AI;
1738   AI.registerAttrInference(AttributeInferer::InferenceDescriptor{
1739       Attribute::NoSync,
1740       // Skip already marked functions.
1741       [](const Function &F) { return F.hasNoSync(); },
1742       // Instructions that break nosync assumption.
1743       [&SCCNodes](Instruction &I) {
1744         return InstrBreaksNoSync(I, SCCNodes);
1745       },
1746       [](Function &F) {
1747         LLVM_DEBUG(dbgs()
1748                    << "Adding nosync attr to fn " << F.getName() << "\n");
1749         F.setNoSync();
1750         ++NumNoSync;
1751       },
1752       /* RequiresExactDefinition= */ true});
1753   AI.run(SCCNodes, Changed);
1754 }
1755 
1756 static SCCNodesResult createSCCNodeSet(ArrayRef<Function *> Functions) {
1757   SCCNodesResult Res;
1758   Res.HasUnknownCall = false;
1759   for (Function *F : Functions) {
1760     if (!F || F->hasOptNone() || F->hasFnAttribute(Attribute::Naked) ||
1761         F->isPresplitCoroutine()) {
1762       // Treat any function we're trying not to optimize as if it were an
1763       // indirect call and omit it from the node set used below.
1764       Res.HasUnknownCall = true;
1765       continue;
1766     }
1767     // Track whether any functions in this SCC have an unknown call edge.
1768     // Note: if this is ever a performance hit, we can common it with
1769     // subsequent routines which also do scans over the instructions of the
1770     // function.
1771     if (!Res.HasUnknownCall) {
1772       for (Instruction &I : instructions(*F)) {
1773         if (auto *CB = dyn_cast<CallBase>(&I)) {
1774           if (!CB->getCalledFunction()) {
1775             Res.HasUnknownCall = true;
1776             break;
1777           }
1778         }
1779       }
1780     }
1781     Res.SCCNodes.insert(F);
1782   }
1783   return Res;
1784 }
1785 
1786 template <typename AARGetterT>
1787 static SmallSet<Function *, 8>
1788 deriveAttrsInPostOrder(ArrayRef<Function *> Functions, AARGetterT &&AARGetter) {
1789   SCCNodesResult Nodes = createSCCNodeSet(Functions);
1790 
1791   // Bail if the SCC only contains optnone functions.
1792   if (Nodes.SCCNodes.empty())
1793     return {};
1794 
1795   SmallSet<Function *, 8> Changed;
1796 
1797   addArgumentReturnedAttrs(Nodes.SCCNodes, Changed);
1798   addReadAttrs(Nodes.SCCNodes, AARGetter, Changed);
1799   addArgumentAttrs(Nodes.SCCNodes, Changed);
1800   inferConvergent(Nodes.SCCNodes, Changed);
1801   addNoReturnAttrs(Nodes.SCCNodes, Changed);
1802   addWillReturn(Nodes.SCCNodes, Changed);
1803 
1804   // If we have no external nodes participating in the SCC, we can deduce some
1805   // more precise attributes as well.
1806   if (!Nodes.HasUnknownCall) {
1807     addNoAliasAttrs(Nodes.SCCNodes, Changed);
1808     addNonNullAttrs(Nodes.SCCNodes, Changed);
1809     inferAttrsFromFunctionBodies(Nodes.SCCNodes, Changed);
1810     addNoRecurseAttrs(Nodes.SCCNodes, Changed);
1811   }
1812 
1813   addNoSyncAttr(Nodes.SCCNodes, Changed);
1814 
1815   // Finally, infer the maximal set of attributes from the ones we've inferred
1816   // above.  This is handling the cases where one attribute on a signature
1817   // implies another, but for implementation reasons the inference rule for
1818   // the later is missing (or simply less sophisticated).
1819   for (Function *F : Nodes.SCCNodes)
1820     if (F)
1821       if (inferAttributesFromOthers(*F))
1822         Changed.insert(F);
1823 
1824   return Changed;
1825 }
1826 
1827 PreservedAnalyses PostOrderFunctionAttrsPass::run(LazyCallGraph::SCC &C,
1828                                                   CGSCCAnalysisManager &AM,
1829                                                   LazyCallGraph &CG,
1830                                                   CGSCCUpdateResult &) {
1831   FunctionAnalysisManager &FAM =
1832       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
1833 
1834   // We pass a lambda into functions to wire them up to the analysis manager
1835   // for getting function analyses.
1836   auto AARGetter = [&](Function &F) -> AAResults & {
1837     return FAM.getResult<AAManager>(F);
1838   };
1839 
1840   SmallVector<Function *, 8> Functions;
1841   for (LazyCallGraph::Node &N : C) {
1842     Functions.push_back(&N.getFunction());
1843   }
1844 
1845   auto ChangedFunctions = deriveAttrsInPostOrder(Functions, AARGetter);
1846   if (ChangedFunctions.empty())
1847     return PreservedAnalyses::all();
1848 
1849   // Invalidate analyses for modified functions so that we don't have to
1850   // invalidate all analyses for all functions in this SCC.
1851   PreservedAnalyses FuncPA;
1852   // We haven't changed the CFG for modified functions.
1853   FuncPA.preserveSet<CFGAnalyses>();
1854   for (Function *Changed : ChangedFunctions) {
1855     FAM.invalidate(*Changed, FuncPA);
1856     // Also invalidate any direct callers of changed functions since analyses
1857     // may care about attributes of direct callees. For example, MemorySSA cares
1858     // about whether or not a call's callee modifies memory and queries that
1859     // through function attributes.
1860     for (auto *U : Changed->users()) {
1861       if (auto *Call = dyn_cast<CallBase>(U)) {
1862         if (Call->getCalledFunction() == Changed)
1863           FAM.invalidate(*Call->getFunction(), FuncPA);
1864       }
1865     }
1866   }
1867 
1868   PreservedAnalyses PA;
1869   // We have not added or removed functions.
1870   PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
1871   // We already invalidated all relevant function analyses above.
1872   PA.preserveSet<AllAnalysesOn<Function>>();
1873   return PA;
1874 }
1875 
1876 namespace {
1877 
1878 struct PostOrderFunctionAttrsLegacyPass : public CallGraphSCCPass {
1879   // Pass identification, replacement for typeid
1880   static char ID;
1881 
1882   PostOrderFunctionAttrsLegacyPass() : CallGraphSCCPass(ID) {
1883     initializePostOrderFunctionAttrsLegacyPassPass(
1884         *PassRegistry::getPassRegistry());
1885   }
1886 
1887   bool runOnSCC(CallGraphSCC &SCC) override;
1888 
1889   void getAnalysisUsage(AnalysisUsage &AU) const override {
1890     AU.setPreservesCFG();
1891     AU.addRequired<AssumptionCacheTracker>();
1892     getAAResultsAnalysisUsage(AU);
1893     CallGraphSCCPass::getAnalysisUsage(AU);
1894   }
1895 };
1896 
1897 } // end anonymous namespace
1898 
1899 char PostOrderFunctionAttrsLegacyPass::ID = 0;
1900 INITIALIZE_PASS_BEGIN(PostOrderFunctionAttrsLegacyPass, "function-attrs",
1901                       "Deduce function attributes", false, false)
1902 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1903 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1904 INITIALIZE_PASS_END(PostOrderFunctionAttrsLegacyPass, "function-attrs",
1905                     "Deduce function attributes", false, false)
1906 
1907 Pass *llvm::createPostOrderFunctionAttrsLegacyPass() {
1908   return new PostOrderFunctionAttrsLegacyPass();
1909 }
1910 
1911 template <typename AARGetterT>
1912 static bool runImpl(CallGraphSCC &SCC, AARGetterT AARGetter) {
1913   SmallVector<Function *, 8> Functions;
1914   for (CallGraphNode *I : SCC) {
1915     Functions.push_back(I->getFunction());
1916   }
1917 
1918   return !deriveAttrsInPostOrder(Functions, AARGetter).empty();
1919 }
1920 
1921 bool PostOrderFunctionAttrsLegacyPass::runOnSCC(CallGraphSCC &SCC) {
1922   if (skipSCC(SCC))
1923     return false;
1924   return runImpl(SCC, LegacyAARGetter(*this));
1925 }
1926 
1927 namespace {
1928 
1929 struct ReversePostOrderFunctionAttrsLegacyPass : public ModulePass {
1930   // Pass identification, replacement for typeid
1931   static char ID;
1932 
1933   ReversePostOrderFunctionAttrsLegacyPass() : ModulePass(ID) {
1934     initializeReversePostOrderFunctionAttrsLegacyPassPass(
1935         *PassRegistry::getPassRegistry());
1936   }
1937 
1938   bool runOnModule(Module &M) override;
1939 
1940   void getAnalysisUsage(AnalysisUsage &AU) const override {
1941     AU.setPreservesCFG();
1942     AU.addRequired<CallGraphWrapperPass>();
1943     AU.addPreserved<CallGraphWrapperPass>();
1944   }
1945 };
1946 
1947 } // end anonymous namespace
1948 
1949 char ReversePostOrderFunctionAttrsLegacyPass::ID = 0;
1950 
1951 INITIALIZE_PASS_BEGIN(ReversePostOrderFunctionAttrsLegacyPass,
1952                       "rpo-function-attrs", "Deduce function attributes in RPO",
1953                       false, false)
1954 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
1955 INITIALIZE_PASS_END(ReversePostOrderFunctionAttrsLegacyPass,
1956                     "rpo-function-attrs", "Deduce function attributes in RPO",
1957                     false, false)
1958 
1959 Pass *llvm::createReversePostOrderFunctionAttrsPass() {
1960   return new ReversePostOrderFunctionAttrsLegacyPass();
1961 }
1962 
1963 static bool addNoRecurseAttrsTopDown(Function &F) {
1964   // We check the preconditions for the function prior to calling this to avoid
1965   // the cost of building up a reversible post-order list. We assert them here
1966   // to make sure none of the invariants this relies on were violated.
1967   assert(!F.isDeclaration() && "Cannot deduce norecurse without a definition!");
1968   assert(!F.doesNotRecurse() &&
1969          "This function has already been deduced as norecurs!");
1970   assert(F.hasInternalLinkage() &&
1971          "Can only do top-down deduction for internal linkage functions!");
1972 
1973   // If F is internal and all of its uses are calls from a non-recursive
1974   // functions, then none of its calls could in fact recurse without going
1975   // through a function marked norecurse, and so we can mark this function too
1976   // as norecurse. Note that the uses must actually be calls -- otherwise
1977   // a pointer to this function could be returned from a norecurse function but
1978   // this function could be recursively (indirectly) called. Note that this
1979   // also detects if F is directly recursive as F is not yet marked as
1980   // a norecurse function.
1981   for (auto *U : F.users()) {
1982     auto *I = dyn_cast<Instruction>(U);
1983     if (!I)
1984       return false;
1985     CallBase *CB = dyn_cast<CallBase>(I);
1986     if (!CB || !CB->getParent()->getParent()->doesNotRecurse())
1987       return false;
1988   }
1989   F.setDoesNotRecurse();
1990   ++NumNoRecurse;
1991   return true;
1992 }
1993 
1994 static bool deduceFunctionAttributeInRPO(Module &M, CallGraph &CG) {
1995   // We only have a post-order SCC traversal (because SCCs are inherently
1996   // discovered in post-order), so we accumulate them in a vector and then walk
1997   // it in reverse. This is simpler than using the RPO iterator infrastructure
1998   // because we need to combine SCC detection and the PO walk of the call
1999   // graph. We can also cheat egregiously because we're primarily interested in
2000   // synthesizing norecurse and so we can only save the singular SCCs as SCCs
2001   // with multiple functions in them will clearly be recursive.
2002   SmallVector<Function *, 16> Worklist;
2003   for (scc_iterator<CallGraph *> I = scc_begin(&CG); !I.isAtEnd(); ++I) {
2004     if (I->size() != 1)
2005       continue;
2006 
2007     Function *F = I->front()->getFunction();
2008     if (F && !F->isDeclaration() && !F->doesNotRecurse() &&
2009         F->hasInternalLinkage())
2010       Worklist.push_back(F);
2011   }
2012 
2013   bool Changed = false;
2014   for (auto *F : llvm::reverse(Worklist))
2015     Changed |= addNoRecurseAttrsTopDown(*F);
2016 
2017   return Changed;
2018 }
2019 
2020 bool ReversePostOrderFunctionAttrsLegacyPass::runOnModule(Module &M) {
2021   if (skipModule(M))
2022     return false;
2023 
2024   auto &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
2025 
2026   return deduceFunctionAttributeInRPO(M, CG);
2027 }
2028 
2029 PreservedAnalyses
2030 ReversePostOrderFunctionAttrsPass::run(Module &M, ModuleAnalysisManager &AM) {
2031   auto &CG = AM.getResult<CallGraphAnalysis>(M);
2032 
2033   if (!deduceFunctionAttributeInRPO(M, CG))
2034     return PreservedAnalyses::all();
2035 
2036   PreservedAnalyses PA;
2037   PA.preserve<CallGraphAnalysis>();
2038   return PA;
2039 }
2040