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