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