106f32e7eSjoerg //===- Attributor.cpp - Module-wide attribute deduction -------------------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
9*da58b97aSjoerg // This file implements an interprocedural pass that deduces and/or propagates
1006f32e7eSjoerg // attributes. This is done in an abstract interpretation style fixpoint
1106f32e7eSjoerg // iteration. See the Attributor.h file comment and the class descriptions in
1206f32e7eSjoerg // that file for more information.
1306f32e7eSjoerg //
1406f32e7eSjoerg //===----------------------------------------------------------------------===//
1506f32e7eSjoerg 
1606f32e7eSjoerg #include "llvm/Transforms/IPO/Attributor.h"
1706f32e7eSjoerg 
18*da58b97aSjoerg #include "llvm/ADT/GraphTraits.h"
19*da58b97aSjoerg #include "llvm/ADT/PointerIntPair.h"
2006f32e7eSjoerg #include "llvm/ADT/Statistic.h"
21*da58b97aSjoerg #include "llvm/ADT/TinyPtrVector.h"
22*da58b97aSjoerg #include "llvm/Analysis/InlineCost.h"
23*da58b97aSjoerg #include "llvm/Analysis/LazyValueInfo.h"
24*da58b97aSjoerg #include "llvm/Analysis/MemorySSAUpdater.h"
25*da58b97aSjoerg #include "llvm/Analysis/MustExecute.h"
2606f32e7eSjoerg #include "llvm/Analysis/ValueTracking.h"
2706f32e7eSjoerg #include "llvm/IR/Attributes.h"
28*da58b97aSjoerg #include "llvm/IR/GlobalValue.h"
29*da58b97aSjoerg #include "llvm/IR/IRBuilder.h"
30*da58b97aSjoerg #include "llvm/IR/NoFolder.h"
31*da58b97aSjoerg #include "llvm/IR/Verifier.h"
32*da58b97aSjoerg #include "llvm/InitializePasses.h"
33*da58b97aSjoerg #include "llvm/Support/Casting.h"
3406f32e7eSjoerg #include "llvm/Support/CommandLine.h"
3506f32e7eSjoerg #include "llvm/Support/Debug.h"
36*da58b97aSjoerg #include "llvm/Support/DebugCounter.h"
37*da58b97aSjoerg #include "llvm/Support/FileSystem.h"
38*da58b97aSjoerg #include "llvm/Support/GraphWriter.h"
3906f32e7eSjoerg #include "llvm/Support/raw_ostream.h"
4006f32e7eSjoerg #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41*da58b97aSjoerg #include "llvm/Transforms/Utils/Cloning.h"
4206f32e7eSjoerg #include "llvm/Transforms/Utils/Local.h"
4306f32e7eSjoerg 
4406f32e7eSjoerg #include <cassert>
45*da58b97aSjoerg #include <string>
4606f32e7eSjoerg 
4706f32e7eSjoerg using namespace llvm;
4806f32e7eSjoerg 
4906f32e7eSjoerg #define DEBUG_TYPE "attributor"
5006f32e7eSjoerg 
51*da58b97aSjoerg DEBUG_COUNTER(ManifestDBGCounter, "attributor-manifest",
52*da58b97aSjoerg               "Determine what attributes are manifested in the IR");
53*da58b97aSjoerg 
54*da58b97aSjoerg STATISTIC(NumFnDeleted, "Number of function deleted");
5506f32e7eSjoerg STATISTIC(NumFnWithExactDefinition,
56*da58b97aSjoerg           "Number of functions with exact definitions");
5706f32e7eSjoerg STATISTIC(NumFnWithoutExactDefinition,
58*da58b97aSjoerg           "Number of functions without exact definitions");
59*da58b97aSjoerg STATISTIC(NumFnShallowWrappersCreated, "Number of shallow wrappers created");
6006f32e7eSjoerg STATISTIC(NumAttributesTimedOut,
6106f32e7eSjoerg           "Number of abstract attributes timed out before fixpoint");
6206f32e7eSjoerg STATISTIC(NumAttributesValidFixpoint,
6306f32e7eSjoerg           "Number of abstract attributes in a valid fixpoint state");
6406f32e7eSjoerg STATISTIC(NumAttributesManifested,
6506f32e7eSjoerg           "Number of abstract attributes manifested in IR");
6606f32e7eSjoerg 
6706f32e7eSjoerg // TODO: Determine a good default value.
6806f32e7eSjoerg //
6906f32e7eSjoerg // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads
7006f32e7eSjoerg // (when run with the first 5 abstract attributes). The results also indicate
7106f32e7eSjoerg // that we never reach 32 iterations but always find a fixpoint sooner.
7206f32e7eSjoerg //
7306f32e7eSjoerg // This will become more evolved once we perform two interleaved fixpoint
7406f32e7eSjoerg // iterations: bottom-up and top-down.
7506f32e7eSjoerg static cl::opt<unsigned>
7606f32e7eSjoerg     MaxFixpointIterations("attributor-max-iterations", cl::Hidden,
7706f32e7eSjoerg                           cl::desc("Maximal number of fixpoint iterations."),
7806f32e7eSjoerg                           cl::init(32));
79*da58b97aSjoerg 
80*da58b97aSjoerg static cl::opt<unsigned, true> MaxInitializationChainLengthX(
81*da58b97aSjoerg     "attributor-max-initialization-chain-length", cl::Hidden,
82*da58b97aSjoerg     cl::desc(
83*da58b97aSjoerg         "Maximal number of chained initializations (to avoid stack overflows)"),
84*da58b97aSjoerg     cl::location(MaxInitializationChainLength), cl::init(1024));
85*da58b97aSjoerg unsigned llvm::MaxInitializationChainLength;
86*da58b97aSjoerg 
8706f32e7eSjoerg static cl::opt<bool> VerifyMaxFixpointIterations(
8806f32e7eSjoerg     "attributor-max-iterations-verify", cl::Hidden,
8906f32e7eSjoerg     cl::desc("Verify that max-iterations is a tight bound for a fixpoint"),
9006f32e7eSjoerg     cl::init(false));
9106f32e7eSjoerg 
92*da58b97aSjoerg static cl::opt<bool> AnnotateDeclarationCallSites(
93*da58b97aSjoerg     "attributor-annotate-decl-cs", cl::Hidden,
94*da58b97aSjoerg     cl::desc("Annotate call sites of function declarations."), cl::init(false));
9506f32e7eSjoerg 
9606f32e7eSjoerg static cl::opt<bool> EnableHeapToStack("enable-heap-to-stack-conversion",
9706f32e7eSjoerg                                        cl::init(true), cl::Hidden);
9806f32e7eSjoerg 
99*da58b97aSjoerg static cl::opt<bool>
100*da58b97aSjoerg     AllowShallowWrappers("attributor-allow-shallow-wrappers", cl::Hidden,
101*da58b97aSjoerg                          cl::desc("Allow the Attributor to create shallow "
102*da58b97aSjoerg                                   "wrappers for non-exact definitions."),
103*da58b97aSjoerg                          cl::init(false));
104*da58b97aSjoerg 
105*da58b97aSjoerg static cl::opt<bool>
106*da58b97aSjoerg     AllowDeepWrapper("attributor-allow-deep-wrappers", cl::Hidden,
107*da58b97aSjoerg                      cl::desc("Allow the Attributor to use IP information "
108*da58b97aSjoerg                               "derived from non-exact functions via cloning"),
109*da58b97aSjoerg                      cl::init(false));
110*da58b97aSjoerg 
111*da58b97aSjoerg // These options can only used for debug builds.
112*da58b97aSjoerg #ifndef NDEBUG
113*da58b97aSjoerg static cl::list<std::string>
114*da58b97aSjoerg     SeedAllowList("attributor-seed-allow-list", cl::Hidden,
115*da58b97aSjoerg                   cl::desc("Comma seperated list of attribute names that are "
116*da58b97aSjoerg                            "allowed to be seeded."),
117*da58b97aSjoerg                   cl::ZeroOrMore, cl::CommaSeparated);
118*da58b97aSjoerg 
119*da58b97aSjoerg static cl::list<std::string> FunctionSeedAllowList(
120*da58b97aSjoerg     "attributor-function-seed-allow-list", cl::Hidden,
121*da58b97aSjoerg     cl::desc("Comma seperated list of function names that are "
122*da58b97aSjoerg              "allowed to be seeded."),
123*da58b97aSjoerg     cl::ZeroOrMore, cl::CommaSeparated);
124*da58b97aSjoerg #endif
125*da58b97aSjoerg 
126*da58b97aSjoerg static cl::opt<bool>
127*da58b97aSjoerg     DumpDepGraph("attributor-dump-dep-graph", cl::Hidden,
128*da58b97aSjoerg                  cl::desc("Dump the dependency graph to dot files."),
129*da58b97aSjoerg                  cl::init(false));
130*da58b97aSjoerg 
131*da58b97aSjoerg static cl::opt<std::string> DepGraphDotFileNamePrefix(
132*da58b97aSjoerg     "attributor-depgraph-dot-filename-prefix", cl::Hidden,
133*da58b97aSjoerg     cl::desc("The prefix used for the CallGraph dot file names."));
134*da58b97aSjoerg 
135*da58b97aSjoerg static cl::opt<bool> ViewDepGraph("attributor-view-dep-graph", cl::Hidden,
136*da58b97aSjoerg                                   cl::desc("View the dependency graph."),
137*da58b97aSjoerg                                   cl::init(false));
138*da58b97aSjoerg 
139*da58b97aSjoerg static cl::opt<bool> PrintDependencies("attributor-print-dep", cl::Hidden,
140*da58b97aSjoerg                                        cl::desc("Print attribute dependencies"),
141*da58b97aSjoerg                                        cl::init(false));
142*da58b97aSjoerg 
143*da58b97aSjoerg static cl::opt<bool> EnableCallSiteSpecific(
144*da58b97aSjoerg     "attributor-enable-call-site-specific-deduction", cl::Hidden,
145*da58b97aSjoerg     cl::desc("Allow the Attributor to do call site specific analysis"),
146*da58b97aSjoerg     cl::init(false));
14706f32e7eSjoerg 
14806f32e7eSjoerg /// Logic operators for the change status enum class.
14906f32e7eSjoerg ///
15006f32e7eSjoerg ///{
operator |(ChangeStatus L,ChangeStatus R)151*da58b97aSjoerg ChangeStatus llvm::operator|(ChangeStatus L, ChangeStatus R) {
152*da58b97aSjoerg   return L == ChangeStatus::CHANGED ? L : R;
15306f32e7eSjoerg }
operator &(ChangeStatus L,ChangeStatus R)154*da58b97aSjoerg ChangeStatus llvm::operator&(ChangeStatus L, ChangeStatus R) {
155*da58b97aSjoerg   return L == ChangeStatus::UNCHANGED ? L : R;
15606f32e7eSjoerg }
15706f32e7eSjoerg ///}
15806f32e7eSjoerg 
15906f32e7eSjoerg /// Return true if \p New is equal or worse than \p Old.
isEqualOrWorse(const Attribute & New,const Attribute & Old)16006f32e7eSjoerg static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) {
16106f32e7eSjoerg   if (!Old.isIntAttribute())
16206f32e7eSjoerg     return true;
16306f32e7eSjoerg 
16406f32e7eSjoerg   return Old.getValueAsInt() >= New.getValueAsInt();
16506f32e7eSjoerg }
16606f32e7eSjoerg 
16706f32e7eSjoerg /// Return true if the information provided by \p Attr was added to the
16806f32e7eSjoerg /// attribute list \p Attrs. This is only the case if it was not already present
16906f32e7eSjoerg /// in \p Attrs at the position describe by \p PK and \p AttrIdx.
addIfNotExistent(LLVMContext & Ctx,const Attribute & Attr,AttributeList & Attrs,int AttrIdx)17006f32e7eSjoerg static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr,
17106f32e7eSjoerg                              AttributeList &Attrs, int AttrIdx) {
17206f32e7eSjoerg 
17306f32e7eSjoerg   if (Attr.isEnumAttribute()) {
17406f32e7eSjoerg     Attribute::AttrKind Kind = Attr.getKindAsEnum();
17506f32e7eSjoerg     if (Attrs.hasAttribute(AttrIdx, Kind))
17606f32e7eSjoerg       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
17706f32e7eSjoerg         return false;
17806f32e7eSjoerg     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
17906f32e7eSjoerg     return true;
18006f32e7eSjoerg   }
18106f32e7eSjoerg   if (Attr.isStringAttribute()) {
18206f32e7eSjoerg     StringRef Kind = Attr.getKindAsString();
18306f32e7eSjoerg     if (Attrs.hasAttribute(AttrIdx, Kind))
18406f32e7eSjoerg       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
18506f32e7eSjoerg         return false;
18606f32e7eSjoerg     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
18706f32e7eSjoerg     return true;
18806f32e7eSjoerg   }
18906f32e7eSjoerg   if (Attr.isIntAttribute()) {
19006f32e7eSjoerg     Attribute::AttrKind Kind = Attr.getKindAsEnum();
19106f32e7eSjoerg     if (Attrs.hasAttribute(AttrIdx, Kind))
19206f32e7eSjoerg       if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind)))
19306f32e7eSjoerg         return false;
19406f32e7eSjoerg     Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind);
19506f32e7eSjoerg     Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr);
19606f32e7eSjoerg     return true;
19706f32e7eSjoerg   }
19806f32e7eSjoerg 
19906f32e7eSjoerg   llvm_unreachable("Expected enum or string attribute!");
20006f32e7eSjoerg }
20106f32e7eSjoerg 
getAssociatedArgument() const202*da58b97aSjoerg Argument *IRPosition::getAssociatedArgument() const {
203*da58b97aSjoerg   if (getPositionKind() == IRP_ARGUMENT)
204*da58b97aSjoerg     return cast<Argument>(&getAnchorValue());
20506f32e7eSjoerg 
206*da58b97aSjoerg   // Not an Argument and no argument number means this is not a call site
207*da58b97aSjoerg   // argument, thus we cannot find a callback argument to return.
208*da58b97aSjoerg   int ArgNo = getCallSiteArgNo();
209*da58b97aSjoerg   if (ArgNo < 0)
21006f32e7eSjoerg     return nullptr;
211*da58b97aSjoerg 
212*da58b97aSjoerg   // Use abstract call sites to make the connection between the call site
213*da58b97aSjoerg   // values and the ones in callbacks. If a callback was found that makes use
214*da58b97aSjoerg   // of the underlying call site operand, we want the corresponding callback
215*da58b97aSjoerg   // callee argument and not the direct callee argument.
216*da58b97aSjoerg   Optional<Argument *> CBCandidateArg;
217*da58b97aSjoerg   SmallVector<const Use *, 4> CallbackUses;
218*da58b97aSjoerg   const auto &CB = cast<CallBase>(getAnchorValue());
219*da58b97aSjoerg   AbstractCallSite::getCallbackUses(CB, CallbackUses);
220*da58b97aSjoerg   for (const Use *U : CallbackUses) {
221*da58b97aSjoerg     AbstractCallSite ACS(U);
222*da58b97aSjoerg     assert(ACS && ACS.isCallbackCall());
223*da58b97aSjoerg     if (!ACS.getCalledFunction())
224*da58b97aSjoerg       continue;
225*da58b97aSjoerg 
226*da58b97aSjoerg     for (unsigned u = 0, e = ACS.getNumArgOperands(); u < e; u++) {
227*da58b97aSjoerg 
228*da58b97aSjoerg       // Test if the underlying call site operand is argument number u of the
229*da58b97aSjoerg       // callback callee.
230*da58b97aSjoerg       if (ACS.getCallArgOperandNo(u) != ArgNo)
231*da58b97aSjoerg         continue;
232*da58b97aSjoerg 
233*da58b97aSjoerg       assert(ACS.getCalledFunction()->arg_size() > u &&
234*da58b97aSjoerg              "ACS mapped into var-args arguments!");
235*da58b97aSjoerg       if (CBCandidateArg.hasValue()) {
236*da58b97aSjoerg         CBCandidateArg = nullptr;
237*da58b97aSjoerg         break;
23806f32e7eSjoerg       }
239*da58b97aSjoerg       CBCandidateArg = ACS.getCalledFunction()->getArg(u);
240*da58b97aSjoerg     }
241*da58b97aSjoerg   }
24206f32e7eSjoerg 
243*da58b97aSjoerg   // If we found a unique callback candidate argument, return it.
244*da58b97aSjoerg   if (CBCandidateArg.hasValue() && CBCandidateArg.getValue())
245*da58b97aSjoerg     return CBCandidateArg.getValue();
246*da58b97aSjoerg 
247*da58b97aSjoerg   // If no callbacks were found, or none used the underlying call site operand
248*da58b97aSjoerg   // exclusively, use the direct callee argument if available.
249*da58b97aSjoerg   const Function *Callee = CB.getCalledFunction();
250*da58b97aSjoerg   if (Callee && Callee->arg_size() > unsigned(ArgNo))
251*da58b97aSjoerg     return Callee->getArg(ArgNo);
252*da58b97aSjoerg 
253*da58b97aSjoerg   return nullptr;
25406f32e7eSjoerg }
25506f32e7eSjoerg 
update(Attributor & A)25606f32e7eSjoerg ChangeStatus AbstractAttribute::update(Attributor &A) {
25706f32e7eSjoerg   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
25806f32e7eSjoerg   if (getState().isAtFixpoint())
25906f32e7eSjoerg     return HasChanged;
26006f32e7eSjoerg 
26106f32e7eSjoerg   LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n");
26206f32e7eSjoerg 
26306f32e7eSjoerg   HasChanged = updateImpl(A);
26406f32e7eSjoerg 
26506f32e7eSjoerg   LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this
26606f32e7eSjoerg                     << "\n");
26706f32e7eSjoerg 
26806f32e7eSjoerg   return HasChanged;
26906f32e7eSjoerg }
27006f32e7eSjoerg 
27106f32e7eSjoerg ChangeStatus
manifestAttrs(Attributor & A,const IRPosition & IRP,const ArrayRef<Attribute> & DeducedAttrs)272*da58b97aSjoerg IRAttributeManifest::manifestAttrs(Attributor &A, const IRPosition &IRP,
27306f32e7eSjoerg                                    const ArrayRef<Attribute> &DeducedAttrs) {
274*da58b97aSjoerg   Function *ScopeFn = IRP.getAnchorScope();
27506f32e7eSjoerg   IRPosition::Kind PK = IRP.getPositionKind();
27606f32e7eSjoerg 
27706f32e7eSjoerg   // In the following some generic code that will manifest attributes in
27806f32e7eSjoerg   // DeducedAttrs if they improve the current IR. Due to the different
27906f32e7eSjoerg   // annotation positions we use the underlying AttributeList interface.
28006f32e7eSjoerg 
28106f32e7eSjoerg   AttributeList Attrs;
28206f32e7eSjoerg   switch (PK) {
28306f32e7eSjoerg   case IRPosition::IRP_INVALID:
28406f32e7eSjoerg   case IRPosition::IRP_FLOAT:
28506f32e7eSjoerg     return ChangeStatus::UNCHANGED;
28606f32e7eSjoerg   case IRPosition::IRP_ARGUMENT:
28706f32e7eSjoerg   case IRPosition::IRP_FUNCTION:
28806f32e7eSjoerg   case IRPosition::IRP_RETURNED:
28906f32e7eSjoerg     Attrs = ScopeFn->getAttributes();
29006f32e7eSjoerg     break;
29106f32e7eSjoerg   case IRPosition::IRP_CALL_SITE:
29206f32e7eSjoerg   case IRPosition::IRP_CALL_SITE_RETURNED:
29306f32e7eSjoerg   case IRPosition::IRP_CALL_SITE_ARGUMENT:
294*da58b97aSjoerg     Attrs = cast<CallBase>(IRP.getAnchorValue()).getAttributes();
29506f32e7eSjoerg     break;
29606f32e7eSjoerg   }
29706f32e7eSjoerg 
29806f32e7eSjoerg   ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
29906f32e7eSjoerg   LLVMContext &Ctx = IRP.getAnchorValue().getContext();
30006f32e7eSjoerg   for (const Attribute &Attr : DeducedAttrs) {
30106f32e7eSjoerg     if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx()))
30206f32e7eSjoerg       continue;
30306f32e7eSjoerg 
30406f32e7eSjoerg     HasChanged = ChangeStatus::CHANGED;
30506f32e7eSjoerg   }
30606f32e7eSjoerg 
30706f32e7eSjoerg   if (HasChanged == ChangeStatus::UNCHANGED)
30806f32e7eSjoerg     return HasChanged;
30906f32e7eSjoerg 
31006f32e7eSjoerg   switch (PK) {
31106f32e7eSjoerg   case IRPosition::IRP_ARGUMENT:
31206f32e7eSjoerg   case IRPosition::IRP_FUNCTION:
31306f32e7eSjoerg   case IRPosition::IRP_RETURNED:
31406f32e7eSjoerg     ScopeFn->setAttributes(Attrs);
31506f32e7eSjoerg     break;
31606f32e7eSjoerg   case IRPosition::IRP_CALL_SITE:
31706f32e7eSjoerg   case IRPosition::IRP_CALL_SITE_RETURNED:
31806f32e7eSjoerg   case IRPosition::IRP_CALL_SITE_ARGUMENT:
319*da58b97aSjoerg     cast<CallBase>(IRP.getAnchorValue()).setAttributes(Attrs);
32006f32e7eSjoerg     break;
32106f32e7eSjoerg   case IRPosition::IRP_INVALID:
32206f32e7eSjoerg   case IRPosition::IRP_FLOAT:
32306f32e7eSjoerg     break;
32406f32e7eSjoerg   }
32506f32e7eSjoerg 
32606f32e7eSjoerg   return HasChanged;
32706f32e7eSjoerg }
32806f32e7eSjoerg 
329*da58b97aSjoerg const IRPosition IRPosition::EmptyKey(DenseMapInfo<void *>::getEmptyKey());
330*da58b97aSjoerg const IRPosition
331*da58b97aSjoerg     IRPosition::TombstoneKey(DenseMapInfo<void *>::getTombstoneKey());
33206f32e7eSjoerg 
SubsumingPositionIterator(const IRPosition & IRP)33306f32e7eSjoerg SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) {
33406f32e7eSjoerg   IRPositions.emplace_back(IRP);
33506f32e7eSjoerg 
336*da58b97aSjoerg   // Helper to determine if operand bundles on a call site are benin or
337*da58b97aSjoerg   // potentially problematic. We handle only llvm.assume for now.
338*da58b97aSjoerg   auto CanIgnoreOperandBundles = [](const CallBase &CB) {
339*da58b97aSjoerg     return (isa<IntrinsicInst>(CB) &&
340*da58b97aSjoerg             cast<IntrinsicInst>(CB).getIntrinsicID() == Intrinsic ::assume);
341*da58b97aSjoerg   };
342*da58b97aSjoerg 
343*da58b97aSjoerg   const auto *CB = dyn_cast<CallBase>(&IRP.getAnchorValue());
34406f32e7eSjoerg   switch (IRP.getPositionKind()) {
34506f32e7eSjoerg   case IRPosition::IRP_INVALID:
34606f32e7eSjoerg   case IRPosition::IRP_FLOAT:
34706f32e7eSjoerg   case IRPosition::IRP_FUNCTION:
34806f32e7eSjoerg     return;
34906f32e7eSjoerg   case IRPosition::IRP_ARGUMENT:
35006f32e7eSjoerg   case IRPosition::IRP_RETURNED:
351*da58b97aSjoerg     IRPositions.emplace_back(IRPosition::function(*IRP.getAnchorScope()));
35206f32e7eSjoerg     return;
35306f32e7eSjoerg   case IRPosition::IRP_CALL_SITE:
354*da58b97aSjoerg     assert(CB && "Expected call site!");
35506f32e7eSjoerg     // TODO: We need to look at the operand bundles similar to the redirection
35606f32e7eSjoerg     //       in CallBase.
357*da58b97aSjoerg     if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB))
358*da58b97aSjoerg       if (const Function *Callee = CB->getCalledFunction())
35906f32e7eSjoerg         IRPositions.emplace_back(IRPosition::function(*Callee));
36006f32e7eSjoerg     return;
36106f32e7eSjoerg   case IRPosition::IRP_CALL_SITE_RETURNED:
362*da58b97aSjoerg     assert(CB && "Expected call site!");
36306f32e7eSjoerg     // TODO: We need to look at the operand bundles similar to the redirection
36406f32e7eSjoerg     //       in CallBase.
365*da58b97aSjoerg     if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
366*da58b97aSjoerg       if (const Function *Callee = CB->getCalledFunction()) {
36706f32e7eSjoerg         IRPositions.emplace_back(IRPosition::returned(*Callee));
36806f32e7eSjoerg         IRPositions.emplace_back(IRPosition::function(*Callee));
369*da58b97aSjoerg         for (const Argument &Arg : Callee->args())
370*da58b97aSjoerg           if (Arg.hasReturnedAttr()) {
37106f32e7eSjoerg             IRPositions.emplace_back(
372*da58b97aSjoerg                 IRPosition::callsite_argument(*CB, Arg.getArgNo()));
373*da58b97aSjoerg             IRPositions.emplace_back(
374*da58b97aSjoerg                 IRPosition::value(*CB->getArgOperand(Arg.getArgNo())));
375*da58b97aSjoerg             IRPositions.emplace_back(IRPosition::argument(Arg));
376*da58b97aSjoerg           }
377*da58b97aSjoerg       }
378*da58b97aSjoerg     }
379*da58b97aSjoerg     IRPositions.emplace_back(IRPosition::callsite_function(*CB));
38006f32e7eSjoerg     return;
38106f32e7eSjoerg   case IRPosition::IRP_CALL_SITE_ARGUMENT: {
382*da58b97aSjoerg     assert(CB && "Expected call site!");
38306f32e7eSjoerg     // TODO: We need to look at the operand bundles similar to the redirection
38406f32e7eSjoerg     //       in CallBase.
385*da58b97aSjoerg     if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
386*da58b97aSjoerg       const Function *Callee = CB->getCalledFunction();
387*da58b97aSjoerg       if (Callee) {
388*da58b97aSjoerg         if (Argument *Arg = IRP.getAssociatedArgument())
389*da58b97aSjoerg           IRPositions.emplace_back(IRPosition::argument(*Arg));
39006f32e7eSjoerg         IRPositions.emplace_back(IRPosition::function(*Callee));
39106f32e7eSjoerg       }
392*da58b97aSjoerg     }
39306f32e7eSjoerg     IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue()));
39406f32e7eSjoerg     return;
39506f32e7eSjoerg   }
39606f32e7eSjoerg   }
39706f32e7eSjoerg }
39806f32e7eSjoerg 
hasAttr(ArrayRef<Attribute::AttrKind> AKs,bool IgnoreSubsumingPositions,Attributor * A) const39906f32e7eSjoerg bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs,
400*da58b97aSjoerg                          bool IgnoreSubsumingPositions, Attributor *A) const {
401*da58b97aSjoerg   SmallVector<Attribute, 4> Attrs;
40206f32e7eSjoerg   for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) {
40306f32e7eSjoerg     for (Attribute::AttrKind AK : AKs)
404*da58b97aSjoerg       if (EquivIRP.getAttrsFromIRAttr(AK, Attrs))
40506f32e7eSjoerg         return true;
40606f32e7eSjoerg     // The first position returned by the SubsumingPositionIterator is
40706f32e7eSjoerg     // always the position itself. If we ignore subsuming positions we
40806f32e7eSjoerg     // are done after the first iteration.
40906f32e7eSjoerg     if (IgnoreSubsumingPositions)
41006f32e7eSjoerg       break;
41106f32e7eSjoerg   }
412*da58b97aSjoerg   if (A)
413*da58b97aSjoerg     for (Attribute::AttrKind AK : AKs)
414*da58b97aSjoerg       if (getAttrsFromAssumes(AK, Attrs, *A))
415*da58b97aSjoerg         return true;
41606f32e7eSjoerg   return false;
41706f32e7eSjoerg }
41806f32e7eSjoerg 
getAttrs(ArrayRef<Attribute::AttrKind> AKs,SmallVectorImpl<Attribute> & Attrs,bool IgnoreSubsumingPositions,Attributor * A) const41906f32e7eSjoerg void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs,
420*da58b97aSjoerg                           SmallVectorImpl<Attribute> &Attrs,
421*da58b97aSjoerg                           bool IgnoreSubsumingPositions, Attributor *A) const {
422*da58b97aSjoerg   for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) {
423*da58b97aSjoerg     for (Attribute::AttrKind AK : AKs)
424*da58b97aSjoerg       EquivIRP.getAttrsFromIRAttr(AK, Attrs);
425*da58b97aSjoerg     // The first position returned by the SubsumingPositionIterator is
426*da58b97aSjoerg     // always the position itself. If we ignore subsuming positions we
427*da58b97aSjoerg     // are done after the first iteration.
428*da58b97aSjoerg     if (IgnoreSubsumingPositions)
429*da58b97aSjoerg       break;
43006f32e7eSjoerg   }
431*da58b97aSjoerg   if (A)
432*da58b97aSjoerg     for (Attribute::AttrKind AK : AKs)
433*da58b97aSjoerg       getAttrsFromAssumes(AK, Attrs, *A);
434*da58b97aSjoerg }
435*da58b97aSjoerg 
getAttrsFromIRAttr(Attribute::AttrKind AK,SmallVectorImpl<Attribute> & Attrs) const436*da58b97aSjoerg bool IRPosition::getAttrsFromIRAttr(Attribute::AttrKind AK,
437*da58b97aSjoerg                                     SmallVectorImpl<Attribute> &Attrs) const {
438*da58b97aSjoerg   if (getPositionKind() == IRP_INVALID || getPositionKind() == IRP_FLOAT)
439*da58b97aSjoerg     return false;
440*da58b97aSjoerg 
441*da58b97aSjoerg   AttributeList AttrList;
442*da58b97aSjoerg   if (const auto *CB = dyn_cast<CallBase>(&getAnchorValue()))
443*da58b97aSjoerg     AttrList = CB->getAttributes();
444*da58b97aSjoerg   else
445*da58b97aSjoerg     AttrList = getAssociatedFunction()->getAttributes();
446*da58b97aSjoerg 
447*da58b97aSjoerg   bool HasAttr = AttrList.hasAttribute(getAttrIdx(), AK);
448*da58b97aSjoerg   if (HasAttr)
449*da58b97aSjoerg     Attrs.push_back(AttrList.getAttribute(getAttrIdx(), AK));
450*da58b97aSjoerg   return HasAttr;
451*da58b97aSjoerg }
452*da58b97aSjoerg 
getAttrsFromAssumes(Attribute::AttrKind AK,SmallVectorImpl<Attribute> & Attrs,Attributor & A) const453*da58b97aSjoerg bool IRPosition::getAttrsFromAssumes(Attribute::AttrKind AK,
454*da58b97aSjoerg                                      SmallVectorImpl<Attribute> &Attrs,
455*da58b97aSjoerg                                      Attributor &A) const {
456*da58b97aSjoerg   assert(getPositionKind() != IRP_INVALID && "Did expect a valid position!");
457*da58b97aSjoerg   Value &AssociatedValue = getAssociatedValue();
458*da58b97aSjoerg 
459*da58b97aSjoerg   const Assume2KnowledgeMap &A2K =
460*da58b97aSjoerg       A.getInfoCache().getKnowledgeMap().lookup({&AssociatedValue, AK});
461*da58b97aSjoerg 
462*da58b97aSjoerg   // Check if we found any potential assume use, if not we don't need to create
463*da58b97aSjoerg   // explorer iterators.
464*da58b97aSjoerg   if (A2K.empty())
465*da58b97aSjoerg     return false;
466*da58b97aSjoerg 
467*da58b97aSjoerg   LLVMContext &Ctx = AssociatedValue.getContext();
468*da58b97aSjoerg   unsigned AttrsSize = Attrs.size();
469*da58b97aSjoerg   MustBeExecutedContextExplorer &Explorer =
470*da58b97aSjoerg       A.getInfoCache().getMustBeExecutedContextExplorer();
471*da58b97aSjoerg   auto EIt = Explorer.begin(getCtxI()), EEnd = Explorer.end(getCtxI());
472*da58b97aSjoerg   for (auto &It : A2K)
473*da58b97aSjoerg     if (Explorer.findInContextOf(It.first, EIt, EEnd))
474*da58b97aSjoerg       Attrs.push_back(Attribute::get(Ctx, AK, It.second.Max));
475*da58b97aSjoerg   return AttrsSize != Attrs.size();
47606f32e7eSjoerg }
47706f32e7eSjoerg 
verify()47806f32e7eSjoerg void IRPosition::verify() {
479*da58b97aSjoerg #ifdef EXPENSIVE_CHECKS
480*da58b97aSjoerg   switch (getPositionKind()) {
48106f32e7eSjoerg   case IRP_INVALID:
482*da58b97aSjoerg     assert((CBContext == nullptr) &&
483*da58b97aSjoerg            "Invalid position must not have CallBaseContext!");
484*da58b97aSjoerg     assert(!Enc.getOpaqueValue() &&
485*da58b97aSjoerg            "Expected a nullptr for an invalid position!");
486*da58b97aSjoerg     return;
48706f32e7eSjoerg   case IRP_FLOAT:
48806f32e7eSjoerg     assert((!isa<CallBase>(&getAssociatedValue()) &&
48906f32e7eSjoerg             !isa<Argument>(&getAssociatedValue())) &&
49006f32e7eSjoerg            "Expected specialized kind for call base and argument values!");
491*da58b97aSjoerg     return;
49206f32e7eSjoerg   case IRP_RETURNED:
493*da58b97aSjoerg     assert(isa<Function>(getAsValuePtr()) &&
49406f32e7eSjoerg            "Expected function for a 'returned' position!");
495*da58b97aSjoerg     assert(getAsValuePtr() == &getAssociatedValue() &&
496*da58b97aSjoerg            "Associated value mismatch!");
497*da58b97aSjoerg     return;
49806f32e7eSjoerg   case IRP_CALL_SITE_RETURNED:
499*da58b97aSjoerg     assert((CBContext == nullptr) &&
500*da58b97aSjoerg            "'call site returned' position must not have CallBaseContext!");
501*da58b97aSjoerg     assert((isa<CallBase>(getAsValuePtr())) &&
50206f32e7eSjoerg            "Expected call base for 'call site returned' position!");
503*da58b97aSjoerg     assert(getAsValuePtr() == &getAssociatedValue() &&
504*da58b97aSjoerg            "Associated value mismatch!");
505*da58b97aSjoerg     return;
50606f32e7eSjoerg   case IRP_CALL_SITE:
507*da58b97aSjoerg     assert((CBContext == nullptr) &&
508*da58b97aSjoerg            "'call site function' position must not have CallBaseContext!");
509*da58b97aSjoerg     assert((isa<CallBase>(getAsValuePtr())) &&
51006f32e7eSjoerg            "Expected call base for 'call site function' position!");
511*da58b97aSjoerg     assert(getAsValuePtr() == &getAssociatedValue() &&
512*da58b97aSjoerg            "Associated value mismatch!");
513*da58b97aSjoerg     return;
51406f32e7eSjoerg   case IRP_FUNCTION:
515*da58b97aSjoerg     assert(isa<Function>(getAsValuePtr()) &&
51606f32e7eSjoerg            "Expected function for a 'function' position!");
517*da58b97aSjoerg     assert(getAsValuePtr() == &getAssociatedValue() &&
518*da58b97aSjoerg            "Associated value mismatch!");
51906f32e7eSjoerg     return;
520*da58b97aSjoerg   case IRP_ARGUMENT:
521*da58b97aSjoerg     assert(isa<Argument>(getAsValuePtr()) &&
522*da58b97aSjoerg            "Expected argument for a 'argument' position!");
523*da58b97aSjoerg     assert(getAsValuePtr() == &getAssociatedValue() &&
524*da58b97aSjoerg            "Associated value mismatch!");
52506f32e7eSjoerg     return;
526*da58b97aSjoerg   case IRP_CALL_SITE_ARGUMENT: {
527*da58b97aSjoerg     assert((CBContext == nullptr) &&
528*da58b97aSjoerg            "'call site argument' position must not have CallBaseContext!");
529*da58b97aSjoerg     Use *U = getAsUsePtr();
530*da58b97aSjoerg     assert(U && "Expected use for a 'call site argument' position!");
531*da58b97aSjoerg     assert(isa<CallBase>(U->getUser()) &&
532*da58b97aSjoerg            "Expected call base user for a 'call site argument' position!");
533*da58b97aSjoerg     assert(cast<CallBase>(U->getUser())->isArgOperand(U) &&
534*da58b97aSjoerg            "Expected call base argument operand for a 'call site argument' "
535*da58b97aSjoerg            "position");
536*da58b97aSjoerg     assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) ==
537*da58b97aSjoerg                unsigned(getCallSiteArgNo()) &&
538*da58b97aSjoerg            "Argument number mismatch!");
539*da58b97aSjoerg     assert(U->get() == &getAssociatedValue() && "Associated value mismatch!");
54006f32e7eSjoerg     return;
54106f32e7eSjoerg   }
54206f32e7eSjoerg   }
543*da58b97aSjoerg #endif
54406f32e7eSjoerg }
54506f32e7eSjoerg 
546*da58b97aSjoerg Optional<Constant *>
getAssumedConstant(const Value & V,const AbstractAttribute & AA,bool & UsedAssumedInformation)547*da58b97aSjoerg Attributor::getAssumedConstant(const Value &V, const AbstractAttribute &AA,
548*da58b97aSjoerg                                bool &UsedAssumedInformation) {
549*da58b97aSjoerg   const auto &ValueSimplifyAA = getAAFor<AAValueSimplify>(
550*da58b97aSjoerg       AA, IRPosition::value(V, AA.getCallBaseContext()), DepClassTy::NONE);
551*da58b97aSjoerg   Optional<Value *> SimplifiedV =
552*da58b97aSjoerg       ValueSimplifyAA.getAssumedSimplifiedValue(*this);
553*da58b97aSjoerg   bool IsKnown = ValueSimplifyAA.isKnown();
554*da58b97aSjoerg   UsedAssumedInformation |= !IsKnown;
555*da58b97aSjoerg   if (!SimplifiedV.hasValue()) {
556*da58b97aSjoerg     recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL);
557*da58b97aSjoerg     return llvm::None;
55806f32e7eSjoerg   }
559*da58b97aSjoerg   if (isa_and_nonnull<UndefValue>(SimplifiedV.getValue())) {
560*da58b97aSjoerg     recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL);
561*da58b97aSjoerg     return llvm::None;
56206f32e7eSjoerg   }
563*da58b97aSjoerg   Constant *CI = dyn_cast_or_null<Constant>(SimplifiedV.getValue());
564*da58b97aSjoerg   if (CI && CI->getType() != V.getType()) {
565*da58b97aSjoerg     // TODO: Check for a save conversion.
56606f32e7eSjoerg     return nullptr;
56706f32e7eSjoerg   }
568*da58b97aSjoerg   if (CI)
569*da58b97aSjoerg     recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL);
570*da58b97aSjoerg   return CI;
57106f32e7eSjoerg }
57206f32e7eSjoerg 
~Attributor()573*da58b97aSjoerg Attributor::~Attributor() {
574*da58b97aSjoerg   // The abstract attributes are allocated via the BumpPtrAllocator Allocator,
575*da58b97aSjoerg   // thus we cannot delete them. We can, and want to, destruct them though.
576*da58b97aSjoerg   for (auto &DepAA : DG.SyntheticRoot.Deps) {
577*da58b97aSjoerg     AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer());
578*da58b97aSjoerg     AA->~AbstractAttribute();
57906f32e7eSjoerg   }
58006f32e7eSjoerg }
58106f32e7eSjoerg 
isAssumedDead(const AbstractAttribute & AA,const AAIsDead * FnLivenessAA,bool CheckBBLivenessOnly,DepClassTy DepClass)582*da58b97aSjoerg bool Attributor::isAssumedDead(const AbstractAttribute &AA,
583*da58b97aSjoerg                                const AAIsDead *FnLivenessAA,
584*da58b97aSjoerg                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
585*da58b97aSjoerg   const IRPosition &IRP = AA.getIRPosition();
586*da58b97aSjoerg   if (!Functions.count(IRP.getAnchorScope()))
587*da58b97aSjoerg     return false;
588*da58b97aSjoerg   return isAssumedDead(IRP, &AA, FnLivenessAA, CheckBBLivenessOnly, DepClass);
58906f32e7eSjoerg }
59006f32e7eSjoerg 
isAssumedDead(const Use & U,const AbstractAttribute * QueryingAA,const AAIsDead * FnLivenessAA,bool CheckBBLivenessOnly,DepClassTy DepClass)591*da58b97aSjoerg bool Attributor::isAssumedDead(const Use &U,
592*da58b97aSjoerg                                const AbstractAttribute *QueryingAA,
593*da58b97aSjoerg                                const AAIsDead *FnLivenessAA,
594*da58b97aSjoerg                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
595*da58b97aSjoerg   Instruction *UserI = dyn_cast<Instruction>(U.getUser());
596*da58b97aSjoerg   if (!UserI)
597*da58b97aSjoerg     return isAssumedDead(IRPosition::value(*U.get()), QueryingAA, FnLivenessAA,
598*da58b97aSjoerg                          CheckBBLivenessOnly, DepClass);
599*da58b97aSjoerg 
600*da58b97aSjoerg   if (auto *CB = dyn_cast<CallBase>(UserI)) {
601*da58b97aSjoerg     // For call site argument uses we can check if the argument is
602*da58b97aSjoerg     // unused/dead.
603*da58b97aSjoerg     if (CB->isArgOperand(&U)) {
604*da58b97aSjoerg       const IRPosition &CSArgPos =
605*da58b97aSjoerg           IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U));
606*da58b97aSjoerg       return isAssumedDead(CSArgPos, QueryingAA, FnLivenessAA,
607*da58b97aSjoerg                            CheckBBLivenessOnly, DepClass);
608*da58b97aSjoerg     }
609*da58b97aSjoerg   } else if (ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) {
610*da58b97aSjoerg     const IRPosition &RetPos = IRPosition::returned(*RI->getFunction());
611*da58b97aSjoerg     return isAssumedDead(RetPos, QueryingAA, FnLivenessAA, CheckBBLivenessOnly,
612*da58b97aSjoerg                          DepClass);
613*da58b97aSjoerg   } else if (PHINode *PHI = dyn_cast<PHINode>(UserI)) {
614*da58b97aSjoerg     BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
615*da58b97aSjoerg     return isAssumedDead(*IncomingBB->getTerminator(), QueryingAA, FnLivenessAA,
616*da58b97aSjoerg                          CheckBBLivenessOnly, DepClass);
61706f32e7eSjoerg   }
61806f32e7eSjoerg 
619*da58b97aSjoerg   return isAssumedDead(IRPosition::value(*UserI), QueryingAA, FnLivenessAA,
620*da58b97aSjoerg                        CheckBBLivenessOnly, DepClass);
62106f32e7eSjoerg }
62206f32e7eSjoerg 
isAssumedDead(const Instruction & I,const AbstractAttribute * QueryingAA,const AAIsDead * FnLivenessAA,bool CheckBBLivenessOnly,DepClassTy DepClass)623*da58b97aSjoerg bool Attributor::isAssumedDead(const Instruction &I,
624*da58b97aSjoerg                                const AbstractAttribute *QueryingAA,
625*da58b97aSjoerg                                const AAIsDead *FnLivenessAA,
626*da58b97aSjoerg                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
627*da58b97aSjoerg   const IRPosition::CallBaseContext *CBCtx =
628*da58b97aSjoerg       QueryingAA ? QueryingAA->getCallBaseContext() : nullptr;
629*da58b97aSjoerg 
630*da58b97aSjoerg   if (!FnLivenessAA)
631*da58b97aSjoerg     FnLivenessAA =
632*da58b97aSjoerg         lookupAAFor<AAIsDead>(IRPosition::function(*I.getFunction(), CBCtx),
633*da58b97aSjoerg                               QueryingAA, DepClassTy::NONE);
634*da58b97aSjoerg 
635*da58b97aSjoerg   // If we have a context instruction and a liveness AA we use it.
636*da58b97aSjoerg   if (FnLivenessAA &&
637*da58b97aSjoerg       FnLivenessAA->getIRPosition().getAnchorScope() == I.getFunction() &&
638*da58b97aSjoerg       FnLivenessAA->isAssumedDead(&I)) {
639*da58b97aSjoerg     if (QueryingAA)
640*da58b97aSjoerg       recordDependence(*FnLivenessAA, *QueryingAA, DepClass);
641*da58b97aSjoerg     return true;
64206f32e7eSjoerg   }
64306f32e7eSjoerg 
644*da58b97aSjoerg   if (CheckBBLivenessOnly)
645*da58b97aSjoerg     return false;
64606f32e7eSjoerg 
647*da58b97aSjoerg   const AAIsDead &IsDeadAA = getOrCreateAAFor<AAIsDead>(
648*da58b97aSjoerg       IRPosition::value(I, CBCtx), QueryingAA, DepClassTy::NONE);
649*da58b97aSjoerg   // Don't check liveness for AAIsDead.
650*da58b97aSjoerg   if (QueryingAA == &IsDeadAA)
651*da58b97aSjoerg     return false;
65206f32e7eSjoerg 
653*da58b97aSjoerg   if (IsDeadAA.isAssumedDead()) {
654*da58b97aSjoerg     if (QueryingAA)
655*da58b97aSjoerg       recordDependence(IsDeadAA, *QueryingAA, DepClass);
656*da58b97aSjoerg     return true;
65706f32e7eSjoerg   }
65806f32e7eSjoerg 
659*da58b97aSjoerg   return false;
66006f32e7eSjoerg }
66106f32e7eSjoerg 
isAssumedDead(const IRPosition & IRP,const AbstractAttribute * QueryingAA,const AAIsDead * FnLivenessAA,bool CheckBBLivenessOnly,DepClassTy DepClass)662*da58b97aSjoerg bool Attributor::isAssumedDead(const IRPosition &IRP,
663*da58b97aSjoerg                                const AbstractAttribute *QueryingAA,
664*da58b97aSjoerg                                const AAIsDead *FnLivenessAA,
665*da58b97aSjoerg                                bool CheckBBLivenessOnly, DepClassTy DepClass) {
666*da58b97aSjoerg   Instruction *CtxI = IRP.getCtxI();
667*da58b97aSjoerg   if (CtxI &&
668*da58b97aSjoerg       isAssumedDead(*CtxI, QueryingAA, FnLivenessAA,
669*da58b97aSjoerg                     /* CheckBBLivenessOnly */ true,
670*da58b97aSjoerg                     CheckBBLivenessOnly ? DepClass : DepClassTy::OPTIONAL))
671*da58b97aSjoerg     return true;
67206f32e7eSjoerg 
673*da58b97aSjoerg   if (CheckBBLivenessOnly)
674*da58b97aSjoerg     return false;
67506f32e7eSjoerg 
676*da58b97aSjoerg   // If we haven't succeeded we query the specific liveness info for the IRP.
677*da58b97aSjoerg   const AAIsDead *IsDeadAA;
678*da58b97aSjoerg   if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE)
679*da58b97aSjoerg     IsDeadAA = &getOrCreateAAFor<AAIsDead>(
680*da58b97aSjoerg         IRPosition::callsite_returned(cast<CallBase>(IRP.getAssociatedValue())),
681*da58b97aSjoerg         QueryingAA, DepClassTy::NONE);
68206f32e7eSjoerg   else
683*da58b97aSjoerg     IsDeadAA = &getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClassTy::NONE);
684*da58b97aSjoerg   // Don't check liveness for AAIsDead.
685*da58b97aSjoerg   if (QueryingAA == IsDeadAA)
68606f32e7eSjoerg     return false;
68706f32e7eSjoerg 
688*da58b97aSjoerg   if (IsDeadAA->isAssumedDead()) {
689*da58b97aSjoerg     if (QueryingAA)
690*da58b97aSjoerg       recordDependence(*IsDeadAA, *QueryingAA, DepClass);
69106f32e7eSjoerg     return true;
69206f32e7eSjoerg   }
69306f32e7eSjoerg 
69406f32e7eSjoerg   return false;
69506f32e7eSjoerg }
69606f32e7eSjoerg 
checkForAllUses(function_ref<bool (const Use &,bool &)> Pred,const AbstractAttribute & QueryingAA,const Value & V,DepClassTy LivenessDepClass)697*da58b97aSjoerg bool Attributor::checkForAllUses(function_ref<bool(const Use &, bool &)> Pred,
698*da58b97aSjoerg                                  const AbstractAttribute &QueryingAA,
699*da58b97aSjoerg                                  const Value &V, DepClassTy LivenessDepClass) {
70006f32e7eSjoerg 
701*da58b97aSjoerg   // Check the trivial case first as it catches void values.
702*da58b97aSjoerg   if (V.use_empty())
703*da58b97aSjoerg     return true;
70406f32e7eSjoerg 
705*da58b97aSjoerg   // If the value is replaced by another one, for now a constant, we do not have
706*da58b97aSjoerg   // uses. Note that this requires users of `checkForAllUses` to not recurse but
707*da58b97aSjoerg   // instead use the `follow` callback argument to look at transitive users,
708*da58b97aSjoerg   // however, that should be clear from the presence of the argument.
709*da58b97aSjoerg   bool UsedAssumedInformation = false;
710*da58b97aSjoerg   Optional<Constant *> C =
711*da58b97aSjoerg       getAssumedConstant(V, QueryingAA, UsedAssumedInformation);
712*da58b97aSjoerg   if (C.hasValue() && C.getValue()) {
713*da58b97aSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] Value is simplified, uses skipped: " << V
714*da58b97aSjoerg                       << " -> " << *C.getValue() << "\n");
715*da58b97aSjoerg     return true;
71606f32e7eSjoerg   }
71706f32e7eSjoerg 
718*da58b97aSjoerg   const IRPosition &IRP = QueryingAA.getIRPosition();
719*da58b97aSjoerg   SmallVector<const Use *, 16> Worklist;
720*da58b97aSjoerg   SmallPtrSet<const Use *, 16> Visited;
72106f32e7eSjoerg 
722*da58b97aSjoerg   for (const Use &U : V.uses())
72306f32e7eSjoerg     Worklist.push_back(&U);
72406f32e7eSjoerg 
725*da58b97aSjoerg   LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size()
726*da58b97aSjoerg                     << " initial uses to check\n");
727*da58b97aSjoerg 
728*da58b97aSjoerg   const Function *ScopeFn = IRP.getAnchorScope();
729*da58b97aSjoerg   const auto *LivenessAA =
730*da58b97aSjoerg       ScopeFn ? &getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*ScopeFn),
731*da58b97aSjoerg                                     DepClassTy::NONE)
732*da58b97aSjoerg               : nullptr;
733*da58b97aSjoerg 
73406f32e7eSjoerg   while (!Worklist.empty()) {
73506f32e7eSjoerg     const Use *U = Worklist.pop_back_val();
73606f32e7eSjoerg     if (!Visited.insert(U).second)
73706f32e7eSjoerg       continue;
738*da58b97aSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << **U << " in "
739*da58b97aSjoerg                       << *U->getUser() << "\n");
740*da58b97aSjoerg     if (isAssumedDead(*U, &QueryingAA, LivenessAA,
741*da58b97aSjoerg                       /* CheckBBLivenessOnly */ false, LivenessDepClass)) {
742*da58b97aSjoerg       LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n");
74306f32e7eSjoerg       continue;
744*da58b97aSjoerg     }
745*da58b97aSjoerg     if (U->getUser()->isDroppable()) {
746*da58b97aSjoerg       LLVM_DEBUG(dbgs() << "[Attributor] Droppable user, skip!\n");
747*da58b97aSjoerg       continue;
748*da58b97aSjoerg     }
749*da58b97aSjoerg 
750*da58b97aSjoerg     bool Follow = false;
751*da58b97aSjoerg     if (!Pred(*U, Follow))
75206f32e7eSjoerg       return false;
753*da58b97aSjoerg     if (!Follow)
75406f32e7eSjoerg       continue;
755*da58b97aSjoerg     for (const Use &UU : U->getUser()->uses())
756*da58b97aSjoerg       Worklist.push_back(&UU);
75706f32e7eSjoerg   }
75806f32e7eSjoerg 
75906f32e7eSjoerg   return true;
76006f32e7eSjoerg }
76106f32e7eSjoerg 
checkForAllCallSites(function_ref<bool (AbstractCallSite)> Pred,const AbstractAttribute & QueryingAA,bool RequireAllCallSites,bool & AllCallSitesKnown)762*da58b97aSjoerg bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
763*da58b97aSjoerg                                       const AbstractAttribute &QueryingAA,
764*da58b97aSjoerg                                       bool RequireAllCallSites,
765*da58b97aSjoerg                                       bool &AllCallSitesKnown) {
76606f32e7eSjoerg   // We can try to determine information from
76706f32e7eSjoerg   // the call sites. However, this is only possible all call sites are known,
76806f32e7eSjoerg   // hence the function has internal linkage.
76906f32e7eSjoerg   const IRPosition &IRP = QueryingAA.getIRPosition();
77006f32e7eSjoerg   const Function *AssociatedFunction = IRP.getAssociatedFunction();
77106f32e7eSjoerg   if (!AssociatedFunction) {
77206f32e7eSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP
77306f32e7eSjoerg                       << "\n");
774*da58b97aSjoerg     AllCallSitesKnown = false;
77506f32e7eSjoerg     return false;
77606f32e7eSjoerg   }
77706f32e7eSjoerg 
77806f32e7eSjoerg   return checkForAllCallSites(Pred, *AssociatedFunction, RequireAllCallSites,
779*da58b97aSjoerg                               &QueryingAA, AllCallSitesKnown);
78006f32e7eSjoerg }
78106f32e7eSjoerg 
checkForAllCallSites(function_ref<bool (AbstractCallSite)> Pred,const Function & Fn,bool RequireAllCallSites,const AbstractAttribute * QueryingAA,bool & AllCallSitesKnown)782*da58b97aSjoerg bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
783*da58b97aSjoerg                                       const Function &Fn,
784*da58b97aSjoerg                                       bool RequireAllCallSites,
785*da58b97aSjoerg                                       const AbstractAttribute *QueryingAA,
786*da58b97aSjoerg                                       bool &AllCallSitesKnown) {
78706f32e7eSjoerg   if (RequireAllCallSites && !Fn.hasLocalLinkage()) {
78806f32e7eSjoerg     LLVM_DEBUG(
78906f32e7eSjoerg         dbgs()
79006f32e7eSjoerg         << "[Attributor] Function " << Fn.getName()
79106f32e7eSjoerg         << " has no internal linkage, hence not all call sites are known\n");
792*da58b97aSjoerg     AllCallSitesKnown = false;
79306f32e7eSjoerg     return false;
79406f32e7eSjoerg   }
79506f32e7eSjoerg 
796*da58b97aSjoerg   // If we do not require all call sites we might not see all.
797*da58b97aSjoerg   AllCallSitesKnown = RequireAllCallSites;
798*da58b97aSjoerg 
799*da58b97aSjoerg   SmallVector<const Use *, 8> Uses(make_pointer_range(Fn.uses()));
800*da58b97aSjoerg   for (unsigned u = 0; u < Uses.size(); ++u) {
801*da58b97aSjoerg     const Use &U = *Uses[u];
802*da58b97aSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << *U << " in "
803*da58b97aSjoerg                       << *U.getUser() << "\n");
804*da58b97aSjoerg     if (isAssumedDead(U, QueryingAA, nullptr, /* CheckBBLivenessOnly */ true)) {
805*da58b97aSjoerg       LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n");
806*da58b97aSjoerg       continue;
807*da58b97aSjoerg     }
808*da58b97aSjoerg     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) {
809*da58b97aSjoerg       if (CE->isCast() && CE->getType()->isPointerTy() &&
810*da58b97aSjoerg           CE->getType()->getPointerElementType()->isFunctionTy()) {
811*da58b97aSjoerg         for (const Use &CEU : CE->uses())
812*da58b97aSjoerg           Uses.push_back(&CEU);
813*da58b97aSjoerg         continue;
814*da58b97aSjoerg       }
815*da58b97aSjoerg     }
816*da58b97aSjoerg 
81706f32e7eSjoerg     AbstractCallSite ACS(&U);
81806f32e7eSjoerg     if (!ACS) {
819*da58b97aSjoerg       LLVM_DEBUG(dbgs() << "[Attributor] Function " << Fn.getName()
82006f32e7eSjoerg                         << " has non call site use " << *U.get() << " in "
82106f32e7eSjoerg                         << *U.getUser() << "\n");
822*da58b97aSjoerg       // BlockAddress users are allowed.
823*da58b97aSjoerg       if (isa<BlockAddress>(U.getUser()))
82406f32e7eSjoerg         continue;
825*da58b97aSjoerg       return false;
82606f32e7eSjoerg     }
82706f32e7eSjoerg 
82806f32e7eSjoerg     const Use *EffectiveUse =
82906f32e7eSjoerg         ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U;
83006f32e7eSjoerg     if (!ACS.isCallee(EffectiveUse)) {
83106f32e7eSjoerg       if (!RequireAllCallSites)
83206f32e7eSjoerg         continue;
83306f32e7eSjoerg       LLVM_DEBUG(dbgs() << "[Attributor] User " << EffectiveUse->getUser()
834*da58b97aSjoerg                         << " is an invalid use of " << Fn.getName() << "\n");
83506f32e7eSjoerg       return false;
83606f32e7eSjoerg     }
83706f32e7eSjoerg 
838*da58b97aSjoerg     // Make sure the arguments that can be matched between the call site and the
839*da58b97aSjoerg     // callee argee on their type. It is unlikely they do not and it doesn't
840*da58b97aSjoerg     // make sense for all attributes to know/care about this.
841*da58b97aSjoerg     assert(&Fn == ACS.getCalledFunction() && "Expected known callee");
842*da58b97aSjoerg     unsigned MinArgsParams =
843*da58b97aSjoerg         std::min(size_t(ACS.getNumArgOperands()), Fn.arg_size());
844*da58b97aSjoerg     for (unsigned u = 0; u < MinArgsParams; ++u) {
845*da58b97aSjoerg       Value *CSArgOp = ACS.getCallArgOperand(u);
846*da58b97aSjoerg       if (CSArgOp && Fn.getArg(u)->getType() != CSArgOp->getType()) {
847*da58b97aSjoerg         LLVM_DEBUG(
848*da58b97aSjoerg             dbgs() << "[Attributor] Call site / callee argument type mismatch ["
849*da58b97aSjoerg                    << u << "@" << Fn.getName() << ": "
850*da58b97aSjoerg                    << *Fn.getArg(u)->getType() << " vs. "
851*da58b97aSjoerg                    << *ACS.getCallArgOperand(u)->getType() << "\n");
852*da58b97aSjoerg         return false;
853*da58b97aSjoerg       }
854*da58b97aSjoerg     }
855*da58b97aSjoerg 
85606f32e7eSjoerg     if (Pred(ACS))
85706f32e7eSjoerg       continue;
85806f32e7eSjoerg 
85906f32e7eSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for "
86006f32e7eSjoerg                       << *ACS.getInstruction() << "\n");
86106f32e7eSjoerg     return false;
86206f32e7eSjoerg   }
86306f32e7eSjoerg 
86406f32e7eSjoerg   return true;
86506f32e7eSjoerg }
86606f32e7eSjoerg 
shouldPropagateCallBaseContext(const IRPosition & IRP)867*da58b97aSjoerg bool Attributor::shouldPropagateCallBaseContext(const IRPosition &IRP) {
868*da58b97aSjoerg   // TODO: Maintain a cache of Values that are
869*da58b97aSjoerg   // on the pathway from a Argument to a Instruction that would effect the
870*da58b97aSjoerg   // liveness/return state etc.
871*da58b97aSjoerg   return EnableCallSiteSpecific;
872*da58b97aSjoerg }
873*da58b97aSjoerg 
checkForAllReturnedValuesAndReturnInsts(function_ref<bool (Value &,const SmallSetVector<ReturnInst *,4> &)> Pred,const AbstractAttribute & QueryingAA)87406f32e7eSjoerg bool Attributor::checkForAllReturnedValuesAndReturnInsts(
875*da58b97aSjoerg     function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred,
87606f32e7eSjoerg     const AbstractAttribute &QueryingAA) {
87706f32e7eSjoerg 
87806f32e7eSjoerg   const IRPosition &IRP = QueryingAA.getIRPosition();
87906f32e7eSjoerg   // Since we need to provide return instructions we have to have an exact
88006f32e7eSjoerg   // definition.
88106f32e7eSjoerg   const Function *AssociatedFunction = IRP.getAssociatedFunction();
88206f32e7eSjoerg   if (!AssociatedFunction)
88306f32e7eSjoerg     return false;
88406f32e7eSjoerg 
88506f32e7eSjoerg   // If this is a call site query we use the call site specific return values
88606f32e7eSjoerg   // and liveness information.
88706f32e7eSjoerg   // TODO: use the function scope once we have call site AAReturnedValues.
88806f32e7eSjoerg   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
889*da58b97aSjoerg   const auto &AARetVal =
890*da58b97aSjoerg       getAAFor<AAReturnedValues>(QueryingAA, QueryIRP, DepClassTy::REQUIRED);
89106f32e7eSjoerg   if (!AARetVal.getState().isValidState())
89206f32e7eSjoerg     return false;
89306f32e7eSjoerg 
89406f32e7eSjoerg   return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred);
89506f32e7eSjoerg }
89606f32e7eSjoerg 
checkForAllReturnedValues(function_ref<bool (Value &)> Pred,const AbstractAttribute & QueryingAA)89706f32e7eSjoerg bool Attributor::checkForAllReturnedValues(
898*da58b97aSjoerg     function_ref<bool(Value &)> Pred, const AbstractAttribute &QueryingAA) {
89906f32e7eSjoerg 
90006f32e7eSjoerg   const IRPosition &IRP = QueryingAA.getIRPosition();
90106f32e7eSjoerg   const Function *AssociatedFunction = IRP.getAssociatedFunction();
90206f32e7eSjoerg   if (!AssociatedFunction)
90306f32e7eSjoerg     return false;
90406f32e7eSjoerg 
90506f32e7eSjoerg   // TODO: use the function scope once we have call site AAReturnedValues.
906*da58b97aSjoerg   const IRPosition &QueryIRP = IRPosition::function(
907*da58b97aSjoerg       *AssociatedFunction, QueryingAA.getCallBaseContext());
908*da58b97aSjoerg   const auto &AARetVal =
909*da58b97aSjoerg       getAAFor<AAReturnedValues>(QueryingAA, QueryIRP, DepClassTy::REQUIRED);
91006f32e7eSjoerg   if (!AARetVal.getState().isValidState())
91106f32e7eSjoerg     return false;
91206f32e7eSjoerg 
91306f32e7eSjoerg   return AARetVal.checkForAllReturnedValuesAndReturnInsts(
91406f32e7eSjoerg       [&](Value &RV, const SmallSetVector<ReturnInst *, 4> &) {
91506f32e7eSjoerg         return Pred(RV);
91606f32e7eSjoerg       });
91706f32e7eSjoerg }
91806f32e7eSjoerg 
checkForAllInstructionsImpl(Attributor * A,InformationCache::OpcodeInstMapTy & OpcodeInstMap,function_ref<bool (Instruction &)> Pred,const AbstractAttribute * QueryingAA,const AAIsDead * LivenessAA,const ArrayRef<unsigned> & Opcodes,bool CheckBBLivenessOnly=false)919*da58b97aSjoerg static bool checkForAllInstructionsImpl(
920*da58b97aSjoerg     Attributor *A, InformationCache::OpcodeInstMapTy &OpcodeInstMap,
921*da58b97aSjoerg     function_ref<bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA,
922*da58b97aSjoerg     const AAIsDead *LivenessAA, const ArrayRef<unsigned> &Opcodes,
923*da58b97aSjoerg     bool CheckBBLivenessOnly = false) {
92406f32e7eSjoerg   for (unsigned Opcode : Opcodes) {
925*da58b97aSjoerg     // Check if we have instructions with this opcode at all first.
926*da58b97aSjoerg     auto *Insts = OpcodeInstMap.lookup(Opcode);
927*da58b97aSjoerg     if (!Insts)
92806f32e7eSjoerg       continue;
929*da58b97aSjoerg 
930*da58b97aSjoerg     for (Instruction *I : *Insts) {
931*da58b97aSjoerg       // Skip dead instructions.
932*da58b97aSjoerg       if (A && A->isAssumedDead(IRPosition::value(*I), QueryingAA, LivenessAA,
933*da58b97aSjoerg                                 CheckBBLivenessOnly))
934*da58b97aSjoerg         continue;
93506f32e7eSjoerg 
93606f32e7eSjoerg       if (!Pred(*I))
93706f32e7eSjoerg         return false;
93806f32e7eSjoerg     }
93906f32e7eSjoerg   }
94006f32e7eSjoerg   return true;
94106f32e7eSjoerg }
94206f32e7eSjoerg 
checkForAllInstructions(function_ref<bool (Instruction &)> Pred,const AbstractAttribute & QueryingAA,const ArrayRef<unsigned> & Opcodes,bool CheckBBLivenessOnly)943*da58b97aSjoerg bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred,
944*da58b97aSjoerg                                          const AbstractAttribute &QueryingAA,
945*da58b97aSjoerg                                          const ArrayRef<unsigned> &Opcodes,
946*da58b97aSjoerg                                          bool CheckBBLivenessOnly) {
94706f32e7eSjoerg 
94806f32e7eSjoerg   const IRPosition &IRP = QueryingAA.getIRPosition();
94906f32e7eSjoerg   // Since we need to provide instructions we have to have an exact definition.
95006f32e7eSjoerg   const Function *AssociatedFunction = IRP.getAssociatedFunction();
95106f32e7eSjoerg   if (!AssociatedFunction)
95206f32e7eSjoerg     return false;
95306f32e7eSjoerg 
95406f32e7eSjoerg   // TODO: use the function scope once we have call site AAReturnedValues.
95506f32e7eSjoerg   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
956*da58b97aSjoerg   const auto *LivenessAA =
957*da58b97aSjoerg       CheckBBLivenessOnly
958*da58b97aSjoerg           ? nullptr
959*da58b97aSjoerg           : &(getAAFor<AAIsDead>(QueryingAA, QueryIRP, DepClassTy::NONE));
96006f32e7eSjoerg 
96106f32e7eSjoerg   auto &OpcodeInstMap =
96206f32e7eSjoerg       InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction);
963*da58b97aSjoerg   if (!checkForAllInstructionsImpl(this, OpcodeInstMap, Pred, &QueryingAA,
964*da58b97aSjoerg                                    LivenessAA, Opcodes, CheckBBLivenessOnly))
96506f32e7eSjoerg     return false;
96606f32e7eSjoerg 
96706f32e7eSjoerg   return true;
96806f32e7eSjoerg }
96906f32e7eSjoerg 
checkForAllReadWriteInstructions(function_ref<bool (Instruction &)> Pred,AbstractAttribute & QueryingAA)97006f32e7eSjoerg bool Attributor::checkForAllReadWriteInstructions(
971*da58b97aSjoerg     function_ref<bool(Instruction &)> Pred, AbstractAttribute &QueryingAA) {
97206f32e7eSjoerg 
97306f32e7eSjoerg   const Function *AssociatedFunction =
97406f32e7eSjoerg       QueryingAA.getIRPosition().getAssociatedFunction();
97506f32e7eSjoerg   if (!AssociatedFunction)
97606f32e7eSjoerg     return false;
97706f32e7eSjoerg 
97806f32e7eSjoerg   // TODO: use the function scope once we have call site AAReturnedValues.
97906f32e7eSjoerg   const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction);
98006f32e7eSjoerg   const auto &LivenessAA =
981*da58b97aSjoerg       getAAFor<AAIsDead>(QueryingAA, QueryIRP, DepClassTy::NONE);
98206f32e7eSjoerg 
98306f32e7eSjoerg   for (Instruction *I :
98406f32e7eSjoerg        InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) {
98506f32e7eSjoerg     // Skip dead instructions.
986*da58b97aSjoerg     if (isAssumedDead(IRPosition::value(*I), &QueryingAA, &LivenessAA))
98706f32e7eSjoerg       continue;
98806f32e7eSjoerg 
98906f32e7eSjoerg     if (!Pred(*I))
99006f32e7eSjoerg       return false;
99106f32e7eSjoerg   }
99206f32e7eSjoerg 
99306f32e7eSjoerg   return true;
99406f32e7eSjoerg }
99506f32e7eSjoerg 
runTillFixpoint()996*da58b97aSjoerg void Attributor::runTillFixpoint() {
997*da58b97aSjoerg   TimeTraceScope TimeScope("Attributor::runTillFixpoint");
99806f32e7eSjoerg   LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
999*da58b97aSjoerg                     << DG.SyntheticRoot.Deps.size()
100006f32e7eSjoerg                     << " abstract attributes.\n");
100106f32e7eSjoerg 
100206f32e7eSjoerg   // Now that all abstract attributes are collected and initialized we start
100306f32e7eSjoerg   // the abstract analysis.
100406f32e7eSjoerg 
100506f32e7eSjoerg   unsigned IterationCounter = 1;
100606f32e7eSjoerg 
1007*da58b97aSjoerg   SmallVector<AbstractAttribute *, 32> ChangedAAs;
1008*da58b97aSjoerg   SetVector<AbstractAttribute *> Worklist, InvalidAAs;
1009*da58b97aSjoerg   Worklist.insert(DG.SyntheticRoot.begin(), DG.SyntheticRoot.end());
101006f32e7eSjoerg 
101106f32e7eSjoerg   do {
101206f32e7eSjoerg     // Remember the size to determine new attributes.
1013*da58b97aSjoerg     size_t NumAAs = DG.SyntheticRoot.Deps.size();
101406f32e7eSjoerg     LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
101506f32e7eSjoerg                       << ", Worklist size: " << Worklist.size() << "\n");
101606f32e7eSjoerg 
1017*da58b97aSjoerg     // For invalid AAs we can fix dependent AAs that have a required dependence,
1018*da58b97aSjoerg     // thereby folding long dependence chains in a single step without the need
1019*da58b97aSjoerg     // to run updates.
1020*da58b97aSjoerg     for (unsigned u = 0; u < InvalidAAs.size(); ++u) {
1021*da58b97aSjoerg       AbstractAttribute *InvalidAA = InvalidAAs[u];
1022*da58b97aSjoerg 
1023*da58b97aSjoerg       // Check the dependences to fast track invalidation.
1024*da58b97aSjoerg       LLVM_DEBUG(dbgs() << "[Attributor] InvalidAA: " << *InvalidAA << " has "
1025*da58b97aSjoerg                         << InvalidAA->Deps.size()
1026*da58b97aSjoerg                         << " required & optional dependences\n");
1027*da58b97aSjoerg       while (!InvalidAA->Deps.empty()) {
1028*da58b97aSjoerg         const auto &Dep = InvalidAA->Deps.back();
1029*da58b97aSjoerg         InvalidAA->Deps.pop_back();
1030*da58b97aSjoerg         AbstractAttribute *DepAA = cast<AbstractAttribute>(Dep.getPointer());
1031*da58b97aSjoerg         if (Dep.getInt() == unsigned(DepClassTy::OPTIONAL)) {
1032*da58b97aSjoerg           Worklist.insert(DepAA);
1033*da58b97aSjoerg           continue;
1034*da58b97aSjoerg         }
1035*da58b97aSjoerg         DepAA->getState().indicatePessimisticFixpoint();
1036*da58b97aSjoerg         assert(DepAA->getState().isAtFixpoint() && "Expected fixpoint state!");
1037*da58b97aSjoerg         if (!DepAA->getState().isValidState())
1038*da58b97aSjoerg           InvalidAAs.insert(DepAA);
1039*da58b97aSjoerg         else
1040*da58b97aSjoerg           ChangedAAs.push_back(DepAA);
1041*da58b97aSjoerg       }
104206f32e7eSjoerg     }
104306f32e7eSjoerg 
104406f32e7eSjoerg     // Add all abstract attributes that are potentially dependent on one that
104506f32e7eSjoerg     // changed to the work list.
1046*da58b97aSjoerg     for (AbstractAttribute *ChangedAA : ChangedAAs)
1047*da58b97aSjoerg       while (!ChangedAA->Deps.empty()) {
1048*da58b97aSjoerg         Worklist.insert(
1049*da58b97aSjoerg             cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer()));
1050*da58b97aSjoerg         ChangedAA->Deps.pop_back();
105106f32e7eSjoerg       }
105206f32e7eSjoerg 
105306f32e7eSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter
105406f32e7eSjoerg                       << ", Worklist+Dependent size: " << Worklist.size()
105506f32e7eSjoerg                       << "\n");
105606f32e7eSjoerg 
1057*da58b97aSjoerg     // Reset the changed and invalid set.
105806f32e7eSjoerg     ChangedAAs.clear();
1059*da58b97aSjoerg     InvalidAAs.clear();
106006f32e7eSjoerg 
106106f32e7eSjoerg     // Update all abstract attribute in the work list and record the ones that
106206f32e7eSjoerg     // changed.
1063*da58b97aSjoerg     for (AbstractAttribute *AA : Worklist) {
1064*da58b97aSjoerg       const auto &AAState = AA->getState();
1065*da58b97aSjoerg       if (!AAState.isAtFixpoint())
1066*da58b97aSjoerg         if (updateAA(*AA) == ChangeStatus::CHANGED)
106706f32e7eSjoerg           ChangedAAs.push_back(AA);
106806f32e7eSjoerg 
1069*da58b97aSjoerg       // Use the InvalidAAs vector to propagate invalid states fast transitively
1070*da58b97aSjoerg       // without requiring updates.
1071*da58b97aSjoerg       if (!AAState.isValidState())
1072*da58b97aSjoerg         InvalidAAs.insert(AA);
1073*da58b97aSjoerg     }
107406f32e7eSjoerg 
107506f32e7eSjoerg     // Add attributes to the changed set if they have been created in the last
107606f32e7eSjoerg     // iteration.
1077*da58b97aSjoerg     ChangedAAs.append(DG.SyntheticRoot.begin() + NumAAs,
1078*da58b97aSjoerg                       DG.SyntheticRoot.end());
107906f32e7eSjoerg 
108006f32e7eSjoerg     // Reset the work list and repopulate with the changed abstract attributes.
108106f32e7eSjoerg     // Note that dependent ones are added above.
108206f32e7eSjoerg     Worklist.clear();
108306f32e7eSjoerg     Worklist.insert(ChangedAAs.begin(), ChangedAAs.end());
108406f32e7eSjoerg 
108506f32e7eSjoerg   } while (!Worklist.empty() && (IterationCounter++ < MaxFixpointIterations ||
108606f32e7eSjoerg                                  VerifyMaxFixpointIterations));
108706f32e7eSjoerg 
108806f32e7eSjoerg   LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
108906f32e7eSjoerg                     << IterationCounter << "/" << MaxFixpointIterations
109006f32e7eSjoerg                     << " iterations\n");
109106f32e7eSjoerg 
109206f32e7eSjoerg   // Reset abstract arguments not settled in a sound fixpoint by now. This
109306f32e7eSjoerg   // happens when we stopped the fixpoint iteration early. Note that only the
109406f32e7eSjoerg   // ones marked as "changed" *and* the ones transitively depending on them
109506f32e7eSjoerg   // need to be reverted to a pessimistic state. Others might not be in a
109606f32e7eSjoerg   // fixpoint state but we can use the optimistic results for them anyway.
109706f32e7eSjoerg   SmallPtrSet<AbstractAttribute *, 32> Visited;
109806f32e7eSjoerg   for (unsigned u = 0; u < ChangedAAs.size(); u++) {
109906f32e7eSjoerg     AbstractAttribute *ChangedAA = ChangedAAs[u];
110006f32e7eSjoerg     if (!Visited.insert(ChangedAA).second)
110106f32e7eSjoerg       continue;
110206f32e7eSjoerg 
110306f32e7eSjoerg     AbstractState &State = ChangedAA->getState();
110406f32e7eSjoerg     if (!State.isAtFixpoint()) {
110506f32e7eSjoerg       State.indicatePessimisticFixpoint();
110606f32e7eSjoerg 
110706f32e7eSjoerg       NumAttributesTimedOut++;
110806f32e7eSjoerg     }
110906f32e7eSjoerg 
1110*da58b97aSjoerg     while (!ChangedAA->Deps.empty()) {
1111*da58b97aSjoerg       ChangedAAs.push_back(
1112*da58b97aSjoerg           cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer()));
1113*da58b97aSjoerg       ChangedAA->Deps.pop_back();
1114*da58b97aSjoerg     }
111506f32e7eSjoerg   }
111606f32e7eSjoerg 
111706f32e7eSjoerg   LLVM_DEBUG({
111806f32e7eSjoerg     if (!Visited.empty())
111906f32e7eSjoerg       dbgs() << "\n[Attributor] Finalized " << Visited.size()
112006f32e7eSjoerg              << " abstract attributes.\n";
112106f32e7eSjoerg   });
112206f32e7eSjoerg 
1123*da58b97aSjoerg   if (VerifyMaxFixpointIterations &&
1124*da58b97aSjoerg       IterationCounter != MaxFixpointIterations) {
1125*da58b97aSjoerg     errs() << "\n[Attributor] Fixpoint iteration done after: "
1126*da58b97aSjoerg            << IterationCounter << "/" << MaxFixpointIterations
1127*da58b97aSjoerg            << " iterations\n";
1128*da58b97aSjoerg     llvm_unreachable("The fixpoint was not reached with exactly the number of "
1129*da58b97aSjoerg                      "specified iterations!");
1130*da58b97aSjoerg   }
1131*da58b97aSjoerg }
1132*da58b97aSjoerg 
manifestAttributes()1133*da58b97aSjoerg ChangeStatus Attributor::manifestAttributes() {
1134*da58b97aSjoerg   TimeTraceScope TimeScope("Attributor::manifestAttributes");
1135*da58b97aSjoerg   size_t NumFinalAAs = DG.SyntheticRoot.Deps.size();
1136*da58b97aSjoerg 
113706f32e7eSjoerg   unsigned NumManifested = 0;
113806f32e7eSjoerg   unsigned NumAtFixpoint = 0;
113906f32e7eSjoerg   ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
1140*da58b97aSjoerg   for (auto &DepAA : DG.SyntheticRoot.Deps) {
1141*da58b97aSjoerg     AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer());
114206f32e7eSjoerg     AbstractState &State = AA->getState();
114306f32e7eSjoerg 
114406f32e7eSjoerg     // If there is not already a fixpoint reached, we can now take the
114506f32e7eSjoerg     // optimistic state. This is correct because we enforced a pessimistic one
114606f32e7eSjoerg     // on abstract attributes that were transitively dependent on a changed one
114706f32e7eSjoerg     // already above.
114806f32e7eSjoerg     if (!State.isAtFixpoint())
114906f32e7eSjoerg       State.indicateOptimisticFixpoint();
115006f32e7eSjoerg 
1151*da58b97aSjoerg     // We must not manifest Attributes that use Callbase info.
1152*da58b97aSjoerg     if (AA->hasCallBaseContext())
1153*da58b97aSjoerg       continue;
115406f32e7eSjoerg     // If the state is invalid, we do not try to manifest it.
115506f32e7eSjoerg     if (!State.isValidState())
115606f32e7eSjoerg       continue;
115706f32e7eSjoerg 
115806f32e7eSjoerg     // Skip dead code.
1159*da58b97aSjoerg     if (isAssumedDead(*AA, nullptr, /* CheckBBLivenessOnly */ true))
1160*da58b97aSjoerg       continue;
1161*da58b97aSjoerg     // Check if the manifest debug counter that allows skipping manifestation of
1162*da58b97aSjoerg     // AAs
1163*da58b97aSjoerg     if (!DebugCounter::shouldExecute(ManifestDBGCounter))
116406f32e7eSjoerg       continue;
116506f32e7eSjoerg     // Manifest the state and record if we changed the IR.
116606f32e7eSjoerg     ChangeStatus LocalChange = AA->manifest(*this);
116706f32e7eSjoerg     if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled())
116806f32e7eSjoerg       AA->trackStatistics();
1169*da58b97aSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA
1170*da58b97aSjoerg                       << "\n");
117106f32e7eSjoerg 
117206f32e7eSjoerg     ManifestChange = ManifestChange | LocalChange;
117306f32e7eSjoerg 
117406f32e7eSjoerg     NumAtFixpoint++;
117506f32e7eSjoerg     NumManifested += (LocalChange == ChangeStatus::CHANGED);
117606f32e7eSjoerg   }
117706f32e7eSjoerg 
117806f32e7eSjoerg   (void)NumManifested;
117906f32e7eSjoerg   (void)NumAtFixpoint;
118006f32e7eSjoerg   LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
118106f32e7eSjoerg                     << " arguments while " << NumAtFixpoint
118206f32e7eSjoerg                     << " were in a valid fixpoint state\n");
118306f32e7eSjoerg 
118406f32e7eSjoerg   NumAttributesManifested += NumManifested;
118506f32e7eSjoerg   NumAttributesValidFixpoint += NumAtFixpoint;
118606f32e7eSjoerg 
118706f32e7eSjoerg   (void)NumFinalAAs;
1188*da58b97aSjoerg   if (NumFinalAAs != DG.SyntheticRoot.Deps.size()) {
1189*da58b97aSjoerg     for (unsigned u = NumFinalAAs; u < DG.SyntheticRoot.Deps.size(); ++u)
1190*da58b97aSjoerg       errs() << "Unexpected abstract attribute: "
1191*da58b97aSjoerg              << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer())
1192*da58b97aSjoerg              << " :: "
1193*da58b97aSjoerg              << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer())
1194*da58b97aSjoerg                     ->getIRPosition()
1195*da58b97aSjoerg                     .getAssociatedValue()
1196*da58b97aSjoerg              << "\n";
1197*da58b97aSjoerg     llvm_unreachable("Expected the final number of abstract attributes to "
1198*da58b97aSjoerg                      "remain unchanged!");
1199*da58b97aSjoerg   }
1200*da58b97aSjoerg   return ManifestChange;
120106f32e7eSjoerg }
120206f32e7eSjoerg 
identifyDeadInternalFunctions()1203*da58b97aSjoerg void Attributor::identifyDeadInternalFunctions() {
1204*da58b97aSjoerg   // Early exit if we don't intend to delete functions.
1205*da58b97aSjoerg   if (!DeleteFns)
1206*da58b97aSjoerg     return;
120706f32e7eSjoerg 
120806f32e7eSjoerg   // Identify dead internal functions and delete them. This happens outside
120906f32e7eSjoerg   // the other fixpoint analysis as we might treat potentially dead functions
121006f32e7eSjoerg   // as live to lower the number of iterations. If they happen to be dead, the
121106f32e7eSjoerg   // below fixpoint loop will identify and eliminate them.
121206f32e7eSjoerg   SmallVector<Function *, 8> InternalFns;
1213*da58b97aSjoerg   for (Function *F : Functions)
1214*da58b97aSjoerg     if (F->hasLocalLinkage())
1215*da58b97aSjoerg       InternalFns.push_back(F);
121606f32e7eSjoerg 
1217*da58b97aSjoerg   SmallPtrSet<Function *, 8> LiveInternalFns;
1218*da58b97aSjoerg   bool FoundLiveInternal = true;
1219*da58b97aSjoerg   while (FoundLiveInternal) {
1220*da58b97aSjoerg     FoundLiveInternal = false;
122106f32e7eSjoerg     for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) {
122206f32e7eSjoerg       Function *F = InternalFns[u];
122306f32e7eSjoerg       if (!F)
122406f32e7eSjoerg         continue;
122506f32e7eSjoerg 
1226*da58b97aSjoerg       bool AllCallSitesKnown;
1227*da58b97aSjoerg       if (checkForAllCallSites(
1228*da58b97aSjoerg               [&](AbstractCallSite ACS) {
1229*da58b97aSjoerg                 Function *Callee = ACS.getInstruction()->getFunction();
1230*da58b97aSjoerg                 return ToBeDeletedFunctions.count(Callee) ||
1231*da58b97aSjoerg                        (Functions.count(Callee) && Callee->hasLocalLinkage() &&
1232*da58b97aSjoerg                         !LiveInternalFns.count(Callee));
1233*da58b97aSjoerg               },
1234*da58b97aSjoerg               *F, true, nullptr, AllCallSitesKnown)) {
1235*da58b97aSjoerg         continue;
1236*da58b97aSjoerg       }
1237*da58b97aSjoerg 
1238*da58b97aSjoerg       LiveInternalFns.insert(F);
1239*da58b97aSjoerg       InternalFns[u] = nullptr;
1240*da58b97aSjoerg       FoundLiveInternal = true;
1241*da58b97aSjoerg     }
1242*da58b97aSjoerg   }
1243*da58b97aSjoerg 
1244*da58b97aSjoerg   for (unsigned u = 0, e = InternalFns.size(); u < e; ++u)
1245*da58b97aSjoerg     if (Function *F = InternalFns[u])
1246*da58b97aSjoerg       ToBeDeletedFunctions.insert(F);
1247*da58b97aSjoerg }
1248*da58b97aSjoerg 
cleanupIR()1249*da58b97aSjoerg ChangeStatus Attributor::cleanupIR() {
1250*da58b97aSjoerg   TimeTraceScope TimeScope("Attributor::cleanupIR");
1251*da58b97aSjoerg   // Delete stuff at the end to avoid invalid references and a nice order.
1252*da58b97aSjoerg   LLVM_DEBUG(dbgs() << "\n[Attributor] Delete at least "
1253*da58b97aSjoerg                     << ToBeDeletedFunctions.size() << " functions and "
1254*da58b97aSjoerg                     << ToBeDeletedBlocks.size() << " blocks and "
1255*da58b97aSjoerg                     << ToBeDeletedInsts.size() << " instructions and "
1256*da58b97aSjoerg                     << ToBeChangedUses.size() << " uses\n");
1257*da58b97aSjoerg 
1258*da58b97aSjoerg   SmallVector<WeakTrackingVH, 32> DeadInsts;
1259*da58b97aSjoerg   SmallVector<Instruction *, 32> TerminatorsToFold;
1260*da58b97aSjoerg 
1261*da58b97aSjoerg   for (auto &It : ToBeChangedUses) {
1262*da58b97aSjoerg     Use *U = It.first;
1263*da58b97aSjoerg     Value *NewV = It.second;
1264*da58b97aSjoerg     Value *OldV = U->get();
1265*da58b97aSjoerg 
1266*da58b97aSjoerg     // Do not replace uses in returns if the value is a must-tail call we will
1267*da58b97aSjoerg     // not delete.
1268*da58b97aSjoerg     if (isa<ReturnInst>(U->getUser()))
1269*da58b97aSjoerg       if (auto *CI = dyn_cast<CallInst>(OldV->stripPointerCasts()))
1270*da58b97aSjoerg         if (CI->isMustTailCall() && !ToBeDeletedInsts.count(CI))
127106f32e7eSjoerg           continue;
127206f32e7eSjoerg 
1273*da58b97aSjoerg     LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser()
1274*da58b97aSjoerg                       << " instead of " << *OldV << "\n");
1275*da58b97aSjoerg     U->set(NewV);
1276*da58b97aSjoerg     // Do not modify call instructions outside the SCC.
1277*da58b97aSjoerg     if (auto *CB = dyn_cast<CallBase>(OldV))
1278*da58b97aSjoerg       if (!Functions.count(CB->getCaller()))
1279*da58b97aSjoerg         continue;
1280*da58b97aSjoerg     if (Instruction *I = dyn_cast<Instruction>(OldV)) {
1281*da58b97aSjoerg       CGModifiedFunctions.insert(I->getFunction());
1282*da58b97aSjoerg       if (!isa<PHINode>(I) && !ToBeDeletedInsts.count(I) &&
1283*da58b97aSjoerg           isInstructionTriviallyDead(I))
1284*da58b97aSjoerg         DeadInsts.push_back(I);
128506f32e7eSjoerg     }
1286*da58b97aSjoerg     if (isa<UndefValue>(NewV) && isa<CallBase>(U->getUser())) {
1287*da58b97aSjoerg       auto *CB = cast<CallBase>(U->getUser());
1288*da58b97aSjoerg       if (CB->isArgOperand(U)) {
1289*da58b97aSjoerg         unsigned Idx = CB->getArgOperandNo(U);
1290*da58b97aSjoerg         CB->removeParamAttr(Idx, Attribute::NoUndef);
1291*da58b97aSjoerg         Function *Fn = CB->getCalledFunction();
1292*da58b97aSjoerg         assert(Fn && "Expected callee when call argument is replaced!");
1293*da58b97aSjoerg         if (Fn->arg_size() > Idx)
1294*da58b97aSjoerg           Fn->removeParamAttr(Idx, Attribute::NoUndef);
1295*da58b97aSjoerg       }
1296*da58b97aSjoerg     }
1297*da58b97aSjoerg     if (isa<Constant>(NewV) && isa<BranchInst>(U->getUser())) {
1298*da58b97aSjoerg       Instruction *UserI = cast<Instruction>(U->getUser());
1299*da58b97aSjoerg       if (isa<UndefValue>(NewV)) {
1300*da58b97aSjoerg         ToBeChangedToUnreachableInsts.insert(UserI);
1301*da58b97aSjoerg       } else {
1302*da58b97aSjoerg         TerminatorsToFold.push_back(UserI);
1303*da58b97aSjoerg       }
1304*da58b97aSjoerg     }
1305*da58b97aSjoerg   }
1306*da58b97aSjoerg   for (auto &V : InvokeWithDeadSuccessor)
1307*da58b97aSjoerg     if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) {
1308*da58b97aSjoerg       bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind);
1309*da58b97aSjoerg       bool NormalBBIsDead = II->hasFnAttr(Attribute::NoReturn);
1310*da58b97aSjoerg       bool Invoke2CallAllowed =
1311*da58b97aSjoerg           !AAIsDead::mayCatchAsynchronousExceptions(*II->getFunction());
1312*da58b97aSjoerg       assert((UnwindBBIsDead || NormalBBIsDead) &&
1313*da58b97aSjoerg              "Invoke does not have dead successors!");
1314*da58b97aSjoerg       BasicBlock *BB = II->getParent();
1315*da58b97aSjoerg       BasicBlock *NormalDestBB = II->getNormalDest();
1316*da58b97aSjoerg       if (UnwindBBIsDead) {
1317*da58b97aSjoerg         Instruction *NormalNextIP = &NormalDestBB->front();
1318*da58b97aSjoerg         if (Invoke2CallAllowed) {
1319*da58b97aSjoerg           changeToCall(II);
1320*da58b97aSjoerg           NormalNextIP = BB->getTerminator();
1321*da58b97aSjoerg         }
1322*da58b97aSjoerg         if (NormalBBIsDead)
1323*da58b97aSjoerg           ToBeChangedToUnreachableInsts.insert(NormalNextIP);
1324*da58b97aSjoerg       } else {
1325*da58b97aSjoerg         assert(NormalBBIsDead && "Broken invariant!");
1326*da58b97aSjoerg         if (!NormalDestBB->getUniquePredecessor())
1327*da58b97aSjoerg           NormalDestBB = SplitBlockPredecessors(NormalDestBB, {BB}, ".dead");
1328*da58b97aSjoerg         ToBeChangedToUnreachableInsts.insert(&NormalDestBB->front());
1329*da58b97aSjoerg       }
1330*da58b97aSjoerg     }
1331*da58b97aSjoerg   for (Instruction *I : TerminatorsToFold) {
1332*da58b97aSjoerg     CGModifiedFunctions.insert(I->getFunction());
1333*da58b97aSjoerg     ConstantFoldTerminator(I->getParent());
1334*da58b97aSjoerg   }
1335*da58b97aSjoerg   for (auto &V : ToBeChangedToUnreachableInsts)
1336*da58b97aSjoerg     if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
1337*da58b97aSjoerg       CGModifiedFunctions.insert(I->getFunction());
1338*da58b97aSjoerg       changeToUnreachable(I, /* UseLLVMTrap */ false);
1339*da58b97aSjoerg     }
1340*da58b97aSjoerg 
1341*da58b97aSjoerg   for (auto &V : ToBeDeletedInsts) {
1342*da58b97aSjoerg     if (Instruction *I = dyn_cast_or_null<Instruction>(V)) {
1343*da58b97aSjoerg       I->dropDroppableUses();
1344*da58b97aSjoerg       CGModifiedFunctions.insert(I->getFunction());
1345*da58b97aSjoerg       if (!I->getType()->isVoidTy())
1346*da58b97aSjoerg         I->replaceAllUsesWith(UndefValue::get(I->getType()));
1347*da58b97aSjoerg       if (!isa<PHINode>(I) && isInstructionTriviallyDead(I))
1348*da58b97aSjoerg         DeadInsts.push_back(I);
1349*da58b97aSjoerg       else
1350*da58b97aSjoerg         I->eraseFromParent();
135106f32e7eSjoerg     }
135206f32e7eSjoerg   }
135306f32e7eSjoerg 
1354*da58b97aSjoerg   LLVM_DEBUG(dbgs() << "[Attributor] DeadInsts size: " << DeadInsts.size()
1355*da58b97aSjoerg                     << "\n");
1356*da58b97aSjoerg 
1357*da58b97aSjoerg   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
1358*da58b97aSjoerg 
1359*da58b97aSjoerg   if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) {
1360*da58b97aSjoerg     SmallVector<BasicBlock *, 8> ToBeDeletedBBs;
1361*da58b97aSjoerg     ToBeDeletedBBs.reserve(NumDeadBlocks);
1362*da58b97aSjoerg     for (BasicBlock *BB : ToBeDeletedBlocks) {
1363*da58b97aSjoerg       CGModifiedFunctions.insert(BB->getParent());
1364*da58b97aSjoerg       ToBeDeletedBBs.push_back(BB);
136506f32e7eSjoerg     }
1366*da58b97aSjoerg     // Actually we do not delete the blocks but squash them into a single
1367*da58b97aSjoerg     // unreachable but untangling branches that jump here is something we need
1368*da58b97aSjoerg     // to do in a more generic way.
1369*da58b97aSjoerg     DetatchDeadBlocks(ToBeDeletedBBs, nullptr);
1370*da58b97aSjoerg   }
1371*da58b97aSjoerg 
1372*da58b97aSjoerg   identifyDeadInternalFunctions();
1373*da58b97aSjoerg 
1374*da58b97aSjoerg   // Rewrite the functions as requested during manifest.
1375*da58b97aSjoerg   ChangeStatus ManifestChange = rewriteFunctionSignatures(CGModifiedFunctions);
1376*da58b97aSjoerg 
1377*da58b97aSjoerg   for (Function *Fn : CGModifiedFunctions)
1378*da58b97aSjoerg     if (!ToBeDeletedFunctions.count(Fn))
1379*da58b97aSjoerg       CGUpdater.reanalyzeFunction(*Fn);
1380*da58b97aSjoerg 
1381*da58b97aSjoerg   for (Function *Fn : ToBeDeletedFunctions) {
1382*da58b97aSjoerg     if (!Functions.count(Fn))
1383*da58b97aSjoerg       continue;
1384*da58b97aSjoerg     CGUpdater.removeFunction(*Fn);
1385*da58b97aSjoerg   }
1386*da58b97aSjoerg 
1387*da58b97aSjoerg   if (!ToBeChangedUses.empty())
1388*da58b97aSjoerg     ManifestChange = ChangeStatus::CHANGED;
1389*da58b97aSjoerg 
1390*da58b97aSjoerg   if (!ToBeChangedToUnreachableInsts.empty())
1391*da58b97aSjoerg     ManifestChange = ChangeStatus::CHANGED;
1392*da58b97aSjoerg 
1393*da58b97aSjoerg   if (!ToBeDeletedFunctions.empty())
1394*da58b97aSjoerg     ManifestChange = ChangeStatus::CHANGED;
1395*da58b97aSjoerg 
1396*da58b97aSjoerg   if (!ToBeDeletedBlocks.empty())
1397*da58b97aSjoerg     ManifestChange = ChangeStatus::CHANGED;
1398*da58b97aSjoerg 
1399*da58b97aSjoerg   if (!ToBeDeletedInsts.empty())
1400*da58b97aSjoerg     ManifestChange = ChangeStatus::CHANGED;
1401*da58b97aSjoerg 
1402*da58b97aSjoerg   if (!InvokeWithDeadSuccessor.empty())
1403*da58b97aSjoerg     ManifestChange = ChangeStatus::CHANGED;
1404*da58b97aSjoerg 
1405*da58b97aSjoerg   if (!DeadInsts.empty())
1406*da58b97aSjoerg     ManifestChange = ChangeStatus::CHANGED;
1407*da58b97aSjoerg 
1408*da58b97aSjoerg   NumFnDeleted += ToBeDeletedFunctions.size();
1409*da58b97aSjoerg 
1410*da58b97aSjoerg   LLVM_DEBUG(dbgs() << "[Attributor] Deleted " << ToBeDeletedFunctions.size()
1411*da58b97aSjoerg                     << " functions after manifest.\n");
1412*da58b97aSjoerg 
1413*da58b97aSjoerg #ifdef EXPENSIVE_CHECKS
1414*da58b97aSjoerg   for (Function *F : Functions) {
1415*da58b97aSjoerg     if (ToBeDeletedFunctions.count(F))
1416*da58b97aSjoerg       continue;
1417*da58b97aSjoerg     assert(!verifyFunction(*F, &errs()) && "Module verification failed!");
1418*da58b97aSjoerg   }
1419*da58b97aSjoerg #endif
142006f32e7eSjoerg 
142106f32e7eSjoerg   return ManifestChange;
142206f32e7eSjoerg }
142306f32e7eSjoerg 
run()1424*da58b97aSjoerg ChangeStatus Attributor::run() {
1425*da58b97aSjoerg   TimeTraceScope TimeScope("Attributor::run");
1426*da58b97aSjoerg 
1427*da58b97aSjoerg   Phase = AttributorPhase::UPDATE;
1428*da58b97aSjoerg   runTillFixpoint();
1429*da58b97aSjoerg 
1430*da58b97aSjoerg   // dump graphs on demand
1431*da58b97aSjoerg   if (DumpDepGraph)
1432*da58b97aSjoerg     DG.dumpGraph();
1433*da58b97aSjoerg 
1434*da58b97aSjoerg   if (ViewDepGraph)
1435*da58b97aSjoerg     DG.viewGraph();
1436*da58b97aSjoerg 
1437*da58b97aSjoerg   if (PrintDependencies)
1438*da58b97aSjoerg     DG.print();
1439*da58b97aSjoerg 
1440*da58b97aSjoerg   Phase = AttributorPhase::MANIFEST;
1441*da58b97aSjoerg   ChangeStatus ManifestChange = manifestAttributes();
1442*da58b97aSjoerg 
1443*da58b97aSjoerg   Phase = AttributorPhase::CLEANUP;
1444*da58b97aSjoerg   ChangeStatus CleanupChange = cleanupIR();
1445*da58b97aSjoerg 
1446*da58b97aSjoerg   return ManifestChange | CleanupChange;
1447*da58b97aSjoerg }
1448*da58b97aSjoerg 
updateAA(AbstractAttribute & AA)1449*da58b97aSjoerg ChangeStatus Attributor::updateAA(AbstractAttribute &AA) {
1450*da58b97aSjoerg   TimeTraceScope TimeScope(
1451*da58b97aSjoerg       AA.getName() + std::to_string(AA.getIRPosition().getPositionKind()) +
1452*da58b97aSjoerg       "::updateAA");
1453*da58b97aSjoerg   assert(Phase == AttributorPhase::UPDATE &&
1454*da58b97aSjoerg          "We can update AA only in the update stage!");
1455*da58b97aSjoerg 
1456*da58b97aSjoerg   // Use a new dependence vector for this update.
1457*da58b97aSjoerg   DependenceVector DV;
1458*da58b97aSjoerg   DependenceStack.push_back(&DV);
1459*da58b97aSjoerg 
1460*da58b97aSjoerg   auto &AAState = AA.getState();
1461*da58b97aSjoerg   ChangeStatus CS = ChangeStatus::UNCHANGED;
1462*da58b97aSjoerg   if (!isAssumedDead(AA, nullptr, /* CheckBBLivenessOnly */ true))
1463*da58b97aSjoerg     CS = AA.update(*this);
1464*da58b97aSjoerg 
1465*da58b97aSjoerg   if (DV.empty()) {
1466*da58b97aSjoerg     // If the attribute did not query any non-fix information, the state
1467*da58b97aSjoerg     // will not change and we can indicate that right away.
1468*da58b97aSjoerg     AAState.indicateOptimisticFixpoint();
1469*da58b97aSjoerg   }
1470*da58b97aSjoerg 
1471*da58b97aSjoerg   if (!AAState.isAtFixpoint())
1472*da58b97aSjoerg     rememberDependences();
1473*da58b97aSjoerg 
1474*da58b97aSjoerg   // Verify the stack was used properly, that is we pop the dependence vector we
1475*da58b97aSjoerg   // put there earlier.
1476*da58b97aSjoerg   DependenceVector *PoppedDV = DependenceStack.pop_back_val();
1477*da58b97aSjoerg   (void)PoppedDV;
1478*da58b97aSjoerg   assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!");
1479*da58b97aSjoerg 
1480*da58b97aSjoerg   return CS;
1481*da58b97aSjoerg }
1482*da58b97aSjoerg 
createShallowWrapper(Function & F)1483*da58b97aSjoerg void Attributor::createShallowWrapper(Function &F) {
1484*da58b97aSjoerg   assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!");
1485*da58b97aSjoerg 
1486*da58b97aSjoerg   Module &M = *F.getParent();
1487*da58b97aSjoerg   LLVMContext &Ctx = M.getContext();
1488*da58b97aSjoerg   FunctionType *FnTy = F.getFunctionType();
1489*da58b97aSjoerg 
1490*da58b97aSjoerg   Function *Wrapper =
1491*da58b97aSjoerg       Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(), F.getName());
1492*da58b97aSjoerg   F.setName(""); // set the inside function anonymous
1493*da58b97aSjoerg   M.getFunctionList().insert(F.getIterator(), Wrapper);
1494*da58b97aSjoerg 
1495*da58b97aSjoerg   F.setLinkage(GlobalValue::InternalLinkage);
1496*da58b97aSjoerg 
1497*da58b97aSjoerg   F.replaceAllUsesWith(Wrapper);
1498*da58b97aSjoerg   assert(F.use_empty() && "Uses remained after wrapper was created!");
1499*da58b97aSjoerg 
1500*da58b97aSjoerg   // Move the COMDAT section to the wrapper.
1501*da58b97aSjoerg   // TODO: Check if we need to keep it for F as well.
1502*da58b97aSjoerg   Wrapper->setComdat(F.getComdat());
1503*da58b97aSjoerg   F.setComdat(nullptr);
1504*da58b97aSjoerg 
1505*da58b97aSjoerg   // Copy all metadata and attributes but keep them on F as well.
1506*da58b97aSjoerg   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
1507*da58b97aSjoerg   F.getAllMetadata(MDs);
1508*da58b97aSjoerg   for (auto MDIt : MDs)
1509*da58b97aSjoerg     Wrapper->addMetadata(MDIt.first, *MDIt.second);
1510*da58b97aSjoerg   Wrapper->setAttributes(F.getAttributes());
1511*da58b97aSjoerg 
1512*da58b97aSjoerg   // Create the call in the wrapper.
1513*da58b97aSjoerg   BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Wrapper);
1514*da58b97aSjoerg 
1515*da58b97aSjoerg   SmallVector<Value *, 8> Args;
1516*da58b97aSjoerg   Argument *FArgIt = F.arg_begin();
1517*da58b97aSjoerg   for (Argument &Arg : Wrapper->args()) {
1518*da58b97aSjoerg     Args.push_back(&Arg);
1519*da58b97aSjoerg     Arg.setName((FArgIt++)->getName());
1520*da58b97aSjoerg   }
1521*da58b97aSjoerg 
1522*da58b97aSjoerg   CallInst *CI = CallInst::Create(&F, Args, "", EntryBB);
1523*da58b97aSjoerg   CI->setTailCall(true);
1524*da58b97aSjoerg   CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoInline);
1525*da58b97aSjoerg   ReturnInst::Create(Ctx, CI->getType()->isVoidTy() ? nullptr : CI, EntryBB);
1526*da58b97aSjoerg 
1527*da58b97aSjoerg   NumFnShallowWrappersCreated++;
1528*da58b97aSjoerg }
1529*da58b97aSjoerg 
1530*da58b97aSjoerg /// Make another copy of the function \p F such that the copied version has
1531*da58b97aSjoerg /// internal linkage afterwards and can be analysed. Then we replace all uses
1532*da58b97aSjoerg /// of the original function to the copied one
1533*da58b97aSjoerg ///
1534*da58b97aSjoerg /// Only non-exactly defined functions that have `linkonce_odr` or `weak_odr`
1535*da58b97aSjoerg /// linkage can be internalized because these linkages guarantee that other
1536*da58b97aSjoerg /// definitions with the same name have the same semantics as this one
1537*da58b97aSjoerg ///
internalizeFunction(Function & F)1538*da58b97aSjoerg static Function *internalizeFunction(Function &F) {
1539*da58b97aSjoerg   assert(AllowDeepWrapper && "Cannot create a copy if not allowed.");
1540*da58b97aSjoerg   assert(!F.isDeclaration() && !F.hasExactDefinition() &&
1541*da58b97aSjoerg          !GlobalValue::isInterposableLinkage(F.getLinkage()) &&
1542*da58b97aSjoerg          "Trying to internalize function which cannot be internalized.");
1543*da58b97aSjoerg 
1544*da58b97aSjoerg   Module &M = *F.getParent();
1545*da58b97aSjoerg   FunctionType *FnTy = F.getFunctionType();
1546*da58b97aSjoerg 
1547*da58b97aSjoerg   // create a copy of the current function
1548*da58b97aSjoerg   Function *Copied = Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(),
1549*da58b97aSjoerg                                       F.getName() + ".internalized");
1550*da58b97aSjoerg   ValueToValueMapTy VMap;
1551*da58b97aSjoerg   auto *NewFArgIt = Copied->arg_begin();
1552*da58b97aSjoerg   for (auto &Arg : F.args()) {
1553*da58b97aSjoerg     auto ArgName = Arg.getName();
1554*da58b97aSjoerg     NewFArgIt->setName(ArgName);
1555*da58b97aSjoerg     VMap[&Arg] = &(*NewFArgIt++);
1556*da58b97aSjoerg   }
1557*da58b97aSjoerg   SmallVector<ReturnInst *, 8> Returns;
1558*da58b97aSjoerg 
1559*da58b97aSjoerg   // Copy the body of the original function to the new one
1560*da58b97aSjoerg   CloneFunctionInto(Copied, &F, VMap, CloneFunctionChangeType::LocalChangesOnly,
1561*da58b97aSjoerg                     Returns);
1562*da58b97aSjoerg 
1563*da58b97aSjoerg   // Set the linakage and visibility late as CloneFunctionInto has some implicit
1564*da58b97aSjoerg   // requirements.
1565*da58b97aSjoerg   Copied->setVisibility(GlobalValue::DefaultVisibility);
1566*da58b97aSjoerg   Copied->setLinkage(GlobalValue::PrivateLinkage);
1567*da58b97aSjoerg 
1568*da58b97aSjoerg   // Copy metadata
1569*da58b97aSjoerg   SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
1570*da58b97aSjoerg   F.getAllMetadata(MDs);
1571*da58b97aSjoerg   for (auto MDIt : MDs)
1572*da58b97aSjoerg     Copied->addMetadata(MDIt.first, *MDIt.second);
1573*da58b97aSjoerg 
1574*da58b97aSjoerg   M.getFunctionList().insert(F.getIterator(), Copied);
1575*da58b97aSjoerg   F.replaceAllUsesWith(Copied);
1576*da58b97aSjoerg   Copied->setDSOLocal(true);
1577*da58b97aSjoerg 
1578*da58b97aSjoerg   return Copied;
1579*da58b97aSjoerg }
1580*da58b97aSjoerg 
isValidFunctionSignatureRewrite(Argument & Arg,ArrayRef<Type * > ReplacementTypes)1581*da58b97aSjoerg bool Attributor::isValidFunctionSignatureRewrite(
1582*da58b97aSjoerg     Argument &Arg, ArrayRef<Type *> ReplacementTypes) {
1583*da58b97aSjoerg 
1584*da58b97aSjoerg   auto CallSiteCanBeChanged = [](AbstractCallSite ACS) {
1585*da58b97aSjoerg     // Forbid the call site to cast the function return type. If we need to
1586*da58b97aSjoerg     // rewrite these functions we need to re-create a cast for the new call site
1587*da58b97aSjoerg     // (if the old had uses).
1588*da58b97aSjoerg     if (!ACS.getCalledFunction() ||
1589*da58b97aSjoerg         ACS.getInstruction()->getType() !=
1590*da58b97aSjoerg             ACS.getCalledFunction()->getReturnType())
1591*da58b97aSjoerg       return false;
1592*da58b97aSjoerg     // Forbid must-tail calls for now.
1593*da58b97aSjoerg     return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall();
1594*da58b97aSjoerg   };
1595*da58b97aSjoerg 
1596*da58b97aSjoerg   Function *Fn = Arg.getParent();
1597*da58b97aSjoerg   // Avoid var-arg functions for now.
1598*da58b97aSjoerg   if (Fn->isVarArg()) {
1599*da58b97aSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n");
1600*da58b97aSjoerg     return false;
1601*da58b97aSjoerg   }
1602*da58b97aSjoerg 
1603*da58b97aSjoerg   // Avoid functions with complicated argument passing semantics.
1604*da58b97aSjoerg   AttributeList FnAttributeList = Fn->getAttributes();
1605*da58b97aSjoerg   if (FnAttributeList.hasAttrSomewhere(Attribute::Nest) ||
1606*da58b97aSjoerg       FnAttributeList.hasAttrSomewhere(Attribute::StructRet) ||
1607*da58b97aSjoerg       FnAttributeList.hasAttrSomewhere(Attribute::InAlloca) ||
1608*da58b97aSjoerg       FnAttributeList.hasAttrSomewhere(Attribute::Preallocated)) {
1609*da58b97aSjoerg     LLVM_DEBUG(
1610*da58b97aSjoerg         dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n");
1611*da58b97aSjoerg     return false;
1612*da58b97aSjoerg   }
1613*da58b97aSjoerg 
1614*da58b97aSjoerg   // Avoid callbacks for now.
1615*da58b97aSjoerg   bool AllCallSitesKnown;
1616*da58b97aSjoerg   if (!checkForAllCallSites(CallSiteCanBeChanged, *Fn, true, nullptr,
1617*da58b97aSjoerg                             AllCallSitesKnown)) {
1618*da58b97aSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n");
1619*da58b97aSjoerg     return false;
1620*da58b97aSjoerg   }
1621*da58b97aSjoerg 
1622*da58b97aSjoerg   auto InstPred = [](Instruction &I) {
1623*da58b97aSjoerg     if (auto *CI = dyn_cast<CallInst>(&I))
1624*da58b97aSjoerg       return !CI->isMustTailCall();
1625*da58b97aSjoerg     return true;
1626*da58b97aSjoerg   };
1627*da58b97aSjoerg 
1628*da58b97aSjoerg   // Forbid must-tail calls for now.
1629*da58b97aSjoerg   // TODO:
1630*da58b97aSjoerg   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn);
1631*da58b97aSjoerg   if (!checkForAllInstructionsImpl(nullptr, OpcodeInstMap, InstPred, nullptr,
1632*da58b97aSjoerg                                    nullptr, {Instruction::Call})) {
1633*da58b97aSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n");
1634*da58b97aSjoerg     return false;
1635*da58b97aSjoerg   }
1636*da58b97aSjoerg 
1637*da58b97aSjoerg   return true;
1638*da58b97aSjoerg }
1639*da58b97aSjoerg 
registerFunctionSignatureRewrite(Argument & Arg,ArrayRef<Type * > ReplacementTypes,ArgumentReplacementInfo::CalleeRepairCBTy && CalleeRepairCB,ArgumentReplacementInfo::ACSRepairCBTy && ACSRepairCB)1640*da58b97aSjoerg bool Attributor::registerFunctionSignatureRewrite(
1641*da58b97aSjoerg     Argument &Arg, ArrayRef<Type *> ReplacementTypes,
1642*da58b97aSjoerg     ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB,
1643*da58b97aSjoerg     ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB) {
1644*da58b97aSjoerg   LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
1645*da58b97aSjoerg                     << Arg.getParent()->getName() << " with "
1646*da58b97aSjoerg                     << ReplacementTypes.size() << " replacements\n");
1647*da58b97aSjoerg   assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) &&
1648*da58b97aSjoerg          "Cannot register an invalid rewrite");
1649*da58b97aSjoerg 
1650*da58b97aSjoerg   Function *Fn = Arg.getParent();
1651*da58b97aSjoerg   SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
1652*da58b97aSjoerg       ArgumentReplacementMap[Fn];
1653*da58b97aSjoerg   if (ARIs.empty())
1654*da58b97aSjoerg     ARIs.resize(Fn->arg_size());
1655*da58b97aSjoerg 
1656*da58b97aSjoerg   // If we have a replacement already with less than or equal new arguments,
1657*da58b97aSjoerg   // ignore this request.
1658*da58b97aSjoerg   std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()];
1659*da58b97aSjoerg   if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) {
1660*da58b97aSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n");
1661*da58b97aSjoerg     return false;
1662*da58b97aSjoerg   }
1663*da58b97aSjoerg 
1664*da58b97aSjoerg   // If we have a replacement already but we like the new one better, delete
1665*da58b97aSjoerg   // the old.
1666*da58b97aSjoerg   ARI.reset();
1667*da58b97aSjoerg 
1668*da58b97aSjoerg   LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
1669*da58b97aSjoerg                     << Arg.getParent()->getName() << " with "
1670*da58b97aSjoerg                     << ReplacementTypes.size() << " replacements\n");
1671*da58b97aSjoerg 
1672*da58b97aSjoerg   // Remember the replacement.
1673*da58b97aSjoerg   ARI.reset(new ArgumentReplacementInfo(*this, Arg, ReplacementTypes,
1674*da58b97aSjoerg                                         std::move(CalleeRepairCB),
1675*da58b97aSjoerg                                         std::move(ACSRepairCB)));
1676*da58b97aSjoerg 
1677*da58b97aSjoerg   return true;
1678*da58b97aSjoerg }
1679*da58b97aSjoerg 
shouldSeedAttribute(AbstractAttribute & AA)1680*da58b97aSjoerg bool Attributor::shouldSeedAttribute(AbstractAttribute &AA) {
1681*da58b97aSjoerg   bool Result = true;
1682*da58b97aSjoerg #ifndef NDEBUG
1683*da58b97aSjoerg   if (SeedAllowList.size() != 0)
1684*da58b97aSjoerg     Result =
1685*da58b97aSjoerg         std::count(SeedAllowList.begin(), SeedAllowList.end(), AA.getName());
1686*da58b97aSjoerg   Function *Fn = AA.getAnchorScope();
1687*da58b97aSjoerg   if (FunctionSeedAllowList.size() != 0 && Fn)
1688*da58b97aSjoerg     Result &= std::count(FunctionSeedAllowList.begin(),
1689*da58b97aSjoerg                          FunctionSeedAllowList.end(), Fn->getName());
1690*da58b97aSjoerg #endif
1691*da58b97aSjoerg   return Result;
1692*da58b97aSjoerg }
1693*da58b97aSjoerg 
rewriteFunctionSignatures(SmallPtrSetImpl<Function * > & ModifiedFns)1694*da58b97aSjoerg ChangeStatus Attributor::rewriteFunctionSignatures(
1695*da58b97aSjoerg     SmallPtrSetImpl<Function *> &ModifiedFns) {
1696*da58b97aSjoerg   ChangeStatus Changed = ChangeStatus::UNCHANGED;
1697*da58b97aSjoerg 
1698*da58b97aSjoerg   for (auto &It : ArgumentReplacementMap) {
1699*da58b97aSjoerg     Function *OldFn = It.getFirst();
1700*da58b97aSjoerg 
1701*da58b97aSjoerg     // Deleted functions do not require rewrites.
1702*da58b97aSjoerg     if (!Functions.count(OldFn) || ToBeDeletedFunctions.count(OldFn))
1703*da58b97aSjoerg       continue;
1704*da58b97aSjoerg 
1705*da58b97aSjoerg     const SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
1706*da58b97aSjoerg         It.getSecond();
1707*da58b97aSjoerg     assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!");
1708*da58b97aSjoerg 
1709*da58b97aSjoerg     SmallVector<Type *, 16> NewArgumentTypes;
1710*da58b97aSjoerg     SmallVector<AttributeSet, 16> NewArgumentAttributes;
1711*da58b97aSjoerg 
1712*da58b97aSjoerg     // Collect replacement argument types and copy over existing attributes.
1713*da58b97aSjoerg     AttributeList OldFnAttributeList = OldFn->getAttributes();
1714*da58b97aSjoerg     for (Argument &Arg : OldFn->args()) {
1715*da58b97aSjoerg       if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
1716*da58b97aSjoerg               ARIs[Arg.getArgNo()]) {
1717*da58b97aSjoerg         NewArgumentTypes.append(ARI->ReplacementTypes.begin(),
1718*da58b97aSjoerg                                 ARI->ReplacementTypes.end());
1719*da58b97aSjoerg         NewArgumentAttributes.append(ARI->getNumReplacementArgs(),
1720*da58b97aSjoerg                                      AttributeSet());
1721*da58b97aSjoerg       } else {
1722*da58b97aSjoerg         NewArgumentTypes.push_back(Arg.getType());
1723*da58b97aSjoerg         NewArgumentAttributes.push_back(
1724*da58b97aSjoerg             OldFnAttributeList.getParamAttributes(Arg.getArgNo()));
1725*da58b97aSjoerg       }
1726*da58b97aSjoerg     }
1727*da58b97aSjoerg 
1728*da58b97aSjoerg     FunctionType *OldFnTy = OldFn->getFunctionType();
1729*da58b97aSjoerg     Type *RetTy = OldFnTy->getReturnType();
1730*da58b97aSjoerg 
1731*da58b97aSjoerg     // Construct the new function type using the new arguments types.
1732*da58b97aSjoerg     FunctionType *NewFnTy =
1733*da58b97aSjoerg         FunctionType::get(RetTy, NewArgumentTypes, OldFnTy->isVarArg());
1734*da58b97aSjoerg 
1735*da58b97aSjoerg     LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName()
1736*da58b97aSjoerg                       << "' from " << *OldFn->getFunctionType() << " to "
1737*da58b97aSjoerg                       << *NewFnTy << "\n");
1738*da58b97aSjoerg 
1739*da58b97aSjoerg     // Create the new function body and insert it into the module.
1740*da58b97aSjoerg     Function *NewFn = Function::Create(NewFnTy, OldFn->getLinkage(),
1741*da58b97aSjoerg                                        OldFn->getAddressSpace(), "");
1742*da58b97aSjoerg     OldFn->getParent()->getFunctionList().insert(OldFn->getIterator(), NewFn);
1743*da58b97aSjoerg     NewFn->takeName(OldFn);
1744*da58b97aSjoerg     NewFn->copyAttributesFrom(OldFn);
1745*da58b97aSjoerg 
1746*da58b97aSjoerg     // Patch the pointer to LLVM function in debug info descriptor.
1747*da58b97aSjoerg     NewFn->setSubprogram(OldFn->getSubprogram());
1748*da58b97aSjoerg     OldFn->setSubprogram(nullptr);
1749*da58b97aSjoerg 
1750*da58b97aSjoerg     // Recompute the parameter attributes list based on the new arguments for
1751*da58b97aSjoerg     // the function.
1752*da58b97aSjoerg     LLVMContext &Ctx = OldFn->getContext();
1753*da58b97aSjoerg     NewFn->setAttributes(AttributeList::get(
1754*da58b97aSjoerg         Ctx, OldFnAttributeList.getFnAttributes(),
1755*da58b97aSjoerg         OldFnAttributeList.getRetAttributes(), NewArgumentAttributes));
1756*da58b97aSjoerg 
1757*da58b97aSjoerg     // Since we have now created the new function, splice the body of the old
1758*da58b97aSjoerg     // function right into the new function, leaving the old rotting hulk of the
1759*da58b97aSjoerg     // function empty.
1760*da58b97aSjoerg     NewFn->getBasicBlockList().splice(NewFn->begin(),
1761*da58b97aSjoerg                                       OldFn->getBasicBlockList());
1762*da58b97aSjoerg 
1763*da58b97aSjoerg     // Fixup block addresses to reference new function.
1764*da58b97aSjoerg     SmallVector<BlockAddress *, 8u> BlockAddresses;
1765*da58b97aSjoerg     for (User *U : OldFn->users())
1766*da58b97aSjoerg       if (auto *BA = dyn_cast<BlockAddress>(U))
1767*da58b97aSjoerg         BlockAddresses.push_back(BA);
1768*da58b97aSjoerg     for (auto *BA : BlockAddresses)
1769*da58b97aSjoerg       BA->replaceAllUsesWith(BlockAddress::get(NewFn, BA->getBasicBlock()));
1770*da58b97aSjoerg 
1771*da58b97aSjoerg     // Set of all "call-like" instructions that invoke the old function mapped
1772*da58b97aSjoerg     // to their new replacements.
1773*da58b97aSjoerg     SmallVector<std::pair<CallBase *, CallBase *>, 8> CallSitePairs;
1774*da58b97aSjoerg 
1775*da58b97aSjoerg     // Callback to create a new "call-like" instruction for a given one.
1776*da58b97aSjoerg     auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) {
1777*da58b97aSjoerg       CallBase *OldCB = cast<CallBase>(ACS.getInstruction());
1778*da58b97aSjoerg       const AttributeList &OldCallAttributeList = OldCB->getAttributes();
1779*da58b97aSjoerg 
1780*da58b97aSjoerg       // Collect the new argument operands for the replacement call site.
1781*da58b97aSjoerg       SmallVector<Value *, 16> NewArgOperands;
1782*da58b97aSjoerg       SmallVector<AttributeSet, 16> NewArgOperandAttributes;
1783*da58b97aSjoerg       for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) {
1784*da58b97aSjoerg         unsigned NewFirstArgNum = NewArgOperands.size();
1785*da58b97aSjoerg         (void)NewFirstArgNum; // only used inside assert.
1786*da58b97aSjoerg         if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
1787*da58b97aSjoerg                 ARIs[OldArgNum]) {
1788*da58b97aSjoerg           if (ARI->ACSRepairCB)
1789*da58b97aSjoerg             ARI->ACSRepairCB(*ARI, ACS, NewArgOperands);
1790*da58b97aSjoerg           assert(ARI->getNumReplacementArgs() + NewFirstArgNum ==
1791*da58b97aSjoerg                      NewArgOperands.size() &&
1792*da58b97aSjoerg                  "ACS repair callback did not provide as many operand as new "
1793*da58b97aSjoerg                  "types were registered!");
1794*da58b97aSjoerg           // TODO: Exose the attribute set to the ACS repair callback
1795*da58b97aSjoerg           NewArgOperandAttributes.append(ARI->ReplacementTypes.size(),
1796*da58b97aSjoerg                                          AttributeSet());
1797*da58b97aSjoerg         } else {
1798*da58b97aSjoerg           NewArgOperands.push_back(ACS.getCallArgOperand(OldArgNum));
1799*da58b97aSjoerg           NewArgOperandAttributes.push_back(
1800*da58b97aSjoerg               OldCallAttributeList.getParamAttributes(OldArgNum));
1801*da58b97aSjoerg         }
1802*da58b97aSjoerg       }
1803*da58b97aSjoerg 
1804*da58b97aSjoerg       assert(NewArgOperands.size() == NewArgOperandAttributes.size() &&
1805*da58b97aSjoerg              "Mismatch # argument operands vs. # argument operand attributes!");
1806*da58b97aSjoerg       assert(NewArgOperands.size() == NewFn->arg_size() &&
1807*da58b97aSjoerg              "Mismatch # argument operands vs. # function arguments!");
1808*da58b97aSjoerg 
1809*da58b97aSjoerg       SmallVector<OperandBundleDef, 4> OperandBundleDefs;
1810*da58b97aSjoerg       OldCB->getOperandBundlesAsDefs(OperandBundleDefs);
1811*da58b97aSjoerg 
1812*da58b97aSjoerg       // Create a new call or invoke instruction to replace the old one.
1813*da58b97aSjoerg       CallBase *NewCB;
1814*da58b97aSjoerg       if (InvokeInst *II = dyn_cast<InvokeInst>(OldCB)) {
1815*da58b97aSjoerg         NewCB =
1816*da58b97aSjoerg             InvokeInst::Create(NewFn, II->getNormalDest(), II->getUnwindDest(),
1817*da58b97aSjoerg                                NewArgOperands, OperandBundleDefs, "", OldCB);
1818*da58b97aSjoerg       } else {
1819*da58b97aSjoerg         auto *NewCI = CallInst::Create(NewFn, NewArgOperands, OperandBundleDefs,
1820*da58b97aSjoerg                                        "", OldCB);
1821*da58b97aSjoerg         NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind());
1822*da58b97aSjoerg         NewCB = NewCI;
1823*da58b97aSjoerg       }
1824*da58b97aSjoerg 
1825*da58b97aSjoerg       // Copy over various properties and the new attributes.
1826*da58b97aSjoerg       NewCB->copyMetadata(*OldCB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
1827*da58b97aSjoerg       NewCB->setCallingConv(OldCB->getCallingConv());
1828*da58b97aSjoerg       NewCB->takeName(OldCB);
1829*da58b97aSjoerg       NewCB->setAttributes(AttributeList::get(
1830*da58b97aSjoerg           Ctx, OldCallAttributeList.getFnAttributes(),
1831*da58b97aSjoerg           OldCallAttributeList.getRetAttributes(), NewArgOperandAttributes));
1832*da58b97aSjoerg 
1833*da58b97aSjoerg       CallSitePairs.push_back({OldCB, NewCB});
1834*da58b97aSjoerg       return true;
1835*da58b97aSjoerg     };
1836*da58b97aSjoerg 
1837*da58b97aSjoerg     // Use the CallSiteReplacementCreator to create replacement call sites.
1838*da58b97aSjoerg     bool AllCallSitesKnown;
1839*da58b97aSjoerg     bool Success = checkForAllCallSites(CallSiteReplacementCreator, *OldFn,
1840*da58b97aSjoerg                                         true, nullptr, AllCallSitesKnown);
1841*da58b97aSjoerg     (void)Success;
1842*da58b97aSjoerg     assert(Success && "Assumed call site replacement to succeed!");
1843*da58b97aSjoerg 
1844*da58b97aSjoerg     // Rewire the arguments.
1845*da58b97aSjoerg     Argument *OldFnArgIt = OldFn->arg_begin();
1846*da58b97aSjoerg     Argument *NewFnArgIt = NewFn->arg_begin();
1847*da58b97aSjoerg     for (unsigned OldArgNum = 0; OldArgNum < ARIs.size();
1848*da58b97aSjoerg          ++OldArgNum, ++OldFnArgIt) {
1849*da58b97aSjoerg       if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
1850*da58b97aSjoerg               ARIs[OldArgNum]) {
1851*da58b97aSjoerg         if (ARI->CalleeRepairCB)
1852*da58b97aSjoerg           ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt);
1853*da58b97aSjoerg         NewFnArgIt += ARI->ReplacementTypes.size();
1854*da58b97aSjoerg       } else {
1855*da58b97aSjoerg         NewFnArgIt->takeName(&*OldFnArgIt);
1856*da58b97aSjoerg         OldFnArgIt->replaceAllUsesWith(&*NewFnArgIt);
1857*da58b97aSjoerg         ++NewFnArgIt;
1858*da58b97aSjoerg       }
1859*da58b97aSjoerg     }
1860*da58b97aSjoerg 
1861*da58b97aSjoerg     // Eliminate the instructions *after* we visited all of them.
1862*da58b97aSjoerg     for (auto &CallSitePair : CallSitePairs) {
1863*da58b97aSjoerg       CallBase &OldCB = *CallSitePair.first;
1864*da58b97aSjoerg       CallBase &NewCB = *CallSitePair.second;
1865*da58b97aSjoerg       assert(OldCB.getType() == NewCB.getType() &&
1866*da58b97aSjoerg              "Cannot handle call sites with different types!");
1867*da58b97aSjoerg       ModifiedFns.insert(OldCB.getFunction());
1868*da58b97aSjoerg       CGUpdater.replaceCallSite(OldCB, NewCB);
1869*da58b97aSjoerg       OldCB.replaceAllUsesWith(&NewCB);
1870*da58b97aSjoerg       OldCB.eraseFromParent();
1871*da58b97aSjoerg     }
1872*da58b97aSjoerg 
1873*da58b97aSjoerg     // Replace the function in the call graph (if any).
1874*da58b97aSjoerg     CGUpdater.replaceFunctionWith(*OldFn, *NewFn);
1875*da58b97aSjoerg 
1876*da58b97aSjoerg     // If the old function was modified and needed to be reanalyzed, the new one
1877*da58b97aSjoerg     // does now.
1878*da58b97aSjoerg     if (ModifiedFns.erase(OldFn))
1879*da58b97aSjoerg       ModifiedFns.insert(NewFn);
1880*da58b97aSjoerg 
1881*da58b97aSjoerg     Changed = ChangeStatus::CHANGED;
1882*da58b97aSjoerg   }
1883*da58b97aSjoerg 
1884*da58b97aSjoerg   return Changed;
1885*da58b97aSjoerg }
1886*da58b97aSjoerg 
initializeInformationCache(const Function & CF,FunctionInfo & FI)1887*da58b97aSjoerg void InformationCache::initializeInformationCache(const Function &CF,
1888*da58b97aSjoerg                                                   FunctionInfo &FI) {
1889*da58b97aSjoerg   // As we do not modify the function here we can remove the const
1890*da58b97aSjoerg   // withouth breaking implicit assumptions. At the end of the day, we could
1891*da58b97aSjoerg   // initialize the cache eagerly which would look the same to the users.
1892*da58b97aSjoerg   Function &F = const_cast<Function &>(CF);
189306f32e7eSjoerg 
189406f32e7eSjoerg   // Walk all instructions to find interesting instructions that might be
189506f32e7eSjoerg   // queried by abstract attributes during their initialization or update.
189606f32e7eSjoerg   // This has to happen before we create attributes.
189706f32e7eSjoerg 
189806f32e7eSjoerg   for (Instruction &I : instructions(&F)) {
189906f32e7eSjoerg     bool IsInterestingOpcode = false;
190006f32e7eSjoerg 
190106f32e7eSjoerg     // To allow easy access to all instructions in a function with a given
190206f32e7eSjoerg     // opcode we store them in the InfoCache. As not all opcodes are interesting
190306f32e7eSjoerg     // to concrete attributes we only cache the ones that are as identified in
190406f32e7eSjoerg     // the following switch.
190506f32e7eSjoerg     // Note: There are no concrete attributes now so this is initially empty.
190606f32e7eSjoerg     switch (I.getOpcode()) {
190706f32e7eSjoerg     default:
1908*da58b97aSjoerg       assert(!isa<CallBase>(&I) &&
1909*da58b97aSjoerg              "New call base instruction type needs to be known in the "
191006f32e7eSjoerg              "Attributor.");
191106f32e7eSjoerg       break;
191206f32e7eSjoerg     case Instruction::Call:
1913*da58b97aSjoerg       // Calls are interesting on their own, additionally:
1914*da58b97aSjoerg       // For `llvm.assume` calls we also fill the KnowledgeMap as we find them.
1915*da58b97aSjoerg       // For `must-tail` calls we remember the caller and callee.
1916*da58b97aSjoerg       if (auto *Assume = dyn_cast<AssumeInst>(&I)) {
1917*da58b97aSjoerg         fillMapFromAssume(*Assume, KnowledgeMap);
1918*da58b97aSjoerg       } else if (cast<CallInst>(I).isMustTailCall()) {
1919*da58b97aSjoerg         FI.ContainsMustTailCall = true;
1920*da58b97aSjoerg         if (const Function *Callee = cast<CallInst>(I).getCalledFunction())
1921*da58b97aSjoerg           getFunctionInfo(*Callee).CalledViaMustTail = true;
1922*da58b97aSjoerg       }
1923*da58b97aSjoerg       LLVM_FALLTHROUGH;
192406f32e7eSjoerg     case Instruction::CallBr:
192506f32e7eSjoerg     case Instruction::Invoke:
192606f32e7eSjoerg     case Instruction::CleanupRet:
192706f32e7eSjoerg     case Instruction::CatchSwitch:
1928*da58b97aSjoerg     case Instruction::AtomicRMW:
1929*da58b97aSjoerg     case Instruction::AtomicCmpXchg:
1930*da58b97aSjoerg     case Instruction::Br:
193106f32e7eSjoerg     case Instruction::Resume:
193206f32e7eSjoerg     case Instruction::Ret:
1933*da58b97aSjoerg     case Instruction::Load:
1934*da58b97aSjoerg       // The alignment of a pointer is interesting for loads.
1935*da58b97aSjoerg     case Instruction::Store:
1936*da58b97aSjoerg       // The alignment of a pointer is interesting for stores.
193706f32e7eSjoerg       IsInterestingOpcode = true;
193806f32e7eSjoerg     }
1939*da58b97aSjoerg     if (IsInterestingOpcode) {
1940*da58b97aSjoerg       auto *&Insts = FI.OpcodeInstMap[I.getOpcode()];
1941*da58b97aSjoerg       if (!Insts)
1942*da58b97aSjoerg         Insts = new (Allocator) InstructionVectorTy();
1943*da58b97aSjoerg       Insts->push_back(&I);
1944*da58b97aSjoerg     }
194506f32e7eSjoerg     if (I.mayReadOrWriteMemory())
1946*da58b97aSjoerg       FI.RWInsts.push_back(&I);
1947*da58b97aSjoerg   }
1948*da58b97aSjoerg 
1949*da58b97aSjoerg   if (F.hasFnAttribute(Attribute::AlwaysInline) &&
1950*da58b97aSjoerg       isInlineViable(F).isSuccess())
1951*da58b97aSjoerg     InlineableFunctions.insert(&F);
1952*da58b97aSjoerg }
1953*da58b97aSjoerg 
getAAResultsForFunction(const Function & F)1954*da58b97aSjoerg AAResults *InformationCache::getAAResultsForFunction(const Function &F) {
1955*da58b97aSjoerg   return AG.getAnalysis<AAManager>(F);
1956*da58b97aSjoerg }
1957*da58b97aSjoerg 
~FunctionInfo()1958*da58b97aSjoerg InformationCache::FunctionInfo::~FunctionInfo() {
1959*da58b97aSjoerg   // The instruction vectors are allocated using a BumpPtrAllocator, we need to
1960*da58b97aSjoerg   // manually destroy them.
1961*da58b97aSjoerg   for (auto &It : OpcodeInstMap)
1962*da58b97aSjoerg     It.getSecond()->~InstructionVectorTy();
1963*da58b97aSjoerg }
1964*da58b97aSjoerg 
recordDependence(const AbstractAttribute & FromAA,const AbstractAttribute & ToAA,DepClassTy DepClass)1965*da58b97aSjoerg void Attributor::recordDependence(const AbstractAttribute &FromAA,
1966*da58b97aSjoerg                                   const AbstractAttribute &ToAA,
1967*da58b97aSjoerg                                   DepClassTy DepClass) {
1968*da58b97aSjoerg   if (DepClass == DepClassTy::NONE)
1969*da58b97aSjoerg     return;
1970*da58b97aSjoerg   // If we are outside of an update, thus before the actual fixpoint iteration
1971*da58b97aSjoerg   // started (= when we create AAs), we do not track dependences because we will
1972*da58b97aSjoerg   // put all AAs into the initial worklist anyway.
1973*da58b97aSjoerg   if (DependenceStack.empty())
1974*da58b97aSjoerg     return;
1975*da58b97aSjoerg   if (FromAA.getState().isAtFixpoint())
1976*da58b97aSjoerg     return;
1977*da58b97aSjoerg   DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass});
1978*da58b97aSjoerg }
1979*da58b97aSjoerg 
rememberDependences()1980*da58b97aSjoerg void Attributor::rememberDependences() {
1981*da58b97aSjoerg   assert(!DependenceStack.empty() && "No dependences to remember!");
1982*da58b97aSjoerg 
1983*da58b97aSjoerg   for (DepInfo &DI : *DependenceStack.back()) {
1984*da58b97aSjoerg     assert((DI.DepClass == DepClassTy::REQUIRED ||
1985*da58b97aSjoerg             DI.DepClass == DepClassTy::OPTIONAL) &&
1986*da58b97aSjoerg            "Expected required or optional dependence (1 bit)!");
1987*da58b97aSjoerg     auto &DepAAs = const_cast<AbstractAttribute &>(*DI.FromAA).Deps;
1988*da58b97aSjoerg     DepAAs.push_back(AbstractAttribute::DepTy(
1989*da58b97aSjoerg         const_cast<AbstractAttribute *>(DI.ToAA), unsigned(DI.DepClass)));
199006f32e7eSjoerg   }
199106f32e7eSjoerg }
199206f32e7eSjoerg 
identifyDefaultAbstractAttributes(Function & F)199306f32e7eSjoerg void Attributor::identifyDefaultAbstractAttributes(Function &F) {
199406f32e7eSjoerg   if (!VisitedFunctions.insert(&F).second)
199506f32e7eSjoerg     return;
1996*da58b97aSjoerg   if (F.isDeclaration())
1997*da58b97aSjoerg     return;
1998*da58b97aSjoerg 
1999*da58b97aSjoerg   // In non-module runs we need to look at the call sites of a function to
2000*da58b97aSjoerg   // determine if it is part of a must-tail call edge. This will influence what
2001*da58b97aSjoerg   // attributes we can derive.
2002*da58b97aSjoerg   InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F);
2003*da58b97aSjoerg   if (!isModulePass() && !FI.CalledViaMustTail) {
2004*da58b97aSjoerg     for (const Use &U : F.uses())
2005*da58b97aSjoerg       if (const auto *CB = dyn_cast<CallBase>(U.getUser()))
2006*da58b97aSjoerg         if (CB->isCallee(&U) && CB->isMustTailCall())
2007*da58b97aSjoerg           FI.CalledViaMustTail = true;
2008*da58b97aSjoerg   }
200906f32e7eSjoerg 
201006f32e7eSjoerg   IRPosition FPos = IRPosition::function(F);
201106f32e7eSjoerg 
201206f32e7eSjoerg   // Check for dead BasicBlocks in every function.
201306f32e7eSjoerg   // We need dead instruction detection because we do not want to deal with
201406f32e7eSjoerg   // broken IR in which SSA rules do not apply.
201506f32e7eSjoerg   getOrCreateAAFor<AAIsDead>(FPos);
201606f32e7eSjoerg 
201706f32e7eSjoerg   // Every function might be "will-return".
201806f32e7eSjoerg   getOrCreateAAFor<AAWillReturn>(FPos);
201906f32e7eSjoerg 
2020*da58b97aSjoerg   // Every function might contain instructions that cause "undefined behavior".
2021*da58b97aSjoerg   getOrCreateAAFor<AAUndefinedBehavior>(FPos);
2022*da58b97aSjoerg 
202306f32e7eSjoerg   // Every function can be nounwind.
202406f32e7eSjoerg   getOrCreateAAFor<AANoUnwind>(FPos);
202506f32e7eSjoerg 
202606f32e7eSjoerg   // Every function might be marked "nosync"
202706f32e7eSjoerg   getOrCreateAAFor<AANoSync>(FPos);
202806f32e7eSjoerg 
202906f32e7eSjoerg   // Every function might be "no-free".
203006f32e7eSjoerg   getOrCreateAAFor<AANoFree>(FPos);
203106f32e7eSjoerg 
203206f32e7eSjoerg   // Every function might be "no-return".
203306f32e7eSjoerg   getOrCreateAAFor<AANoReturn>(FPos);
203406f32e7eSjoerg 
203506f32e7eSjoerg   // Every function might be "no-recurse".
203606f32e7eSjoerg   getOrCreateAAFor<AANoRecurse>(FPos);
203706f32e7eSjoerg 
203806f32e7eSjoerg   // Every function might be "readnone/readonly/writeonly/...".
203906f32e7eSjoerg   getOrCreateAAFor<AAMemoryBehavior>(FPos);
204006f32e7eSjoerg 
2041*da58b97aSjoerg   // Every function can be "readnone/argmemonly/inaccessiblememonly/...".
2042*da58b97aSjoerg   getOrCreateAAFor<AAMemoryLocation>(FPos);
2043*da58b97aSjoerg 
204406f32e7eSjoerg   // Every function might be applicable for Heap-To-Stack conversion.
204506f32e7eSjoerg   if (EnableHeapToStack)
204606f32e7eSjoerg     getOrCreateAAFor<AAHeapToStack>(FPos);
204706f32e7eSjoerg 
204806f32e7eSjoerg   // Return attributes are only appropriate if the return type is non void.
204906f32e7eSjoerg   Type *ReturnType = F.getReturnType();
205006f32e7eSjoerg   if (!ReturnType->isVoidTy()) {
205106f32e7eSjoerg     // Argument attribute "returned" --- Create only one per function even
205206f32e7eSjoerg     // though it is an argument attribute.
205306f32e7eSjoerg     getOrCreateAAFor<AAReturnedValues>(FPos);
205406f32e7eSjoerg 
205506f32e7eSjoerg     IRPosition RetPos = IRPosition::returned(F);
205606f32e7eSjoerg 
2057*da58b97aSjoerg     // Every returned value might be dead.
2058*da58b97aSjoerg     getOrCreateAAFor<AAIsDead>(RetPos);
2059*da58b97aSjoerg 
206006f32e7eSjoerg     // Every function might be simplified.
206106f32e7eSjoerg     getOrCreateAAFor<AAValueSimplify>(RetPos);
206206f32e7eSjoerg 
2063*da58b97aSjoerg     // Every returned value might be marked noundef.
2064*da58b97aSjoerg     getOrCreateAAFor<AANoUndef>(RetPos);
2065*da58b97aSjoerg 
206606f32e7eSjoerg     if (ReturnType->isPointerTy()) {
206706f32e7eSjoerg 
206806f32e7eSjoerg       // Every function with pointer return type might be marked align.
206906f32e7eSjoerg       getOrCreateAAFor<AAAlign>(RetPos);
207006f32e7eSjoerg 
207106f32e7eSjoerg       // Every function with pointer return type might be marked nonnull.
207206f32e7eSjoerg       getOrCreateAAFor<AANonNull>(RetPos);
207306f32e7eSjoerg 
207406f32e7eSjoerg       // Every function with pointer return type might be marked noalias.
207506f32e7eSjoerg       getOrCreateAAFor<AANoAlias>(RetPos);
207606f32e7eSjoerg 
207706f32e7eSjoerg       // Every function with pointer return type might be marked
207806f32e7eSjoerg       // dereferenceable.
207906f32e7eSjoerg       getOrCreateAAFor<AADereferenceable>(RetPos);
208006f32e7eSjoerg     }
208106f32e7eSjoerg   }
208206f32e7eSjoerg 
208306f32e7eSjoerg   for (Argument &Arg : F.args()) {
208406f32e7eSjoerg     IRPosition ArgPos = IRPosition::argument(Arg);
208506f32e7eSjoerg 
208606f32e7eSjoerg     // Every argument might be simplified.
208706f32e7eSjoerg     getOrCreateAAFor<AAValueSimplify>(ArgPos);
208806f32e7eSjoerg 
2089*da58b97aSjoerg     // Every argument might be dead.
2090*da58b97aSjoerg     getOrCreateAAFor<AAIsDead>(ArgPos);
2091*da58b97aSjoerg 
2092*da58b97aSjoerg     // Every argument might be marked noundef.
2093*da58b97aSjoerg     getOrCreateAAFor<AANoUndef>(ArgPos);
2094*da58b97aSjoerg 
209506f32e7eSjoerg     if (Arg.getType()->isPointerTy()) {
209606f32e7eSjoerg       // Every argument with pointer type might be marked nonnull.
209706f32e7eSjoerg       getOrCreateAAFor<AANonNull>(ArgPos);
209806f32e7eSjoerg 
209906f32e7eSjoerg       // Every argument with pointer type might be marked noalias.
210006f32e7eSjoerg       getOrCreateAAFor<AANoAlias>(ArgPos);
210106f32e7eSjoerg 
210206f32e7eSjoerg       // Every argument with pointer type might be marked dereferenceable.
210306f32e7eSjoerg       getOrCreateAAFor<AADereferenceable>(ArgPos);
210406f32e7eSjoerg 
210506f32e7eSjoerg       // Every argument with pointer type might be marked align.
210606f32e7eSjoerg       getOrCreateAAFor<AAAlign>(ArgPos);
210706f32e7eSjoerg 
210806f32e7eSjoerg       // Every argument with pointer type might be marked nocapture.
210906f32e7eSjoerg       getOrCreateAAFor<AANoCapture>(ArgPos);
211006f32e7eSjoerg 
211106f32e7eSjoerg       // Every argument with pointer type might be marked
211206f32e7eSjoerg       // "readnone/readonly/writeonly/..."
211306f32e7eSjoerg       getOrCreateAAFor<AAMemoryBehavior>(ArgPos);
2114*da58b97aSjoerg 
2115*da58b97aSjoerg       // Every argument with pointer type might be marked nofree.
2116*da58b97aSjoerg       getOrCreateAAFor<AANoFree>(ArgPos);
2117*da58b97aSjoerg 
2118*da58b97aSjoerg       // Every argument with pointer type might be privatizable (or promotable)
2119*da58b97aSjoerg       getOrCreateAAFor<AAPrivatizablePtr>(ArgPos);
212006f32e7eSjoerg     }
212106f32e7eSjoerg   }
212206f32e7eSjoerg 
212306f32e7eSjoerg   auto CallSitePred = [&](Instruction &I) -> bool {
2124*da58b97aSjoerg     auto &CB = cast<CallBase>(I);
2125*da58b97aSjoerg     IRPosition CBRetPos = IRPosition::callsite_returned(CB);
212606f32e7eSjoerg 
2127*da58b97aSjoerg     // Call sites might be dead if they do not have side effects and no live
2128*da58b97aSjoerg     // users. The return value might be dead if there are no live users.
2129*da58b97aSjoerg     getOrCreateAAFor<AAIsDead>(CBRetPos);
2130*da58b97aSjoerg 
2131*da58b97aSjoerg     Function *Callee = CB.getCalledFunction();
2132*da58b97aSjoerg     // TODO: Even if the callee is not known now we might be able to simplify
2133*da58b97aSjoerg     //       the call/callee.
2134*da58b97aSjoerg     if (!Callee)
2135*da58b97aSjoerg       return true;
2136*da58b97aSjoerg 
2137*da58b97aSjoerg     // Skip declarations except if annotations on their call sites were
2138*da58b97aSjoerg     // explicitly requested.
2139*da58b97aSjoerg     if (!AnnotateDeclarationCallSites && Callee->isDeclaration() &&
2140*da58b97aSjoerg         !Callee->hasMetadata(LLVMContext::MD_callback))
2141*da58b97aSjoerg       return true;
2142*da58b97aSjoerg 
2143*da58b97aSjoerg     if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) {
2144*da58b97aSjoerg 
2145*da58b97aSjoerg       IRPosition CBRetPos = IRPosition::callsite_returned(CB);
2146*da58b97aSjoerg 
2147*da58b97aSjoerg       // Call site return integer values might be limited by a constant range.
2148*da58b97aSjoerg       if (Callee->getReturnType()->isIntegerTy())
2149*da58b97aSjoerg         getOrCreateAAFor<AAValueConstantRange>(CBRetPos);
2150*da58b97aSjoerg     }
2151*da58b97aSjoerg 
2152*da58b97aSjoerg     for (int I = 0, E = CB.getNumArgOperands(); I < E; ++I) {
2153*da58b97aSjoerg 
2154*da58b97aSjoerg       IRPosition CBArgPos = IRPosition::callsite_argument(CB, I);
2155*da58b97aSjoerg 
2156*da58b97aSjoerg       // Every call site argument might be dead.
2157*da58b97aSjoerg       getOrCreateAAFor<AAIsDead>(CBArgPos);
215806f32e7eSjoerg 
215906f32e7eSjoerg       // Call site argument might be simplified.
2160*da58b97aSjoerg       getOrCreateAAFor<AAValueSimplify>(CBArgPos);
216106f32e7eSjoerg 
2162*da58b97aSjoerg       // Every call site argument might be marked "noundef".
2163*da58b97aSjoerg       getOrCreateAAFor<AANoUndef>(CBArgPos);
2164*da58b97aSjoerg 
2165*da58b97aSjoerg       if (!CB.getArgOperand(I)->getType()->isPointerTy())
216606f32e7eSjoerg         continue;
216706f32e7eSjoerg 
216806f32e7eSjoerg       // Call site argument attribute "non-null".
2169*da58b97aSjoerg       getOrCreateAAFor<AANonNull>(CBArgPos);
2170*da58b97aSjoerg 
2171*da58b97aSjoerg       // Call site argument attribute "nocapture".
2172*da58b97aSjoerg       getOrCreateAAFor<AANoCapture>(CBArgPos);
217306f32e7eSjoerg 
217406f32e7eSjoerg       // Call site argument attribute "no-alias".
2175*da58b97aSjoerg       getOrCreateAAFor<AANoAlias>(CBArgPos);
217606f32e7eSjoerg 
217706f32e7eSjoerg       // Call site argument attribute "dereferenceable".
2178*da58b97aSjoerg       getOrCreateAAFor<AADereferenceable>(CBArgPos);
217906f32e7eSjoerg 
218006f32e7eSjoerg       // Call site argument attribute "align".
2181*da58b97aSjoerg       getOrCreateAAFor<AAAlign>(CBArgPos);
2182*da58b97aSjoerg 
2183*da58b97aSjoerg       // Call site argument attribute
2184*da58b97aSjoerg       // "readnone/readonly/writeonly/..."
2185*da58b97aSjoerg       getOrCreateAAFor<AAMemoryBehavior>(CBArgPos);
2186*da58b97aSjoerg 
2187*da58b97aSjoerg       // Call site argument attribute "nofree".
2188*da58b97aSjoerg       getOrCreateAAFor<AANoFree>(CBArgPos);
218906f32e7eSjoerg     }
219006f32e7eSjoerg     return true;
219106f32e7eSjoerg   };
219206f32e7eSjoerg 
219306f32e7eSjoerg   auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
2194*da58b97aSjoerg   bool Success;
219506f32e7eSjoerg   Success = checkForAllInstructionsImpl(
2196*da58b97aSjoerg       nullptr, OpcodeInstMap, CallSitePred, nullptr, nullptr,
219706f32e7eSjoerg       {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
219806f32e7eSjoerg        (unsigned)Instruction::Call});
219906f32e7eSjoerg   (void)Success;
2200*da58b97aSjoerg   assert(Success && "Expected the check call to be successful!");
220106f32e7eSjoerg 
220206f32e7eSjoerg   auto LoadStorePred = [&](Instruction &I) -> bool {
220306f32e7eSjoerg     if (isa<LoadInst>(I))
220406f32e7eSjoerg       getOrCreateAAFor<AAAlign>(
220506f32e7eSjoerg           IRPosition::value(*cast<LoadInst>(I).getPointerOperand()));
220606f32e7eSjoerg     else
220706f32e7eSjoerg       getOrCreateAAFor<AAAlign>(
220806f32e7eSjoerg           IRPosition::value(*cast<StoreInst>(I).getPointerOperand()));
220906f32e7eSjoerg     return true;
221006f32e7eSjoerg   };
221106f32e7eSjoerg   Success = checkForAllInstructionsImpl(
2212*da58b97aSjoerg       nullptr, OpcodeInstMap, LoadStorePred, nullptr, nullptr,
221306f32e7eSjoerg       {(unsigned)Instruction::Load, (unsigned)Instruction::Store});
221406f32e7eSjoerg   (void)Success;
2215*da58b97aSjoerg   assert(Success && "Expected the check call to be successful!");
221606f32e7eSjoerg }
221706f32e7eSjoerg 
221806f32e7eSjoerg /// Helpers to ease debugging through output streams and print calls.
221906f32e7eSjoerg ///
222006f32e7eSjoerg ///{
operator <<(raw_ostream & OS,ChangeStatus S)222106f32e7eSjoerg raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) {
222206f32e7eSjoerg   return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
222306f32e7eSjoerg }
222406f32e7eSjoerg 
operator <<(raw_ostream & OS,IRPosition::Kind AP)222506f32e7eSjoerg raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) {
222606f32e7eSjoerg   switch (AP) {
222706f32e7eSjoerg   case IRPosition::IRP_INVALID:
222806f32e7eSjoerg     return OS << "inv";
222906f32e7eSjoerg   case IRPosition::IRP_FLOAT:
223006f32e7eSjoerg     return OS << "flt";
223106f32e7eSjoerg   case IRPosition::IRP_RETURNED:
223206f32e7eSjoerg     return OS << "fn_ret";
223306f32e7eSjoerg   case IRPosition::IRP_CALL_SITE_RETURNED:
223406f32e7eSjoerg     return OS << "cs_ret";
223506f32e7eSjoerg   case IRPosition::IRP_FUNCTION:
223606f32e7eSjoerg     return OS << "fn";
223706f32e7eSjoerg   case IRPosition::IRP_CALL_SITE:
223806f32e7eSjoerg     return OS << "cs";
223906f32e7eSjoerg   case IRPosition::IRP_ARGUMENT:
224006f32e7eSjoerg     return OS << "arg";
224106f32e7eSjoerg   case IRPosition::IRP_CALL_SITE_ARGUMENT:
224206f32e7eSjoerg     return OS << "cs_arg";
224306f32e7eSjoerg   }
224406f32e7eSjoerg   llvm_unreachable("Unknown attribute position!");
224506f32e7eSjoerg }
224606f32e7eSjoerg 
operator <<(raw_ostream & OS,const IRPosition & Pos)224706f32e7eSjoerg raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) {
224806f32e7eSjoerg   const Value &AV = Pos.getAssociatedValue();
2249*da58b97aSjoerg   OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " ["
2250*da58b97aSjoerg      << Pos.getAnchorValue().getName() << "@" << Pos.getCallSiteArgNo() << "]";
2251*da58b97aSjoerg 
2252*da58b97aSjoerg   if (Pos.hasCallBaseContext())
2253*da58b97aSjoerg     OS << "[cb_context:" << *Pos.getCallBaseContext() << "]";
2254*da58b97aSjoerg   return OS << "}";
225506f32e7eSjoerg }
225606f32e7eSjoerg 
operator <<(raw_ostream & OS,const IntegerRangeState & S)2257*da58b97aSjoerg raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerRangeState &S) {
2258*da58b97aSjoerg   OS << "range-state(" << S.getBitWidth() << ")<";
2259*da58b97aSjoerg   S.getKnown().print(OS);
2260*da58b97aSjoerg   OS << " / ";
2261*da58b97aSjoerg   S.getAssumed().print(OS);
2262*da58b97aSjoerg   OS << ">";
2263*da58b97aSjoerg 
2264*da58b97aSjoerg   return OS << static_cast<const AbstractState &>(S);
226506f32e7eSjoerg }
226606f32e7eSjoerg 
operator <<(raw_ostream & OS,const AbstractState & S)226706f32e7eSjoerg raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) {
226806f32e7eSjoerg   return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
226906f32e7eSjoerg }
227006f32e7eSjoerg 
operator <<(raw_ostream & OS,const AbstractAttribute & AA)227106f32e7eSjoerg raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) {
227206f32e7eSjoerg   AA.print(OS);
227306f32e7eSjoerg   return OS;
227406f32e7eSjoerg }
227506f32e7eSjoerg 
operator <<(raw_ostream & OS,const PotentialConstantIntValuesState & S)2276*da58b97aSjoerg raw_ostream &llvm::operator<<(raw_ostream &OS,
2277*da58b97aSjoerg                               const PotentialConstantIntValuesState &S) {
2278*da58b97aSjoerg   OS << "set-state(< {";
2279*da58b97aSjoerg   if (!S.isValidState())
2280*da58b97aSjoerg     OS << "full-set";
2281*da58b97aSjoerg   else {
2282*da58b97aSjoerg     for (auto &it : S.getAssumedSet())
2283*da58b97aSjoerg       OS << it << ", ";
2284*da58b97aSjoerg     if (S.undefIsContained())
2285*da58b97aSjoerg       OS << "undef ";
2286*da58b97aSjoerg   }
2287*da58b97aSjoerg   OS << "} >)";
2288*da58b97aSjoerg 
2289*da58b97aSjoerg   return OS;
2290*da58b97aSjoerg }
2291*da58b97aSjoerg 
print(raw_ostream & OS) const229206f32e7eSjoerg void AbstractAttribute::print(raw_ostream &OS) const {
2293*da58b97aSjoerg   OS << "[";
2294*da58b97aSjoerg   OS << getName();
2295*da58b97aSjoerg   OS << "] for CtxI ";
2296*da58b97aSjoerg 
2297*da58b97aSjoerg   if (auto *I = getCtxI()) {
2298*da58b97aSjoerg     OS << "'";
2299*da58b97aSjoerg     I->print(OS);
2300*da58b97aSjoerg     OS << "'";
2301*da58b97aSjoerg   } else
2302*da58b97aSjoerg     OS << "<<null inst>>";
2303*da58b97aSjoerg 
2304*da58b97aSjoerg   OS << " at position " << getIRPosition() << " with state " << getAsStr()
2305*da58b97aSjoerg      << '\n';
2306*da58b97aSjoerg }
2307*da58b97aSjoerg 
printWithDeps(raw_ostream & OS) const2308*da58b97aSjoerg void AbstractAttribute::printWithDeps(raw_ostream &OS) const {
2309*da58b97aSjoerg   print(OS);
2310*da58b97aSjoerg 
2311*da58b97aSjoerg   for (const auto &DepAA : Deps) {
2312*da58b97aSjoerg     auto *AA = DepAA.getPointer();
2313*da58b97aSjoerg     OS << "  updates ";
2314*da58b97aSjoerg     AA->print(OS);
2315*da58b97aSjoerg   }
2316*da58b97aSjoerg 
2317*da58b97aSjoerg   OS << '\n';
231806f32e7eSjoerg }
231906f32e7eSjoerg ///}
232006f32e7eSjoerg 
232106f32e7eSjoerg /// ----------------------------------------------------------------------------
232206f32e7eSjoerg ///                       Pass (Manager) Boilerplate
232306f32e7eSjoerg /// ----------------------------------------------------------------------------
232406f32e7eSjoerg 
runAttributorOnFunctions(InformationCache & InfoCache,SetVector<Function * > & Functions,AnalysisGetter & AG,CallGraphUpdater & CGUpdater,bool DeleteFns)2325*da58b97aSjoerg static bool runAttributorOnFunctions(InformationCache &InfoCache,
2326*da58b97aSjoerg                                      SetVector<Function *> &Functions,
2327*da58b97aSjoerg                                      AnalysisGetter &AG,
2328*da58b97aSjoerg                                      CallGraphUpdater &CGUpdater,
2329*da58b97aSjoerg                                      bool DeleteFns) {
2330*da58b97aSjoerg   if (Functions.empty())
233106f32e7eSjoerg     return false;
233206f32e7eSjoerg 
2333*da58b97aSjoerg   LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << Functions.size()
233406f32e7eSjoerg                     << " functions.\n");
233506f32e7eSjoerg 
233606f32e7eSjoerg   // Create an Attributor and initially empty information cache that is filled
233706f32e7eSjoerg   // while we identify default attribute opportunities.
2338*da58b97aSjoerg   Attributor A(Functions, InfoCache, CGUpdater, /* Allowed */ nullptr,
2339*da58b97aSjoerg                DeleteFns);
234006f32e7eSjoerg 
2341*da58b97aSjoerg   // Create shallow wrappers for all functions that are not IPO amendable
2342*da58b97aSjoerg   if (AllowShallowWrappers)
2343*da58b97aSjoerg     for (Function *F : Functions)
2344*da58b97aSjoerg       if (!A.isFunctionIPOAmendable(*F))
2345*da58b97aSjoerg         Attributor::createShallowWrapper(*F);
234606f32e7eSjoerg 
2347*da58b97aSjoerg   // Internalize non-exact functions
2348*da58b97aSjoerg   // TODO: for now we eagerly internalize functions without calculating the
2349*da58b97aSjoerg   //       cost, we need a cost interface to determine whether internalizing
2350*da58b97aSjoerg   //       a function is "benefitial"
2351*da58b97aSjoerg   if (AllowDeepWrapper) {
2352*da58b97aSjoerg     unsigned FunSize = Functions.size();
2353*da58b97aSjoerg     for (unsigned u = 0; u < FunSize; u++) {
2354*da58b97aSjoerg       Function *F = Functions[u];
2355*da58b97aSjoerg       if (!F->isDeclaration() && !F->isDefinitionExact() && F->getNumUses() &&
2356*da58b97aSjoerg           !GlobalValue::isInterposableLinkage(F->getLinkage())) {
2357*da58b97aSjoerg         Function *NewF = internalizeFunction(*F);
2358*da58b97aSjoerg         Functions.insert(NewF);
2359*da58b97aSjoerg 
2360*da58b97aSjoerg         // Update call graph
2361*da58b97aSjoerg         CGUpdater.replaceFunctionWith(*F, *NewF);
2362*da58b97aSjoerg         for (const Use &U : NewF->uses())
2363*da58b97aSjoerg           if (CallBase *CB = dyn_cast<CallBase>(U.getUser())) {
2364*da58b97aSjoerg             auto *CallerF = CB->getCaller();
2365*da58b97aSjoerg             CGUpdater.reanalyzeFunction(*CallerF);
2366*da58b97aSjoerg           }
2367*da58b97aSjoerg       }
2368*da58b97aSjoerg     }
2369*da58b97aSjoerg   }
2370*da58b97aSjoerg 
2371*da58b97aSjoerg   for (Function *F : Functions) {
2372*da58b97aSjoerg     if (F->hasExactDefinition())
237306f32e7eSjoerg       NumFnWithExactDefinition++;
237406f32e7eSjoerg     else
237506f32e7eSjoerg       NumFnWithoutExactDefinition++;
237606f32e7eSjoerg 
237706f32e7eSjoerg     // We look at internal functions only on-demand but if any use is not a
2378*da58b97aSjoerg     // direct call or outside the current set of analyzed functions, we have
2379*da58b97aSjoerg     // to do it eagerly.
2380*da58b97aSjoerg     if (F->hasLocalLinkage()) {
2381*da58b97aSjoerg       if (llvm::all_of(F->uses(), [&Functions](const Use &U) {
2382*da58b97aSjoerg             const auto *CB = dyn_cast<CallBase>(U.getUser());
2383*da58b97aSjoerg             return CB && CB->isCallee(&U) &&
2384*da58b97aSjoerg                    Functions.count(const_cast<Function *>(CB->getCaller()));
238506f32e7eSjoerg           }))
238606f32e7eSjoerg         continue;
238706f32e7eSjoerg     }
238806f32e7eSjoerg 
238906f32e7eSjoerg     // Populate the Attributor with abstract attribute opportunities in the
239006f32e7eSjoerg     // function and the information cache with IR information.
2391*da58b97aSjoerg     A.identifyDefaultAbstractAttributes(*F);
239206f32e7eSjoerg   }
239306f32e7eSjoerg 
2394*da58b97aSjoerg   ChangeStatus Changed = A.run();
2395*da58b97aSjoerg 
2396*da58b97aSjoerg   LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size()
2397*da58b97aSjoerg                     << " functions, result: " << Changed << ".\n");
2398*da58b97aSjoerg   return Changed == ChangeStatus::CHANGED;
2399*da58b97aSjoerg }
2400*da58b97aSjoerg 
viewGraph()2401*da58b97aSjoerg void AADepGraph::viewGraph() { llvm::ViewGraph(this, "Dependency Graph"); }
2402*da58b97aSjoerg 
dumpGraph()2403*da58b97aSjoerg void AADepGraph::dumpGraph() {
2404*da58b97aSjoerg   static std::atomic<int> CallTimes;
2405*da58b97aSjoerg   std::string Prefix;
2406*da58b97aSjoerg 
2407*da58b97aSjoerg   if (!DepGraphDotFileNamePrefix.empty())
2408*da58b97aSjoerg     Prefix = DepGraphDotFileNamePrefix;
2409*da58b97aSjoerg   else
2410*da58b97aSjoerg     Prefix = "dep_graph";
2411*da58b97aSjoerg   std::string Filename =
2412*da58b97aSjoerg       Prefix + "_" + std::to_string(CallTimes.load()) + ".dot";
2413*da58b97aSjoerg 
2414*da58b97aSjoerg   outs() << "Dependency graph dump to " << Filename << ".\n";
2415*da58b97aSjoerg 
2416*da58b97aSjoerg   std::error_code EC;
2417*da58b97aSjoerg 
2418*da58b97aSjoerg   raw_fd_ostream File(Filename, EC, sys::fs::OF_TextWithCRLF);
2419*da58b97aSjoerg   if (!EC)
2420*da58b97aSjoerg     llvm::WriteGraph(File, this);
2421*da58b97aSjoerg 
2422*da58b97aSjoerg   CallTimes++;
2423*da58b97aSjoerg }
2424*da58b97aSjoerg 
print()2425*da58b97aSjoerg void AADepGraph::print() {
2426*da58b97aSjoerg   for (auto DepAA : SyntheticRoot.Deps)
2427*da58b97aSjoerg     cast<AbstractAttribute>(DepAA.getPointer())->printWithDeps(outs());
242806f32e7eSjoerg }
242906f32e7eSjoerg 
run(Module & M,ModuleAnalysisManager & AM)243006f32e7eSjoerg PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) {
2431*da58b97aSjoerg   FunctionAnalysisManager &FAM =
2432*da58b97aSjoerg       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2433*da58b97aSjoerg   AnalysisGetter AG(FAM);
2434*da58b97aSjoerg 
2435*da58b97aSjoerg   SetVector<Function *> Functions;
2436*da58b97aSjoerg   for (Function &F : M)
2437*da58b97aSjoerg     Functions.insert(&F);
2438*da58b97aSjoerg 
2439*da58b97aSjoerg   CallGraphUpdater CGUpdater;
2440*da58b97aSjoerg   BumpPtrAllocator Allocator;
2441*da58b97aSjoerg   InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
2442*da58b97aSjoerg   if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
2443*da58b97aSjoerg                                /* DeleteFns */ true)) {
244406f32e7eSjoerg     // FIXME: Think about passes we will preserve and add them here.
244506f32e7eSjoerg     return PreservedAnalyses::none();
244606f32e7eSjoerg   }
244706f32e7eSjoerg   return PreservedAnalyses::all();
244806f32e7eSjoerg }
244906f32e7eSjoerg 
run(LazyCallGraph::SCC & C,CGSCCAnalysisManager & AM,LazyCallGraph & CG,CGSCCUpdateResult & UR)2450*da58b97aSjoerg PreservedAnalyses AttributorCGSCCPass::run(LazyCallGraph::SCC &C,
2451*da58b97aSjoerg                                            CGSCCAnalysisManager &AM,
2452*da58b97aSjoerg                                            LazyCallGraph &CG,
2453*da58b97aSjoerg                                            CGSCCUpdateResult &UR) {
2454*da58b97aSjoerg   FunctionAnalysisManager &FAM =
2455*da58b97aSjoerg       AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager();
2456*da58b97aSjoerg   AnalysisGetter AG(FAM);
2457*da58b97aSjoerg 
2458*da58b97aSjoerg   SetVector<Function *> Functions;
2459*da58b97aSjoerg   for (LazyCallGraph::Node &N : C)
2460*da58b97aSjoerg     Functions.insert(&N.getFunction());
2461*da58b97aSjoerg 
2462*da58b97aSjoerg   if (Functions.empty())
2463*da58b97aSjoerg     return PreservedAnalyses::all();
2464*da58b97aSjoerg 
2465*da58b97aSjoerg   Module &M = *Functions.back()->getParent();
2466*da58b97aSjoerg   CallGraphUpdater CGUpdater;
2467*da58b97aSjoerg   CGUpdater.initialize(CG, C, AM, UR);
2468*da58b97aSjoerg   BumpPtrAllocator Allocator;
2469*da58b97aSjoerg   InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
2470*da58b97aSjoerg   if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
2471*da58b97aSjoerg                                /* DeleteFns */ false)) {
2472*da58b97aSjoerg     // FIXME: Think about passes we will preserve and add them here.
2473*da58b97aSjoerg     PreservedAnalyses PA;
2474*da58b97aSjoerg     PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
2475*da58b97aSjoerg     return PA;
2476*da58b97aSjoerg   }
2477*da58b97aSjoerg   return PreservedAnalyses::all();
2478*da58b97aSjoerg }
2479*da58b97aSjoerg 
2480*da58b97aSjoerg namespace llvm {
2481*da58b97aSjoerg 
2482*da58b97aSjoerg template <> struct GraphTraits<AADepGraphNode *> {
2483*da58b97aSjoerg   using NodeRef = AADepGraphNode *;
2484*da58b97aSjoerg   using DepTy = PointerIntPair<AADepGraphNode *, 1>;
2485*da58b97aSjoerg   using EdgeRef = PointerIntPair<AADepGraphNode *, 1>;
2486*da58b97aSjoerg 
getEntryNodellvm::GraphTraits2487*da58b97aSjoerg   static NodeRef getEntryNode(AADepGraphNode *DGN) { return DGN; }
DepGetValllvm::GraphTraits2488*da58b97aSjoerg   static NodeRef DepGetVal(DepTy &DT) { return DT.getPointer(); }
2489*da58b97aSjoerg 
2490*da58b97aSjoerg   using ChildIteratorType =
2491*da58b97aSjoerg       mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>;
2492*da58b97aSjoerg   using ChildEdgeIteratorType = TinyPtrVector<DepTy>::iterator;
2493*da58b97aSjoerg 
child_beginllvm::GraphTraits2494*da58b97aSjoerg   static ChildIteratorType child_begin(NodeRef N) { return N->child_begin(); }
2495*da58b97aSjoerg 
child_endllvm::GraphTraits2496*da58b97aSjoerg   static ChildIteratorType child_end(NodeRef N) { return N->child_end(); }
2497*da58b97aSjoerg };
2498*da58b97aSjoerg 
2499*da58b97aSjoerg template <>
2500*da58b97aSjoerg struct GraphTraits<AADepGraph *> : public GraphTraits<AADepGraphNode *> {
getEntryNodellvm::GraphTraits2501*da58b97aSjoerg   static NodeRef getEntryNode(AADepGraph *DG) { return DG->GetEntryNode(); }
2502*da58b97aSjoerg 
2503*da58b97aSjoerg   using nodes_iterator =
2504*da58b97aSjoerg       mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>;
2505*da58b97aSjoerg 
nodes_beginllvm::GraphTraits2506*da58b97aSjoerg   static nodes_iterator nodes_begin(AADepGraph *DG) { return DG->begin(); }
2507*da58b97aSjoerg 
nodes_endllvm::GraphTraits2508*da58b97aSjoerg   static nodes_iterator nodes_end(AADepGraph *DG) { return DG->end(); }
2509*da58b97aSjoerg };
2510*da58b97aSjoerg 
2511*da58b97aSjoerg template <> struct DOTGraphTraits<AADepGraph *> : public DefaultDOTGraphTraits {
DOTGraphTraitsllvm::DOTGraphTraits2512*da58b97aSjoerg   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2513*da58b97aSjoerg 
getNodeLabelllvm::DOTGraphTraits2514*da58b97aSjoerg   static std::string getNodeLabel(const AADepGraphNode *Node,
2515*da58b97aSjoerg                                   const AADepGraph *DG) {
2516*da58b97aSjoerg     std::string AAString;
2517*da58b97aSjoerg     raw_string_ostream O(AAString);
2518*da58b97aSjoerg     Node->print(O);
2519*da58b97aSjoerg     return AAString;
2520*da58b97aSjoerg   }
2521*da58b97aSjoerg };
2522*da58b97aSjoerg 
2523*da58b97aSjoerg } // end namespace llvm
2524*da58b97aSjoerg 
252506f32e7eSjoerg namespace {
252606f32e7eSjoerg 
252706f32e7eSjoerg struct AttributorLegacyPass : public ModulePass {
252806f32e7eSjoerg   static char ID;
252906f32e7eSjoerg 
AttributorLegacyPass__anonfe0f36560a11::AttributorLegacyPass253006f32e7eSjoerg   AttributorLegacyPass() : ModulePass(ID) {
253106f32e7eSjoerg     initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry());
253206f32e7eSjoerg   }
253306f32e7eSjoerg 
runOnModule__anonfe0f36560a11::AttributorLegacyPass253406f32e7eSjoerg   bool runOnModule(Module &M) override {
253506f32e7eSjoerg     if (skipModule(M))
253606f32e7eSjoerg       return false;
253706f32e7eSjoerg 
253806f32e7eSjoerg     AnalysisGetter AG;
2539*da58b97aSjoerg     SetVector<Function *> Functions;
2540*da58b97aSjoerg     for (Function &F : M)
2541*da58b97aSjoerg       Functions.insert(&F);
2542*da58b97aSjoerg 
2543*da58b97aSjoerg     CallGraphUpdater CGUpdater;
2544*da58b97aSjoerg     BumpPtrAllocator Allocator;
2545*da58b97aSjoerg     InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
2546*da58b97aSjoerg     return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
2547*da58b97aSjoerg                                     /* DeleteFns*/ true);
254806f32e7eSjoerg   }
254906f32e7eSjoerg 
getAnalysisUsage__anonfe0f36560a11::AttributorLegacyPass255006f32e7eSjoerg   void getAnalysisUsage(AnalysisUsage &AU) const override {
255106f32e7eSjoerg     // FIXME: Think about passes we will preserve and add them here.
255206f32e7eSjoerg     AU.addRequired<TargetLibraryInfoWrapperPass>();
255306f32e7eSjoerg   }
255406f32e7eSjoerg };
255506f32e7eSjoerg 
2556*da58b97aSjoerg struct AttributorCGSCCLegacyPass : public CallGraphSCCPass {
2557*da58b97aSjoerg   static char ID;
2558*da58b97aSjoerg 
AttributorCGSCCLegacyPass__anonfe0f36560a11::AttributorCGSCCLegacyPass2559*da58b97aSjoerg   AttributorCGSCCLegacyPass() : CallGraphSCCPass(ID) {
2560*da58b97aSjoerg     initializeAttributorCGSCCLegacyPassPass(*PassRegistry::getPassRegistry());
2561*da58b97aSjoerg   }
2562*da58b97aSjoerg 
runOnSCC__anonfe0f36560a11::AttributorCGSCCLegacyPass2563*da58b97aSjoerg   bool runOnSCC(CallGraphSCC &SCC) override {
2564*da58b97aSjoerg     if (skipSCC(SCC))
2565*da58b97aSjoerg       return false;
2566*da58b97aSjoerg 
2567*da58b97aSjoerg     SetVector<Function *> Functions;
2568*da58b97aSjoerg     for (CallGraphNode *CGN : SCC)
2569*da58b97aSjoerg       if (Function *Fn = CGN->getFunction())
2570*da58b97aSjoerg         if (!Fn->isDeclaration())
2571*da58b97aSjoerg           Functions.insert(Fn);
2572*da58b97aSjoerg 
2573*da58b97aSjoerg     if (Functions.empty())
2574*da58b97aSjoerg       return false;
2575*da58b97aSjoerg 
2576*da58b97aSjoerg     AnalysisGetter AG;
2577*da58b97aSjoerg     CallGraph &CG = const_cast<CallGraph &>(SCC.getCallGraph());
2578*da58b97aSjoerg     CallGraphUpdater CGUpdater;
2579*da58b97aSjoerg     CGUpdater.initialize(CG, SCC);
2580*da58b97aSjoerg     Module &M = *Functions.back()->getParent();
2581*da58b97aSjoerg     BumpPtrAllocator Allocator;
2582*da58b97aSjoerg     InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
2583*da58b97aSjoerg     return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
2584*da58b97aSjoerg                                     /* DeleteFns */ false);
2585*da58b97aSjoerg   }
2586*da58b97aSjoerg 
getAnalysisUsage__anonfe0f36560a11::AttributorCGSCCLegacyPass2587*da58b97aSjoerg   void getAnalysisUsage(AnalysisUsage &AU) const override {
2588*da58b97aSjoerg     // FIXME: Think about passes we will preserve and add them here.
2589*da58b97aSjoerg     AU.addRequired<TargetLibraryInfoWrapperPass>();
2590*da58b97aSjoerg     CallGraphSCCPass::getAnalysisUsage(AU);
2591*da58b97aSjoerg   }
2592*da58b97aSjoerg };
2593*da58b97aSjoerg 
259406f32e7eSjoerg } // end anonymous namespace
259506f32e7eSjoerg 
createAttributorLegacyPass()259606f32e7eSjoerg Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); }
createAttributorCGSCCLegacyPass()2597*da58b97aSjoerg Pass *llvm::createAttributorCGSCCLegacyPass() {
2598*da58b97aSjoerg   return new AttributorCGSCCLegacyPass();
2599*da58b97aSjoerg }
260006f32e7eSjoerg 
260106f32e7eSjoerg char AttributorLegacyPass::ID = 0;
2602*da58b97aSjoerg char AttributorCGSCCLegacyPass::ID = 0;
260306f32e7eSjoerg 
260406f32e7eSjoerg INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor",
260506f32e7eSjoerg                       "Deduce and propagate attributes", false, false)
260606f32e7eSjoerg INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
260706f32e7eSjoerg INITIALIZE_PASS_END(AttributorLegacyPass, "attributor",
260806f32e7eSjoerg                     "Deduce and propagate attributes", false, false)
2609*da58b97aSjoerg INITIALIZE_PASS_BEGIN(AttributorCGSCCLegacyPass, "attributor-cgscc",
2610*da58b97aSjoerg                       "Deduce and propagate attributes (CGSCC pass)", false,
2611*da58b97aSjoerg                       false)
2612*da58b97aSjoerg INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2613*da58b97aSjoerg INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
2614*da58b97aSjoerg INITIALIZE_PASS_END(AttributorCGSCCLegacyPass, "attributor-cgscc",
2615*da58b97aSjoerg                     "Deduce and propagate attributes (CGSCC pass)", false,
2616*da58b97aSjoerg                     false)
2617