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