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