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