1 //===- Attributor.cpp - Module-wide attribute deduction -------------------===//
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 // This file implements an interprocedural pass that deduces and/or propagates
10 // attributes. This is done in an abstract interpretation style fixpoint
11 // iteration. See the Attributor.h file comment and the class descriptions in
12 // that file for more information.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/IPO/Attributor.h"
17 
18 #include "llvm/ADT/PointerIntPair.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/TinyPtrVector.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/CallGraph.h"
24 #include "llvm/Analysis/CallGraphSCCPass.h"
25 #include "llvm/Analysis/InlineCost.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/MustExecute.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/Constant.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/GlobalValue.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/IR/Instruction.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/IntrinsicInst.h"
36 #include "llvm/IR/ValueHandle.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/DebugCounter.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/GraphWriter.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Cloning.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 
49 #ifdef EXPENSIVE_CHECKS
50 #include "llvm/IR/Verifier.h"
51 #endif
52 
53 #include <cassert>
54 #include <string>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "attributor"
59 
60 DEBUG_COUNTER(ManifestDBGCounter, "attributor-manifest",
61               "Determine what attributes are manifested in the IR");
62 
63 STATISTIC(NumFnDeleted, "Number of function deleted");
64 STATISTIC(NumFnWithExactDefinition,
65           "Number of functions with exact definitions");
66 STATISTIC(NumFnWithoutExactDefinition,
67           "Number of functions without exact definitions");
68 STATISTIC(NumFnShallowWrappersCreated, "Number of shallow wrappers created");
69 STATISTIC(NumAttributesTimedOut,
70           "Number of abstract attributes timed out before fixpoint");
71 STATISTIC(NumAttributesValidFixpoint,
72           "Number of abstract attributes in a valid fixpoint state");
73 STATISTIC(NumAttributesManifested,
74           "Number of abstract attributes manifested in IR");
75 
76 // TODO: Determine a good default value.
77 //
78 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads
79 // (when run with the first 5 abstract attributes). The results also indicate
80 // that we never reach 32 iterations but always find a fixpoint sooner.
81 //
82 // This will become more evolved once we perform two interleaved fixpoint
83 // iterations: bottom-up and top-down.
84 static cl::opt<unsigned>
85     SetFixpointIterations("attributor-max-iterations", cl::Hidden,
86                           cl::desc("Maximal number of fixpoint iterations."),
87                           cl::init(32));
88 
89 static cl::opt<unsigned, true> MaxInitializationChainLengthX(
90     "attributor-max-initialization-chain-length", cl::Hidden,
91     cl::desc(
92         "Maximal number of chained initializations (to avoid stack overflows)"),
93     cl::location(MaxInitializationChainLength), cl::init(1024));
94 unsigned llvm::MaxInitializationChainLength;
95 
96 static cl::opt<bool> VerifyMaxFixpointIterations(
97     "attributor-max-iterations-verify", cl::Hidden,
98     cl::desc("Verify that max-iterations is a tight bound for a fixpoint"),
99     cl::init(false));
100 
101 static cl::opt<bool> AnnotateDeclarationCallSites(
102     "attributor-annotate-decl-cs", cl::Hidden,
103     cl::desc("Annotate call sites of function declarations."), cl::init(false));
104 
105 static cl::opt<bool> EnableHeapToStack("enable-heap-to-stack-conversion",
106                                        cl::init(true), cl::Hidden);
107 
108 static cl::opt<bool>
109     AllowShallowWrappers("attributor-allow-shallow-wrappers", cl::Hidden,
110                          cl::desc("Allow the Attributor to create shallow "
111                                   "wrappers for non-exact definitions."),
112                          cl::init(false));
113 
114 static cl::opt<bool>
115     AllowDeepWrapper("attributor-allow-deep-wrappers", cl::Hidden,
116                      cl::desc("Allow the Attributor to use IP information "
117                               "derived from non-exact functions via cloning"),
118                      cl::init(false));
119 
120 // These options can only used for debug builds.
121 #ifndef NDEBUG
122 static cl::list<std::string>
123     SeedAllowList("attributor-seed-allow-list", cl::Hidden,
124                   cl::desc("Comma seperated list of attribute names that are "
125                            "allowed to be seeded."),
126                   cl::CommaSeparated);
127 
128 static cl::list<std::string> FunctionSeedAllowList(
129     "attributor-function-seed-allow-list", cl::Hidden,
130     cl::desc("Comma seperated list of function names that are "
131              "allowed to be seeded."),
132     cl::CommaSeparated);
133 #endif
134 
135 static cl::opt<bool>
136     DumpDepGraph("attributor-dump-dep-graph", cl::Hidden,
137                  cl::desc("Dump the dependency graph to dot files."),
138                  cl::init(false));
139 
140 static cl::opt<std::string> DepGraphDotFileNamePrefix(
141     "attributor-depgraph-dot-filename-prefix", cl::Hidden,
142     cl::desc("The prefix used for the CallGraph dot file names."));
143 
144 static cl::opt<bool> ViewDepGraph("attributor-view-dep-graph", cl::Hidden,
145                                   cl::desc("View the dependency graph."),
146                                   cl::init(false));
147 
148 static cl::opt<bool> PrintDependencies("attributor-print-dep", cl::Hidden,
149                                        cl::desc("Print attribute dependencies"),
150                                        cl::init(false));
151 
152 static cl::opt<bool> EnableCallSiteSpecific(
153     "attributor-enable-call-site-specific-deduction", cl::Hidden,
154     cl::desc("Allow the Attributor to do call site specific analysis"),
155     cl::init(false));
156 
157 static cl::opt<bool>
158     PrintCallGraph("attributor-print-call-graph", cl::Hidden,
159                    cl::desc("Print Attributor's internal call graph"),
160                    cl::init(false));
161 
162 static cl::opt<bool> SimplifyAllLoads("attributor-simplify-all-loads",
163                                       cl::Hidden,
164                                       cl::desc("Try to simplify all loads."),
165                                       cl::init(true));
166 
167 /// Logic operators for the change status enum class.
168 ///
169 ///{
170 ChangeStatus llvm::operator|(ChangeStatus L, ChangeStatus R) {
171   return L == ChangeStatus::CHANGED ? L : R;
172 }
173 ChangeStatus &llvm::operator|=(ChangeStatus &L, ChangeStatus R) {
174   L = L | R;
175   return L;
176 }
177 ChangeStatus llvm::operator&(ChangeStatus L, ChangeStatus R) {
178   return L == ChangeStatus::UNCHANGED ? L : R;
179 }
180 ChangeStatus &llvm::operator&=(ChangeStatus &L, ChangeStatus R) {
181   L = L & R;
182   return L;
183 }
184 ///}
185 
186 bool AA::isNoSyncInst(Attributor &A, const Instruction &I,
187                       const AbstractAttribute &QueryingAA) {
188   // We are looking for volatile instructions or non-relaxed atomics.
189   if (const auto *CB = dyn_cast<CallBase>(&I)) {
190     if (CB->hasFnAttr(Attribute::NoSync))
191       return true;
192 
193     // Non-convergent and readnone imply nosync.
194     if (!CB->isConvergent() && !CB->mayReadOrWriteMemory())
195       return true;
196 
197     if (AANoSync::isNoSyncIntrinsic(&I))
198       return true;
199 
200     const auto &NoSyncAA = A.getAAFor<AANoSync>(
201         QueryingAA, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL);
202     return NoSyncAA.isAssumedNoSync();
203   }
204 
205   if (!I.mayReadOrWriteMemory())
206     return true;
207 
208   return !I.isVolatile() && !AANoSync::isNonRelaxedAtomic(&I);
209 }
210 
211 bool AA::isDynamicallyUnique(Attributor &A, const AbstractAttribute &QueryingAA,
212                              const Value &V, bool ForAnalysisOnly) {
213   // TODO: See the AAInstanceInfo class comment.
214   if (!ForAnalysisOnly)
215     return false;
216   auto &InstanceInfoAA = A.getAAFor<AAInstanceInfo>(
217       QueryingAA, IRPosition::value(V), DepClassTy::OPTIONAL);
218   return InstanceInfoAA.isAssumedUniqueForAnalysis();
219 }
220 
221 Constant *AA::getInitialValueForObj(Value &Obj, Type &Ty,
222                                     const TargetLibraryInfo *TLI) {
223   if (isa<AllocaInst>(Obj))
224     return UndefValue::get(&Ty);
225   if (Constant *Init = getInitialValueOfAllocation(&Obj, TLI, &Ty))
226     return Init;
227   auto *GV = dyn_cast<GlobalVariable>(&Obj);
228   if (!GV)
229     return nullptr;
230   if (!GV->hasLocalLinkage() && !(GV->isConstant() && GV->hasInitializer()))
231     return nullptr;
232   if (!GV->hasInitializer())
233     return UndefValue::get(&Ty);
234   return dyn_cast_or_null<Constant>(getWithType(*GV->getInitializer(), Ty));
235 }
236 
237 bool AA::isValidInScope(const Value &V, const Function *Scope) {
238   if (isa<Constant>(V))
239     return true;
240   if (auto *I = dyn_cast<Instruction>(&V))
241     return I->getFunction() == Scope;
242   if (auto *A = dyn_cast<Argument>(&V))
243     return A->getParent() == Scope;
244   return false;
245 }
246 
247 bool AA::isValidAtPosition(const AA::ValueAndContext &VAC,
248                            InformationCache &InfoCache) {
249   if (isa<Constant>(VAC.getValue()) || VAC.getValue() == VAC.getCtxI())
250     return true;
251   const Function *Scope = nullptr;
252   const Instruction *CtxI = VAC.getCtxI();
253   if (CtxI)
254     Scope = CtxI->getFunction();
255   if (auto *A = dyn_cast<Argument>(VAC.getValue()))
256     return A->getParent() == Scope;
257   if (auto *I = dyn_cast<Instruction>(VAC.getValue())) {
258     if (I->getFunction() == Scope) {
259       if (const DominatorTree *DT =
260               InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(
261                   *Scope))
262         return DT->dominates(I, CtxI);
263       // Local dominance check mostly for the old PM passes.
264       if (CtxI && I->getParent() == CtxI->getParent())
265         return llvm::any_of(
266             make_range(I->getIterator(), I->getParent()->end()),
267             [&](const Instruction &AfterI) { return &AfterI == CtxI; });
268     }
269   }
270   return false;
271 }
272 
273 Value *AA::getWithType(Value &V, Type &Ty) {
274   if (V.getType() == &Ty)
275     return &V;
276   if (isa<PoisonValue>(V))
277     return PoisonValue::get(&Ty);
278   if (isa<UndefValue>(V))
279     return UndefValue::get(&Ty);
280   if (auto *C = dyn_cast<Constant>(&V)) {
281     if (C->isNullValue())
282       return Constant::getNullValue(&Ty);
283     if (C->getType()->isPointerTy() && Ty.isPointerTy())
284       return ConstantExpr::getPointerCast(C, &Ty);
285     if (C->getType()->getPrimitiveSizeInBits() >= Ty.getPrimitiveSizeInBits()) {
286       if (C->getType()->isIntegerTy() && Ty.isIntegerTy())
287         return ConstantExpr::getTrunc(C, &Ty, /* OnlyIfReduced */ true);
288       if (C->getType()->isFloatingPointTy() && Ty.isFloatingPointTy())
289         return ConstantExpr::getFPTrunc(C, &Ty, /* OnlyIfReduced */ true);
290     }
291   }
292   return nullptr;
293 }
294 
295 Optional<Value *>
296 AA::combineOptionalValuesInAAValueLatice(const Optional<Value *> &A,
297                                          const Optional<Value *> &B, Type *Ty) {
298   if (A == B)
299     return A;
300   if (!B)
301     return A;
302   if (*B == nullptr)
303     return nullptr;
304   if (!A)
305     return Ty ? getWithType(**B, *Ty) : nullptr;
306   if (*A == nullptr)
307     return nullptr;
308   if (!Ty)
309     Ty = (*A)->getType();
310   if (isa_and_nonnull<UndefValue>(*A))
311     return getWithType(**B, *Ty);
312   if (isa<UndefValue>(*B))
313     return A;
314   if (*A && *B && *A == getWithType(**B, *Ty))
315     return A;
316   return nullptr;
317 }
318 
319 template <bool IsLoad, typename Ty>
320 static bool getPotentialCopiesOfMemoryValue(
321     Attributor &A, Ty &I, SmallSetVector<Value *, 4> &PotentialCopies,
322     SmallSetVector<Instruction *, 4> &PotentialValueOrigins,
323     const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
324     bool OnlyExact) {
325   LLVM_DEBUG(dbgs() << "Trying to determine the potential copies of " << I
326                     << " (only exact: " << OnlyExact << ")\n";);
327 
328   Value &Ptr = *I.getPointerOperand();
329   SmallSetVector<Value *, 8> Objects;
330   if (!AA::getAssumedUnderlyingObjects(A, Ptr, Objects, QueryingAA, &I,
331                                        UsedAssumedInformation)) {
332     LLVM_DEBUG(
333         dbgs() << "Underlying objects stored into could not be determined\n";);
334     return false;
335   }
336 
337   // Containers to remember the pointer infos and new copies while we are not
338   // sure that we can find all of them. If we abort we want to avoid spurious
339   // dependences and potential copies in the provided container.
340   SmallVector<const AAPointerInfo *> PIs;
341   SmallVector<Value *> NewCopies;
342   SmallVector<Instruction *> NewCopyOrigins;
343 
344   const auto *TLI =
345       A.getInfoCache().getTargetLibraryInfoForFunction(*I.getFunction());
346   LLVM_DEBUG(dbgs() << "Visit " << Objects.size() << " objects:\n");
347   for (Value *Obj : Objects) {
348     LLVM_DEBUG(dbgs() << "Visit underlying object " << *Obj << "\n");
349     if (isa<UndefValue>(Obj))
350       continue;
351     if (isa<ConstantPointerNull>(Obj)) {
352       // A null pointer access can be undefined but any offset from null may
353       // be OK. We do not try to optimize the latter.
354       if (!NullPointerIsDefined(I.getFunction(),
355                                 Ptr.getType()->getPointerAddressSpace()) &&
356           A.getAssumedSimplified(Ptr, QueryingAA, UsedAssumedInformation,
357                                  AA::Interprocedural) == Obj)
358         continue;
359       LLVM_DEBUG(
360           dbgs() << "Underlying object is a valid nullptr, giving up.\n";);
361       return false;
362     }
363     // TODO: Use assumed noalias return.
364     if (!isa<AllocaInst>(Obj) && !isa<GlobalVariable>(Obj) &&
365         !(IsLoad ? isAllocationFn(Obj, TLI) : isNoAliasCall(Obj))) {
366       LLVM_DEBUG(dbgs() << "Underlying object is not supported yet: " << *Obj
367                         << "\n";);
368       return false;
369     }
370     if (auto *GV = dyn_cast<GlobalVariable>(Obj))
371       if (!GV->hasLocalLinkage() &&
372           !(GV->isConstant() && GV->hasInitializer())) {
373         LLVM_DEBUG(dbgs() << "Underlying object is global with external "
374                              "linkage, not supported yet: "
375                           << *Obj << "\n";);
376         return false;
377       }
378 
379     bool NullOnly = true;
380     bool NullRequired = false;
381     auto CheckForNullOnlyAndUndef = [&](Optional<Value *> V) {
382       if (!V || *V == nullptr)
383         NullOnly = false;
384       else if (isa<UndefValue>(*V))
385         /* No op */;
386       else if (isa<Constant>(*V) && cast<Constant>(*V)->isNullValue())
387         NullRequired = true;
388       else
389         NullOnly = false;
390     };
391 
392     if (IsLoad) {
393       Value *InitialValue = AA::getInitialValueForObj(*Obj, *I.getType(), TLI);
394       if (!InitialValue) {
395         LLVM_DEBUG(dbgs() << "Failed to get initial value: " << *Obj << "\n");
396         return false;
397       }
398       CheckForNullOnlyAndUndef(InitialValue);
399       NewCopies.push_back(InitialValue);
400       NewCopyOrigins.push_back(nullptr);
401     }
402 
403     auto CheckAccess = [&](const AAPointerInfo::Access &Acc, bool IsExact) {
404       if ((IsLoad && !Acc.isWrite()) || (!IsLoad && !Acc.isRead()))
405         return true;
406       if (IsLoad && Acc.isWrittenValueYetUndetermined())
407         return true;
408       CheckForNullOnlyAndUndef(Acc.getContent());
409       if (OnlyExact && !IsExact && !NullOnly &&
410           !isa_and_nonnull<UndefValue>(Acc.getWrittenValue())) {
411         LLVM_DEBUG(dbgs() << "Non exact access " << *Acc.getRemoteInst()
412                           << ", abort!\n");
413         return false;
414       }
415       if (NullRequired && !NullOnly) {
416         LLVM_DEBUG(dbgs() << "Required all `null` accesses due to non exact "
417                              "one, however found non-null one: "
418                           << *Acc.getRemoteInst() << ", abort!\n");
419         return false;
420       }
421       if (IsLoad) {
422         assert(isa<LoadInst>(I) && "Expected load or store instruction only!");
423         if (!Acc.isWrittenValueUnknown()) {
424           NewCopies.push_back(Acc.getWrittenValue());
425           NewCopyOrigins.push_back(Acc.getRemoteInst());
426           return true;
427         }
428         auto *SI = dyn_cast<StoreInst>(Acc.getRemoteInst());
429         if (!SI) {
430           LLVM_DEBUG(dbgs() << "Underlying object written through a non-store "
431                                "instruction not supported yet: "
432                             << *Acc.getRemoteInst() << "\n";);
433           return false;
434         }
435         NewCopies.push_back(SI->getValueOperand());
436         NewCopyOrigins.push_back(SI);
437       } else {
438         assert(isa<StoreInst>(I) && "Expected load or store instruction only!");
439         auto *LI = dyn_cast<LoadInst>(Acc.getRemoteInst());
440         if (!LI && OnlyExact) {
441           LLVM_DEBUG(dbgs() << "Underlying object read through a non-load "
442                                "instruction not supported yet: "
443                             << *Acc.getRemoteInst() << "\n";);
444           return false;
445         }
446         NewCopies.push_back(Acc.getRemoteInst());
447       }
448       return true;
449     };
450 
451     auto &PI = A.getAAFor<AAPointerInfo>(QueryingAA, IRPosition::value(*Obj),
452                                          DepClassTy::NONE);
453     if (!PI.forallInterferingAccesses(A, QueryingAA, I, CheckAccess)) {
454       LLVM_DEBUG(
455           dbgs()
456           << "Failed to verify all interfering accesses for underlying object: "
457           << *Obj << "\n");
458       return false;
459     }
460     PIs.push_back(&PI);
461   }
462 
463   // Only if we were successful collection all potential copies we record
464   // dependences (on non-fix AAPointerInfo AAs). We also only then modify the
465   // given PotentialCopies container.
466   for (auto *PI : PIs) {
467     if (!PI->getState().isAtFixpoint())
468       UsedAssumedInformation = true;
469     A.recordDependence(*PI, QueryingAA, DepClassTy::OPTIONAL);
470   }
471   PotentialCopies.insert(NewCopies.begin(), NewCopies.end());
472   PotentialValueOrigins.insert(NewCopyOrigins.begin(), NewCopyOrigins.end());
473 
474   return true;
475 }
476 
477 bool AA::getPotentiallyLoadedValues(
478     Attributor &A, LoadInst &LI, SmallSetVector<Value *, 4> &PotentialValues,
479     SmallSetVector<Instruction *, 4> &PotentialValueOrigins,
480     const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
481     bool OnlyExact) {
482   return getPotentialCopiesOfMemoryValue</* IsLoad */ true>(
483       A, LI, PotentialValues, PotentialValueOrigins, QueryingAA,
484       UsedAssumedInformation, OnlyExact);
485 }
486 
487 bool AA::getPotentialCopiesOfStoredValue(
488     Attributor &A, StoreInst &SI, SmallSetVector<Value *, 4> &PotentialCopies,
489     const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
490     bool OnlyExact) {
491   SmallSetVector<Instruction *, 4> PotentialValueOrigins;
492   return getPotentialCopiesOfMemoryValue</* IsLoad */ false>(
493       A, SI, PotentialCopies, PotentialValueOrigins, QueryingAA,
494       UsedAssumedInformation, OnlyExact);
495 }
496 
497 static bool isAssumedReadOnlyOrReadNone(Attributor &A, const IRPosition &IRP,
498                                         const AbstractAttribute &QueryingAA,
499                                         bool RequireReadNone, bool &IsKnown) {
500 
501   IRPosition::Kind Kind = IRP.getPositionKind();
502   if (Kind == IRPosition::IRP_FUNCTION || Kind == IRPosition::IRP_CALL_SITE) {
503     const auto &MemLocAA =
504         A.getAAFor<AAMemoryLocation>(QueryingAA, IRP, DepClassTy::NONE);
505     if (MemLocAA.isAssumedReadNone()) {
506       IsKnown = MemLocAA.isKnownReadNone();
507       if (!IsKnown)
508         A.recordDependence(MemLocAA, QueryingAA, DepClassTy::OPTIONAL);
509       return true;
510     }
511   }
512 
513   const auto &MemBehaviorAA =
514       A.getAAFor<AAMemoryBehavior>(QueryingAA, IRP, DepClassTy::NONE);
515   if (MemBehaviorAA.isAssumedReadNone() ||
516       (!RequireReadNone && MemBehaviorAA.isAssumedReadOnly())) {
517     IsKnown = RequireReadNone ? MemBehaviorAA.isKnownReadNone()
518                               : MemBehaviorAA.isKnownReadOnly();
519     if (!IsKnown)
520       A.recordDependence(MemBehaviorAA, QueryingAA, DepClassTy::OPTIONAL);
521     return true;
522   }
523 
524   return false;
525 }
526 
527 bool AA::isAssumedReadOnly(Attributor &A, const IRPosition &IRP,
528                            const AbstractAttribute &QueryingAA, bool &IsKnown) {
529   return isAssumedReadOnlyOrReadNone(A, IRP, QueryingAA,
530                                      /* RequireReadNone */ false, IsKnown);
531 }
532 bool AA::isAssumedReadNone(Attributor &A, const IRPosition &IRP,
533                            const AbstractAttribute &QueryingAA, bool &IsKnown) {
534   return isAssumedReadOnlyOrReadNone(A, IRP, QueryingAA,
535                                      /* RequireReadNone */ true, IsKnown);
536 }
537 
538 static bool
539 isPotentiallyReachable(Attributor &A, const Instruction &FromI,
540                        const Instruction *ToI, const Function &ToFn,
541                        const AbstractAttribute &QueryingAA,
542                        std::function<bool(const Function &F)> GoBackwardsCB) {
543   LLVM_DEBUG(dbgs() << "[AA] isPotentiallyReachable @" << ToFn.getName()
544                     << " from " << FromI << " [GBCB: " << bool(GoBackwardsCB)
545                     << "]\n");
546 
547   SmallPtrSet<const Instruction *, 8> Visited;
548   SmallVector<const Instruction *> Worklist;
549   Worklist.push_back(&FromI);
550 
551   const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(
552       QueryingAA, IRPosition::function(ToFn), DepClassTy::OPTIONAL);
553   while (!Worklist.empty()) {
554     const Instruction *CurFromI = Worklist.pop_back_val();
555     if (!Visited.insert(CurFromI).second)
556       continue;
557 
558     const Function *FromFn = CurFromI->getFunction();
559     if (FromFn == &ToFn) {
560       if (!ToI)
561         return true;
562       LLVM_DEBUG(dbgs() << "[AA] check " << *ToI << " from " << *CurFromI
563                         << " intraprocedurally\n");
564       const auto &ReachabilityAA = A.getAAFor<AAReachability>(
565           QueryingAA, IRPosition::function(ToFn), DepClassTy::OPTIONAL);
566       bool Result = ReachabilityAA.isAssumedReachable(A, *CurFromI, *ToI);
567       LLVM_DEBUG(dbgs() << "[AA] " << *CurFromI << " "
568                         << (Result ? "can potentially " : "cannot ") << "reach "
569                         << *ToI << " [Intra]\n");
570       if (Result)
571         return true;
572       if (NoRecurseAA.isAssumedNoRecurse())
573         continue;
574     }
575 
576     // TODO: If we can go arbitrarily backwards we will eventually reach an
577     // entry point that can reach ToI. Only once this takes a set of blocks
578     // through which we cannot go, or once we track internal functions not
579     // accessible from the outside, it makes sense to perform backwards analysis
580     // in the absence of a GoBackwardsCB.
581     if (!GoBackwardsCB) {
582       LLVM_DEBUG(dbgs() << "[AA] check @" << ToFn.getName() << " from "
583                         << *CurFromI << " is not checked backwards, abort\n");
584       return true;
585     }
586 
587     // Check if the current instruction is already known to reach the ToFn.
588     const auto &FnReachabilityAA = A.getAAFor<AAFunctionReachability>(
589         QueryingAA, IRPosition::function(*FromFn), DepClassTy::OPTIONAL);
590     bool Result = FnReachabilityAA.instructionCanReach(
591         A, *CurFromI, ToFn, /* UseBackwards */ false);
592     LLVM_DEBUG(dbgs() << "[AA] " << *CurFromI << " in @" << FromFn->getName()
593                       << " " << (Result ? "can potentially " : "cannot ")
594                       << "reach @" << ToFn.getName() << " [FromFn]\n");
595     if (Result)
596       return true;
597 
598     // If we do not go backwards from the FromFn we are done here and so far we
599     // could not find a way to reach ToFn/ToI.
600     if (!GoBackwardsCB(*FromFn))
601       continue;
602 
603     LLVM_DEBUG(dbgs() << "Stepping backwards to the call sites of @"
604                       << FromFn->getName() << "\n");
605 
606     auto CheckCallSite = [&](AbstractCallSite ACS) {
607       CallBase *CB = ACS.getInstruction();
608       if (!CB)
609         return false;
610 
611       if (isa<InvokeInst>(CB))
612         return false;
613 
614       Instruction *Inst = CB->getNextNonDebugInstruction();
615       Worklist.push_back(Inst);
616       return true;
617     };
618 
619     bool UsedAssumedInformation = false;
620     Result = !A.checkForAllCallSites(CheckCallSite, *FromFn,
621                                      /* RequireAllCallSites */ true,
622                                      &QueryingAA, UsedAssumedInformation);
623     if (Result) {
624       LLVM_DEBUG(dbgs() << "[AA] stepping back to call sites from " << *CurFromI
625                         << " in @" << FromFn->getName()
626                         << " failed, give up\n");
627       return true;
628     }
629 
630     LLVM_DEBUG(dbgs() << "[AA] stepped back to call sites from " << *CurFromI
631                       << " in @" << FromFn->getName()
632                       << " worklist size is: " << Worklist.size() << "\n");
633   }
634   return false;
635 }
636 
637 bool AA::isPotentiallyReachable(
638     Attributor &A, const Instruction &FromI, const Instruction &ToI,
639     const AbstractAttribute &QueryingAA,
640     std::function<bool(const Function &F)> GoBackwardsCB) {
641   LLVM_DEBUG(dbgs() << "[AA] isPotentiallyReachable " << ToI << " from "
642                     << FromI << " [GBCB: " << bool(GoBackwardsCB) << "]\n");
643   const Function *ToFn = ToI.getFunction();
644   return ::isPotentiallyReachable(A, FromI, &ToI, *ToFn, QueryingAA,
645                                   GoBackwardsCB);
646 }
647 
648 bool AA::isPotentiallyReachable(
649     Attributor &A, const Instruction &FromI, const Function &ToFn,
650     const AbstractAttribute &QueryingAA,
651     std::function<bool(const Function &F)> GoBackwardsCB) {
652   return ::isPotentiallyReachable(A, FromI, /* ToI */ nullptr, ToFn, QueryingAA,
653                                   GoBackwardsCB);
654 }
655 
656 /// Return true if \p New is equal or worse than \p Old.
657 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) {
658   if (!Old.isIntAttribute())
659     return true;
660 
661   return Old.getValueAsInt() >= New.getValueAsInt();
662 }
663 
664 /// Return true if the information provided by \p Attr was added to the
665 /// attribute list \p Attrs. This is only the case if it was not already present
666 /// in \p Attrs at the position describe by \p PK and \p AttrIdx.
667 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr,
668                              AttributeList &Attrs, int AttrIdx,
669                              bool ForceReplace = false) {
670 
671   if (Attr.isEnumAttribute()) {
672     Attribute::AttrKind Kind = Attr.getKindAsEnum();
673     if (Attrs.hasAttributeAtIndex(AttrIdx, Kind))
674       if (!ForceReplace &&
675           isEqualOrWorse(Attr, Attrs.getAttributeAtIndex(AttrIdx, Kind)))
676         return false;
677     Attrs = Attrs.addAttributeAtIndex(Ctx, AttrIdx, Attr);
678     return true;
679   }
680   if (Attr.isStringAttribute()) {
681     StringRef Kind = Attr.getKindAsString();
682     if (Attrs.hasAttributeAtIndex(AttrIdx, Kind))
683       if (!ForceReplace &&
684           isEqualOrWorse(Attr, Attrs.getAttributeAtIndex(AttrIdx, Kind)))
685         return false;
686     Attrs = Attrs.addAttributeAtIndex(Ctx, AttrIdx, Attr);
687     return true;
688   }
689   if (Attr.isIntAttribute()) {
690     Attribute::AttrKind Kind = Attr.getKindAsEnum();
691     if (Attrs.hasAttributeAtIndex(AttrIdx, Kind))
692       if (!ForceReplace &&
693           isEqualOrWorse(Attr, Attrs.getAttributeAtIndex(AttrIdx, Kind)))
694         return false;
695     Attrs = Attrs.removeAttributeAtIndex(Ctx, AttrIdx, Kind);
696     Attrs = Attrs.addAttributeAtIndex(Ctx, AttrIdx, Attr);
697     return true;
698   }
699 
700   llvm_unreachable("Expected enum or string attribute!");
701 }
702 
703 Argument *IRPosition::getAssociatedArgument() const {
704   if (getPositionKind() == IRP_ARGUMENT)
705     return cast<Argument>(&getAnchorValue());
706 
707   // Not an Argument and no argument number means this is not a call site
708   // argument, thus we cannot find a callback argument to return.
709   int ArgNo = getCallSiteArgNo();
710   if (ArgNo < 0)
711     return nullptr;
712 
713   // Use abstract call sites to make the connection between the call site
714   // values and the ones in callbacks. If a callback was found that makes use
715   // of the underlying call site operand, we want the corresponding callback
716   // callee argument and not the direct callee argument.
717   Optional<Argument *> CBCandidateArg;
718   SmallVector<const Use *, 4> CallbackUses;
719   const auto &CB = cast<CallBase>(getAnchorValue());
720   AbstractCallSite::getCallbackUses(CB, CallbackUses);
721   for (const Use *U : CallbackUses) {
722     AbstractCallSite ACS(U);
723     assert(ACS && ACS.isCallbackCall());
724     if (!ACS.getCalledFunction())
725       continue;
726 
727     for (unsigned u = 0, e = ACS.getNumArgOperands(); u < e; u++) {
728 
729       // Test if the underlying call site operand is argument number u of the
730       // callback callee.
731       if (ACS.getCallArgOperandNo(u) != ArgNo)
732         continue;
733 
734       assert(ACS.getCalledFunction()->arg_size() > u &&
735              "ACS mapped into var-args arguments!");
736       if (CBCandidateArg) {
737         CBCandidateArg = nullptr;
738         break;
739       }
740       CBCandidateArg = ACS.getCalledFunction()->getArg(u);
741     }
742   }
743 
744   // If we found a unique callback candidate argument, return it.
745   if (CBCandidateArg && CBCandidateArg.value())
746     return CBCandidateArg.value();
747 
748   // If no callbacks were found, or none used the underlying call site operand
749   // exclusively, use the direct callee argument if available.
750   const Function *Callee = CB.getCalledFunction();
751   if (Callee && Callee->arg_size() > unsigned(ArgNo))
752     return Callee->getArg(ArgNo);
753 
754   return nullptr;
755 }
756 
757 ChangeStatus AbstractAttribute::update(Attributor &A) {
758   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
759   if (getState().isAtFixpoint())
760     return HasChanged;
761 
762   LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n");
763 
764   HasChanged = updateImpl(A);
765 
766   LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this
767                     << "\n");
768 
769   return HasChanged;
770 }
771 
772 ChangeStatus
773 IRAttributeManifest::manifestAttrs(Attributor &A, const IRPosition &IRP,
774                                    const ArrayRef<Attribute> &DeducedAttrs,
775                                    bool ForceReplace) {
776   Function *ScopeFn = IRP.getAnchorScope();
777   IRPosition::Kind PK = IRP.getPositionKind();
778 
779   // In the following some generic code that will manifest attributes in
780   // DeducedAttrs if they improve the current IR. Due to the different
781   // annotation positions we use the underlying AttributeList interface.
782 
783   AttributeList Attrs;
784   switch (PK) {
785   case IRPosition::IRP_INVALID:
786   case IRPosition::IRP_FLOAT:
787     return ChangeStatus::UNCHANGED;
788   case IRPosition::IRP_ARGUMENT:
789   case IRPosition::IRP_FUNCTION:
790   case IRPosition::IRP_RETURNED:
791     Attrs = ScopeFn->getAttributes();
792     break;
793   case IRPosition::IRP_CALL_SITE:
794   case IRPosition::IRP_CALL_SITE_RETURNED:
795   case IRPosition::IRP_CALL_SITE_ARGUMENT:
796     Attrs = cast<CallBase>(IRP.getAnchorValue()).getAttributes();
797     break;
798   }
799 
800   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
801   LLVMContext &Ctx = IRP.getAnchorValue().getContext();
802   for (const Attribute &Attr : DeducedAttrs) {
803     if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx(), ForceReplace))
804       continue;
805 
806     HasChanged = ChangeStatus::CHANGED;
807   }
808 
809   if (HasChanged == ChangeStatus::UNCHANGED)
810     return HasChanged;
811 
812   switch (PK) {
813   case IRPosition::IRP_ARGUMENT:
814   case IRPosition::IRP_FUNCTION:
815   case IRPosition::IRP_RETURNED:
816     ScopeFn->setAttributes(Attrs);
817     break;
818   case IRPosition::IRP_CALL_SITE:
819   case IRPosition::IRP_CALL_SITE_RETURNED:
820   case IRPosition::IRP_CALL_SITE_ARGUMENT:
821     cast<CallBase>(IRP.getAnchorValue()).setAttributes(Attrs);
822     break;
823   case IRPosition::IRP_INVALID:
824   case IRPosition::IRP_FLOAT:
825     break;
826   }
827 
828   return HasChanged;
829 }
830 
831 const IRPosition IRPosition::EmptyKey(DenseMapInfo<void *>::getEmptyKey());
832 const IRPosition
833     IRPosition::TombstoneKey(DenseMapInfo<void *>::getTombstoneKey());
834 
835 SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) {
836   IRPositions.emplace_back(IRP);
837 
838   // Helper to determine if operand bundles on a call site are benin or
839   // potentially problematic. We handle only llvm.assume for now.
840   auto CanIgnoreOperandBundles = [](const CallBase &CB) {
841     return (isa<IntrinsicInst>(CB) &&
842             cast<IntrinsicInst>(CB).getIntrinsicID() == Intrinsic ::assume);
843   };
844 
845   const auto *CB = dyn_cast<CallBase>(&IRP.getAnchorValue());
846   switch (IRP.getPositionKind()) {
847   case IRPosition::IRP_INVALID:
848   case IRPosition::IRP_FLOAT:
849   case IRPosition::IRP_FUNCTION:
850     return;
851   case IRPosition::IRP_ARGUMENT:
852   case IRPosition::IRP_RETURNED:
853     IRPositions.emplace_back(IRPosition::function(*IRP.getAnchorScope()));
854     return;
855   case IRPosition::IRP_CALL_SITE:
856     assert(CB && "Expected call site!");
857     // TODO: We need to look at the operand bundles similar to the redirection
858     //       in CallBase.
859     if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB))
860       if (const Function *Callee = CB->getCalledFunction())
861         IRPositions.emplace_back(IRPosition::function(*Callee));
862     return;
863   case IRPosition::IRP_CALL_SITE_RETURNED:
864     assert(CB && "Expected call site!");
865     // TODO: We need to look at the operand bundles similar to the redirection
866     //       in CallBase.
867     if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
868       if (const Function *Callee = CB->getCalledFunction()) {
869         IRPositions.emplace_back(IRPosition::returned(*Callee));
870         IRPositions.emplace_back(IRPosition::function(*Callee));
871         for (const Argument &Arg : Callee->args())
872           if (Arg.hasReturnedAttr()) {
873             IRPositions.emplace_back(
874                 IRPosition::callsite_argument(*CB, Arg.getArgNo()));
875             IRPositions.emplace_back(
876                 IRPosition::value(*CB->getArgOperand(Arg.getArgNo())));
877             IRPositions.emplace_back(IRPosition::argument(Arg));
878           }
879       }
880     }
881     IRPositions.emplace_back(IRPosition::callsite_function(*CB));
882     return;
883   case IRPosition::IRP_CALL_SITE_ARGUMENT: {
884     assert(CB && "Expected call site!");
885     // TODO: We need to look at the operand bundles similar to the redirection
886     //       in CallBase.
887     if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
888       const Function *Callee = CB->getCalledFunction();
889       if (Callee) {
890         if (Argument *Arg = IRP.getAssociatedArgument())
891           IRPositions.emplace_back(IRPosition::argument(*Arg));
892         IRPositions.emplace_back(IRPosition::function(*Callee));
893       }
894     }
895     IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue()));
896     return;
897   }
898   }
899 }
900 
901 bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs,
902                          bool IgnoreSubsumingPositions, Attributor *A) const {
903   SmallVector<Attribute, 4> Attrs;
904   for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) {
905     for (Attribute::AttrKind AK : AKs)
906       if (EquivIRP.getAttrsFromIRAttr(AK, Attrs))
907         return true;
908     // The first position returned by the SubsumingPositionIterator is
909     // always the position itself. If we ignore subsuming positions we
910     // are done after the first iteration.
911     if (IgnoreSubsumingPositions)
912       break;
913   }
914   if (A)
915     for (Attribute::AttrKind AK : AKs)
916       if (getAttrsFromAssumes(AK, Attrs, *A))
917         return true;
918   return false;
919 }
920 
921 void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs,
922                           SmallVectorImpl<Attribute> &Attrs,
923                           bool IgnoreSubsumingPositions, Attributor *A) const {
924   for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) {
925     for (Attribute::AttrKind AK : AKs)
926       EquivIRP.getAttrsFromIRAttr(AK, Attrs);
927     // The first position returned by the SubsumingPositionIterator is
928     // always the position itself. If we ignore subsuming positions we
929     // are done after the first iteration.
930     if (IgnoreSubsumingPositions)
931       break;
932   }
933   if (A)
934     for (Attribute::AttrKind AK : AKs)
935       getAttrsFromAssumes(AK, Attrs, *A);
936 }
937 
938 bool IRPosition::getAttrsFromIRAttr(Attribute::AttrKind AK,
939                                     SmallVectorImpl<Attribute> &Attrs) const {
940   if (getPositionKind() == IRP_INVALID || getPositionKind() == IRP_FLOAT)
941     return false;
942 
943   AttributeList AttrList;
944   if (const auto *CB = dyn_cast<CallBase>(&getAnchorValue()))
945     AttrList = CB->getAttributes();
946   else
947     AttrList = getAssociatedFunction()->getAttributes();
948 
949   bool HasAttr = AttrList.hasAttributeAtIndex(getAttrIdx(), AK);
950   if (HasAttr)
951     Attrs.push_back(AttrList.getAttributeAtIndex(getAttrIdx(), AK));
952   return HasAttr;
953 }
954 
955 bool IRPosition::getAttrsFromAssumes(Attribute::AttrKind AK,
956                                      SmallVectorImpl<Attribute> &Attrs,
957                                      Attributor &A) const {
958   assert(getPositionKind() != IRP_INVALID && "Did expect a valid position!");
959   Value &AssociatedValue = getAssociatedValue();
960 
961   const Assume2KnowledgeMap &A2K =
962       A.getInfoCache().getKnowledgeMap().lookup({&AssociatedValue, AK});
963 
964   // Check if we found any potential assume use, if not we don't need to create
965   // explorer iterators.
966   if (A2K.empty())
967     return false;
968 
969   LLVMContext &Ctx = AssociatedValue.getContext();
970   unsigned AttrsSize = Attrs.size();
971   MustBeExecutedContextExplorer &Explorer =
972       A.getInfoCache().getMustBeExecutedContextExplorer();
973   auto EIt = Explorer.begin(getCtxI()), EEnd = Explorer.end(getCtxI());
974   for (auto &It : A2K)
975     if (Explorer.findInContextOf(It.first, EIt, EEnd))
976       Attrs.push_back(Attribute::get(Ctx, AK, It.second.Max));
977   return AttrsSize != Attrs.size();
978 }
979 
980 void IRPosition::verify() {
981 #ifdef EXPENSIVE_CHECKS
982   switch (getPositionKind()) {
983   case IRP_INVALID:
984     assert((CBContext == nullptr) &&
985            "Invalid position must not have CallBaseContext!");
986     assert(!Enc.getOpaqueValue() &&
987            "Expected a nullptr for an invalid position!");
988     return;
989   case IRP_FLOAT:
990     assert((!isa<Argument>(&getAssociatedValue())) &&
991            "Expected specialized kind for argument values!");
992     return;
993   case IRP_RETURNED:
994     assert(isa<Function>(getAsValuePtr()) &&
995            "Expected function for a 'returned' position!");
996     assert(getAsValuePtr() == &getAssociatedValue() &&
997            "Associated value mismatch!");
998     return;
999   case IRP_CALL_SITE_RETURNED:
1000     assert((CBContext == nullptr) &&
1001            "'call site returned' position must not have CallBaseContext!");
1002     assert((isa<CallBase>(getAsValuePtr())) &&
1003            "Expected call base for 'call site returned' position!");
1004     assert(getAsValuePtr() == &getAssociatedValue() &&
1005            "Associated value mismatch!");
1006     return;
1007   case IRP_CALL_SITE:
1008     assert((CBContext == nullptr) &&
1009            "'call site function' position must not have CallBaseContext!");
1010     assert((isa<CallBase>(getAsValuePtr())) &&
1011            "Expected call base for 'call site function' position!");
1012     assert(getAsValuePtr() == &getAssociatedValue() &&
1013            "Associated value mismatch!");
1014     return;
1015   case IRP_FUNCTION:
1016     assert(isa<Function>(getAsValuePtr()) &&
1017            "Expected function for a 'function' position!");
1018     assert(getAsValuePtr() == &getAssociatedValue() &&
1019            "Associated value mismatch!");
1020     return;
1021   case IRP_ARGUMENT:
1022     assert(isa<Argument>(getAsValuePtr()) &&
1023            "Expected argument for a 'argument' position!");
1024     assert(getAsValuePtr() == &getAssociatedValue() &&
1025            "Associated value mismatch!");
1026     return;
1027   case IRP_CALL_SITE_ARGUMENT: {
1028     assert((CBContext == nullptr) &&
1029            "'call site argument' position must not have CallBaseContext!");
1030     Use *U = getAsUsePtr();
1031     (void)U; // Silence unused variable warning.
1032     assert(U && "Expected use for a 'call site argument' position!");
1033     assert(isa<CallBase>(U->getUser()) &&
1034            "Expected call base user for a 'call site argument' position!");
1035     assert(cast<CallBase>(U->getUser())->isArgOperand(U) &&
1036            "Expected call base argument operand for a 'call site argument' "
1037            "position");
1038     assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) ==
1039                unsigned(getCallSiteArgNo()) &&
1040            "Argument number mismatch!");
1041     assert(U->get() == &getAssociatedValue() && "Associated value mismatch!");
1042     return;
1043   }
1044   }
1045 #endif
1046 }
1047 
1048 Optional<Constant *>
1049 Attributor::getAssumedConstant(const IRPosition &IRP,
1050                                const AbstractAttribute &AA,
1051                                bool &UsedAssumedInformation) {
1052   // First check all callbacks provided by outside AAs. If any of them returns
1053   // a non-null value that is different from the associated value, or None, we
1054   // assume it's simplified.
1055   for (auto &CB : SimplificationCallbacks.lookup(IRP)) {
1056     Optional<Value *> SimplifiedV = CB(IRP, &AA, UsedAssumedInformation);
1057     if (!SimplifiedV)
1058       return llvm::None;
1059     if (isa_and_nonnull<Constant>(*SimplifiedV))
1060       return cast<Constant>(*SimplifiedV);
1061     return nullptr;
1062   }
1063   if (auto *C = dyn_cast<Constant>(&IRP.getAssociatedValue()))
1064     return C;
1065   SmallVector<AA::ValueAndContext> Values;
1066   if (getAssumedSimplifiedValues(IRP, &AA, Values,
1067                                  AA::ValueScope::Interprocedural,
1068                                  UsedAssumedInformation)) {
1069     if (Values.empty())
1070       return llvm::None;
1071     if (auto *C = dyn_cast_or_null<Constant>(
1072             AAPotentialValues::getSingleValue(*this, AA, IRP, Values)))
1073       return C;
1074   }
1075   return nullptr;
1076 }
1077 
1078 Optional<Value *> Attributor::getAssumedSimplified(const IRPosition &IRP,
1079                                                    const AbstractAttribute *AA,
1080                                                    bool &UsedAssumedInformation,
1081                                                    AA::ValueScope S) {
1082   // First check all callbacks provided by outside AAs. If any of them returns
1083   // a non-null value that is different from the associated value, or None, we
1084   // assume it's simplified.
1085   for (auto &CB : SimplificationCallbacks.lookup(IRP))
1086     return CB(IRP, AA, UsedAssumedInformation);
1087 
1088   SmallVector<AA::ValueAndContext> Values;
1089   if (!getAssumedSimplifiedValues(IRP, AA, Values, S, UsedAssumedInformation))
1090     return &IRP.getAssociatedValue();
1091   if (Values.empty())
1092     return llvm::None;
1093   if (AA)
1094     if (Value *V = AAPotentialValues::getSingleValue(*this, *AA, IRP, Values))
1095       return V;
1096   if (IRP.getPositionKind() == IRPosition::IRP_RETURNED ||
1097       IRP.getPositionKind() == IRPosition::IRP_CALL_SITE_RETURNED)
1098     return nullptr;
1099   return &IRP.getAssociatedValue();
1100 }
1101 
1102 bool Attributor::getAssumedSimplifiedValues(
1103     const IRPosition &IRP, const AbstractAttribute *AA,
1104     SmallVectorImpl<AA::ValueAndContext> &Values, AA::ValueScope S,
1105     bool &UsedAssumedInformation) {
1106   // First check all callbacks provided by outside AAs. If any of them returns
1107   // a non-null value that is different from the associated value, or None, we
1108   // assume it's simplified.
1109   const auto &SimplificationCBs = SimplificationCallbacks.lookup(IRP);
1110   for (auto &CB : SimplificationCBs) {
1111     Optional<Value *> CBResult = CB(IRP, AA, UsedAssumedInformation);
1112     if (!CBResult.hasValue())
1113       continue;
1114     Value *V = CBResult.getValue();
1115     if (!V)
1116       return false;
1117     if ((S & AA::ValueScope::Interprocedural) ||
1118         AA::isValidInScope(*V, IRP.getAnchorScope()))
1119       Values.push_back(AA::ValueAndContext{*V, nullptr});
1120     else
1121       return false;
1122   }
1123   if (!SimplificationCBs.empty())
1124     return true;
1125 
1126   // If no high-level/outside simplification occurred, use AAPotentialValues.
1127   const auto &PotentialValuesAA =
1128       getOrCreateAAFor<AAPotentialValues>(IRP, AA, DepClassTy::OPTIONAL);
1129   if (!PotentialValuesAA.getAssumedSimplifiedValues(*this, Values, S))
1130     return false;
1131   UsedAssumedInformation |= !PotentialValuesAA.isAtFixpoint();
1132   return true;
1133 }
1134 
1135 Optional<Value *> Attributor::translateArgumentToCallSiteContent(
1136     Optional<Value *> V, CallBase &CB, const AbstractAttribute &AA,
1137     bool &UsedAssumedInformation) {
1138   if (!V)
1139     return V;
1140   if (*V == nullptr || isa<Constant>(*V))
1141     return V;
1142   if (auto *Arg = dyn_cast<Argument>(*V))
1143     if (CB.getCalledFunction() == Arg->getParent())
1144       if (!Arg->hasPointeeInMemoryValueAttr())
1145         return getAssumedSimplified(
1146             IRPosition::callsite_argument(CB, Arg->getArgNo()), AA,
1147             UsedAssumedInformation, AA::Intraprocedural);
1148   return nullptr;
1149 }
1150 
1151 Attributor::~Attributor() {
1152   // The abstract attributes are allocated via the BumpPtrAllocator Allocator,
1153   // thus we cannot delete them. We can, and want to, destruct them though.
1154   for (auto &DepAA : DG.SyntheticRoot.Deps) {
1155     AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer());
1156     AA->~AbstractAttribute();
1157   }
1158 }
1159 
1160 bool Attributor::isAssumedDead(const AbstractAttribute &AA,
1161                                const AAIsDead *FnLivenessAA,
1162                                bool &UsedAssumedInformation,
1163                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
1164   const IRPosition &IRP = AA.getIRPosition();
1165   if (!Functions.count(IRP.getAnchorScope()))
1166     return false;
1167   return isAssumedDead(IRP, &AA, FnLivenessAA, UsedAssumedInformation,
1168                        CheckBBLivenessOnly, DepClass);
1169 }
1170 
1171 bool Attributor::isAssumedDead(const Use &U,
1172                                const AbstractAttribute *QueryingAA,
1173                                const AAIsDead *FnLivenessAA,
1174                                bool &UsedAssumedInformation,
1175                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
1176   Instruction *UserI = dyn_cast<Instruction>(U.getUser());
1177   if (!UserI)
1178     return isAssumedDead(IRPosition::value(*U.get()), QueryingAA, FnLivenessAA,
1179                          UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1180 
1181   if (auto *CB = dyn_cast<CallBase>(UserI)) {
1182     // For call site argument uses we can check if the argument is
1183     // unused/dead.
1184     if (CB->isArgOperand(&U)) {
1185       const IRPosition &CSArgPos =
1186           IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U));
1187       return isAssumedDead(CSArgPos, QueryingAA, FnLivenessAA,
1188                            UsedAssumedInformation, CheckBBLivenessOnly,
1189                            DepClass);
1190     }
1191   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) {
1192     const IRPosition &RetPos = IRPosition::returned(*RI->getFunction());
1193     return isAssumedDead(RetPos, QueryingAA, FnLivenessAA,
1194                          UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1195   } else if (PHINode *PHI = dyn_cast<PHINode>(UserI)) {
1196     BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
1197     return isAssumedDead(*IncomingBB->getTerminator(), QueryingAA, FnLivenessAA,
1198                          UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1199   } else if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
1200     if (!CheckBBLivenessOnly && SI->getPointerOperand() != U.get()) {
1201       const IRPosition IRP = IRPosition::inst(*SI);
1202       const AAIsDead &IsDeadAA =
1203           getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClassTy::NONE);
1204       if (IsDeadAA.isRemovableStore()) {
1205         if (QueryingAA)
1206           recordDependence(IsDeadAA, *QueryingAA, DepClass);
1207         if (!IsDeadAA.isKnown(AAIsDead::IS_REMOVABLE))
1208           UsedAssumedInformation = true;
1209         return true;
1210       }
1211     }
1212   }
1213 
1214   return isAssumedDead(IRPosition::inst(*UserI), QueryingAA, FnLivenessAA,
1215                        UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1216 }
1217 
1218 bool Attributor::isAssumedDead(const Instruction &I,
1219                                const AbstractAttribute *QueryingAA,
1220                                const AAIsDead *FnLivenessAA,
1221                                bool &UsedAssumedInformation,
1222                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
1223   const IRPosition::CallBaseContext *CBCtx =
1224       QueryingAA ? QueryingAA->getCallBaseContext() : nullptr;
1225 
1226   if (ManifestAddedBlocks.contains(I.getParent()))
1227     return false;
1228 
1229   if (!FnLivenessAA)
1230     FnLivenessAA =
1231         lookupAAFor<AAIsDead>(IRPosition::function(*I.getFunction(), CBCtx),
1232                               QueryingAA, DepClassTy::NONE);
1233 
1234   // If we have a context instruction and a liveness AA we use it.
1235   if (FnLivenessAA &&
1236       FnLivenessAA->getIRPosition().getAnchorScope() == I.getFunction() &&
1237       (CheckBBLivenessOnly ? FnLivenessAA->isAssumedDead(I.getParent())
1238                            : FnLivenessAA->isAssumedDead(&I))) {
1239     if (QueryingAA)
1240       recordDependence(*FnLivenessAA, *QueryingAA, DepClass);
1241     if (!FnLivenessAA->isKnownDead(&I))
1242       UsedAssumedInformation = true;
1243     return true;
1244   }
1245 
1246   if (CheckBBLivenessOnly)
1247     return false;
1248 
1249   const IRPosition IRP = IRPosition::inst(I, CBCtx);
1250   const AAIsDead &IsDeadAA =
1251       getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClassTy::NONE);
1252   // Don't check liveness for AAIsDead.
1253   if (QueryingAA == &IsDeadAA)
1254     return false;
1255 
1256   if (IsDeadAA.isAssumedDead()) {
1257     if (QueryingAA)
1258       recordDependence(IsDeadAA, *QueryingAA, DepClass);
1259     if (!IsDeadAA.isKnownDead())
1260       UsedAssumedInformation = true;
1261     return true;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 bool Attributor::isAssumedDead(const IRPosition &IRP,
1268                                const AbstractAttribute *QueryingAA,
1269                                const AAIsDead *FnLivenessAA,
1270                                bool &UsedAssumedInformation,
1271                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
1272   Instruction *CtxI = IRP.getCtxI();
1273   if (CtxI &&
1274       isAssumedDead(*CtxI, QueryingAA, FnLivenessAA, UsedAssumedInformation,
1275                     /* CheckBBLivenessOnly */ true,
1276                     CheckBBLivenessOnly ? DepClass : DepClassTy::OPTIONAL))
1277     return true;
1278 
1279   if (CheckBBLivenessOnly)
1280     return false;
1281 
1282   // If we haven't succeeded we query the specific liveness info for the IRP.
1283   const AAIsDead *IsDeadAA;
1284   if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE)
1285     IsDeadAA = &getOrCreateAAFor<AAIsDead>(
1286         IRPosition::callsite_returned(cast<CallBase>(IRP.getAssociatedValue())),
1287         QueryingAA, DepClassTy::NONE);
1288   else
1289     IsDeadAA = &getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClassTy::NONE);
1290   // Don't check liveness for AAIsDead.
1291   if (QueryingAA == IsDeadAA)
1292     return false;
1293 
1294   if (IsDeadAA->isAssumedDead()) {
1295     if (QueryingAA)
1296       recordDependence(*IsDeadAA, *QueryingAA, DepClass);
1297     if (!IsDeadAA->isKnownDead())
1298       UsedAssumedInformation = true;
1299     return true;
1300   }
1301 
1302   return false;
1303 }
1304 
1305 bool Attributor::isAssumedDead(const BasicBlock &BB,
1306                                const AbstractAttribute *QueryingAA,
1307                                const AAIsDead *FnLivenessAA,
1308                                DepClassTy DepClass) {
1309   if (!FnLivenessAA)
1310     FnLivenessAA = lookupAAFor<AAIsDead>(IRPosition::function(*BB.getParent()),
1311                                          QueryingAA, DepClassTy::NONE);
1312   if (FnLivenessAA->isAssumedDead(&BB)) {
1313     if (QueryingAA)
1314       recordDependence(*FnLivenessAA, *QueryingAA, DepClass);
1315     return true;
1316   }
1317 
1318   return false;
1319 }
1320 
1321 bool Attributor::checkForAllUses(
1322     function_ref<bool(const Use &, bool &)> Pred,
1323     const AbstractAttribute &QueryingAA, const Value &V,
1324     bool CheckBBLivenessOnly, DepClassTy LivenessDepClass,
1325     bool IgnoreDroppableUses,
1326     function_ref<bool(const Use &OldU, const Use &NewU)> EquivalentUseCB) {
1327 
1328   // Check the trivial case first as it catches void values.
1329   if (V.use_empty())
1330     return true;
1331 
1332   const IRPosition &IRP = QueryingAA.getIRPosition();
1333   SmallVector<const Use *, 16> Worklist;
1334   SmallPtrSet<const Use *, 16> Visited;
1335 
1336   for (const Use &U : V.uses())
1337     Worklist.push_back(&U);
1338 
1339   LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size()
1340                     << " initial uses to check\n");
1341 
1342   const Function *ScopeFn = IRP.getAnchorScope();
1343   const auto *LivenessAA =
1344       ScopeFn ? &getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*ScopeFn),
1345                                     DepClassTy::NONE)
1346               : nullptr;
1347 
1348   while (!Worklist.empty()) {
1349     const Use *U = Worklist.pop_back_val();
1350     if (isa<PHINode>(U->getUser()) && !Visited.insert(U).second)
1351       continue;
1352     LLVM_DEBUG({
1353       if (auto *Fn = dyn_cast<Function>(U->getUser()))
1354         dbgs() << "[Attributor] Check use: " << **U << " in " << Fn->getName()
1355                << "\n";
1356       else
1357         dbgs() << "[Attributor] Check use: " << **U << " in " << *U->getUser()
1358                << "\n";
1359     });
1360     bool UsedAssumedInformation = false;
1361     if (isAssumedDead(*U, &QueryingAA, LivenessAA, UsedAssumedInformation,
1362                       CheckBBLivenessOnly, LivenessDepClass)) {
1363       LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n");
1364       continue;
1365     }
1366     if (IgnoreDroppableUses && U->getUser()->isDroppable()) {
1367       LLVM_DEBUG(dbgs() << "[Attributor] Droppable user, skip!\n");
1368       continue;
1369     }
1370 
1371     if (auto *SI = dyn_cast<StoreInst>(U->getUser())) {
1372       if (&SI->getOperandUse(0) == U) {
1373         if (!Visited.insert(U).second)
1374           continue;
1375         SmallSetVector<Value *, 4> PotentialCopies;
1376         if (AA::getPotentialCopiesOfStoredValue(
1377                 *this, *SI, PotentialCopies, QueryingAA, UsedAssumedInformation,
1378                 /* OnlyExact */ true)) {
1379           LLVM_DEBUG(dbgs() << "[Attributor] Value is stored, continue with "
1380                             << PotentialCopies.size()
1381                             << " potential copies instead!\n");
1382           for (Value *PotentialCopy : PotentialCopies)
1383             for (const Use &CopyUse : PotentialCopy->uses()) {
1384               if (EquivalentUseCB && !EquivalentUseCB(*U, CopyUse)) {
1385                 LLVM_DEBUG(dbgs() << "[Attributor] Potential copy was "
1386                                      "rejected by the equivalence call back: "
1387                                   << *CopyUse << "!\n");
1388                 return false;
1389               }
1390               Worklist.push_back(&CopyUse);
1391             }
1392           continue;
1393         }
1394       }
1395     }
1396 
1397     bool Follow = false;
1398     if (!Pred(*U, Follow))
1399       return false;
1400     if (!Follow)
1401       continue;
1402     for (const Use &UU : U->getUser()->uses())
1403       Worklist.push_back(&UU);
1404   }
1405 
1406   return true;
1407 }
1408 
1409 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
1410                                       const AbstractAttribute &QueryingAA,
1411                                       bool RequireAllCallSites,
1412                                       bool &UsedAssumedInformation) {
1413   // We can try to determine information from
1414   // the call sites. However, this is only possible all call sites are known,
1415   // hence the function has internal linkage.
1416   const IRPosition &IRP = QueryingAA.getIRPosition();
1417   const Function *AssociatedFunction = IRP.getAssociatedFunction();
1418   if (!AssociatedFunction) {
1419     LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP
1420                       << "\n");
1421     return false;
1422   }
1423 
1424   return checkForAllCallSites(Pred, *AssociatedFunction, RequireAllCallSites,
1425                               &QueryingAA, UsedAssumedInformation);
1426 }
1427 
1428 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
1429                                       const Function &Fn,
1430                                       bool RequireAllCallSites,
1431                                       const AbstractAttribute *QueryingAA,
1432                                       bool &UsedAssumedInformation) {
1433   if (RequireAllCallSites && !Fn.hasLocalLinkage()) {
1434     LLVM_DEBUG(
1435         dbgs()
1436         << "[Attributor] Function " << Fn.getName()
1437         << " has no internal linkage, hence not all call sites are known\n");
1438     return false;
1439   }
1440 
1441   SmallVector<const Use *, 8> Uses(make_pointer_range(Fn.uses()));
1442   for (unsigned u = 0; u < Uses.size(); ++u) {
1443     const Use &U = *Uses[u];
1444     LLVM_DEBUG({
1445       if (auto *Fn = dyn_cast<Function>(U))
1446         dbgs() << "[Attributor] Check use: " << Fn->getName() << " in "
1447                << *U.getUser() << "\n";
1448       else
1449         dbgs() << "[Attributor] Check use: " << *U << " in " << *U.getUser()
1450                << "\n";
1451     });
1452     if (isAssumedDead(U, QueryingAA, nullptr, UsedAssumedInformation,
1453                       /* CheckBBLivenessOnly */ true)) {
1454       LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n");
1455       continue;
1456     }
1457     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) {
1458       if (CE->isCast() && CE->getType()->isPointerTy()) {
1459         LLVM_DEBUG(
1460             dbgs() << "[Attributor] Use, is constant cast expression, add "
1461                    << CE->getNumUses()
1462                    << " uses of that expression instead!\n");
1463         for (const Use &CEU : CE->uses())
1464           Uses.push_back(&CEU);
1465         continue;
1466       }
1467     }
1468 
1469     AbstractCallSite ACS(&U);
1470     if (!ACS) {
1471       LLVM_DEBUG(dbgs() << "[Attributor] Function " << Fn.getName()
1472                         << " has non call site use " << *U.get() << " in "
1473                         << *U.getUser() << "\n");
1474       // BlockAddress users are allowed.
1475       if (isa<BlockAddress>(U.getUser()))
1476         continue;
1477       return false;
1478     }
1479 
1480     const Use *EffectiveUse =
1481         ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U;
1482     if (!ACS.isCallee(EffectiveUse)) {
1483       if (!RequireAllCallSites) {
1484         LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
1485                           << " is not a call of " << Fn.getName()
1486                           << ", skip use\n");
1487         continue;
1488       }
1489       LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
1490                         << " is an invalid use of " << Fn.getName() << "\n");
1491       return false;
1492     }
1493 
1494     // Make sure the arguments that can be matched between the call site and the
1495     // callee argee on their type. It is unlikely they do not and it doesn't
1496     // make sense for all attributes to know/care about this.
1497     assert(&Fn == ACS.getCalledFunction() && "Expected known callee");
1498     unsigned MinArgsParams =
1499         std::min(size_t(ACS.getNumArgOperands()), Fn.arg_size());
1500     for (unsigned u = 0; u < MinArgsParams; ++u) {
1501       Value *CSArgOp = ACS.getCallArgOperand(u);
1502       if (CSArgOp && Fn.getArg(u)->getType() != CSArgOp->getType()) {
1503         LLVM_DEBUG(
1504             dbgs() << "[Attributor] Call site / callee argument type mismatch ["
1505                    << u << "@" << Fn.getName() << ": "
1506                    << *Fn.getArg(u)->getType() << " vs. "
1507                    << *ACS.getCallArgOperand(u)->getType() << "\n");
1508         return false;
1509       }
1510     }
1511 
1512     if (Pred(ACS))
1513       continue;
1514 
1515     LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for "
1516                       << *ACS.getInstruction() << "\n");
1517     return false;
1518   }
1519 
1520   return true;
1521 }
1522 
1523 bool Attributor::shouldPropagateCallBaseContext(const IRPosition &IRP) {
1524   // TODO: Maintain a cache of Values that are
1525   // on the pathway from a Argument to a Instruction that would effect the
1526   // liveness/return state etc.
1527   return EnableCallSiteSpecific;
1528 }
1529 
1530 bool Attributor::checkForAllReturnedValuesAndReturnInsts(
1531     function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred,
1532     const AbstractAttribute &QueryingAA) {
1533 
1534   const IRPosition &IRP = QueryingAA.getIRPosition();
1535   // Since we need to provide return instructions we have to have an exact
1536   // definition.
1537   const Function *AssociatedFunction = IRP.getAssociatedFunction();
1538   if (!AssociatedFunction)
1539     return false;
1540 
1541   // If this is a call site query we use the call site specific return values
1542   // and liveness information.
1543   // TODO: use the function scope once we have call site AAReturnedValues.
1544   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
1545   const auto &AARetVal =
1546       getAAFor<AAReturnedValues>(QueryingAA, QueryIRP, DepClassTy::REQUIRED);
1547   if (!AARetVal.getState().isValidState())
1548     return false;
1549 
1550   return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred);
1551 }
1552 
1553 bool Attributor::checkForAllReturnedValues(
1554     function_ref<bool(Value &)> Pred, const AbstractAttribute &QueryingAA) {
1555 
1556   const IRPosition &IRP = QueryingAA.getIRPosition();
1557   const Function *AssociatedFunction = IRP.getAssociatedFunction();
1558   if (!AssociatedFunction)
1559     return false;
1560 
1561   // TODO: use the function scope once we have call site AAReturnedValues.
1562   const IRPosition &QueryIRP = IRPosition::function(
1563       *AssociatedFunction, QueryingAA.getCallBaseContext());
1564   const auto &AARetVal =
1565       getAAFor<AAReturnedValues>(QueryingAA, QueryIRP, DepClassTy::REQUIRED);
1566   if (!AARetVal.getState().isValidState())
1567     return false;
1568 
1569   return AARetVal.checkForAllReturnedValuesAndReturnInsts(
1570       [&](Value &RV, const SmallSetVector<ReturnInst *, 4> &) {
1571         return Pred(RV);
1572       });
1573 }
1574 
1575 static bool checkForAllInstructionsImpl(
1576     Attributor *A, InformationCache::OpcodeInstMapTy &OpcodeInstMap,
1577     function_ref<bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA,
1578     const AAIsDead *LivenessAA, const ArrayRef<unsigned> &Opcodes,
1579     bool &UsedAssumedInformation, bool CheckBBLivenessOnly = false,
1580     bool CheckPotentiallyDead = false) {
1581   for (unsigned Opcode : Opcodes) {
1582     // Check if we have instructions with this opcode at all first.
1583     auto *Insts = OpcodeInstMap.lookup(Opcode);
1584     if (!Insts)
1585       continue;
1586 
1587     for (Instruction *I : *Insts) {
1588       // Skip dead instructions.
1589       if (A && !CheckPotentiallyDead &&
1590           A->isAssumedDead(IRPosition::inst(*I), QueryingAA, LivenessAA,
1591                            UsedAssumedInformation, CheckBBLivenessOnly)) {
1592         LLVM_DEBUG(dbgs() << "[Attributor] Instruction " << *I
1593                           << " is potentially dead, skip!\n";);
1594         continue;
1595       }
1596 
1597       if (!Pred(*I))
1598         return false;
1599     }
1600   }
1601   return true;
1602 }
1603 
1604 bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred,
1605                                          const Function *Fn,
1606                                          const AbstractAttribute &QueryingAA,
1607                                          const ArrayRef<unsigned> &Opcodes,
1608                                          bool &UsedAssumedInformation,
1609                                          bool CheckBBLivenessOnly,
1610                                          bool CheckPotentiallyDead) {
1611   // Since we need to provide instructions we have to have an exact definition.
1612   if (!Fn || Fn->isDeclaration())
1613     return false;
1614 
1615   // TODO: use the function scope once we have call site AAReturnedValues.
1616   const IRPosition &QueryIRP = IRPosition::function(*Fn);
1617   const auto *LivenessAA =
1618       (CheckBBLivenessOnly || CheckPotentiallyDead)
1619           ? nullptr
1620           : &(getAAFor<AAIsDead>(QueryingAA, QueryIRP, DepClassTy::NONE));
1621 
1622   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
1623   if (!checkForAllInstructionsImpl(this, OpcodeInstMap, Pred, &QueryingAA,
1624                                    LivenessAA, Opcodes, UsedAssumedInformation,
1625                                    CheckBBLivenessOnly, CheckPotentiallyDead))
1626     return false;
1627 
1628   return true;
1629 }
1630 
1631 bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred,
1632                                          const AbstractAttribute &QueryingAA,
1633                                          const ArrayRef<unsigned> &Opcodes,
1634                                          bool &UsedAssumedInformation,
1635                                          bool CheckBBLivenessOnly,
1636                                          bool CheckPotentiallyDead) {
1637   const IRPosition &IRP = QueryingAA.getIRPosition();
1638   const Function *AssociatedFunction = IRP.getAssociatedFunction();
1639   return checkForAllInstructions(Pred, AssociatedFunction, QueryingAA, Opcodes,
1640                                  UsedAssumedInformation, CheckBBLivenessOnly,
1641                                  CheckPotentiallyDead);
1642 }
1643 
1644 bool Attributor::checkForAllReadWriteInstructions(
1645     function_ref<bool(Instruction &)> Pred, AbstractAttribute &QueryingAA,
1646     bool &UsedAssumedInformation) {
1647 
1648   const Function *AssociatedFunction =
1649       QueryingAA.getIRPosition().getAssociatedFunction();
1650   if (!AssociatedFunction)
1651     return false;
1652 
1653   // TODO: use the function scope once we have call site AAReturnedValues.
1654   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
1655   const auto &LivenessAA =
1656       getAAFor<AAIsDead>(QueryingAA, QueryIRP, DepClassTy::NONE);
1657 
1658   for (Instruction *I :
1659        InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) {
1660     // Skip dead instructions.
1661     if (isAssumedDead(IRPosition::inst(*I), &QueryingAA, &LivenessAA,
1662                       UsedAssumedInformation))
1663       continue;
1664 
1665     if (!Pred(*I))
1666       return false;
1667   }
1668 
1669   return true;
1670 }
1671 
1672 void Attributor::runTillFixpoint() {
1673   TimeTraceScope TimeScope("Attributor::runTillFixpoint");
1674   LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
1675                     << DG.SyntheticRoot.Deps.size()
1676                     << " abstract attributes.\n");
1677 
1678   // Now that all abstract attributes are collected and initialized we start
1679   // the abstract analysis.
1680 
1681   unsigned IterationCounter = 1;
1682   unsigned MaxIterations =
1683       Configuration.MaxFixpointIterations.value_or(SetFixpointIterations);
1684 
1685   SmallVector<AbstractAttribute *, 32> ChangedAAs;
1686   SetVector<AbstractAttribute *> Worklist, InvalidAAs;
1687   Worklist.insert(DG.SyntheticRoot.begin(), DG.SyntheticRoot.end());
1688 
1689   do {
1690     // Remember the size to determine new attributes.
1691     size_t NumAAs = DG.SyntheticRoot.Deps.size();
1692     LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
1693                       << ", Worklist size: " << Worklist.size() << "\n");
1694 
1695     // For invalid AAs we can fix dependent AAs that have a required dependence,
1696     // thereby folding long dependence chains in a single step without the need
1697     // to run updates.
1698     for (unsigned u = 0; u < InvalidAAs.size(); ++u) {
1699       AbstractAttribute *InvalidAA = InvalidAAs[u];
1700 
1701       // Check the dependences to fast track invalidation.
1702       LLVM_DEBUG(dbgs() << "[Attributor] InvalidAA: " << *InvalidAA << " has "
1703                         << InvalidAA->Deps.size()
1704                         << " required & optional dependences\n");
1705       while (!InvalidAA->Deps.empty()) {
1706         const auto &Dep = InvalidAA->Deps.back();
1707         InvalidAA->Deps.pop_back();
1708         AbstractAttribute *DepAA = cast<AbstractAttribute>(Dep.getPointer());
1709         if (Dep.getInt() == unsigned(DepClassTy::OPTIONAL)) {
1710           LLVM_DEBUG(dbgs() << " - recompute: " << *DepAA);
1711           Worklist.insert(DepAA);
1712           continue;
1713         }
1714         LLVM_DEBUG(dbgs() << " - invalidate: " << *DepAA);
1715         DepAA->getState().indicatePessimisticFixpoint();
1716         assert(DepAA->getState().isAtFixpoint() && "Expected fixpoint state!");
1717         if (!DepAA->getState().isValidState())
1718           InvalidAAs.insert(DepAA);
1719         else
1720           ChangedAAs.push_back(DepAA);
1721       }
1722     }
1723 
1724     // Add all abstract attributes that are potentially dependent on one that
1725     // changed to the work list.
1726     for (AbstractAttribute *ChangedAA : ChangedAAs)
1727       while (!ChangedAA->Deps.empty()) {
1728         Worklist.insert(
1729             cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer()));
1730         ChangedAA->Deps.pop_back();
1731       }
1732 
1733     LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter
1734                       << ", Worklist+Dependent size: " << Worklist.size()
1735                       << "\n");
1736 
1737     // Reset the changed and invalid set.
1738     ChangedAAs.clear();
1739     InvalidAAs.clear();
1740 
1741     // Update all abstract attribute in the work list and record the ones that
1742     // changed.
1743     for (AbstractAttribute *AA : Worklist) {
1744       const auto &AAState = AA->getState();
1745       if (!AAState.isAtFixpoint())
1746         if (updateAA(*AA) == ChangeStatus::CHANGED)
1747           ChangedAAs.push_back(AA);
1748 
1749       // Use the InvalidAAs vector to propagate invalid states fast transitively
1750       // without requiring updates.
1751       if (!AAState.isValidState())
1752         InvalidAAs.insert(AA);
1753     }
1754 
1755     // Add attributes to the changed set if they have been created in the last
1756     // iteration.
1757     ChangedAAs.append(DG.SyntheticRoot.begin() + NumAAs,
1758                       DG.SyntheticRoot.end());
1759 
1760     // Reset the work list and repopulate with the changed abstract attributes.
1761     // Note that dependent ones are added above.
1762     Worklist.clear();
1763     Worklist.insert(ChangedAAs.begin(), ChangedAAs.end());
1764     Worklist.insert(QueryAAsAwaitingUpdate.begin(),
1765                     QueryAAsAwaitingUpdate.end());
1766     QueryAAsAwaitingUpdate.clear();
1767 
1768   } while (!Worklist.empty() &&
1769            (IterationCounter++ < MaxIterations || VerifyMaxFixpointIterations));
1770 
1771   if (IterationCounter > MaxIterations && !Functions.empty()) {
1772     auto Remark = [&](OptimizationRemarkMissed ORM) {
1773       return ORM << "Attributor did not reach a fixpoint after "
1774                  << ore::NV("Iterations", MaxIterations) << " iterations.";
1775     };
1776     Function *F = Functions.front();
1777     emitRemark<OptimizationRemarkMissed>(F, "FixedPoint", Remark);
1778   }
1779 
1780   LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
1781                     << IterationCounter << "/" << MaxIterations
1782                     << " iterations\n");
1783 
1784   // Reset abstract arguments not settled in a sound fixpoint by now. This
1785   // happens when we stopped the fixpoint iteration early. Note that only the
1786   // ones marked as "changed" *and* the ones transitively depending on them
1787   // need to be reverted to a pessimistic state. Others might not be in a
1788   // fixpoint state but we can use the optimistic results for them anyway.
1789   SmallPtrSet<AbstractAttribute *, 32> Visited;
1790   for (unsigned u = 0; u < ChangedAAs.size(); u++) {
1791     AbstractAttribute *ChangedAA = ChangedAAs[u];
1792     if (!Visited.insert(ChangedAA).second)
1793       continue;
1794 
1795     AbstractState &State = ChangedAA->getState();
1796     if (!State.isAtFixpoint()) {
1797       State.indicatePessimisticFixpoint();
1798 
1799       NumAttributesTimedOut++;
1800     }
1801 
1802     while (!ChangedAA->Deps.empty()) {
1803       ChangedAAs.push_back(
1804           cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer()));
1805       ChangedAA->Deps.pop_back();
1806     }
1807   }
1808 
1809   LLVM_DEBUG({
1810     if (!Visited.empty())
1811       dbgs() << "\n[Attributor] Finalized " << Visited.size()
1812              << " abstract attributes.\n";
1813   });
1814 
1815   if (VerifyMaxFixpointIterations && IterationCounter != MaxIterations) {
1816     errs() << "\n[Attributor] Fixpoint iteration done after: "
1817            << IterationCounter << "/" << MaxIterations << " iterations\n";
1818     llvm_unreachable("The fixpoint was not reached with exactly the number of "
1819                      "specified iterations!");
1820   }
1821 }
1822 
1823 void Attributor::registerForUpdate(AbstractAttribute &AA) {
1824   assert(AA.isQueryAA() &&
1825          "Non-query AAs should not be required to register for updates!");
1826   QueryAAsAwaitingUpdate.insert(&AA);
1827 }
1828 
1829 ChangeStatus Attributor::manifestAttributes() {
1830   TimeTraceScope TimeScope("Attributor::manifestAttributes");
1831   size_t NumFinalAAs = DG.SyntheticRoot.Deps.size();
1832 
1833   unsigned NumManifested = 0;
1834   unsigned NumAtFixpoint = 0;
1835   ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
1836   for (auto &DepAA : DG.SyntheticRoot.Deps) {
1837     AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer());
1838     AbstractState &State = AA->getState();
1839 
1840     // If there is not already a fixpoint reached, we can now take the
1841     // optimistic state. This is correct because we enforced a pessimistic one
1842     // on abstract attributes that were transitively dependent on a changed one
1843     // already above.
1844     if (!State.isAtFixpoint())
1845       State.indicateOptimisticFixpoint();
1846 
1847     // We must not manifest Attributes that use Callbase info.
1848     if (AA->hasCallBaseContext())
1849       continue;
1850     // If the state is invalid, we do not try to manifest it.
1851     if (!State.isValidState())
1852       continue;
1853 
1854     if (AA->getCtxI() && !isRunOn(*AA->getAnchorScope()))
1855       continue;
1856 
1857     // Skip dead code.
1858     bool UsedAssumedInformation = false;
1859     if (isAssumedDead(*AA, nullptr, UsedAssumedInformation,
1860                       /* CheckBBLivenessOnly */ true))
1861       continue;
1862     // Check if the manifest debug counter that allows skipping manifestation of
1863     // AAs
1864     if (!DebugCounter::shouldExecute(ManifestDBGCounter))
1865       continue;
1866     // Manifest the state and record if we changed the IR.
1867     ChangeStatus LocalChange = AA->manifest(*this);
1868     if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled())
1869       AA->trackStatistics();
1870     LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA
1871                       << "\n");
1872 
1873     ManifestChange = ManifestChange | LocalChange;
1874 
1875     NumAtFixpoint++;
1876     NumManifested += (LocalChange == ChangeStatus::CHANGED);
1877   }
1878 
1879   (void)NumManifested;
1880   (void)NumAtFixpoint;
1881   LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
1882                     << " arguments while " << NumAtFixpoint
1883                     << " were in a valid fixpoint state\n");
1884 
1885   NumAttributesManifested += NumManifested;
1886   NumAttributesValidFixpoint += NumAtFixpoint;
1887 
1888   (void)NumFinalAAs;
1889   if (NumFinalAAs != DG.SyntheticRoot.Deps.size()) {
1890     for (unsigned u = NumFinalAAs; u < DG.SyntheticRoot.Deps.size(); ++u)
1891       errs() << "Unexpected abstract attribute: "
1892              << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer())
1893              << " :: "
1894              << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer())
1895                     ->getIRPosition()
1896                     .getAssociatedValue()
1897              << "\n";
1898     llvm_unreachable("Expected the final number of abstract attributes to "
1899                      "remain unchanged!");
1900   }
1901   return ManifestChange;
1902 }
1903 
1904 void Attributor::identifyDeadInternalFunctions() {
1905   // Early exit if we don't intend to delete functions.
1906   if (!Configuration.DeleteFns)
1907     return;
1908 
1909   // Identify dead internal functions and delete them. This happens outside
1910   // the other fixpoint analysis as we might treat potentially dead functions
1911   // as live to lower the number of iterations. If they happen to be dead, the
1912   // below fixpoint loop will identify and eliminate them.
1913   SmallVector<Function *, 8> InternalFns;
1914   for (Function *F : Functions)
1915     if (F->hasLocalLinkage())
1916       InternalFns.push_back(F);
1917 
1918   SmallPtrSet<Function *, 8> LiveInternalFns;
1919   bool FoundLiveInternal = true;
1920   while (FoundLiveInternal) {
1921     FoundLiveInternal = false;
1922     for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) {
1923       Function *F = InternalFns[u];
1924       if (!F)
1925         continue;
1926 
1927       bool UsedAssumedInformation = false;
1928       if (checkForAllCallSites(
1929               [&](AbstractCallSite ACS) {
1930                 Function *Callee = ACS.getInstruction()->getFunction();
1931                 return ToBeDeletedFunctions.count(Callee) ||
1932                        (Functions.count(Callee) && Callee->hasLocalLinkage() &&
1933                         !LiveInternalFns.count(Callee));
1934               },
1935               *F, true, nullptr, UsedAssumedInformation)) {
1936         continue;
1937       }
1938 
1939       LiveInternalFns.insert(F);
1940       InternalFns[u] = nullptr;
1941       FoundLiveInternal = true;
1942     }
1943   }
1944 
1945   for (unsigned u = 0, e = InternalFns.size(); u < e; ++u)
1946     if (Function *F = InternalFns[u])
1947       ToBeDeletedFunctions.insert(F);
1948 }
1949 
1950 ChangeStatus Attributor::cleanupIR() {
1951   TimeTraceScope TimeScope("Attributor::cleanupIR");
1952   // Delete stuff at the end to avoid invalid references and a nice order.
1953   LLVM_DEBUG(dbgs() << "\n[Attributor] Delete/replace at least "
1954                     << ToBeDeletedFunctions.size() << " functions and "
1955                     << ToBeDeletedBlocks.size() << " blocks and "
1956                     << ToBeDeletedInsts.size() << " instructions and "
1957                     << ToBeChangedValues.size() << " values and "
1958                     << ToBeChangedUses.size() << " uses. To insert "
1959                     << ToBeChangedToUnreachableInsts.size()
1960                     << " unreachables.\n"
1961                     << "Preserve manifest added " << ManifestAddedBlocks.size()
1962                     << " blocks\n");
1963 
1964   SmallVector<WeakTrackingVH, 32> DeadInsts;
1965   SmallVector<Instruction *, 32> TerminatorsToFold;
1966 
1967   auto ReplaceUse = [&](Use *U, Value *NewV) {
1968     Value *OldV = U->get();
1969 
1970     // If we plan to replace NewV we need to update it at this point.
1971     do {
1972       const auto &Entry = ToBeChangedValues.lookup(NewV);
1973       if (!Entry.first)
1974         break;
1975       NewV = Entry.first;
1976     } while (true);
1977 
1978     Instruction *I = dyn_cast<Instruction>(U->getUser());
1979     assert((!I || isRunOn(*I->getFunction())) &&
1980            "Cannot replace an instruction outside the current SCC!");
1981 
1982     // Do not replace uses in returns if the value is a must-tail call we will
1983     // not delete.
1984     if (auto *RI = dyn_cast_or_null<ReturnInst>(I)) {
1985       if (auto *CI = dyn_cast<CallInst>(OldV->stripPointerCasts()))
1986         if (CI->isMustTailCall() && !ToBeDeletedInsts.count(CI))
1987           return;
1988       // If we rewrite a return and the new value is not an argument, strip the
1989       // `returned` attribute as it is wrong now.
1990       if (!isa<Argument>(NewV))
1991         for (auto &Arg : RI->getFunction()->args())
1992           Arg.removeAttr(Attribute::Returned);
1993     }
1994 
1995     // Do not perform call graph altering changes outside the SCC.
1996     if (auto *CB = dyn_cast_or_null<CallBase>(I))
1997       if (CB->isCallee(U))
1998         return;
1999 
2000     LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser()
2001                       << " instead of " << *OldV << "\n");
2002     U->set(NewV);
2003 
2004     if (Instruction *I = dyn_cast<Instruction>(OldV)) {
2005       CGModifiedFunctions.insert(I->getFunction());
2006       if (!isa<PHINode>(I) && !ToBeDeletedInsts.count(I) &&
2007           isInstructionTriviallyDead(I))
2008         DeadInsts.push_back(I);
2009     }
2010     if (isa<UndefValue>(NewV) && isa<CallBase>(U->getUser())) {
2011       auto *CB = cast<CallBase>(U->getUser());
2012       if (CB->isArgOperand(U)) {
2013         unsigned Idx = CB->getArgOperandNo(U);
2014         CB->removeParamAttr(Idx, Attribute::NoUndef);
2015         Function *Fn = CB->getCalledFunction();
2016         if (Fn && Fn->arg_size() > Idx)
2017           Fn->removeParamAttr(Idx, Attribute::NoUndef);
2018       }
2019     }
2020     if (isa<Constant>(NewV) && isa<BranchInst>(U->getUser())) {
2021       Instruction *UserI = cast<Instruction>(U->getUser());
2022       if (isa<UndefValue>(NewV)) {
2023         ToBeChangedToUnreachableInsts.insert(UserI);
2024       } else {
2025         TerminatorsToFold.push_back(UserI);
2026       }
2027     }
2028   };
2029 
2030   for (auto &It : ToBeChangedUses) {
2031     Use *U = It.first;
2032     Value *NewV = It.second;
2033     ReplaceUse(U, NewV);
2034   }
2035 
2036   SmallVector<Use *, 4> Uses;
2037   for (auto &It : ToBeChangedValues) {
2038     Value *OldV = It.first;
2039     auto &Entry = It.second;
2040     Value *NewV = Entry.first;
2041     Uses.clear();
2042     for (auto &U : OldV->uses())
2043       if (Entry.second || !U.getUser()->isDroppable())
2044         Uses.push_back(&U);
2045     for (Use *U : Uses) {
2046       if (auto *I = dyn_cast<Instruction>(U->getUser()))
2047         if (!isRunOn(*I->getFunction()))
2048           continue;
2049       ReplaceUse(U, NewV);
2050     }
2051   }
2052 
2053   for (auto &V : InvokeWithDeadSuccessor)
2054     if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) {
2055       assert(isRunOn(*II->getFunction()) &&
2056              "Cannot replace an invoke outside the current SCC!");
2057       bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind);
2058       bool NormalBBIsDead = II->hasFnAttr(Attribute::NoReturn);
2059       bool Invoke2CallAllowed =
2060           !AAIsDead::mayCatchAsynchronousExceptions(*II->getFunction());
2061       assert((UnwindBBIsDead || NormalBBIsDead) &&
2062              "Invoke does not have dead successors!");
2063       BasicBlock *BB = II->getParent();
2064       BasicBlock *NormalDestBB = II->getNormalDest();
2065       if (UnwindBBIsDead) {
2066         Instruction *NormalNextIP = &NormalDestBB->front();
2067         if (Invoke2CallAllowed) {
2068           changeToCall(II);
2069           NormalNextIP = BB->getTerminator();
2070         }
2071         if (NormalBBIsDead)
2072           ToBeChangedToUnreachableInsts.insert(NormalNextIP);
2073       } else {
2074         assert(NormalBBIsDead && "Broken invariant!");
2075         if (!NormalDestBB->getUniquePredecessor())
2076           NormalDestBB = SplitBlockPredecessors(NormalDestBB, {BB}, ".dead");
2077         ToBeChangedToUnreachableInsts.insert(&NormalDestBB->front());
2078       }
2079     }
2080   for (Instruction *I : TerminatorsToFold) {
2081     assert(isRunOn(*I->getFunction()) &&
2082            "Cannot replace a terminator outside the current SCC!");
2083     CGModifiedFunctions.insert(I->getFunction());
2084     ConstantFoldTerminator(I->getParent());
2085   }
2086   for (auto &V : ToBeChangedToUnreachableInsts)
2087     if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
2088       LLVM_DEBUG(dbgs() << "[Attributor] Change to unreachable: " << *I
2089                         << "\n");
2090       assert(isRunOn(*I->getFunction()) &&
2091              "Cannot replace an instruction outside the current SCC!");
2092       CGModifiedFunctions.insert(I->getFunction());
2093       changeToUnreachable(I);
2094     }
2095 
2096   for (auto &V : ToBeDeletedInsts) {
2097     if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
2098       if (auto *CB = dyn_cast<CallBase>(I)) {
2099         assert(isRunOn(*I->getFunction()) &&
2100                "Cannot delete an instruction outside the current SCC!");
2101         if (!isa<IntrinsicInst>(CB))
2102           Configuration.CGUpdater.removeCallSite(*CB);
2103       }
2104       I->dropDroppableUses();
2105       CGModifiedFunctions.insert(I->getFunction());
2106       if (!I->getType()->isVoidTy())
2107         I->replaceAllUsesWith(UndefValue::get(I->getType()));
2108       if (!isa<PHINode>(I) && isInstructionTriviallyDead(I))
2109         DeadInsts.push_back(I);
2110       else
2111         I->eraseFromParent();
2112     }
2113   }
2114 
2115   llvm::erase_if(DeadInsts, [&](WeakTrackingVH I) { return !I; });
2116 
2117   LLVM_DEBUG({
2118     dbgs() << "[Attributor] DeadInsts size: " << DeadInsts.size() << "\n";
2119     for (auto &I : DeadInsts)
2120       if (I)
2121         dbgs() << "  - " << *I << "\n";
2122   });
2123 
2124   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
2125 
2126   if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) {
2127     SmallVector<BasicBlock *, 8> ToBeDeletedBBs;
2128     ToBeDeletedBBs.reserve(NumDeadBlocks);
2129     for (BasicBlock *BB : ToBeDeletedBlocks) {
2130       assert(isRunOn(*BB->getParent()) &&
2131              "Cannot delete a block outside the current SCC!");
2132       CGModifiedFunctions.insert(BB->getParent());
2133       // Do not delete BBs added during manifests of AAs.
2134       if (ManifestAddedBlocks.contains(BB))
2135         continue;
2136       ToBeDeletedBBs.push_back(BB);
2137     }
2138     // Actually we do not delete the blocks but squash them into a single
2139     // unreachable but untangling branches that jump here is something we need
2140     // to do in a more generic way.
2141     detachDeadBlocks(ToBeDeletedBBs, nullptr);
2142   }
2143 
2144   identifyDeadInternalFunctions();
2145 
2146   // Rewrite the functions as requested during manifest.
2147   ChangeStatus ManifestChange = rewriteFunctionSignatures(CGModifiedFunctions);
2148 
2149   for (Function *Fn : CGModifiedFunctions)
2150     if (!ToBeDeletedFunctions.count(Fn) && Functions.count(Fn))
2151       Configuration.CGUpdater.reanalyzeFunction(*Fn);
2152 
2153   for (Function *Fn : ToBeDeletedFunctions) {
2154     if (!Functions.count(Fn))
2155       continue;
2156     Configuration.CGUpdater.removeFunction(*Fn);
2157   }
2158 
2159   if (!ToBeChangedUses.empty())
2160     ManifestChange = ChangeStatus::CHANGED;
2161 
2162   if (!ToBeChangedToUnreachableInsts.empty())
2163     ManifestChange = ChangeStatus::CHANGED;
2164 
2165   if (!ToBeDeletedFunctions.empty())
2166     ManifestChange = ChangeStatus::CHANGED;
2167 
2168   if (!ToBeDeletedBlocks.empty())
2169     ManifestChange = ChangeStatus::CHANGED;
2170 
2171   if (!ToBeDeletedInsts.empty())
2172     ManifestChange = ChangeStatus::CHANGED;
2173 
2174   if (!InvokeWithDeadSuccessor.empty())
2175     ManifestChange = ChangeStatus::CHANGED;
2176 
2177   if (!DeadInsts.empty())
2178     ManifestChange = ChangeStatus::CHANGED;
2179 
2180   NumFnDeleted += ToBeDeletedFunctions.size();
2181 
2182   LLVM_DEBUG(dbgs() << "[Attributor] Deleted " << ToBeDeletedFunctions.size()
2183                     << " functions after manifest.\n");
2184 
2185 #ifdef EXPENSIVE_CHECKS
2186   for (Function *F : Functions) {
2187     if (ToBeDeletedFunctions.count(F))
2188       continue;
2189     assert(!verifyFunction(*F, &errs()) && "Module verification failed!");
2190   }
2191 #endif
2192 
2193   return ManifestChange;
2194 }
2195 
2196 ChangeStatus Attributor::run() {
2197   TimeTraceScope TimeScope("Attributor::run");
2198   AttributorCallGraph ACallGraph(*this);
2199 
2200   if (PrintCallGraph)
2201     ACallGraph.populateAll();
2202 
2203   Phase = AttributorPhase::UPDATE;
2204   runTillFixpoint();
2205 
2206   // dump graphs on demand
2207   if (DumpDepGraph)
2208     DG.dumpGraph();
2209 
2210   if (ViewDepGraph)
2211     DG.viewGraph();
2212 
2213   if (PrintDependencies)
2214     DG.print();
2215 
2216   Phase = AttributorPhase::MANIFEST;
2217   ChangeStatus ManifestChange = manifestAttributes();
2218 
2219   Phase = AttributorPhase::CLEANUP;
2220   ChangeStatus CleanupChange = cleanupIR();
2221 
2222   if (PrintCallGraph)
2223     ACallGraph.print();
2224 
2225   return ManifestChange | CleanupChange;
2226 }
2227 
2228 ChangeStatus Attributor::updateAA(AbstractAttribute &AA) {
2229   TimeTraceScope TimeScope(
2230       AA.getName() + std::to_string(AA.getIRPosition().getPositionKind()) +
2231       "::updateAA");
2232   assert(Phase == AttributorPhase::UPDATE &&
2233          "We can update AA only in the update stage!");
2234 
2235   // Use a new dependence vector for this update.
2236   DependenceVector DV;
2237   DependenceStack.push_back(&DV);
2238 
2239   auto &AAState = AA.getState();
2240   ChangeStatus CS = ChangeStatus::UNCHANGED;
2241   bool UsedAssumedInformation = false;
2242   if (!isAssumedDead(AA, nullptr, UsedAssumedInformation,
2243                      /* CheckBBLivenessOnly */ true))
2244     CS = AA.update(*this);
2245 
2246   if (!AA.isQueryAA() && DV.empty()) {
2247     // If the attribute did not query any non-fix information, the state
2248     // will not change and we can indicate that right away.
2249     AAState.indicateOptimisticFixpoint();
2250   }
2251 
2252   if (!AAState.isAtFixpoint())
2253     rememberDependences();
2254 
2255   // Verify the stack was used properly, that is we pop the dependence vector we
2256   // put there earlier.
2257   DependenceVector *PoppedDV = DependenceStack.pop_back_val();
2258   (void)PoppedDV;
2259   assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!");
2260 
2261   return CS;
2262 }
2263 
2264 void Attributor::createShallowWrapper(Function &F) {
2265   assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!");
2266 
2267   Module &M = *F.getParent();
2268   LLVMContext &Ctx = M.getContext();
2269   FunctionType *FnTy = F.getFunctionType();
2270 
2271   Function *Wrapper =
2272       Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(), F.getName());
2273   F.setName(""); // set the inside function anonymous
2274   M.getFunctionList().insert(F.getIterator(), Wrapper);
2275 
2276   F.setLinkage(GlobalValue::InternalLinkage);
2277 
2278   F.replaceAllUsesWith(Wrapper);
2279   assert(F.use_empty() && "Uses remained after wrapper was created!");
2280 
2281   // Move the COMDAT section to the wrapper.
2282   // TODO: Check if we need to keep it for F as well.
2283   Wrapper->setComdat(F.getComdat());
2284   F.setComdat(nullptr);
2285 
2286   // Copy all metadata and attributes but keep them on F as well.
2287   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
2288   F.getAllMetadata(MDs);
2289   for (auto MDIt : MDs)
2290     Wrapper->addMetadata(MDIt.first, *MDIt.second);
2291   Wrapper->setAttributes(F.getAttributes());
2292 
2293   // Create the call in the wrapper.
2294   BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Wrapper);
2295 
2296   SmallVector<Value *, 8> Args;
2297   Argument *FArgIt = F.arg_begin();
2298   for (Argument &Arg : Wrapper->args()) {
2299     Args.push_back(&Arg);
2300     Arg.setName((FArgIt++)->getName());
2301   }
2302 
2303   CallInst *CI = CallInst::Create(&F, Args, "", EntryBB);
2304   CI->setTailCall(true);
2305   CI->addFnAttr(Attribute::NoInline);
2306   ReturnInst::Create(Ctx, CI->getType()->isVoidTy() ? nullptr : CI, EntryBB);
2307 
2308   NumFnShallowWrappersCreated++;
2309 }
2310 
2311 bool Attributor::isInternalizable(Function &F) {
2312   if (F.isDeclaration() || F.hasLocalLinkage() ||
2313       GlobalValue::isInterposableLinkage(F.getLinkage()))
2314     return false;
2315   return true;
2316 }
2317 
2318 Function *Attributor::internalizeFunction(Function &F, bool Force) {
2319   if (!AllowDeepWrapper && !Force)
2320     return nullptr;
2321   if (!isInternalizable(F))
2322     return nullptr;
2323 
2324   SmallPtrSet<Function *, 2> FnSet = {&F};
2325   DenseMap<Function *, Function *> InternalizedFns;
2326   internalizeFunctions(FnSet, InternalizedFns);
2327 
2328   return InternalizedFns[&F];
2329 }
2330 
2331 bool Attributor::internalizeFunctions(SmallPtrSetImpl<Function *> &FnSet,
2332                                       DenseMap<Function *, Function *> &FnMap) {
2333   for (Function *F : FnSet)
2334     if (!Attributor::isInternalizable(*F))
2335       return false;
2336 
2337   FnMap.clear();
2338   // Generate the internalized version of each function.
2339   for (Function *F : FnSet) {
2340     Module &M = *F->getParent();
2341     FunctionType *FnTy = F->getFunctionType();
2342 
2343     // Create a copy of the current function
2344     Function *Copied =
2345         Function::Create(FnTy, F->getLinkage(), F->getAddressSpace(),
2346                          F->getName() + ".internalized");
2347     ValueToValueMapTy VMap;
2348     auto *NewFArgIt = Copied->arg_begin();
2349     for (auto &Arg : F->args()) {
2350       auto ArgName = Arg.getName();
2351       NewFArgIt->setName(ArgName);
2352       VMap[&Arg] = &(*NewFArgIt++);
2353     }
2354     SmallVector<ReturnInst *, 8> Returns;
2355 
2356     // Copy the body of the original function to the new one
2357     CloneFunctionInto(Copied, F, VMap,
2358                       CloneFunctionChangeType::LocalChangesOnly, Returns);
2359 
2360     // Set the linakage and visibility late as CloneFunctionInto has some
2361     // implicit requirements.
2362     Copied->setVisibility(GlobalValue::DefaultVisibility);
2363     Copied->setLinkage(GlobalValue::PrivateLinkage);
2364 
2365     // Copy metadata
2366     SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
2367     F->getAllMetadata(MDs);
2368     for (auto MDIt : MDs)
2369       if (!Copied->hasMetadata())
2370         Copied->addMetadata(MDIt.first, *MDIt.second);
2371 
2372     M.getFunctionList().insert(F->getIterator(), Copied);
2373     Copied->setDSOLocal(true);
2374     FnMap[F] = Copied;
2375   }
2376 
2377   // Replace all uses of the old function with the new internalized function
2378   // unless the caller is a function that was just internalized.
2379   for (Function *F : FnSet) {
2380     auto &InternalizedFn = FnMap[F];
2381     auto IsNotInternalized = [&](Use &U) -> bool {
2382       if (auto *CB = dyn_cast<CallBase>(U.getUser()))
2383         return !FnMap.lookup(CB->getCaller());
2384       return false;
2385     };
2386     F->replaceUsesWithIf(InternalizedFn, IsNotInternalized);
2387   }
2388 
2389   return true;
2390 }
2391 
2392 bool Attributor::isValidFunctionSignatureRewrite(
2393     Argument &Arg, ArrayRef<Type *> ReplacementTypes) {
2394 
2395   if (!Configuration.RewriteSignatures)
2396     return false;
2397 
2398   Function *Fn = Arg.getParent();
2399   auto CallSiteCanBeChanged = [Fn](AbstractCallSite ACS) {
2400     // Forbid the call site to cast the function return type. If we need to
2401     // rewrite these functions we need to re-create a cast for the new call site
2402     // (if the old had uses).
2403     if (!ACS.getCalledFunction() ||
2404         ACS.getInstruction()->getType() !=
2405             ACS.getCalledFunction()->getReturnType())
2406       return false;
2407     if (ACS.getCalledOperand()->getType() != Fn->getType())
2408       return false;
2409     // Forbid must-tail calls for now.
2410     return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall();
2411   };
2412 
2413   // Avoid var-arg functions for now.
2414   if (Fn->isVarArg()) {
2415     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n");
2416     return false;
2417   }
2418 
2419   // Avoid functions with complicated argument passing semantics.
2420   AttributeList FnAttributeList = Fn->getAttributes();
2421   if (FnAttributeList.hasAttrSomewhere(Attribute::Nest) ||
2422       FnAttributeList.hasAttrSomewhere(Attribute::StructRet) ||
2423       FnAttributeList.hasAttrSomewhere(Attribute::InAlloca) ||
2424       FnAttributeList.hasAttrSomewhere(Attribute::Preallocated)) {
2425     LLVM_DEBUG(
2426         dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n");
2427     return false;
2428   }
2429 
2430   // Avoid callbacks for now.
2431   bool UsedAssumedInformation = false;
2432   if (!checkForAllCallSites(CallSiteCanBeChanged, *Fn, true, nullptr,
2433                             UsedAssumedInformation)) {
2434     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n");
2435     return false;
2436   }
2437 
2438   auto InstPred = [](Instruction &I) {
2439     if (auto *CI = dyn_cast<CallInst>(&I))
2440       return !CI->isMustTailCall();
2441     return true;
2442   };
2443 
2444   // Forbid must-tail calls for now.
2445   // TODO:
2446   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
2447   if (!checkForAllInstructionsImpl(nullptr, OpcodeInstMap, InstPred, nullptr,
2448                                    nullptr, {Instruction::Call},
2449                                    UsedAssumedInformation)) {
2450     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n");
2451     return false;
2452   }
2453 
2454   return true;
2455 }
2456 
2457 bool Attributor::registerFunctionSignatureRewrite(
2458     Argument &Arg, ArrayRef<Type *> ReplacementTypes,
2459     ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB,
2460     ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB) {
2461   LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
2462                     << Arg.getParent()->getName() << " with "
2463                     << ReplacementTypes.size() << " replacements\n");
2464   assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) &&
2465          "Cannot register an invalid rewrite");
2466 
2467   Function *Fn = Arg.getParent();
2468   SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
2469       ArgumentReplacementMap[Fn];
2470   if (ARIs.empty())
2471     ARIs.resize(Fn->arg_size());
2472 
2473   // If we have a replacement already with less than or equal new arguments,
2474   // ignore this request.
2475   std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()];
2476   if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) {
2477     LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n");
2478     return false;
2479   }
2480 
2481   // If we have a replacement already but we like the new one better, delete
2482   // the old.
2483   ARI.reset();
2484 
2485   LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
2486                     << Arg.getParent()->getName() << " with "
2487                     << ReplacementTypes.size() << " replacements\n");
2488 
2489   // Remember the replacement.
2490   ARI.reset(new ArgumentReplacementInfo(*this, Arg, ReplacementTypes,
2491                                         std::move(CalleeRepairCB),
2492                                         std::move(ACSRepairCB)));
2493 
2494   return true;
2495 }
2496 
2497 bool Attributor::shouldSeedAttribute(AbstractAttribute &AA) {
2498   bool Result = true;
2499 #ifndef NDEBUG
2500   if (SeedAllowList.size() != 0)
2501     Result = llvm::is_contained(SeedAllowList, AA.getName());
2502   Function *Fn = AA.getAnchorScope();
2503   if (FunctionSeedAllowList.size() != 0 && Fn)
2504     Result &= llvm::is_contained(FunctionSeedAllowList, Fn->getName());
2505 #endif
2506   return Result;
2507 }
2508 
2509 ChangeStatus Attributor::rewriteFunctionSignatures(
2510     SmallSetVector<Function *, 8> &ModifiedFns) {
2511   ChangeStatus Changed = ChangeStatus::UNCHANGED;
2512 
2513   for (auto &It : ArgumentReplacementMap) {
2514     Function *OldFn = It.getFirst();
2515 
2516     // Deleted functions do not require rewrites.
2517     if (!Functions.count(OldFn) || ToBeDeletedFunctions.count(OldFn))
2518       continue;
2519 
2520     const SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
2521         It.getSecond();
2522     assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!");
2523 
2524     SmallVector<Type *, 16> NewArgumentTypes;
2525     SmallVector<AttributeSet, 16> NewArgumentAttributes;
2526 
2527     // Collect replacement argument types and copy over existing attributes.
2528     AttributeList OldFnAttributeList = OldFn->getAttributes();
2529     for (Argument &Arg : OldFn->args()) {
2530       if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
2531               ARIs[Arg.getArgNo()]) {
2532         NewArgumentTypes.append(ARI->ReplacementTypes.begin(),
2533                                 ARI->ReplacementTypes.end());
2534         NewArgumentAttributes.append(ARI->getNumReplacementArgs(),
2535                                      AttributeSet());
2536       } else {
2537         NewArgumentTypes.push_back(Arg.getType());
2538         NewArgumentAttributes.push_back(
2539             OldFnAttributeList.getParamAttrs(Arg.getArgNo()));
2540       }
2541     }
2542 
2543     uint64_t LargestVectorWidth = 0;
2544     for (auto *I : NewArgumentTypes)
2545       if (auto *VT = dyn_cast<llvm::VectorType>(I))
2546         LargestVectorWidth = std::max(
2547             LargestVectorWidth, VT->getPrimitiveSizeInBits().getKnownMinSize());
2548 
2549     FunctionType *OldFnTy = OldFn->getFunctionType();
2550     Type *RetTy = OldFnTy->getReturnType();
2551 
2552     // Construct the new function type using the new arguments types.
2553     FunctionType *NewFnTy =
2554         FunctionType::get(RetTy, NewArgumentTypes, OldFnTy->isVarArg());
2555 
2556     LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName()
2557                       << "' from " << *OldFn->getFunctionType() << " to "
2558                       << *NewFnTy << "\n");
2559 
2560     // Create the new function body and insert it into the module.
2561     Function *NewFn = Function::Create(NewFnTy, OldFn->getLinkage(),
2562                                        OldFn->getAddressSpace(), "");
2563     Functions.insert(NewFn);
2564     OldFn->getParent()->getFunctionList().insert(OldFn->getIterator(), NewFn);
2565     NewFn->takeName(OldFn);
2566     NewFn->copyAttributesFrom(OldFn);
2567 
2568     // Patch the pointer to LLVM function in debug info descriptor.
2569     NewFn->setSubprogram(OldFn->getSubprogram());
2570     OldFn->setSubprogram(nullptr);
2571 
2572     // Recompute the parameter attributes list based on the new arguments for
2573     // the function.
2574     LLVMContext &Ctx = OldFn->getContext();
2575     NewFn->setAttributes(AttributeList::get(
2576         Ctx, OldFnAttributeList.getFnAttrs(), OldFnAttributeList.getRetAttrs(),
2577         NewArgumentAttributes));
2578     AttributeFuncs::updateMinLegalVectorWidthAttr(*NewFn, LargestVectorWidth);
2579 
2580     // Since we have now created the new function, splice the body of the old
2581     // function right into the new function, leaving the old rotting hulk of the
2582     // function empty.
2583     NewFn->getBasicBlockList().splice(NewFn->begin(),
2584                                       OldFn->getBasicBlockList());
2585 
2586     // Fixup block addresses to reference new function.
2587     SmallVector<BlockAddress *, 8u> BlockAddresses;
2588     for (User *U : OldFn->users())
2589       if (auto *BA = dyn_cast<BlockAddress>(U))
2590         BlockAddresses.push_back(BA);
2591     for (auto *BA : BlockAddresses)
2592       BA->replaceAllUsesWith(BlockAddress::get(NewFn, BA->getBasicBlock()));
2593 
2594     // Set of all "call-like" instructions that invoke the old function mapped
2595     // to their new replacements.
2596     SmallVector<std::pair<CallBase *, CallBase *>, 8> CallSitePairs;
2597 
2598     // Callback to create a new "call-like" instruction for a given one.
2599     auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) {
2600       CallBase *OldCB = cast<CallBase>(ACS.getInstruction());
2601       const AttributeList &OldCallAttributeList = OldCB->getAttributes();
2602 
2603       // Collect the new argument operands for the replacement call site.
2604       SmallVector<Value *, 16> NewArgOperands;
2605       SmallVector<AttributeSet, 16> NewArgOperandAttributes;
2606       for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) {
2607         unsigned NewFirstArgNum = NewArgOperands.size();
2608         (void)NewFirstArgNum; // only used inside assert.
2609         if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
2610                 ARIs[OldArgNum]) {
2611           if (ARI->ACSRepairCB)
2612             ARI->ACSRepairCB(*ARI, ACS, NewArgOperands);
2613           assert(ARI->getNumReplacementArgs() + NewFirstArgNum ==
2614                      NewArgOperands.size() &&
2615                  "ACS repair callback did not provide as many operand as new "
2616                  "types were registered!");
2617           // TODO: Exose the attribute set to the ACS repair callback
2618           NewArgOperandAttributes.append(ARI->ReplacementTypes.size(),
2619                                          AttributeSet());
2620         } else {
2621           NewArgOperands.push_back(ACS.getCallArgOperand(OldArgNum));
2622           NewArgOperandAttributes.push_back(
2623               OldCallAttributeList.getParamAttrs(OldArgNum));
2624         }
2625       }
2626 
2627       assert(NewArgOperands.size() == NewArgOperandAttributes.size() &&
2628              "Mismatch # argument operands vs. # argument operand attributes!");
2629       assert(NewArgOperands.size() == NewFn->arg_size() &&
2630              "Mismatch # argument operands vs. # function arguments!");
2631 
2632       SmallVector<OperandBundleDef, 4> OperandBundleDefs;
2633       OldCB->getOperandBundlesAsDefs(OperandBundleDefs);
2634 
2635       // Create a new call or invoke instruction to replace the old one.
2636       CallBase *NewCB;
2637       if (InvokeInst *II = dyn_cast<InvokeInst>(OldCB)) {
2638         NewCB =
2639             InvokeInst::Create(NewFn, II->getNormalDest(), II->getUnwindDest(),
2640                                NewArgOperands, OperandBundleDefs, "", OldCB);
2641       } else {
2642         auto *NewCI = CallInst::Create(NewFn, NewArgOperands, OperandBundleDefs,
2643                                        "", OldCB);
2644         NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind());
2645         NewCB = NewCI;
2646       }
2647 
2648       // Copy over various properties and the new attributes.
2649       NewCB->copyMetadata(*OldCB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
2650       NewCB->setCallingConv(OldCB->getCallingConv());
2651       NewCB->takeName(OldCB);
2652       NewCB->setAttributes(AttributeList::get(
2653           Ctx, OldCallAttributeList.getFnAttrs(),
2654           OldCallAttributeList.getRetAttrs(), NewArgOperandAttributes));
2655 
2656       AttributeFuncs::updateMinLegalVectorWidthAttr(*NewCB->getCaller(),
2657                                                     LargestVectorWidth);
2658 
2659       CallSitePairs.push_back({OldCB, NewCB});
2660       return true;
2661     };
2662 
2663     // Use the CallSiteReplacementCreator to create replacement call sites.
2664     bool UsedAssumedInformation = false;
2665     bool Success = checkForAllCallSites(CallSiteReplacementCreator, *OldFn,
2666                                         true, nullptr, UsedAssumedInformation);
2667     (void)Success;
2668     assert(Success && "Assumed call site replacement to succeed!");
2669 
2670     // Rewire the arguments.
2671     Argument *OldFnArgIt = OldFn->arg_begin();
2672     Argument *NewFnArgIt = NewFn->arg_begin();
2673     for (unsigned OldArgNum = 0; OldArgNum < ARIs.size();
2674          ++OldArgNum, ++OldFnArgIt) {
2675       if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
2676               ARIs[OldArgNum]) {
2677         if (ARI->CalleeRepairCB)
2678           ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt);
2679         if (ARI->ReplacementTypes.empty())
2680           OldFnArgIt->replaceAllUsesWith(
2681               PoisonValue::get(OldFnArgIt->getType()));
2682         NewFnArgIt += ARI->ReplacementTypes.size();
2683       } else {
2684         NewFnArgIt->takeName(&*OldFnArgIt);
2685         OldFnArgIt->replaceAllUsesWith(&*NewFnArgIt);
2686         ++NewFnArgIt;
2687       }
2688     }
2689 
2690     // Eliminate the instructions *after* we visited all of them.
2691     for (auto &CallSitePair : CallSitePairs) {
2692       CallBase &OldCB = *CallSitePair.first;
2693       CallBase &NewCB = *CallSitePair.second;
2694       assert(OldCB.getType() == NewCB.getType() &&
2695              "Cannot handle call sites with different types!");
2696       ModifiedFns.insert(OldCB.getFunction());
2697       Configuration.CGUpdater.replaceCallSite(OldCB, NewCB);
2698       OldCB.replaceAllUsesWith(&NewCB);
2699       OldCB.eraseFromParent();
2700     }
2701 
2702     // Replace the function in the call graph (if any).
2703     Configuration.CGUpdater.replaceFunctionWith(*OldFn, *NewFn);
2704 
2705     // If the old function was modified and needed to be reanalyzed, the new one
2706     // does now.
2707     if (ModifiedFns.remove(OldFn))
2708       ModifiedFns.insert(NewFn);
2709 
2710     Changed = ChangeStatus::CHANGED;
2711   }
2712 
2713   return Changed;
2714 }
2715 
2716 void InformationCache::initializeInformationCache(const Function &CF,
2717                                                   FunctionInfo &FI) {
2718   // As we do not modify the function here we can remove the const
2719   // withouth breaking implicit assumptions. At the end of the day, we could
2720   // initialize the cache eagerly which would look the same to the users.
2721   Function &F = const_cast<Function &>(CF);
2722 
2723   // Walk all instructions to find interesting instructions that might be
2724   // queried by abstract attributes during their initialization or update.
2725   // This has to happen before we create attributes.
2726 
2727   DenseMap<const Value *, Optional<short>> AssumeUsesMap;
2728 
2729   // Add \p V to the assume uses map which track the number of uses outside of
2730   // "visited" assumes. If no outside uses are left the value is added to the
2731   // assume only use vector.
2732   auto AddToAssumeUsesMap = [&](const Value &V) -> void {
2733     SmallVector<const Instruction *> Worklist;
2734     if (auto *I = dyn_cast<Instruction>(&V))
2735       Worklist.push_back(I);
2736     while (!Worklist.empty()) {
2737       const Instruction *I = Worklist.pop_back_val();
2738       Optional<short> &NumUses = AssumeUsesMap[I];
2739       if (!NumUses)
2740         NumUses = I->getNumUses();
2741       NumUses = NumUses.value() - /* this assume */ 1;
2742       if (NumUses.value() != 0)
2743         continue;
2744       AssumeOnlyValues.insert(I);
2745       for (const Value *Op : I->operands())
2746         if (auto *OpI = dyn_cast<Instruction>(Op))
2747           Worklist.push_back(OpI);
2748     }
2749   };
2750 
2751   for (Instruction &I : instructions(&F)) {
2752     bool IsInterestingOpcode = false;
2753 
2754     // To allow easy access to all instructions in a function with a given
2755     // opcode we store them in the InfoCache. As not all opcodes are interesting
2756     // to concrete attributes we only cache the ones that are as identified in
2757     // the following switch.
2758     // Note: There are no concrete attributes now so this is initially empty.
2759     switch (I.getOpcode()) {
2760     default:
2761       assert(!isa<CallBase>(&I) &&
2762              "New call base instruction type needs to be known in the "
2763              "Attributor.");
2764       break;
2765     case Instruction::Call:
2766       // Calls are interesting on their own, additionally:
2767       // For `llvm.assume` calls we also fill the KnowledgeMap as we find them.
2768       // For `must-tail` calls we remember the caller and callee.
2769       if (auto *Assume = dyn_cast<AssumeInst>(&I)) {
2770         fillMapFromAssume(*Assume, KnowledgeMap);
2771         AddToAssumeUsesMap(*Assume->getArgOperand(0));
2772       } else if (cast<CallInst>(I).isMustTailCall()) {
2773         FI.ContainsMustTailCall = true;
2774         if (const Function *Callee = cast<CallInst>(I).getCalledFunction())
2775           getFunctionInfo(*Callee).CalledViaMustTail = true;
2776       }
2777       LLVM_FALLTHROUGH;
2778     case Instruction::CallBr:
2779     case Instruction::Invoke:
2780     case Instruction::CleanupRet:
2781     case Instruction::CatchSwitch:
2782     case Instruction::AtomicRMW:
2783     case Instruction::AtomicCmpXchg:
2784     case Instruction::Br:
2785     case Instruction::Resume:
2786     case Instruction::Ret:
2787     case Instruction::Load:
2788       // The alignment of a pointer is interesting for loads.
2789     case Instruction::Store:
2790       // The alignment of a pointer is interesting for stores.
2791     case Instruction::Alloca:
2792     case Instruction::AddrSpaceCast:
2793       IsInterestingOpcode = true;
2794     }
2795     if (IsInterestingOpcode) {
2796       auto *&Insts = FI.OpcodeInstMap[I.getOpcode()];
2797       if (!Insts)
2798         Insts = new (Allocator) InstructionVectorTy();
2799       Insts->push_back(&I);
2800     }
2801     if (I.mayReadOrWriteMemory())
2802       FI.RWInsts.push_back(&I);
2803   }
2804 
2805   if (F.hasFnAttribute(Attribute::AlwaysInline) &&
2806       isInlineViable(F).isSuccess())
2807     InlineableFunctions.insert(&F);
2808 }
2809 
2810 AAResults *InformationCache::getAAResultsForFunction(const Function &F) {
2811   return AG.getAnalysis<AAManager>(F);
2812 }
2813 
2814 InformationCache::FunctionInfo::~FunctionInfo() {
2815   // The instruction vectors are allocated using a BumpPtrAllocator, we need to
2816   // manually destroy them.
2817   for (auto &It : OpcodeInstMap)
2818     It.getSecond()->~InstructionVectorTy();
2819 }
2820 
2821 void Attributor::recordDependence(const AbstractAttribute &FromAA,
2822                                   const AbstractAttribute &ToAA,
2823                                   DepClassTy DepClass) {
2824   if (DepClass == DepClassTy::NONE)
2825     return;
2826   // If we are outside of an update, thus before the actual fixpoint iteration
2827   // started (= when we create AAs), we do not track dependences because we will
2828   // put all AAs into the initial worklist anyway.
2829   if (DependenceStack.empty())
2830     return;
2831   if (FromAA.getState().isAtFixpoint())
2832     return;
2833   DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass});
2834 }
2835 
2836 void Attributor::rememberDependences() {
2837   assert(!DependenceStack.empty() && "No dependences to remember!");
2838 
2839   for (DepInfo &DI : *DependenceStack.back()) {
2840     assert((DI.DepClass == DepClassTy::REQUIRED ||
2841             DI.DepClass == DepClassTy::OPTIONAL) &&
2842            "Expected required or optional dependence (1 bit)!");
2843     auto &DepAAs = const_cast<AbstractAttribute &>(*DI.FromAA).Deps;
2844     DepAAs.push_back(AbstractAttribute::DepTy(
2845         const_cast<AbstractAttribute *>(DI.ToAA), unsigned(DI.DepClass)));
2846   }
2847 }
2848 
2849 void Attributor::identifyDefaultAbstractAttributes(Function &F) {
2850   if (!VisitedFunctions.insert(&F).second)
2851     return;
2852   if (F.isDeclaration())
2853     return;
2854 
2855   // In non-module runs we need to look at the call sites of a function to
2856   // determine if it is part of a must-tail call edge. This will influence what
2857   // attributes we can derive.
2858   InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F);
2859   if (!isModulePass() && !FI.CalledViaMustTail) {
2860     for (const Use &U : F.uses())
2861       if (const auto *CB = dyn_cast<CallBase>(U.getUser()))
2862         if (CB->isCallee(&U) && CB->isMustTailCall())
2863           FI.CalledViaMustTail = true;
2864   }
2865 
2866   IRPosition FPos = IRPosition::function(F);
2867 
2868   // Check for dead BasicBlocks in every function.
2869   // We need dead instruction detection because we do not want to deal with
2870   // broken IR in which SSA rules do not apply.
2871   getOrCreateAAFor<AAIsDead>(FPos);
2872 
2873   // Every function might be "will-return".
2874   getOrCreateAAFor<AAWillReturn>(FPos);
2875 
2876   // Every function might contain instructions that cause "undefined behavior".
2877   getOrCreateAAFor<AAUndefinedBehavior>(FPos);
2878 
2879   // Every function can be nounwind.
2880   getOrCreateAAFor<AANoUnwind>(FPos);
2881 
2882   // Every function might be marked "nosync"
2883   getOrCreateAAFor<AANoSync>(FPos);
2884 
2885   // Every function might be "no-free".
2886   getOrCreateAAFor<AANoFree>(FPos);
2887 
2888   // Every function might be "no-return".
2889   getOrCreateAAFor<AANoReturn>(FPos);
2890 
2891   // Every function might be "no-recurse".
2892   getOrCreateAAFor<AANoRecurse>(FPos);
2893 
2894   // Every function might be "readnone/readonly/writeonly/...".
2895   getOrCreateAAFor<AAMemoryBehavior>(FPos);
2896 
2897   // Every function can be "readnone/argmemonly/inaccessiblememonly/...".
2898   getOrCreateAAFor<AAMemoryLocation>(FPos);
2899 
2900   // Every function can track active assumptions.
2901   getOrCreateAAFor<AAAssumptionInfo>(FPos);
2902 
2903   // Every function might be applicable for Heap-To-Stack conversion.
2904   if (EnableHeapToStack)
2905     getOrCreateAAFor<AAHeapToStack>(FPos);
2906 
2907   // Return attributes are only appropriate if the return type is non void.
2908   Type *ReturnType = F.getReturnType();
2909   if (!ReturnType->isVoidTy()) {
2910     // Argument attribute "returned" --- Create only one per function even
2911     // though it is an argument attribute.
2912     getOrCreateAAFor<AAReturnedValues>(FPos);
2913 
2914     IRPosition RetPos = IRPosition::returned(F);
2915 
2916     // Every returned value might be dead.
2917     getOrCreateAAFor<AAIsDead>(RetPos);
2918 
2919     // Every function might be simplified.
2920     bool UsedAssumedInformation = false;
2921     getAssumedSimplified(RetPos, nullptr, UsedAssumedInformation,
2922                          AA::Intraprocedural);
2923 
2924     // Every returned value might be marked noundef.
2925     getOrCreateAAFor<AANoUndef>(RetPos);
2926 
2927     if (ReturnType->isPointerTy()) {
2928 
2929       // Every function with pointer return type might be marked align.
2930       getOrCreateAAFor<AAAlign>(RetPos);
2931 
2932       // Every function with pointer return type might be marked nonnull.
2933       getOrCreateAAFor<AANonNull>(RetPos);
2934 
2935       // Every function with pointer return type might be marked noalias.
2936       getOrCreateAAFor<AANoAlias>(RetPos);
2937 
2938       // Every function with pointer return type might be marked
2939       // dereferenceable.
2940       getOrCreateAAFor<AADereferenceable>(RetPos);
2941     }
2942   }
2943 
2944   for (Argument &Arg : F.args()) {
2945     IRPosition ArgPos = IRPosition::argument(Arg);
2946 
2947     // Every argument might be simplified. We have to go through the Attributor
2948     // interface though as outside AAs can register custom simplification
2949     // callbacks.
2950     bool UsedAssumedInformation = false;
2951     getAssumedSimplified(ArgPos, /* AA */ nullptr, UsedAssumedInformation,
2952                          AA::Intraprocedural);
2953 
2954     // Every argument might be dead.
2955     getOrCreateAAFor<AAIsDead>(ArgPos);
2956 
2957     // Every argument might be marked noundef.
2958     getOrCreateAAFor<AANoUndef>(ArgPos);
2959 
2960     if (Arg.getType()->isPointerTy()) {
2961       // Every argument with pointer type might be marked nonnull.
2962       getOrCreateAAFor<AANonNull>(ArgPos);
2963 
2964       // Every argument with pointer type might be marked noalias.
2965       getOrCreateAAFor<AANoAlias>(ArgPos);
2966 
2967       // Every argument with pointer type might be marked dereferenceable.
2968       getOrCreateAAFor<AADereferenceable>(ArgPos);
2969 
2970       // Every argument with pointer type might be marked align.
2971       getOrCreateAAFor<AAAlign>(ArgPos);
2972 
2973       // Every argument with pointer type might be marked nocapture.
2974       getOrCreateAAFor<AANoCapture>(ArgPos);
2975 
2976       // Every argument with pointer type might be marked
2977       // "readnone/readonly/writeonly/..."
2978       getOrCreateAAFor<AAMemoryBehavior>(ArgPos);
2979 
2980       // Every argument with pointer type might be marked nofree.
2981       getOrCreateAAFor<AANoFree>(ArgPos);
2982 
2983       // Every argument with pointer type might be privatizable (or promotable)
2984       getOrCreateAAFor<AAPrivatizablePtr>(ArgPos);
2985     }
2986   }
2987 
2988   auto CallSitePred = [&](Instruction &I) -> bool {
2989     auto &CB = cast<CallBase>(I);
2990     IRPosition CBInstPos = IRPosition::inst(CB);
2991     IRPosition CBFnPos = IRPosition::callsite_function(CB);
2992 
2993     // Call sites might be dead if they do not have side effects and no live
2994     // users. The return value might be dead if there are no live users.
2995     getOrCreateAAFor<AAIsDead>(CBInstPos);
2996 
2997     Function *Callee = CB.getCalledFunction();
2998     // TODO: Even if the callee is not known now we might be able to simplify
2999     //       the call/callee.
3000     if (!Callee)
3001       return true;
3002 
3003     // Every call site can track active assumptions.
3004     getOrCreateAAFor<AAAssumptionInfo>(CBFnPos);
3005 
3006     // Skip declarations except if annotations on their call sites were
3007     // explicitly requested.
3008     if (!AnnotateDeclarationCallSites && Callee->isDeclaration() &&
3009         !Callee->hasMetadata(LLVMContext::MD_callback))
3010       return true;
3011 
3012     if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) {
3013 
3014       IRPosition CBRetPos = IRPosition::callsite_returned(CB);
3015       bool UsedAssumedInformation = false;
3016       getAssumedSimplified(CBRetPos, nullptr, UsedAssumedInformation,
3017                            AA::Intraprocedural);
3018     }
3019 
3020     for (int I = 0, E = CB.arg_size(); I < E; ++I) {
3021 
3022       IRPosition CBArgPos = IRPosition::callsite_argument(CB, I);
3023 
3024       // Every call site argument might be dead.
3025       getOrCreateAAFor<AAIsDead>(CBArgPos);
3026 
3027       // Call site argument might be simplified. We have to go through the
3028       // Attributor interface though as outside AAs can register custom
3029       // simplification callbacks.
3030       bool UsedAssumedInformation = false;
3031       getAssumedSimplified(CBArgPos, /* AA */ nullptr, UsedAssumedInformation,
3032                            AA::Intraprocedural);
3033 
3034       // Every call site argument might be marked "noundef".
3035       getOrCreateAAFor<AANoUndef>(CBArgPos);
3036 
3037       if (!CB.getArgOperand(I)->getType()->isPointerTy())
3038         continue;
3039 
3040       // Call site argument attribute "non-null".
3041       getOrCreateAAFor<AANonNull>(CBArgPos);
3042 
3043       // Call site argument attribute "nocapture".
3044       getOrCreateAAFor<AANoCapture>(CBArgPos);
3045 
3046       // Call site argument attribute "no-alias".
3047       getOrCreateAAFor<AANoAlias>(CBArgPos);
3048 
3049       // Call site argument attribute "dereferenceable".
3050       getOrCreateAAFor<AADereferenceable>(CBArgPos);
3051 
3052       // Call site argument attribute "align".
3053       getOrCreateAAFor<AAAlign>(CBArgPos);
3054 
3055       // Call site argument attribute
3056       // "readnone/readonly/writeonly/..."
3057       getOrCreateAAFor<AAMemoryBehavior>(CBArgPos);
3058 
3059       // Call site argument attribute "nofree".
3060       getOrCreateAAFor<AANoFree>(CBArgPos);
3061     }
3062     return true;
3063   };
3064 
3065   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
3066   bool Success;
3067   bool UsedAssumedInformation = false;
3068   Success = checkForAllInstructionsImpl(
3069       nullptr, OpcodeInstMap, CallSitePred, nullptr, nullptr,
3070       {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
3071        (unsigned)Instruction::Call},
3072       UsedAssumedInformation);
3073   (void)Success;
3074   assert(Success && "Expected the check call to be successful!");
3075 
3076   auto LoadStorePred = [&](Instruction &I) -> bool {
3077     if (isa<LoadInst>(I)) {
3078       getOrCreateAAFor<AAAlign>(
3079           IRPosition::value(*cast<LoadInst>(I).getPointerOperand()));
3080       if (SimplifyAllLoads)
3081         getAssumedSimplified(IRPosition::value(I), nullptr,
3082                              UsedAssumedInformation, AA::Intraprocedural);
3083     } else {
3084       auto &SI = cast<StoreInst>(I);
3085       getOrCreateAAFor<AAIsDead>(IRPosition::inst(I));
3086       getAssumedSimplified(IRPosition::value(*SI.getValueOperand()), nullptr,
3087                            UsedAssumedInformation, AA::Intraprocedural);
3088       getOrCreateAAFor<AAAlign>(IRPosition::value(*SI.getPointerOperand()));
3089     }
3090     return true;
3091   };
3092   Success = checkForAllInstructionsImpl(
3093       nullptr, OpcodeInstMap, LoadStorePred, nullptr, nullptr,
3094       {(unsigned)Instruction::Load, (unsigned)Instruction::Store},
3095       UsedAssumedInformation);
3096   (void)Success;
3097   assert(Success && "Expected the check call to be successful!");
3098 }
3099 
3100 /// Helpers to ease debugging through output streams and print calls.
3101 ///
3102 ///{
3103 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) {
3104   return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
3105 }
3106 
3107 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) {
3108   switch (AP) {
3109   case IRPosition::IRP_INVALID:
3110     return OS << "inv";
3111   case IRPosition::IRP_FLOAT:
3112     return OS << "flt";
3113   case IRPosition::IRP_RETURNED:
3114     return OS << "fn_ret";
3115   case IRPosition::IRP_CALL_SITE_RETURNED:
3116     return OS << "cs_ret";
3117   case IRPosition::IRP_FUNCTION:
3118     return OS << "fn";
3119   case IRPosition::IRP_CALL_SITE:
3120     return OS << "cs";
3121   case IRPosition::IRP_ARGUMENT:
3122     return OS << "arg";
3123   case IRPosition::IRP_CALL_SITE_ARGUMENT:
3124     return OS << "cs_arg";
3125   }
3126   llvm_unreachable("Unknown attribute position!");
3127 }
3128 
3129 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) {
3130   const Value &AV = Pos.getAssociatedValue();
3131   OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " ["
3132      << Pos.getAnchorValue().getName() << "@" << Pos.getCallSiteArgNo() << "]";
3133 
3134   if (Pos.hasCallBaseContext())
3135     OS << "[cb_context:" << *Pos.getCallBaseContext() << "]";
3136   return OS << "}";
3137 }
3138 
3139 raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerRangeState &S) {
3140   OS << "range-state(" << S.getBitWidth() << ")<";
3141   S.getKnown().print(OS);
3142   OS << " / ";
3143   S.getAssumed().print(OS);
3144   OS << ">";
3145 
3146   return OS << static_cast<const AbstractState &>(S);
3147 }
3148 
3149 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) {
3150   return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
3151 }
3152 
3153 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) {
3154   AA.print(OS);
3155   return OS;
3156 }
3157 
3158 raw_ostream &llvm::operator<<(raw_ostream &OS,
3159                               const PotentialConstantIntValuesState &S) {
3160   OS << "set-state(< {";
3161   if (!S.isValidState())
3162     OS << "full-set";
3163   else {
3164     for (auto &It : S.getAssumedSet())
3165       OS << It << ", ";
3166     if (S.undefIsContained())
3167       OS << "undef ";
3168   }
3169   OS << "} >)";
3170 
3171   return OS;
3172 }
3173 
3174 raw_ostream &llvm::operator<<(raw_ostream &OS,
3175                               const PotentialLLVMValuesState &S) {
3176   OS << "set-state(< {";
3177   if (!S.isValidState())
3178     OS << "full-set";
3179   else {
3180     for (auto &It : S.getAssumedSet()) {
3181       if (auto *F = dyn_cast<Function>(It.first.getValue()))
3182         OS << "@" << F->getName() << "[" << int(It.second) << "], ";
3183       else
3184         OS << *It.first.getValue() << "[" << int(It.second) << "], ";
3185     }
3186     if (S.undefIsContained())
3187       OS << "undef ";
3188   }
3189   OS << "} >)";
3190 
3191   return OS;
3192 }
3193 
3194 void AbstractAttribute::print(raw_ostream &OS) const {
3195   OS << "[";
3196   OS << getName();
3197   OS << "] for CtxI ";
3198 
3199   if (auto *I = getCtxI()) {
3200     OS << "'";
3201     I->print(OS);
3202     OS << "'";
3203   } else
3204     OS << "<<null inst>>";
3205 
3206   OS << " at position " << getIRPosition() << " with state " << getAsStr()
3207      << '\n';
3208 }
3209 
3210 void AbstractAttribute::printWithDeps(raw_ostream &OS) const {
3211   print(OS);
3212 
3213   for (const auto &DepAA : Deps) {
3214     auto *AA = DepAA.getPointer();
3215     OS << "  updates ";
3216     AA->print(OS);
3217   }
3218 
3219   OS << '\n';
3220 }
3221 
3222 raw_ostream &llvm::operator<<(raw_ostream &OS,
3223                               const AAPointerInfo::Access &Acc) {
3224   OS << " [" << Acc.getKind() << "] " << *Acc.getRemoteInst();
3225   if (Acc.getLocalInst() != Acc.getRemoteInst())
3226     OS << " via " << *Acc.getLocalInst();
3227   if (Acc.getContent()) {
3228     if (*Acc.getContent())
3229       OS << " [" << **Acc.getContent() << "]";
3230     else
3231       OS << " [ <unknown> ]";
3232   }
3233   return OS;
3234 }
3235 ///}
3236 
3237 /// ----------------------------------------------------------------------------
3238 ///                       Pass (Manager) Boilerplate
3239 /// ----------------------------------------------------------------------------
3240 
3241 static bool runAttributorOnFunctions(InformationCache &InfoCache,
3242                                      SetVector<Function *> &Functions,
3243                                      AnalysisGetter &AG,
3244                                      CallGraphUpdater &CGUpdater,
3245                                      bool DeleteFns, bool IsModulePass) {
3246   if (Functions.empty())
3247     return false;
3248 
3249   LLVM_DEBUG({
3250     dbgs() << "[Attributor] Run on module with " << Functions.size()
3251            << " functions:\n";
3252     for (Function *Fn : Functions)
3253       dbgs() << "  - " << Fn->getName() << "\n";
3254   });
3255 
3256   // Create an Attributor and initially empty information cache that is filled
3257   // while we identify default attribute opportunities.
3258   AttributorConfig AC(CGUpdater);
3259   AC.IsModulePass = IsModulePass;
3260   AC.DeleteFns = DeleteFns;
3261   Attributor A(Functions, InfoCache, AC);
3262 
3263   // Create shallow wrappers for all functions that are not IPO amendable
3264   if (AllowShallowWrappers)
3265     for (Function *F : Functions)
3266       if (!A.isFunctionIPOAmendable(*F))
3267         Attributor::createShallowWrapper(*F);
3268 
3269   // Internalize non-exact functions
3270   // TODO: for now we eagerly internalize functions without calculating the
3271   //       cost, we need a cost interface to determine whether internalizing
3272   //       a function is "benefitial"
3273   if (AllowDeepWrapper) {
3274     unsigned FunSize = Functions.size();
3275     for (unsigned u = 0; u < FunSize; u++) {
3276       Function *F = Functions[u];
3277       if (!F->isDeclaration() && !F->isDefinitionExact() && F->getNumUses() &&
3278           !GlobalValue::isInterposableLinkage(F->getLinkage())) {
3279         Function *NewF = Attributor::internalizeFunction(*F);
3280         assert(NewF && "Could not internalize function.");
3281         Functions.insert(NewF);
3282 
3283         // Update call graph
3284         CGUpdater.replaceFunctionWith(*F, *NewF);
3285         for (const Use &U : NewF->uses())
3286           if (CallBase *CB = dyn_cast<CallBase>(U.getUser())) {
3287             auto *CallerF = CB->getCaller();
3288             CGUpdater.reanalyzeFunction(*CallerF);
3289           }
3290       }
3291     }
3292   }
3293 
3294   for (Function *F : Functions) {
3295     if (F->hasExactDefinition())
3296       NumFnWithExactDefinition++;
3297     else
3298       NumFnWithoutExactDefinition++;
3299 
3300     // We look at internal functions only on-demand but if any use is not a
3301     // direct call or outside the current set of analyzed functions, we have
3302     // to do it eagerly.
3303     if (F->hasLocalLinkage()) {
3304       if (llvm::all_of(F->uses(), [&Functions](const Use &U) {
3305             const auto *CB = dyn_cast<CallBase>(U.getUser());
3306             return CB && CB->isCallee(&U) &&
3307                    Functions.count(const_cast<Function *>(CB->getCaller()));
3308           }))
3309         continue;
3310     }
3311 
3312     // Populate the Attributor with abstract attribute opportunities in the
3313     // function and the information cache with IR information.
3314     A.identifyDefaultAbstractAttributes(*F);
3315   }
3316 
3317   ChangeStatus Changed = A.run();
3318 
3319   LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size()
3320                     << " functions, result: " << Changed << ".\n");
3321   return Changed == ChangeStatus::CHANGED;
3322 }
3323 
3324 void AADepGraph::viewGraph() { llvm::ViewGraph(this, "Dependency Graph"); }
3325 
3326 void AADepGraph::dumpGraph() {
3327   static std::atomic<int> CallTimes;
3328   std::string Prefix;
3329 
3330   if (!DepGraphDotFileNamePrefix.empty())
3331     Prefix = DepGraphDotFileNamePrefix;
3332   else
3333     Prefix = "dep_graph";
3334   std::string Filename =
3335       Prefix + "_" + std::to_string(CallTimes.load()) + ".dot";
3336 
3337   outs() << "Dependency graph dump to " << Filename << ".\n";
3338 
3339   std::error_code EC;
3340 
3341   raw_fd_ostream File(Filename, EC, sys::fs::OF_TextWithCRLF);
3342   if (!EC)
3343     llvm::WriteGraph(File, this);
3344 
3345   CallTimes++;
3346 }
3347 
3348 void AADepGraph::print() {
3349   for (auto DepAA : SyntheticRoot.Deps)
3350     cast<AbstractAttribute>(DepAA.getPointer())->printWithDeps(outs());
3351 }
3352 
3353 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) {
3354   FunctionAnalysisManager &FAM =
3355       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
3356   AnalysisGetter AG(FAM);
3357 
3358   SetVector<Function *> Functions;
3359   for (Function &F : M)
3360     Functions.insert(&F);
3361 
3362   CallGraphUpdater CGUpdater;
3363   BumpPtrAllocator Allocator;
3364   InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
3365   if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
3366                                /* DeleteFns */ true, /* IsModulePass */ true)) {
3367     // FIXME: Think about passes we will preserve and add them here.
3368     return PreservedAnalyses::none();
3369   }
3370   return PreservedAnalyses::all();
3371 }
3372 
3373 PreservedAnalyses AttributorCGSCCPass::run(LazyCallGraph::SCC &C,
3374                                            CGSCCAnalysisManager &AM,
3375                                            LazyCallGraph &CG,
3376                                            CGSCCUpdateResult &UR) {
3377   FunctionAnalysisManager &FAM =
3378       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
3379   AnalysisGetter AG(FAM);
3380 
3381   SetVector<Function *> Functions;
3382   for (LazyCallGraph::Node &N : C)
3383     Functions.insert(&N.getFunction());
3384 
3385   if (Functions.empty())
3386     return PreservedAnalyses::all();
3387 
3388   Module &M = *Functions.back()->getParent();
3389   CallGraphUpdater CGUpdater;
3390   CGUpdater.initialize(CG, C, AM, UR);
3391   BumpPtrAllocator Allocator;
3392   InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
3393   if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
3394                                /* DeleteFns */ false,
3395                                /* IsModulePass */ false)) {
3396     // FIXME: Think about passes we will preserve and add them here.
3397     PreservedAnalyses PA;
3398     PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
3399     return PA;
3400   }
3401   return PreservedAnalyses::all();
3402 }
3403 
3404 namespace llvm {
3405 
3406 template <> struct GraphTraits<AADepGraphNode *> {
3407   using NodeRef = AADepGraphNode *;
3408   using DepTy = PointerIntPair<AADepGraphNode *, 1>;
3409   using EdgeRef = PointerIntPair<AADepGraphNode *, 1>;
3410 
3411   static NodeRef getEntryNode(AADepGraphNode *DGN) { return DGN; }
3412   static NodeRef DepGetVal(DepTy &DT) { return DT.getPointer(); }
3413 
3414   using ChildIteratorType =
3415       mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>;
3416   using ChildEdgeIteratorType = TinyPtrVector<DepTy>::iterator;
3417 
3418   static ChildIteratorType child_begin(NodeRef N) { return N->child_begin(); }
3419 
3420   static ChildIteratorType child_end(NodeRef N) { return N->child_end(); }
3421 };
3422 
3423 template <>
3424 struct GraphTraits<AADepGraph *> : public GraphTraits<AADepGraphNode *> {
3425   static NodeRef getEntryNode(AADepGraph *DG) { return DG->GetEntryNode(); }
3426 
3427   using nodes_iterator =
3428       mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>;
3429 
3430   static nodes_iterator nodes_begin(AADepGraph *DG) { return DG->begin(); }
3431 
3432   static nodes_iterator nodes_end(AADepGraph *DG) { return DG->end(); }
3433 };
3434 
3435 template <> struct DOTGraphTraits<AADepGraph *> : public DefaultDOTGraphTraits {
3436   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3437 
3438   static std::string getNodeLabel(const AADepGraphNode *Node,
3439                                   const AADepGraph *DG) {
3440     std::string AAString;
3441     raw_string_ostream O(AAString);
3442     Node->print(O);
3443     return AAString;
3444   }
3445 };
3446 
3447 } // end namespace llvm
3448 
3449 namespace {
3450 
3451 struct AttributorLegacyPass : public ModulePass {
3452   static char ID;
3453 
3454   AttributorLegacyPass() : ModulePass(ID) {
3455     initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry());
3456   }
3457 
3458   bool runOnModule(Module &M) override {
3459     if (skipModule(M))
3460       return false;
3461 
3462     AnalysisGetter AG;
3463     SetVector<Function *> Functions;
3464     for (Function &F : M)
3465       Functions.insert(&F);
3466 
3467     CallGraphUpdater CGUpdater;
3468     BumpPtrAllocator Allocator;
3469     InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
3470     return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
3471                                     /* DeleteFns*/ true,
3472                                     /* IsModulePass */ true);
3473   }
3474 
3475   void getAnalysisUsage(AnalysisUsage &AU) const override {
3476     // FIXME: Think about passes we will preserve and add them here.
3477     AU.addRequired<TargetLibraryInfoWrapperPass>();
3478   }
3479 };
3480 
3481 struct AttributorCGSCCLegacyPass : public CallGraphSCCPass {
3482   static char ID;
3483 
3484   AttributorCGSCCLegacyPass() : CallGraphSCCPass(ID) {
3485     initializeAttributorCGSCCLegacyPassPass(*PassRegistry::getPassRegistry());
3486   }
3487 
3488   bool runOnSCC(CallGraphSCC &SCC) override {
3489     if (skipSCC(SCC))
3490       return false;
3491 
3492     SetVector<Function *> Functions;
3493     for (CallGraphNode *CGN : SCC)
3494       if (Function *Fn = CGN->getFunction())
3495         if (!Fn->isDeclaration())
3496           Functions.insert(Fn);
3497 
3498     if (Functions.empty())
3499       return false;
3500 
3501     AnalysisGetter AG;
3502     CallGraph &CG = const_cast<CallGraph &>(SCC.getCallGraph());
3503     CallGraphUpdater CGUpdater;
3504     CGUpdater.initialize(CG, SCC);
3505     Module &M = *Functions.back()->getParent();
3506     BumpPtrAllocator Allocator;
3507     InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
3508     return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
3509                                     /* DeleteFns */ false,
3510                                     /* IsModulePass */ false);
3511   }
3512 
3513   void getAnalysisUsage(AnalysisUsage &AU) const override {
3514     // FIXME: Think about passes we will preserve and add them here.
3515     AU.addRequired<TargetLibraryInfoWrapperPass>();
3516     CallGraphSCCPass::getAnalysisUsage(AU);
3517   }
3518 };
3519 
3520 } // end anonymous namespace
3521 
3522 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); }
3523 Pass *llvm::createAttributorCGSCCLegacyPass() {
3524   return new AttributorCGSCCLegacyPass();
3525 }
3526 
3527 char AttributorLegacyPass::ID = 0;
3528 char AttributorCGSCCLegacyPass::ID = 0;
3529 
3530 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor",
3531                       "Deduce and propagate attributes", false, false)
3532 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3533 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor",
3534                     "Deduce and propagate attributes", false, false)
3535 INITIALIZE_PASS_BEGIN(AttributorCGSCCLegacyPass, "attributor-cgscc",
3536                       "Deduce and propagate attributes (CGSCC pass)", false,
3537                       false)
3538 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3539 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
3540 INITIALIZE_PASS_END(AttributorCGSCCLegacyPass, "attributor-cgscc",
3541                     "Deduce and propagate attributes (CGSCC pass)", false,
3542                     false)
3543