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