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