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