1//===- Attributor.cpp - Module-wide attribute deduction -------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements an interprocedural pass that deduces and/or propagates
10// attributes. This is done in an abstract interpretation style fixpoint
11// iteration. See the Attributor.h file comment and the class descriptions in
12// that file for more information.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Transforms/IPO/Attributor.h"
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/CallGraph.h"
25#include "llvm/Analysis/InlineCost.h"
26#include "llvm/Analysis/MemoryBuiltins.h"
27#include "llvm/Analysis/MustExecute.h"
28#include "llvm/IR/AttributeMask.h"
29#include "llvm/IR/Attributes.h"
30#include "llvm/IR/Constant.h"
31#include "llvm/IR/ConstantFold.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/GlobalValue.h"
35#include "llvm/IR/GlobalVariable.h"
36#include "llvm/IR/Instruction.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/LLVMContext.h"
40#include "llvm/IR/ValueHandle.h"
41#include "llvm/Support/Casting.h"
42#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Debug.h"
44#include "llvm/Support/DebugCounter.h"
45#include "llvm/Support/FileSystem.h"
46#include "llvm/Support/GraphWriter.h"
47#include "llvm/Support/ModRef.h"
48#include "llvm/Support/raw_ostream.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Cloning.h"
51#include "llvm/Transforms/Utils/Local.h"
52#include <cstdint>
53#include <memory>
54
55#ifdef EXPENSIVE_CHECKS
56#include "llvm/IR/Verifier.h"
57#endif
58
59#include <cassert>
60#include <optional>
61#include <string>
62
63using namespace llvm;
64
65#define DEBUG_TYPE "attributor"
66#define VERBOSE_DEBUG_TYPE DEBUG_TYPE "-verbose"
67
68DEBUG_COUNTER(ManifestDBGCounter, "attributor-manifest",
69 "Determine what attributes are manifested in the IR");
70
71STATISTIC(NumFnDeleted, "Number of function deleted");
72STATISTIC(NumFnWithExactDefinition,
73 "Number of functions with exact definitions");
74STATISTIC(NumFnWithoutExactDefinition,
75 "Number of functions without exact definitions");
76STATISTIC(NumFnShallowWrappersCreated, "Number of shallow wrappers created");
77STATISTIC(NumAttributesTimedOut,
78 "Number of abstract attributes timed out before fixpoint");
79STATISTIC(NumAttributesValidFixpoint,
80 "Number of abstract attributes in a valid fixpoint state");
81STATISTIC(NumAttributesManifested,
82 "Number of abstract attributes manifested in IR");
83
84// TODO: Determine a good default value.
85//
86// In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads
87// (when run with the first 5 abstract attributes). The results also indicate
88// that we never reach 32 iterations but always find a fixpoint sooner.
89//
90// This will become more evolved once we perform two interleaved fixpoint
91// iterations: bottom-up and top-down.
92static cl::opt<unsigned>
93 SetFixpointIterations("attributor-max-iterations", cl::Hidden,
94 cl::desc("Maximal number of fixpoint iterations."),
95 cl::init(Val: 32));
96
97static cl::opt<unsigned>
98 MaxSpecializationPerCB("attributor-max-specializations-per-call-base",
99 cl::Hidden,
100 cl::desc("Maximal number of callees specialized for "
101 "a call base"),
102 cl::init(UINT32_MAX));
103
104static cl::opt<unsigned, true> MaxInitializationChainLengthX(
105 "attributor-max-initialization-chain-length", cl::Hidden,
106 cl::desc(
107 "Maximal number of chained initializations (to avoid stack overflows)"),
108 cl::location(L&: MaxInitializationChainLength), cl::init(Val: 1024));
109unsigned llvm::MaxInitializationChainLength;
110
111static cl::opt<bool> AnnotateDeclarationCallSites(
112 "attributor-annotate-decl-cs", cl::Hidden,
113 cl::desc("Annotate call sites of function declarations."), cl::init(Val: false));
114
115static cl::opt<bool> EnableHeapToStack("enable-heap-to-stack-conversion",
116 cl::init(Val: true), cl::Hidden);
117
118static cl::opt<bool>
119 AllowShallowWrappers("attributor-allow-shallow-wrappers", cl::Hidden,
120 cl::desc("Allow the Attributor to create shallow "
121 "wrappers for non-exact definitions."),
122 cl::init(Val: false));
123
124static cl::opt<bool>
125 AllowDeepWrapper("attributor-allow-deep-wrappers", cl::Hidden,
126 cl::desc("Allow the Attributor to use IP information "
127 "derived from non-exact functions via cloning"),
128 cl::init(Val: false));
129
130// These options can only used for debug builds.
131#ifndef NDEBUG
132static cl::list<std::string>
133 SeedAllowList("attributor-seed-allow-list", cl::Hidden,
134 cl::desc("Comma separated list of attribute names that are "
135 "allowed to be seeded."),
136 cl::CommaSeparated);
137
138static cl::list<std::string> FunctionSeedAllowList(
139 "attributor-function-seed-allow-list", cl::Hidden,
140 cl::desc("Comma separated list of function names that are "
141 "allowed to be seeded."),
142 cl::CommaSeparated);
143#endif
144
145static cl::opt<bool>
146 DumpDepGraph("attributor-dump-dep-graph", cl::Hidden,
147 cl::desc("Dump the dependency graph to dot files."),
148 cl::init(Val: false));
149
150static cl::opt<std::string> DepGraphDotFileNamePrefix(
151 "attributor-depgraph-dot-filename-prefix", cl::Hidden,
152 cl::desc("The prefix used for the CallGraph dot file names."));
153
154static cl::opt<bool> ViewDepGraph("attributor-view-dep-graph", cl::Hidden,
155 cl::desc("View the dependency graph."),
156 cl::init(Val: false));
157
158static cl::opt<bool> PrintDependencies("attributor-print-dep", cl::Hidden,
159 cl::desc("Print attribute dependencies"),
160 cl::init(Val: false));
161
162static cl::opt<bool> EnableCallSiteSpecific(
163 "attributor-enable-call-site-specific-deduction", cl::Hidden,
164 cl::desc("Allow the Attributor to do call site specific analysis"),
165 cl::init(Val: false));
166
167static cl::opt<bool>
168 PrintCallGraph("attributor-print-call-graph", cl::Hidden,
169 cl::desc("Print Attributor's internal call graph"),
170 cl::init(Val: false));
171
172static cl::opt<bool> SimplifyAllLoads("attributor-simplify-all-loads",
173 cl::Hidden,
174 cl::desc("Try to simplify all loads."),
175 cl::init(Val: true));
176
177static cl::opt<bool> CloseWorldAssumption(
178 "attributor-assume-closed-world", cl::Hidden,
179 cl::desc("Should a closed world be assumed, or not. Default if not set."));
180
181/// Logic operators for the change status enum class.
182///
183///{
184ChangeStatus llvm::operator|(ChangeStatus L, ChangeStatus R) {
185 return L == ChangeStatus::CHANGED ? L : R;
186}
187ChangeStatus &llvm::operator|=(ChangeStatus &L, ChangeStatus R) {
188 L = L | R;
189 return L;
190}
191ChangeStatus llvm::operator&(ChangeStatus L, ChangeStatus R) {
192 return L == ChangeStatus::UNCHANGED ? L : R;
193}
194ChangeStatus &llvm::operator&=(ChangeStatus &L, ChangeStatus R) {
195 L = L & R;
196 return L;
197}
198///}
199
200namespace {
201/// NVPTX/AMDGPU address space values (shared between both targets)
202enum class NVPTXAMDGPUAddressSpace : unsigned {
203 Generic = 0,
204 Global = 1,
205 Shared = 3,
206 Constant = 4,
207 Local = 5,
208};
209
210/// SPIRV address space values (StorageClass)
211enum class SPIRVAddressSpace : unsigned {
212 Local = 0, // Function (private/local)
213 Global = 1, // CrossWorkgroup (global)
214 Constant = 2, // UniformConstant (constant)
215 Shared = 3, // Workgroup (shared)
216 Generic = 4, // Generic
217};
218} // namespace
219
220bool AA::isGPU(const Module &M) {
221 Triple T(M.getTargetTriple());
222 return T.isGPU();
223}
224
225bool AA::isGPUGenericAddressSpace(const Module &M, unsigned AS) {
226 assert(AA::isGPU(M) && "Only callable on GPU targets");
227 Triple T(M.getTargetTriple());
228
229 if (T.isSPIRV())
230 return AS == static_cast<unsigned>(SPIRVAddressSpace::Generic);
231
232 return AS == static_cast<unsigned>(NVPTXAMDGPUAddressSpace::Generic);
233}
234
235bool AA::isGPUGlobalAddressSpace(const Module &M, unsigned AS) {
236 assert(AA::isGPU(M) && "Only callable on GPU targets");
237 Triple T(M.getTargetTriple());
238
239 if (T.isSPIRV())
240 return AS == static_cast<unsigned>(SPIRVAddressSpace::Global);
241
242 return AS == static_cast<unsigned>(NVPTXAMDGPUAddressSpace::Global);
243}
244
245bool AA::isGPUSharedAddressSpace(const Module &M, unsigned AS) {
246 assert(AA::isGPU(M) && "Only callable on GPU targets");
247 Triple T(M.getTargetTriple());
248
249 if (T.isSPIRV())
250 return AS == static_cast<unsigned>(SPIRVAddressSpace::Shared);
251
252 return AS == static_cast<unsigned>(NVPTXAMDGPUAddressSpace::Shared);
253}
254
255bool AA::isGPUConstantAddressSpace(const Module &M, unsigned AS) {
256 assert(AA::isGPU(M) && "Only callable on GPU targets");
257 Triple T(M.getTargetTriple());
258
259 if (T.isSPIRV())
260 return AS == static_cast<unsigned>(SPIRVAddressSpace::Constant);
261
262 return AS == static_cast<unsigned>(NVPTXAMDGPUAddressSpace::Constant);
263}
264
265bool AA::isGPULocalAddressSpace(const Module &M, unsigned AS) {
266 assert(AA::isGPU(M) && "Only callable on GPU targets");
267 Triple T(M.getTargetTriple());
268
269 if (T.isSPIRV())
270 return AS == static_cast<unsigned>(SPIRVAddressSpace::Local);
271
272 return AS == static_cast<unsigned>(NVPTXAMDGPUAddressSpace::Local);
273}
274
275bool AA::isNoSyncInst(Attributor &A, const Instruction &I,
276 const AbstractAttribute &QueryingAA) {
277 // We are looking for volatile instructions or non-relaxed atomics.
278 if (const auto *CB = dyn_cast<CallBase>(Val: &I)) {
279 if (CB->hasFnAttr(Kind: Attribute::NoSync))
280 return true;
281
282 // Non-convergent and readnone imply nosync.
283 if (!CB->isConvergent() && !CB->mayReadOrWriteMemory())
284 return true;
285
286 bool IsKnownNoSync;
287 return AA::hasAssumedIRAttr<Attribute::NoSync>(
288 A, QueryingAA: &QueryingAA, IRP: IRPosition::callsite_function(CB: *CB),
289 DepClass: DepClassTy::OPTIONAL, IsKnown&: IsKnownNoSync);
290 }
291
292 if (!I.mayReadOrWriteMemory())
293 return true;
294
295 return !AANoSync::isNonRelaxedAtomic(I: &I);
296}
297
298bool AA::isDynamicallyUnique(Attributor &A, const AbstractAttribute &QueryingAA,
299 const Value &V, bool ForAnalysisOnly) {
300 // TODO: See the AAInstanceInfo class comment.
301 if (!ForAnalysisOnly)
302 return false;
303 auto *InstanceInfoAA = A.getAAFor<AAInstanceInfo>(
304 QueryingAA, IRP: IRPosition::value(V), DepClass: DepClassTy::OPTIONAL);
305 return InstanceInfoAA && InstanceInfoAA->isAssumedUniqueForAnalysis();
306}
307
308Constant *
309AA::getInitialValueForObj(Attributor &A, const AbstractAttribute &QueryingAA,
310 Value &Obj, Type &Ty, const TargetLibraryInfo *TLI,
311 const DataLayout &DL, AA::RangeTy *RangePtr) {
312 if (Constant *Init = getInitialValueOfAllocation(V: &Obj, TLI, Ty: &Ty))
313 return Init;
314 auto *GV = dyn_cast<GlobalVariable>(Val: &Obj);
315 if (!GV)
316 return nullptr;
317
318 bool UsedAssumedInformation = false;
319 Constant *Initializer = nullptr;
320 if (A.hasGlobalVariableSimplificationCallback(GV: *GV)) {
321 auto AssumedGV = A.getAssumedInitializerFromCallBack(
322 GV: *GV, AA: &QueryingAA, UsedAssumedInformation);
323 Initializer = *AssumedGV;
324 if (!Initializer)
325 return nullptr;
326 } else {
327 if (!GV->hasLocalLinkage()) {
328 // Externally visible global that's either non-constant,
329 // or a constant with an uncertain initializer.
330 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
331 return nullptr;
332 }
333
334 // Globals with local linkage are always initialized.
335 assert(!GV->hasLocalLinkage() || GV->hasInitializer());
336
337 if (!Initializer)
338 Initializer = GV->getInitializer();
339 }
340
341 if (RangePtr && !RangePtr->offsetOrSizeAreUnknown()) {
342 int64_t StorageSize = DL.getTypeStoreSize(Ty: &Ty);
343 if (StorageSize != RangePtr->Size)
344 return nullptr;
345 APInt Offset = APInt(64, RangePtr->Offset);
346 return ConstantFoldLoadFromConst(C: Initializer, Ty: &Ty, Offset, DL);
347 }
348
349 return ConstantFoldLoadFromUniformValue(C: Initializer, Ty: &Ty, DL);
350}
351
352bool AA::isValidInScope(const Value &V, const Function *Scope) {
353 if (isa<Constant>(Val: V))
354 return true;
355 if (auto *I = dyn_cast<Instruction>(Val: &V))
356 return I->getFunction() == Scope;
357 if (auto *A = dyn_cast<Argument>(Val: &V))
358 return A->getParent() == Scope;
359 return false;
360}
361
362bool AA::isValidAtPosition(const AA::ValueAndContext &VAC,
363 InformationCache &InfoCache) {
364 if (isa<Constant>(Val: VAC.getValue()) || VAC.getValue() == VAC.getCtxI())
365 return true;
366 const Function *Scope = nullptr;
367 const Instruction *CtxI = VAC.getCtxI();
368 if (CtxI)
369 Scope = CtxI->getFunction();
370 if (auto *A = dyn_cast<Argument>(Val: VAC.getValue()))
371 return A->getParent() == Scope;
372 if (auto *I = dyn_cast<Instruction>(Val: VAC.getValue())) {
373 if (I->getFunction() == Scope) {
374 if (const DominatorTree *DT =
375 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(
376 F: *Scope))
377 return DT->dominates(Def: I, User: CtxI);
378 // Local dominance check mostly for the old PM passes.
379 if (CtxI && I->getParent() == CtxI->getParent())
380 return llvm::any_of(
381 Range: make_range(x: I->getIterator(), y: I->getParent()->end()),
382 P: [&](const Instruction &AfterI) { return &AfterI == CtxI; });
383 }
384 }
385 return false;
386}
387
388Value *AA::getWithType(Value &V, Type &Ty) {
389 if (V.getType() == &Ty)
390 return &V;
391 if (isa<PoisonValue>(Val: V))
392 return PoisonValue::get(T: &Ty);
393 if (isa<UndefValue>(Val: V))
394 return UndefValue::get(T: &Ty);
395 if (auto *C = dyn_cast<Constant>(Val: &V)) {
396 if (C->isNullValue() && !Ty.isPtrOrPtrVectorTy())
397 return Constant::getNullValue(Ty: &Ty);
398 if (C->getType()->isPointerTy() && Ty.isPointerTy())
399 return ConstantExpr::getPointerCast(C, Ty: &Ty);
400 if (C->getType()->getPrimitiveSizeInBits() >= Ty.getPrimitiveSizeInBits()) {
401 if (C->getType()->isIntegerTy() && Ty.isIntegerTy())
402 return ConstantExpr::getTrunc(C, Ty: &Ty, /* OnlyIfReduced */ true);
403 if (C->getType()->isFloatingPointTy() && Ty.isFloatingPointTy())
404 return ConstantFoldCastInstruction(opcode: Instruction::FPTrunc, V: C, DestTy: &Ty);
405 }
406 }
407 return nullptr;
408}
409
410std::optional<Value *>
411AA::combineOptionalValuesInAAValueLatice(const std::optional<Value *> &A,
412 const std::optional<Value *> &B,
413 Type *Ty) {
414 if (A == B)
415 return A;
416 if (!B)
417 return A;
418 if (*B == nullptr)
419 return nullptr;
420 if (!A)
421 return Ty ? getWithType(V&: **B, Ty&: *Ty) : nullptr;
422 if (*A == nullptr)
423 return nullptr;
424 if (!Ty)
425 Ty = (*A)->getType();
426 if (isa_and_nonnull<UndefValue>(Val: *A))
427 return getWithType(V&: **B, Ty&: *Ty);
428 if (isa<UndefValue>(Val: *B))
429 return A;
430 if (*A && *B && *A == getWithType(V&: **B, Ty&: *Ty))
431 return A;
432 return nullptr;
433}
434
435template <bool IsLoad, typename Ty>
436static bool getPotentialCopiesOfMemoryValue(
437 Attributor &A, Ty &I, SmallSetVector<Value *, 4> &PotentialCopies,
438 SmallSetVector<Instruction *, 4> *PotentialValueOrigins,
439 const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
440 bool OnlyExact) {
441 LLVM_DEBUG(dbgs() << "Trying to determine the potential copies of " << I
442 << " (only exact: " << OnlyExact << ")\n";);
443
444 Value &Ptr = *I.getPointerOperand();
445 // Containers to remember the pointer infos and new copies while we are not
446 // sure that we can find all of them. If we abort we want to avoid spurious
447 // dependences and potential copies in the provided container.
448 SmallVector<const AAPointerInfo *> PIs;
449 SmallSetVector<Value *, 8> NewCopies;
450 SmallSetVector<Instruction *, 8> NewCopyOrigins;
451
452 const auto *TLI =
453 A.getInfoCache().getTargetLibraryInfoForFunction(F: *I.getFunction());
454
455 auto Pred = [&](Value &Obj) {
456 LLVM_DEBUG(dbgs() << "Visit underlying object " << Obj << "\n");
457 if (isa<UndefValue>(Val: &Obj))
458 return true;
459 if (isa<ConstantPointerNull>(Val: &Obj)) {
460 // A null pointer access can be undefined but any offset from null may
461 // be OK. We do not try to optimize the latter.
462 if (!NullPointerIsDefined(I.getFunction(),
463 Ptr.getType()->getPointerAddressSpace()) &&
464 A.getAssumedSimplified(V: Ptr, AA: QueryingAA, UsedAssumedInformation,
465 S: AA::Interprocedural) == &Obj)
466 return true;
467 LLVM_DEBUG(
468 dbgs() << "Underlying object is a valid nullptr, giving up.\n";);
469 return false;
470 }
471 // TODO: Use assumed noalias return.
472 if (!isa<AllocaInst>(Val: &Obj) && !isa<GlobalVariable>(Val: &Obj) &&
473 !(IsLoad ? isAllocationFn(&Obj, TLI) : isNoAliasCall(V: &Obj))) {
474 LLVM_DEBUG(dbgs() << "Underlying object is not supported yet: " << Obj
475 << "\n";);
476 return false;
477 }
478 if (auto *GV = dyn_cast<GlobalVariable>(Val: &Obj))
479 if (!GV->hasLocalLinkage() &&
480 !(GV->isConstant() && GV->hasInitializer())) {
481 LLVM_DEBUG(dbgs() << "Underlying object is global with external "
482 "linkage, not supported yet: "
483 << Obj << "\n";);
484 return false;
485 }
486
487 bool NullOnly = true;
488 bool NullRequired = false;
489 auto CheckForNullOnlyAndUndef = [&](std::optional<Value *> V,
490 bool IsExact) {
491 if (!V || *V == nullptr)
492 NullOnly = false;
493 else if (isa<UndefValue>(Val: *V))
494 /* No op */;
495 else if (isa<Constant>(Val: *V) && cast<Constant>(Val: *V)->isNullValue())
496 NullRequired = !IsExact;
497 else
498 NullOnly = false;
499 };
500
501 auto AdjustWrittenValueType = [&](const AAPointerInfo::Access &Acc,
502 Value &V) {
503 Value *AdjV = AA::getWithType(V, Ty&: *I.getType());
504 if (!AdjV) {
505 LLVM_DEBUG(dbgs() << "Underlying object written but stored value "
506 "cannot be converted to read type: "
507 << *Acc.getRemoteInst() << " : " << *I.getType()
508 << "\n";);
509 }
510 return AdjV;
511 };
512
513 auto SkipCB = [&](const AAPointerInfo::Access &Acc) {
514 if ((IsLoad && !Acc.isWriteOrAssumption()) || (!IsLoad && !Acc.isRead()))
515 return true;
516 if (IsLoad) {
517 if (Acc.isWrittenValueYetUndetermined())
518 return true;
519 if (PotentialValueOrigins && !isa<AssumeInst>(Val: Acc.getRemoteInst()))
520 return false;
521 if (!Acc.isWrittenValueUnknown())
522 if (Value *V = AdjustWrittenValueType(Acc, *Acc.getWrittenValue()))
523 if (NewCopies.count(key: V)) {
524 NewCopyOrigins.insert(X: Acc.getRemoteInst());
525 return true;
526 }
527 if (auto *SI = dyn_cast<StoreInst>(Val: Acc.getRemoteInst()))
528 if (Value *V = AdjustWrittenValueType(Acc, *SI->getValueOperand()))
529 if (NewCopies.count(key: V)) {
530 NewCopyOrigins.insert(X: Acc.getRemoteInst());
531 return true;
532 }
533 }
534 return false;
535 };
536
537 auto CheckAccess = [&](const AAPointerInfo::Access &Acc, bool IsExact) {
538 if ((IsLoad && !Acc.isWriteOrAssumption()) || (!IsLoad && !Acc.isRead()))
539 return true;
540 if (IsLoad && Acc.isWrittenValueYetUndetermined())
541 return true;
542 CheckForNullOnlyAndUndef(Acc.getContent(), IsExact);
543 if (OnlyExact && !IsExact && !NullOnly &&
544 !isa_and_nonnull<UndefValue>(Val: Acc.getWrittenValue())) {
545 LLVM_DEBUG(dbgs() << "Non exact access " << *Acc.getRemoteInst()
546 << ", abort!\n");
547 return false;
548 }
549 if (NullRequired && !NullOnly) {
550 LLVM_DEBUG(dbgs() << "Required all `null` accesses due to non exact "
551 "one, however found non-null one: "
552 << *Acc.getRemoteInst() << ", abort!\n");
553 return false;
554 }
555 if (IsLoad) {
556 assert(isa<LoadInst>(I) && "Expected load or store instruction only!");
557 if (!Acc.isWrittenValueUnknown()) {
558 Value *V = AdjustWrittenValueType(Acc, *Acc.getWrittenValue());
559 if (!V)
560 return false;
561 NewCopies.insert(X: V);
562 if (PotentialValueOrigins)
563 NewCopyOrigins.insert(X: Acc.getRemoteInst());
564 return true;
565 }
566 auto *SI = dyn_cast<StoreInst>(Val: Acc.getRemoteInst());
567 if (!SI) {
568 LLVM_DEBUG(dbgs() << "Underlying object written through a non-store "
569 "instruction not supported yet: "
570 << *Acc.getRemoteInst() << "\n";);
571 return false;
572 }
573 Value *V = AdjustWrittenValueType(Acc, *SI->getValueOperand());
574 if (!V)
575 return false;
576 NewCopies.insert(X: V);
577 if (PotentialValueOrigins)
578 NewCopyOrigins.insert(X: SI);
579 } else {
580 assert(isa<StoreInst>(I) && "Expected load or store instruction only!");
581 auto *LI = dyn_cast<LoadInst>(Val: Acc.getRemoteInst());
582 if (!LI && OnlyExact) {
583 LLVM_DEBUG(dbgs() << "Underlying object read through a non-load "
584 "instruction not supported yet: "
585 << *Acc.getRemoteInst() << "\n";);
586 return false;
587 }
588 NewCopies.insert(X: Acc.getRemoteInst());
589 }
590 return true;
591 };
592
593 // If the value has been written to we don't need the initial value of the
594 // object.
595 bool HasBeenWrittenTo = false;
596
597 AA::RangeTy Range;
598 auto *PI = A.getAAFor<AAPointerInfo>(QueryingAA, IRP: IRPosition::value(V: Obj),
599 DepClass: DepClassTy::NONE);
600 if (!PI || !PI->forallInterferingAccesses(
601 A, QueryingAA, I,
602 /* FindInterferingWrites */ IsLoad,
603 /* FindInterferingReads */ !IsLoad, CheckAccess,
604 HasBeenWrittenTo, Range, SkipCB)) {
605 LLVM_DEBUG(
606 dbgs()
607 << "Failed to verify all interfering accesses for underlying object: "
608 << Obj << "\n");
609 return false;
610 }
611
612 if (IsLoad && !HasBeenWrittenTo && !Range.isUnassigned()) {
613 const DataLayout &DL = A.getDataLayout();
614 Value *InitialValue = AA::getInitialValueForObj(
615 A, QueryingAA, Obj, Ty&: *I.getType(), TLI, DL, RangePtr: &Range);
616 if (!InitialValue) {
617 LLVM_DEBUG(dbgs() << "Could not determine required initial value of "
618 "underlying object, abort!\n");
619 return false;
620 }
621 CheckForNullOnlyAndUndef(InitialValue, /* IsExact */ true);
622 if (NullRequired && !NullOnly) {
623 LLVM_DEBUG(dbgs() << "Non exact access but initial value that is not "
624 "null or undef, abort!\n");
625 return false;
626 }
627
628 NewCopies.insert(X: InitialValue);
629 if (PotentialValueOrigins)
630 NewCopyOrigins.insert(X: nullptr);
631 }
632
633 PIs.push_back(Elt: PI);
634
635 return true;
636 };
637
638 const auto *AAUO = A.getAAFor<AAUnderlyingObjects>(
639 QueryingAA, IRP: IRPosition::value(V: Ptr), DepClass: DepClassTy::OPTIONAL);
640 if (!AAUO || !AAUO->forallUnderlyingObjects(Pred)) {
641 LLVM_DEBUG(
642 dbgs() << "Underlying objects stored into could not be determined\n";);
643 return false;
644 }
645
646 // Only if we were successful collection all potential copies we record
647 // dependences (on non-fix AAPointerInfo AAs). We also only then modify the
648 // given PotentialCopies container.
649 for (const auto *PI : PIs) {
650 if (!PI->getState().isAtFixpoint())
651 UsedAssumedInformation = true;
652 A.recordDependence(FromAA: *PI, ToAA: QueryingAA, DepClass: DepClassTy::OPTIONAL);
653 }
654 PotentialCopies.insert_range(R&: NewCopies);
655 if (PotentialValueOrigins)
656 PotentialValueOrigins->insert_range(R&: NewCopyOrigins);
657
658 return true;
659}
660
661bool AA::getPotentiallyLoadedValues(
662 Attributor &A, LoadInst &LI, SmallSetVector<Value *, 4> &PotentialValues,
663 SmallSetVector<Instruction *, 4> &PotentialValueOrigins,
664 const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
665 bool OnlyExact) {
666 return getPotentialCopiesOfMemoryValue</* IsLoad */ true>(
667 A, I&: LI, PotentialCopies&: PotentialValues, PotentialValueOrigins: &PotentialValueOrigins, QueryingAA,
668 UsedAssumedInformation, OnlyExact);
669}
670
671bool AA::getPotentialCopiesOfStoredValue(
672 Attributor &A, StoreInst &SI, SmallSetVector<Value *, 4> &PotentialCopies,
673 const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation,
674 bool OnlyExact) {
675 return getPotentialCopiesOfMemoryValue</* IsLoad */ false>(
676 A, I&: SI, PotentialCopies, PotentialValueOrigins: nullptr, QueryingAA, UsedAssumedInformation,
677 OnlyExact);
678}
679
680static bool isAssumedReadOnlyOrReadNone(Attributor &A, const IRPosition &IRP,
681 const AbstractAttribute &QueryingAA,
682 bool RequireReadNone, bool &IsKnown) {
683 if (RequireReadNone) {
684 if (AA::hasAssumedIRAttr<Attribute::ReadNone>(
685 A, QueryingAA: &QueryingAA, IRP, DepClass: DepClassTy::OPTIONAL, IsKnown,
686 /* IgnoreSubsumingPositions */ true))
687 return true;
688 } else if (AA::hasAssumedIRAttr<Attribute::ReadOnly>(
689 A, QueryingAA: &QueryingAA, IRP, DepClass: DepClassTy::OPTIONAL, IsKnown,
690 /* IgnoreSubsumingPositions */ true))
691 return true;
692
693 IRPosition::Kind Kind = IRP.getPositionKind();
694 if (Kind == IRPosition::IRP_FUNCTION || Kind == IRPosition::IRP_CALL_SITE) {
695 const auto *MemLocAA =
696 A.getAAFor<AAMemoryLocation>(QueryingAA, IRP, DepClass: DepClassTy::NONE);
697 if (MemLocAA && MemLocAA->isAssumedReadNone()) {
698 IsKnown = MemLocAA->isKnownReadNone();
699 if (!IsKnown)
700 A.recordDependence(FromAA: *MemLocAA, ToAA: QueryingAA, DepClass: DepClassTy::OPTIONAL);
701 return true;
702 }
703 }
704
705 const auto *MemBehaviorAA =
706 A.getAAFor<AAMemoryBehavior>(QueryingAA, IRP, DepClass: DepClassTy::NONE);
707 if (MemBehaviorAA &&
708 (MemBehaviorAA->isAssumedReadNone() ||
709 (!RequireReadNone && MemBehaviorAA->isAssumedReadOnly()))) {
710 IsKnown = RequireReadNone ? MemBehaviorAA->isKnownReadNone()
711 : MemBehaviorAA->isKnownReadOnly();
712 if (!IsKnown)
713 A.recordDependence(FromAA: *MemBehaviorAA, ToAA: QueryingAA, DepClass: DepClassTy::OPTIONAL);
714 return true;
715 }
716
717 return false;
718}
719
720bool AA::isAssumedReadOnly(Attributor &A, const IRPosition &IRP,
721 const AbstractAttribute &QueryingAA, bool &IsKnown) {
722 return isAssumedReadOnlyOrReadNone(A, IRP, QueryingAA,
723 /* RequireReadNone */ false, IsKnown);
724}
725bool AA::isAssumedReadNone(Attributor &A, const IRPosition &IRP,
726 const AbstractAttribute &QueryingAA, bool &IsKnown) {
727 return isAssumedReadOnlyOrReadNone(A, IRP, QueryingAA,
728 /* RequireReadNone */ true, IsKnown);
729}
730
731static bool
732isPotentiallyReachable(Attributor &A, const Instruction &FromI,
733 const Instruction *ToI, const Function &ToFn,
734 const AbstractAttribute &QueryingAA,
735 const AA::InstExclusionSetTy *ExclusionSet,
736 std::function<bool(const Function &F)> GoBackwardsCB) {
737 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, {
738 dbgs() << "[AA] isPotentiallyReachable @" << ToFn.getName() << " from "
739 << FromI << " [GBCB: " << bool(GoBackwardsCB) << "][#ExS: "
740 << (ExclusionSet ? std::to_string(ExclusionSet->size()) : "none")
741 << "]\n";
742 if (ExclusionSet)
743 for (auto *ES : *ExclusionSet)
744 dbgs() << *ES << "\n";
745 });
746
747 // We know kernels (generally) cannot be called from within the module. Thus,
748 // for reachability we would need to step back from a kernel which would allow
749 // us to reach anything anyway. Even if a kernel is invoked from another
750 // kernel, values like allocas and shared memory are not accessible. We
751 // implicitly check for this situation to avoid costly lookups.
752 if (GoBackwardsCB && &ToFn != FromI.getFunction() &&
753 !GoBackwardsCB(*FromI.getFunction()) && A.getInfoCache().isKernel(F: ToFn) &&
754 A.getInfoCache().isKernel(F: *FromI.getFunction())) {
755 LLVM_DEBUG(dbgs() << "[AA] assume kernel cannot be reached from within the "
756 "module; success\n";);
757 return false;
758 }
759
760 // If we can go arbitrarily backwards we will eventually reach an entry point
761 // that can reach ToI. Only if a set of blocks through which we cannot go is
762 // provided, or once we track internal functions not accessible from the
763 // outside, it makes sense to perform backwards analysis in the absence of a
764 // GoBackwardsCB.
765 if (!GoBackwardsCB && !ExclusionSet) {
766 LLVM_DEBUG(dbgs() << "[AA] check @" << ToFn.getName() << " from " << FromI
767 << " is not checked backwards and does not have an "
768 "exclusion set, abort\n");
769 return true;
770 }
771
772 SmallPtrSet<const Instruction *, 8> Visited;
773 SmallVector<const Instruction *> Worklist;
774 Worklist.push_back(Elt: &FromI);
775
776 while (!Worklist.empty()) {
777 const Instruction *CurFromI = Worklist.pop_back_val();
778 if (!Visited.insert(Ptr: CurFromI).second)
779 continue;
780
781 const Function *FromFn = CurFromI->getFunction();
782 if (FromFn == &ToFn) {
783 if (!ToI)
784 return true;
785 LLVM_DEBUG(dbgs() << "[AA] check " << *ToI << " from " << *CurFromI
786 << " intraprocedurally\n");
787 const auto *ReachabilityAA = A.getAAFor<AAIntraFnReachability>(
788 QueryingAA, IRP: IRPosition::function(F: ToFn), DepClass: DepClassTy::OPTIONAL);
789 bool Result = !ReachabilityAA || ReachabilityAA->isAssumedReachable(
790 A, From: *CurFromI, To: *ToI, ExclusionSet);
791 LLVM_DEBUG(dbgs() << "[AA] " << *CurFromI << " "
792 << (Result ? "can potentially " : "cannot ") << "reach "
793 << *ToI << " [Intra]\n");
794 if (Result)
795 return true;
796 }
797
798 bool Result = true;
799 if (!ToFn.isDeclaration() && ToI) {
800 const auto *ToReachabilityAA = A.getAAFor<AAIntraFnReachability>(
801 QueryingAA, IRP: IRPosition::function(F: ToFn), DepClass: DepClassTy::OPTIONAL);
802 const Instruction &EntryI = ToFn.getEntryBlock().front();
803 Result = !ToReachabilityAA || ToReachabilityAA->isAssumedReachable(
804 A, From: EntryI, To: *ToI, ExclusionSet);
805 LLVM_DEBUG(dbgs() << "[AA] Entry " << EntryI << " of @" << ToFn.getName()
806 << " " << (Result ? "can potentially " : "cannot ")
807 << "reach @" << *ToI << " [ToFn]\n");
808 }
809
810 if (Result) {
811 // The entry of the ToFn can reach the instruction ToI. If the current
812 // instruction is already known to reach the ToFn.
813 const auto *FnReachabilityAA = A.getAAFor<AAInterFnReachability>(
814 QueryingAA, IRP: IRPosition::function(F: *FromFn), DepClass: DepClassTy::OPTIONAL);
815 Result = !FnReachabilityAA || FnReachabilityAA->instructionCanReach(
816 A, Inst: *CurFromI, Fn: ToFn, ExclusionSet);
817 LLVM_DEBUG(dbgs() << "[AA] " << *CurFromI << " in @" << FromFn->getName()
818 << " " << (Result ? "can potentially " : "cannot ")
819 << "reach @" << ToFn.getName() << " [FromFn]\n");
820 if (Result)
821 return true;
822 }
823
824 // TODO: Check assumed nounwind.
825 const auto *ReachabilityAA = A.getAAFor<AAIntraFnReachability>(
826 QueryingAA, IRP: IRPosition::function(F: *FromFn), DepClass: DepClassTy::OPTIONAL);
827 auto ReturnInstCB = [&](Instruction &Ret) {
828 bool Result = !ReachabilityAA || ReachabilityAA->isAssumedReachable(
829 A, From: *CurFromI, To: Ret, ExclusionSet);
830 LLVM_DEBUG(dbgs() << "[AA][Ret] " << *CurFromI << " "
831 << (Result ? "can potentially " : "cannot ") << "reach "
832 << Ret << " [Intra]\n");
833 return !Result;
834 };
835
836 // Check if we can reach returns.
837 bool UsedAssumedInformation = false;
838 if (A.checkForAllInstructions(Pred: ReturnInstCB, Fn: FromFn, QueryingAA: &QueryingAA,
839 Opcodes: {Instruction::Ret}, UsedAssumedInformation)) {
840 LLVM_DEBUG(dbgs() << "[AA] No return is reachable, done\n");
841 continue;
842 }
843
844 if (!GoBackwardsCB) {
845 LLVM_DEBUG(dbgs() << "[AA] check @" << ToFn.getName() << " from " << FromI
846 << " is not checked backwards, abort\n");
847 return true;
848 }
849
850 // If we do not go backwards from the FromFn we are done here and so far we
851 // could not find a way to reach ToFn/ToI.
852 if (!GoBackwardsCB(*FromFn))
853 continue;
854
855 LLVM_DEBUG(dbgs() << "Stepping backwards to the call sites of @"
856 << FromFn->getName() << "\n");
857
858 auto CheckCallSite = [&](AbstractCallSite ACS) {
859 CallBase *CB = ACS.getInstruction();
860 if (!CB)
861 return false;
862
863 if (isa<InvokeInst>(Val: CB))
864 return false;
865
866 Instruction *Inst = CB->getNextNode();
867 Worklist.push_back(Elt: Inst);
868 return true;
869 };
870
871 Result = !A.checkForAllCallSites(Pred: CheckCallSite, Fn: *FromFn,
872 /* RequireAllCallSites */ true,
873 QueryingAA: &QueryingAA, UsedAssumedInformation);
874 if (Result) {
875 LLVM_DEBUG(dbgs() << "[AA] stepping back to call sites from " << *CurFromI
876 << " in @" << FromFn->getName()
877 << " failed, give up\n");
878 return true;
879 }
880
881 LLVM_DEBUG(dbgs() << "[AA] stepped back to call sites from " << *CurFromI
882 << " in @" << FromFn->getName()
883 << " worklist size is: " << Worklist.size() << "\n");
884 }
885 return false;
886}
887
888bool AA::isPotentiallyReachable(
889 Attributor &A, const Instruction &FromI, const Instruction &ToI,
890 const AbstractAttribute &QueryingAA,
891 const AA::InstExclusionSetTy *ExclusionSet,
892 std::function<bool(const Function &F)> GoBackwardsCB) {
893 const Function *ToFn = ToI.getFunction();
894 return ::isPotentiallyReachable(A, FromI, ToI: &ToI, ToFn: *ToFn, QueryingAA,
895 ExclusionSet, GoBackwardsCB);
896}
897
898bool AA::isPotentiallyReachable(
899 Attributor &A, const Instruction &FromI, const Function &ToFn,
900 const AbstractAttribute &QueryingAA,
901 const AA::InstExclusionSetTy *ExclusionSet,
902 std::function<bool(const Function &F)> GoBackwardsCB) {
903 return ::isPotentiallyReachable(A, FromI, /* ToI */ nullptr, ToFn, QueryingAA,
904 ExclusionSet, GoBackwardsCB);
905}
906
907bool AA::isAssumedThreadLocalObject(Attributor &A, Value &Obj,
908 const AbstractAttribute &QueryingAA) {
909 if (isa<UndefValue>(Val: Obj))
910 return true;
911 if (isa<AllocaInst>(Val: Obj)) {
912 InformationCache &InfoCache = A.getInfoCache();
913 if (!InfoCache.stackIsAccessibleByOtherThreads()) {
914 LLVM_DEBUG(
915 dbgs() << "[AA] Object '" << Obj
916 << "' is thread local; stack objects are thread local.\n");
917 return true;
918 }
919 bool IsKnownNoCapture;
920 bool IsAssumedNoCapture = AA::hasAssumedIRAttr<Attribute::Captures>(
921 A, QueryingAA: &QueryingAA, IRP: IRPosition::value(V: Obj), DepClass: DepClassTy::OPTIONAL,
922 IsKnown&: IsKnownNoCapture);
923 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj << "' is "
924 << (IsAssumedNoCapture ? "" : "not") << " thread local; "
925 << (IsAssumedNoCapture ? "non-" : "")
926 << "captured stack object.\n");
927 return IsAssumedNoCapture;
928 }
929 if (auto *GV = dyn_cast<GlobalVariable>(Val: &Obj)) {
930 if (GV->isConstant()) {
931 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
932 << "' is thread local; constant global\n");
933 return true;
934 }
935 if (GV->isThreadLocal()) {
936 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
937 << "' is thread local; thread local global\n");
938 return true;
939 }
940 }
941
942 if (A.getInfoCache().IsTargetGPU()) {
943 if (AA::isGPULocalAddressSpace(M: A.getInfoCache().getModule(),
944 AS: Obj.getType()->getPointerAddressSpace())) {
945 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
946 << "' is thread local; GPU local memory\n");
947 return true;
948 }
949 if (AA::isGPUConstantAddressSpace(
950 M: A.getInfoCache().getModule(),
951 AS: Obj.getType()->getPointerAddressSpace())) {
952 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj
953 << "' is thread local; GPU constant memory\n");
954 return true;
955 }
956 }
957
958 LLVM_DEBUG(dbgs() << "[AA] Object '" << Obj << "' is not thread local\n");
959 return false;
960}
961
962bool AA::isPotentiallyAffectedByBarrier(Attributor &A, const Instruction &I,
963 const AbstractAttribute &QueryingAA) {
964 if (!I.mayHaveSideEffects() && !I.mayReadFromMemory())
965 return false;
966
967 SmallSetVector<const Value *, 8> Ptrs;
968
969 auto AddLocationPtr = [&](std::optional<MemoryLocation> Loc) {
970 if (!Loc || !Loc->Ptr) {
971 LLVM_DEBUG(
972 dbgs() << "[AA] Access to unknown location; -> requires barriers\n");
973 return false;
974 }
975 Ptrs.insert(X: Loc->Ptr);
976 return true;
977 };
978
979 if (const MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Val: &I)) {
980 if (!AddLocationPtr(MemoryLocation::getForDest(MI)))
981 return true;
982 if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(Val: &I))
983 if (!AddLocationPtr(MemoryLocation::getForSource(MTI)))
984 return true;
985 } else if (!AddLocationPtr(MemoryLocation::getOrNone(Inst: &I)))
986 return true;
987
988 return isPotentiallyAffectedByBarrier(A, Ptrs: Ptrs.getArrayRef(), QueryingAA, CtxI: &I);
989}
990
991bool AA::isPotentiallyAffectedByBarrier(Attributor &A,
992 ArrayRef<const Value *> Ptrs,
993 const AbstractAttribute &QueryingAA,
994 const Instruction *CtxI) {
995 for (const Value *Ptr : Ptrs) {
996 if (!Ptr) {
997 LLVM_DEBUG(dbgs() << "[AA] nullptr; -> requires barriers\n");
998 return true;
999 }
1000
1001 auto Pred = [&](Value &Obj) {
1002 if (AA::isAssumedThreadLocalObject(A, Obj, QueryingAA))
1003 return true;
1004 LLVM_DEBUG(dbgs() << "[AA] Access to '" << Obj << "' via '" << *Ptr
1005 << "'; -> requires barrier\n");
1006 return false;
1007 };
1008
1009 const auto *UnderlyingObjsAA = A.getAAFor<AAUnderlyingObjects>(
1010 QueryingAA, IRP: IRPosition::value(V: *Ptr), DepClass: DepClassTy::OPTIONAL);
1011 if (!UnderlyingObjsAA || !UnderlyingObjsAA->forallUnderlyingObjects(Pred))
1012 return true;
1013 }
1014 return false;
1015}
1016
1017/// Return true if \p New is equal or worse than \p Old.
1018static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) {
1019 if (!Old.isIntAttribute())
1020 return true;
1021
1022 return Old.getValueAsInt() >= New.getValueAsInt();
1023}
1024
1025/// Return true if the information provided by \p Attr was added to the
1026/// attribute set \p AttrSet. This is only the case if it was not already
1027/// present in \p AttrSet.
1028static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr,
1029 AttributeSet AttrSet, bool ForceReplace,
1030 AttrBuilder &AB) {
1031
1032 if (Attr.isEnumAttribute()) {
1033 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1034 if (AttrSet.hasAttribute(Kind))
1035 return false;
1036 AB.addAttribute(Val: Kind);
1037 return true;
1038 }
1039 if (Attr.isStringAttribute()) {
1040 StringRef Kind = Attr.getKindAsString();
1041 if (AttrSet.hasAttribute(Kind)) {
1042 if (!ForceReplace)
1043 return false;
1044 }
1045 AB.addAttribute(A: Kind, V: Attr.getValueAsString());
1046 return true;
1047 }
1048 if (Attr.isIntAttribute()) {
1049 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1050 if (!ForceReplace && Kind == Attribute::Memory) {
1051 MemoryEffects ME = Attr.getMemoryEffects() & AttrSet.getMemoryEffects();
1052 if (ME == AttrSet.getMemoryEffects())
1053 return false;
1054 AB.addMemoryAttr(ME);
1055 return true;
1056 }
1057 if (AttrSet.hasAttribute(Kind)) {
1058 if (!ForceReplace && isEqualOrWorse(New: Attr, Old: AttrSet.getAttribute(Kind)))
1059 return false;
1060 }
1061 AB.addAttribute(A: Attr);
1062 return true;
1063 }
1064 if (Attr.isConstantRangeAttribute()) {
1065 Attribute::AttrKind Kind = Attr.getKindAsEnum();
1066 if (!ForceReplace && AttrSet.hasAttribute(Kind))
1067 return false;
1068 AB.addAttribute(A: Attr);
1069 return true;
1070 }
1071
1072 llvm_unreachable("Expected enum or string attribute!");
1073}
1074
1075Argument *IRPosition::getAssociatedArgument() const {
1076 if (getPositionKind() == IRP_ARGUMENT)
1077 return cast<Argument>(Val: &getAnchorValue());
1078
1079 // Not an Argument and no argument number means this is not a call site
1080 // argument, thus we cannot find a callback argument to return.
1081 int ArgNo = getCallSiteArgNo();
1082 if (ArgNo < 0)
1083 return nullptr;
1084
1085 // Use abstract call sites to make the connection between the call site
1086 // values and the ones in callbacks. If a callback was found that makes use
1087 // of the underlying call site operand, we want the corresponding callback
1088 // callee argument and not the direct callee argument.
1089 std::optional<Argument *> CBCandidateArg;
1090 SmallVector<const Use *, 4> CallbackUses;
1091 const auto &CB = cast<CallBase>(Val&: getAnchorValue());
1092 AbstractCallSite::getCallbackUses(CB, CallbackUses);
1093 for (const Use *U : CallbackUses) {
1094 AbstractCallSite ACS(U);
1095 assert(ACS && ACS.isCallbackCall());
1096 if (!ACS.getCalledFunction())
1097 continue;
1098
1099 for (unsigned u = 0, e = ACS.getNumArgOperands(); u < e; u++) {
1100
1101 // Test if the underlying call site operand is argument number u of the
1102 // callback callee.
1103 if (ACS.getCallArgOperandNo(ArgNo: u) != ArgNo)
1104 continue;
1105
1106 assert(ACS.getCalledFunction()->arg_size() > u &&
1107 "ACS mapped into var-args arguments!");
1108 if (CBCandidateArg) {
1109 CBCandidateArg = nullptr;
1110 break;
1111 }
1112 CBCandidateArg = ACS.getCalledFunction()->getArg(i: u);
1113 }
1114 }
1115
1116 // If we found a unique callback candidate argument, return it.
1117 if (CBCandidateArg && *CBCandidateArg)
1118 return *CBCandidateArg;
1119
1120 // If no callbacks were found, or none used the underlying call site operand
1121 // exclusively, use the direct callee argument if available.
1122 auto *Callee = dyn_cast_if_present<Function>(Val: CB.getCalledOperand());
1123 if (Callee && Callee->arg_size() > unsigned(ArgNo))
1124 return Callee->getArg(i: ArgNo);
1125
1126 return nullptr;
1127}
1128
1129ChangeStatus AbstractAttribute::update(Attributor &A) {
1130 ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
1131 if (getState().isAtFixpoint())
1132 return HasChanged;
1133
1134 LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n");
1135
1136 HasChanged = updateImpl(A);
1137
1138 LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this
1139 << "\n");
1140
1141 return HasChanged;
1142}
1143
1144Attributor::Attributor(SetVector<Function *> &Functions,
1145 InformationCache &InfoCache,
1146 AttributorConfig Configuration)
1147 : Allocator(InfoCache.Allocator), Functions(Functions),
1148 InfoCache(InfoCache), Configuration(Configuration) {
1149 if (!isClosedWorldModule())
1150 return;
1151 for (Function *Fn : Functions)
1152 if (Fn->hasAddressTaken(/*PutOffender=*/nullptr,
1153 /*IgnoreCallbackUses=*/false,
1154 /*IgnoreAssumeLikeCalls=*/true,
1155 /*IgnoreLLVMUsed=*/IngoreLLVMUsed: true,
1156 /*IgnoreARCAttachedCall=*/false,
1157 /*IgnoreCastedDirectCall=*/true))
1158 InfoCache.IndirectlyCallableFunctions.push_back(Elt: Fn);
1159}
1160
1161bool Attributor::getAttrsFromAssumes(const IRPosition &IRP,
1162 Attribute::AttrKind AK,
1163 SmallVectorImpl<Attribute> &Attrs) {
1164 assert(IRP.getPositionKind() != IRPosition::IRP_INVALID &&
1165 "Did expect a valid position!");
1166 MustBeExecutedContextExplorer *Explorer =
1167 getInfoCache().getMustBeExecutedContextExplorer();
1168 if (!Explorer)
1169 return false;
1170
1171 Value &AssociatedValue = IRP.getAssociatedValue();
1172
1173 const Assume2KnowledgeMap &A2K =
1174 getInfoCache().getKnowledgeMap().lookup(Val: {&AssociatedValue, AK});
1175
1176 // Check if we found any potential assume use, if not we don't need to create
1177 // explorer iterators.
1178 if (A2K.empty())
1179 return false;
1180
1181 LLVMContext &Ctx = AssociatedValue.getContext();
1182 unsigned AttrsSize = Attrs.size();
1183 auto EIt = Explorer->begin(PP: IRP.getCtxI()),
1184 EEnd = Explorer->end(IRP.getCtxI());
1185 for (const auto &It : A2K)
1186 if (Explorer->findInContextOf(I: It.first, EIt, EEnd))
1187 Attrs.push_back(Elt: Attribute::get(Context&: Ctx, Kind: AK, Val: It.second.Max));
1188 return AttrsSize != Attrs.size();
1189}
1190
1191template <typename DescTy>
1192ChangeStatus
1193Attributor::updateAttrMap(const IRPosition &IRP, ArrayRef<DescTy> AttrDescs,
1194 function_ref<bool(const DescTy &, AttributeSet,
1195 AttributeMask &, AttrBuilder &)>
1196 CB) {
1197 if (AttrDescs.empty())
1198 return ChangeStatus::UNCHANGED;
1199 switch (IRP.getPositionKind()) {
1200 case IRPosition::IRP_FLOAT:
1201 case IRPosition::IRP_INVALID:
1202 return ChangeStatus::UNCHANGED;
1203 default:
1204 break;
1205 };
1206
1207 AttributeList AL = IRP.getAttrList();
1208 Value *AttrListAnchor = IRP.getAttrListAnchor();
1209 auto [Iter, Inserted] = AttrsMap.insert(KV: {AttrListAnchor, AL});
1210 if (!Inserted)
1211 AL = Iter->second;
1212
1213 LLVMContext &Ctx = IRP.getAnchorValue().getContext();
1214 auto AttrIdx = IRP.getAttrIdx();
1215 AttributeSet AS = AL.getAttributes(Index: AttrIdx);
1216 AttributeMask AM;
1217 AttrBuilder AB(Ctx);
1218
1219 ChangeStatus HasChanged = ChangeStatus::UNCHANGED;
1220 for (const DescTy &AttrDesc : AttrDescs)
1221 if (CB(AttrDesc, AS, AM, AB))
1222 HasChanged = ChangeStatus::CHANGED;
1223
1224 if (HasChanged == ChangeStatus::UNCHANGED)
1225 return ChangeStatus::UNCHANGED;
1226
1227 AL = AL.removeAttributesAtIndex(C&: Ctx, Index: AttrIdx, AttrsToRemove: AM);
1228 AL = AL.addAttributesAtIndex(C&: Ctx, Index: AttrIdx, B: AB);
1229
1230 Iter->second = AL;
1231 return HasChanged;
1232}
1233
1234bool Attributor::hasAttr(const IRPosition &IRP,
1235 ArrayRef<Attribute::AttrKind> AttrKinds,
1236 bool IgnoreSubsumingPositions,
1237 Attribute::AttrKind ImpliedAttributeKind) {
1238 bool Implied = false;
1239 bool HasAttr = false;
1240 auto HasAttrCB = [&](const Attribute::AttrKind &Kind, AttributeSet AttrSet,
1241 AttributeMask &, AttrBuilder &) {
1242 if (AttrSet.hasAttribute(Kind)) {
1243 Implied |= Kind != ImpliedAttributeKind;
1244 HasAttr = true;
1245 }
1246 return false;
1247 };
1248 for (const IRPosition &EquivIRP : SubsumingPositionIterator(IRP)) {
1249 updateAttrMap<Attribute::AttrKind>(IRP: EquivIRP, AttrDescs: AttrKinds, CB: HasAttrCB);
1250 if (HasAttr)
1251 break;
1252 // The first position returned by the SubsumingPositionIterator is
1253 // always the position itself. If we ignore subsuming positions we
1254 // are done after the first iteration.
1255 if (IgnoreSubsumingPositions)
1256 break;
1257 Implied = true;
1258 }
1259 if (!HasAttr) {
1260 Implied = true;
1261 SmallVector<Attribute> Attrs;
1262 for (Attribute::AttrKind AK : AttrKinds)
1263 if (getAttrsFromAssumes(IRP, AK, Attrs)) {
1264 HasAttr = true;
1265 break;
1266 }
1267 }
1268
1269 // Check if we should manifest the implied attribute kind at the IRP.
1270 if (ImpliedAttributeKind != Attribute::None && HasAttr && Implied)
1271 manifestAttrs(IRP, DeducedAttrs: {Attribute::get(Context&: IRP.getAnchorValue().getContext(),
1272 Kind: ImpliedAttributeKind)});
1273 return HasAttr;
1274}
1275
1276void Attributor::getAttrs(const IRPosition &IRP,
1277 ArrayRef<Attribute::AttrKind> AttrKinds,
1278 SmallVectorImpl<Attribute> &Attrs,
1279 bool IgnoreSubsumingPositions) {
1280 auto CollectAttrCB = [&](const Attribute::AttrKind &Kind,
1281 AttributeSet AttrSet, AttributeMask &,
1282 AttrBuilder &) {
1283 if (AttrSet.hasAttribute(Kind))
1284 Attrs.push_back(Elt: AttrSet.getAttribute(Kind));
1285 return false;
1286 };
1287 for (const IRPosition &EquivIRP : SubsumingPositionIterator(IRP)) {
1288 updateAttrMap<Attribute::AttrKind>(IRP: EquivIRP, AttrDescs: AttrKinds, CB: CollectAttrCB);
1289 // The first position returned by the SubsumingPositionIterator is
1290 // always the position itself. If we ignore subsuming positions we
1291 // are done after the first iteration.
1292 if (IgnoreSubsumingPositions)
1293 break;
1294 }
1295 for (Attribute::AttrKind AK : AttrKinds)
1296 getAttrsFromAssumes(IRP, AK, Attrs);
1297}
1298
1299ChangeStatus Attributor::removeAttrs(const IRPosition &IRP,
1300 ArrayRef<Attribute::AttrKind> AttrKinds) {
1301 auto RemoveAttrCB = [&](const Attribute::AttrKind &Kind, AttributeSet AttrSet,
1302 AttributeMask &AM, AttrBuilder &) {
1303 if (!AttrSet.hasAttribute(Kind))
1304 return false;
1305 AM.addAttribute(Val: Kind);
1306 return true;
1307 };
1308 return updateAttrMap<Attribute::AttrKind>(IRP, AttrDescs: AttrKinds, CB: RemoveAttrCB);
1309}
1310
1311ChangeStatus Attributor::removeAttrs(const IRPosition &IRP,
1312 ArrayRef<StringRef> Attrs) {
1313 auto RemoveAttrCB = [&](StringRef Attr, AttributeSet AttrSet,
1314 AttributeMask &AM, AttrBuilder &) -> bool {
1315 if (!AttrSet.hasAttribute(Kind: Attr))
1316 return false;
1317 AM.addAttribute(A: Attr);
1318 return true;
1319 };
1320
1321 return updateAttrMap<StringRef>(IRP, AttrDescs: Attrs, CB: RemoveAttrCB);
1322}
1323
1324ChangeStatus Attributor::manifestAttrs(const IRPosition &IRP,
1325 ArrayRef<Attribute> Attrs,
1326 bool ForceReplace) {
1327 LLVMContext &Ctx = IRP.getAnchorValue().getContext();
1328 auto AddAttrCB = [&](const Attribute &Attr, AttributeSet AttrSet,
1329 AttributeMask &, AttrBuilder &AB) {
1330 return addIfNotExistent(Ctx, Attr, AttrSet, ForceReplace, AB);
1331 };
1332 return updateAttrMap<Attribute>(IRP, AttrDescs: Attrs, CB: AddAttrCB);
1333}
1334
1335SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) {
1336 IRPositions.emplace_back(Args: IRP);
1337
1338 // Helper to determine if operand bundles on a call site are benign or
1339 // potentially problematic. We handle only llvm.assume for now.
1340 auto CanIgnoreOperandBundles = [](const CallBase &CB) {
1341 return (isa<IntrinsicInst>(Val: CB) &&
1342 cast<IntrinsicInst>(Val: CB).getIntrinsicID() == Intrinsic ::assume);
1343 };
1344
1345 const auto *CB = dyn_cast<CallBase>(Val: &IRP.getAnchorValue());
1346 switch (IRP.getPositionKind()) {
1347 case IRPosition::IRP_INVALID:
1348 case IRPosition::IRP_FLOAT:
1349 case IRPosition::IRP_FUNCTION:
1350 return;
1351 case IRPosition::IRP_ARGUMENT:
1352 case IRPosition::IRP_RETURNED:
1353 IRPositions.emplace_back(Args: IRPosition::function(F: *IRP.getAnchorScope()));
1354 return;
1355 case IRPosition::IRP_CALL_SITE:
1356 assert(CB && "Expected call site!");
1357 // TODO: We need to look at the operand bundles similar to the redirection
1358 // in CallBase.
1359 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB))
1360 if (auto *Callee = dyn_cast_if_present<Function>(Val: CB->getCalledOperand()))
1361 IRPositions.emplace_back(Args: IRPosition::function(F: *Callee));
1362 return;
1363 case IRPosition::IRP_CALL_SITE_RETURNED:
1364 assert(CB && "Expected call site!");
1365 // TODO: We need to look at the operand bundles similar to the redirection
1366 // in CallBase.
1367 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
1368 if (auto *Callee =
1369 dyn_cast_if_present<Function>(Val: CB->getCalledOperand())) {
1370 IRPositions.emplace_back(Args: IRPosition::returned(F: *Callee));
1371 IRPositions.emplace_back(Args: IRPosition::function(F: *Callee));
1372 for (const Argument &Arg : Callee->args())
1373 if (Arg.hasReturnedAttr()) {
1374 IRPositions.emplace_back(
1375 Args: IRPosition::callsite_argument(CB: *CB, ArgNo: Arg.getArgNo()));
1376 IRPositions.emplace_back(
1377 Args: IRPosition::value(V: *CB->getArgOperand(i: Arg.getArgNo())));
1378 IRPositions.emplace_back(Args: IRPosition::argument(Arg));
1379 }
1380 }
1381 }
1382 IRPositions.emplace_back(Args: IRPosition::callsite_function(CB: *CB));
1383 return;
1384 case IRPosition::IRP_CALL_SITE_ARGUMENT: {
1385 assert(CB && "Expected call site!");
1386 // TODO: We need to look at the operand bundles similar to the redirection
1387 // in CallBase.
1388 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) {
1389 auto *Callee = dyn_cast_if_present<Function>(Val: CB->getCalledOperand());
1390 if (Callee) {
1391 if (Argument *Arg = IRP.getAssociatedArgument())
1392 IRPositions.emplace_back(Args: IRPosition::argument(Arg: *Arg));
1393 IRPositions.emplace_back(Args: IRPosition::function(F: *Callee));
1394 }
1395 }
1396 IRPositions.emplace_back(Args: IRPosition::value(V: IRP.getAssociatedValue()));
1397 return;
1398 }
1399 }
1400}
1401
1402void IRPosition::verify() {
1403#ifdef EXPENSIVE_CHECKS
1404 switch (getPositionKind()) {
1405 case IRP_INVALID:
1406 assert((CBContext == nullptr) &&
1407 "Invalid position must not have CallBaseContext!");
1408 assert(!Enc.getOpaqueValue() &&
1409 "Expected a nullptr for an invalid position!");
1410 return;
1411 case IRP_FLOAT:
1412 assert((!isa<Argument>(&getAssociatedValue())) &&
1413 "Expected specialized kind for argument values!");
1414 return;
1415 case IRP_RETURNED:
1416 assert(isa<Function>(getAsValuePtr()) &&
1417 "Expected function for a 'returned' position!");
1418 assert(getAsValuePtr() == &getAssociatedValue() &&
1419 "Associated value mismatch!");
1420 return;
1421 case IRP_CALL_SITE_RETURNED:
1422 assert((CBContext == nullptr) &&
1423 "'call site returned' position must not have CallBaseContext!");
1424 assert((isa<CallBase>(getAsValuePtr())) &&
1425 "Expected call base for 'call site returned' position!");
1426 assert(getAsValuePtr() == &getAssociatedValue() &&
1427 "Associated value mismatch!");
1428 return;
1429 case IRP_CALL_SITE:
1430 assert((CBContext == nullptr) &&
1431 "'call site function' position must not have CallBaseContext!");
1432 assert((isa<CallBase>(getAsValuePtr())) &&
1433 "Expected call base for 'call site function' position!");
1434 assert(getAsValuePtr() == &getAssociatedValue() &&
1435 "Associated value mismatch!");
1436 return;
1437 case IRP_FUNCTION:
1438 assert(isa<Function>(getAsValuePtr()) &&
1439 "Expected function for a 'function' position!");
1440 assert(getAsValuePtr() == &getAssociatedValue() &&
1441 "Associated value mismatch!");
1442 return;
1443 case IRP_ARGUMENT:
1444 assert(isa<Argument>(getAsValuePtr()) &&
1445 "Expected argument for a 'argument' position!");
1446 assert(getAsValuePtr() == &getAssociatedValue() &&
1447 "Associated value mismatch!");
1448 return;
1449 case IRP_CALL_SITE_ARGUMENT: {
1450 assert((CBContext == nullptr) &&
1451 "'call site argument' position must not have CallBaseContext!");
1452 Use *U = getAsUsePtr();
1453 (void)U; // Silence unused variable warning.
1454 assert(U && "Expected use for a 'call site argument' position!");
1455 assert(isa<CallBase>(U->getUser()) &&
1456 "Expected call base user for a 'call site argument' position!");
1457 assert(cast<CallBase>(U->getUser())->isArgOperand(U) &&
1458 "Expected call base argument operand for a 'call site argument' "
1459 "position");
1460 assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) ==
1461 unsigned(getCallSiteArgNo()) &&
1462 "Argument number mismatch!");
1463 assert(U->get() == &getAssociatedValue() && "Associated value mismatch!");
1464 return;
1465 }
1466 }
1467#endif
1468}
1469
1470std::optional<Constant *>
1471Attributor::getAssumedConstant(const IRPosition &IRP,
1472 const AbstractAttribute &AA,
1473 bool &UsedAssumedInformation) {
1474 // First check all callbacks provided by outside AAs. If any of them returns
1475 // a non-null value that is different from the associated value, or
1476 // std::nullopt, we assume it's simplified.
1477 for (auto &CB : SimplificationCallbacks.lookup(Val: IRP)) {
1478 std::optional<Value *> SimplifiedV = CB(IRP, &AA, UsedAssumedInformation);
1479 if (!SimplifiedV)
1480 return std::nullopt;
1481 if (isa_and_nonnull<Constant>(Val: *SimplifiedV))
1482 return cast<Constant>(Val: *SimplifiedV);
1483 return nullptr;
1484 }
1485 if (auto *C = dyn_cast<Constant>(Val: &IRP.getAssociatedValue()))
1486 return C;
1487 SmallVector<AA::ValueAndContext> Values;
1488 if (getAssumedSimplifiedValues(IRP, AA: &AA, Values,
1489 S: AA::ValueScope::Interprocedural,
1490 UsedAssumedInformation)) {
1491 if (Values.empty())
1492 return std::nullopt;
1493 if (auto *C = dyn_cast_or_null<Constant>(
1494 Val: AAPotentialValues::getSingleValue(A&: *this, AA, IRP, Values)))
1495 return C;
1496 }
1497 return nullptr;
1498}
1499
1500std::optional<Value *> Attributor::getAssumedSimplified(
1501 const IRPosition &IRP, const AbstractAttribute *AA,
1502 bool &UsedAssumedInformation, AA::ValueScope S) {
1503 // First check all callbacks provided by outside AAs. If any of them returns
1504 // a non-null value that is different from the associated value, or
1505 // std::nullopt, we assume it's simplified.
1506 for (auto &CB : SimplificationCallbacks.lookup(Val: IRP))
1507 return CB(IRP, AA, UsedAssumedInformation);
1508
1509 SmallVector<AA::ValueAndContext> Values;
1510 if (!getAssumedSimplifiedValues(IRP, AA, Values, S, UsedAssumedInformation))
1511 return &IRP.getAssociatedValue();
1512 if (Values.empty())
1513 return std::nullopt;
1514 if (AA)
1515 if (Value *V = AAPotentialValues::getSingleValue(A&: *this, AA: *AA, IRP, Values))
1516 return V;
1517 if (IRP.getPositionKind() == IRPosition::IRP_RETURNED ||
1518 IRP.getPositionKind() == IRPosition::IRP_CALL_SITE_RETURNED)
1519 return nullptr;
1520 return &IRP.getAssociatedValue();
1521}
1522
1523bool Attributor::getAssumedSimplifiedValues(
1524 const IRPosition &InitialIRP, const AbstractAttribute *AA,
1525 SmallVectorImpl<AA::ValueAndContext> &Values, AA::ValueScope S,
1526 bool &UsedAssumedInformation, bool RecurseForSelectAndPHI) {
1527 SmallPtrSet<Value *, 8> Seen;
1528 SmallVector<IRPosition, 8> Worklist;
1529 Worklist.push_back(Elt: InitialIRP);
1530 while (!Worklist.empty()) {
1531 const IRPosition &IRP = Worklist.pop_back_val();
1532
1533 // First check all callbacks provided by outside AAs. If any of them returns
1534 // a non-null value that is different from the associated value, or
1535 // std::nullopt, we assume it's simplified.
1536 int NV = Values.size();
1537 const auto &SimplificationCBs = SimplificationCallbacks.lookup(Val: IRP);
1538 for (const auto &CB : SimplificationCBs) {
1539 std::optional<Value *> CBResult = CB(IRP, AA, UsedAssumedInformation);
1540 if (!CBResult.has_value())
1541 continue;
1542 Value *V = *CBResult;
1543 if (!V)
1544 return false;
1545 if ((S & AA::ValueScope::Interprocedural) ||
1546 AA::isValidInScope(V: *V, Scope: IRP.getAnchorScope()))
1547 Values.push_back(Elt: AA::ValueAndContext{*V, nullptr});
1548 else
1549 return false;
1550 }
1551 if (SimplificationCBs.empty()) {
1552 // If no high-level/outside simplification occurred, use
1553 // AAPotentialValues.
1554 const auto *PotentialValuesAA =
1555 getOrCreateAAFor<AAPotentialValues>(IRP, QueryingAA: AA, DepClass: DepClassTy::OPTIONAL);
1556 if (PotentialValuesAA &&
1557 PotentialValuesAA->getAssumedSimplifiedValues(A&: *this, Values, S)) {
1558 UsedAssumedInformation |= !PotentialValuesAA->isAtFixpoint();
1559 } else if (IRP.getPositionKind() != IRPosition::IRP_RETURNED) {
1560 Values.push_back(Elt: {IRP.getAssociatedValue(), IRP.getCtxI()});
1561 } else {
1562 // TODO: We could visit all returns and add the operands.
1563 return false;
1564 }
1565 }
1566
1567 if (!RecurseForSelectAndPHI)
1568 break;
1569
1570 for (int I = NV, E = Values.size(); I < E; ++I) {
1571 Value *V = Values[I].getValue();
1572 if (!isa<PHINode>(Val: V) && !isa<SelectInst>(Val: V))
1573 continue;
1574 if (!Seen.insert(Ptr: V).second)
1575 continue;
1576 // Move the last element to this slot.
1577 Values[I] = Values[E - 1];
1578 // Eliminate the last slot, adjust the indices.
1579 Values.pop_back();
1580 --E;
1581 --I;
1582 // Add a new value (select or phi) to the worklist.
1583 Worklist.push_back(Elt: IRPosition::value(V: *V));
1584 }
1585 }
1586 return true;
1587}
1588
1589std::optional<Value *> Attributor::translateArgumentToCallSiteContent(
1590 std::optional<Value *> V, CallBase &CB, const AbstractAttribute &AA,
1591 bool &UsedAssumedInformation) {
1592 if (!V)
1593 return V;
1594 if (*V == nullptr || isa<Constant>(Val: *V))
1595 return V;
1596 if (auto *Arg = dyn_cast<Argument>(Val: *V))
1597 if (CB.getCalledOperand() == Arg->getParent() &&
1598 CB.arg_size() > Arg->getArgNo())
1599 if (!Arg->hasPointeeInMemoryValueAttr())
1600 return getAssumedSimplified(
1601 IRP: IRPosition::callsite_argument(CB, ArgNo: Arg->getArgNo()), AA,
1602 UsedAssumedInformation, S: AA::Intraprocedural);
1603 return nullptr;
1604}
1605
1606Attributor::~Attributor() {
1607 // The abstract attributes are allocated via the BumpPtrAllocator Allocator,
1608 // thus we cannot delete them. We can, and want to, destruct them though.
1609 for (auto &It : AAMap) {
1610 AbstractAttribute *AA = It.getSecond();
1611 AA->~AbstractAttribute();
1612 }
1613}
1614
1615bool Attributor::isAssumedDead(const AbstractAttribute &AA,
1616 const AAIsDead *FnLivenessAA,
1617 bool &UsedAssumedInformation,
1618 bool CheckBBLivenessOnly, DepClassTy DepClass) {
1619 if (!Configuration.UseLiveness)
1620 return false;
1621 const IRPosition &IRP = AA.getIRPosition();
1622 if (!Functions.count(key: IRP.getAnchorScope()))
1623 return false;
1624 return isAssumedDead(IRP, QueryingAA: &AA, FnLivenessAA, UsedAssumedInformation,
1625 CheckBBLivenessOnly, DepClass);
1626}
1627
1628bool Attributor::isAssumedDead(const Use &U,
1629 const AbstractAttribute *QueryingAA,
1630 const AAIsDead *FnLivenessAA,
1631 bool &UsedAssumedInformation,
1632 bool CheckBBLivenessOnly, DepClassTy DepClass) {
1633 if (!Configuration.UseLiveness)
1634 return false;
1635 Instruction *UserI = dyn_cast<Instruction>(Val: U.getUser());
1636 if (!UserI)
1637 return isAssumedDead(IRP: IRPosition::value(V: *U.get()), QueryingAA, FnLivenessAA,
1638 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1639
1640 if (auto *CB = dyn_cast<CallBase>(Val: UserI)) {
1641 // For call site argument uses we can check if the argument is
1642 // unused/dead.
1643 if (CB->isArgOperand(U: &U)) {
1644 const IRPosition &CSArgPos =
1645 IRPosition::callsite_argument(CB: *CB, ArgNo: CB->getArgOperandNo(U: &U));
1646 return isAssumedDead(IRP: CSArgPos, QueryingAA, FnLivenessAA,
1647 UsedAssumedInformation, CheckBBLivenessOnly,
1648 DepClass);
1649 }
1650 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(Val: UserI)) {
1651 const IRPosition &RetPos = IRPosition::returned(F: *RI->getFunction());
1652 return isAssumedDead(IRP: RetPos, QueryingAA, FnLivenessAA,
1653 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1654 } else if (PHINode *PHI = dyn_cast<PHINode>(Val: UserI)) {
1655 BasicBlock *IncomingBB = PHI->getIncomingBlock(U);
1656 return isAssumedDead(I: *IncomingBB->getTerminator(), QueryingAA, LivenessAA: FnLivenessAA,
1657 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1658 } else if (StoreInst *SI = dyn_cast<StoreInst>(Val: UserI)) {
1659 if (!CheckBBLivenessOnly && SI->getPointerOperand() != U.get()) {
1660 const IRPosition IRP = IRPosition::inst(I: *SI);
1661 const AAIsDead *IsDeadAA =
1662 getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClass: DepClassTy::NONE);
1663 if (IsDeadAA && IsDeadAA->isRemovableStore()) {
1664 if (QueryingAA)
1665 recordDependence(FromAA: *IsDeadAA, ToAA: *QueryingAA, DepClass);
1666 if (!IsDeadAA->isKnown(BitsEncoding: AAIsDead::IS_REMOVABLE))
1667 UsedAssumedInformation = true;
1668 return true;
1669 }
1670 }
1671 }
1672
1673 return isAssumedDead(IRP: IRPosition::inst(I: *UserI), QueryingAA, FnLivenessAA,
1674 UsedAssumedInformation, CheckBBLivenessOnly, DepClass);
1675}
1676
1677bool Attributor::isAssumedDead(const Instruction &I,
1678 const AbstractAttribute *QueryingAA,
1679 const AAIsDead *FnLivenessAA,
1680 bool &UsedAssumedInformation,
1681 bool CheckBBLivenessOnly, DepClassTy DepClass,
1682 bool CheckForDeadStore) {
1683 if (!Configuration.UseLiveness)
1684 return false;
1685 const IRPosition::CallBaseContext *CBCtx =
1686 QueryingAA ? QueryingAA->getCallBaseContext() : nullptr;
1687
1688 if (ManifestAddedBlocks.contains(Ptr: I.getParent()))
1689 return false;
1690
1691 const Function &F = *I.getFunction();
1692 if (!FnLivenessAA || FnLivenessAA->getAnchorScope() != &F)
1693 FnLivenessAA = getOrCreateAAFor<AAIsDead>(IRP: IRPosition::function(F, CBContext: CBCtx),
1694 QueryingAA, DepClass: DepClassTy::NONE);
1695
1696 // Don't use recursive reasoning.
1697 if (!FnLivenessAA || QueryingAA == FnLivenessAA)
1698 return false;
1699
1700 // If we have a context instruction and a liveness AA we use it.
1701 if (CheckBBLivenessOnly ? FnLivenessAA->isAssumedDead(BB: I.getParent())
1702 : FnLivenessAA->isAssumedDead(I: &I)) {
1703 if (QueryingAA)
1704 recordDependence(FromAA: *FnLivenessAA, ToAA: *QueryingAA, DepClass);
1705 if (!FnLivenessAA->isKnownDead(I: &I))
1706 UsedAssumedInformation = true;
1707 return true;
1708 }
1709
1710 if (CheckBBLivenessOnly)
1711 return false;
1712
1713 const IRPosition IRP = IRPosition::inst(I, CBContext: CBCtx);
1714 const AAIsDead *IsDeadAA =
1715 getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClass: DepClassTy::NONE);
1716
1717 // Don't use recursive reasoning.
1718 if (!IsDeadAA || QueryingAA == IsDeadAA)
1719 return false;
1720
1721 if (IsDeadAA->isAssumedDead()) {
1722 if (QueryingAA)
1723 recordDependence(FromAA: *IsDeadAA, ToAA: *QueryingAA, DepClass);
1724 if (!IsDeadAA->isKnownDead())
1725 UsedAssumedInformation = true;
1726 return true;
1727 }
1728
1729 if (CheckForDeadStore && isa<StoreInst>(Val: I) && IsDeadAA->isRemovableStore()) {
1730 if (QueryingAA)
1731 recordDependence(FromAA: *IsDeadAA, ToAA: *QueryingAA, DepClass);
1732 if (!IsDeadAA->isKnownDead())
1733 UsedAssumedInformation = true;
1734 return true;
1735 }
1736
1737 return false;
1738}
1739
1740bool Attributor::isAssumedDead(const IRPosition &IRP,
1741 const AbstractAttribute *QueryingAA,
1742 const AAIsDead *FnLivenessAA,
1743 bool &UsedAssumedInformation,
1744 bool CheckBBLivenessOnly, DepClassTy DepClass) {
1745 if (!Configuration.UseLiveness)
1746 return false;
1747 // Don't check liveness for constants, e.g. functions, used as (floating)
1748 // values since the context instruction and such is here meaningless.
1749 if (IRP.getPositionKind() == IRPosition::IRP_FLOAT &&
1750 isa<Constant>(Val: IRP.getAssociatedValue())) {
1751 return false;
1752 }
1753
1754 Instruction *CtxI = IRP.getCtxI();
1755 if (CtxI &&
1756 isAssumedDead(I: *CtxI, QueryingAA, FnLivenessAA, UsedAssumedInformation,
1757 /* CheckBBLivenessOnly */ true,
1758 DepClass: CheckBBLivenessOnly ? DepClass : DepClassTy::OPTIONAL))
1759 return true;
1760
1761 if (CheckBBLivenessOnly)
1762 return false;
1763
1764 // If we haven't succeeded we query the specific liveness info for the IRP.
1765 const AAIsDead *IsDeadAA;
1766 if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE)
1767 IsDeadAA = getOrCreateAAFor<AAIsDead>(
1768 IRP: IRPosition::callsite_returned(CB: cast<CallBase>(Val&: IRP.getAssociatedValue())),
1769 QueryingAA, DepClass: DepClassTy::NONE);
1770 else
1771 IsDeadAA = getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClass: DepClassTy::NONE);
1772
1773 // Don't use recursive reasoning.
1774 if (!IsDeadAA || QueryingAA == IsDeadAA)
1775 return false;
1776
1777 if (IsDeadAA->isAssumedDead()) {
1778 if (QueryingAA)
1779 recordDependence(FromAA: *IsDeadAA, ToAA: *QueryingAA, DepClass);
1780 if (!IsDeadAA->isKnownDead())
1781 UsedAssumedInformation = true;
1782 return true;
1783 }
1784
1785 return false;
1786}
1787
1788bool Attributor::isAssumedDead(const BasicBlock &BB,
1789 const AbstractAttribute *QueryingAA,
1790 const AAIsDead *FnLivenessAA,
1791 DepClassTy DepClass) {
1792 if (!Configuration.UseLiveness)
1793 return false;
1794 const Function &F = *BB.getParent();
1795 if (!FnLivenessAA || FnLivenessAA->getAnchorScope() != &F)
1796 FnLivenessAA = getOrCreateAAFor<AAIsDead>(IRP: IRPosition::function(F),
1797 QueryingAA, DepClass: DepClassTy::NONE);
1798
1799 // Don't use recursive reasoning.
1800 if (!FnLivenessAA || QueryingAA == FnLivenessAA)
1801 return false;
1802
1803 if (FnLivenessAA->isAssumedDead(BB: &BB)) {
1804 if (QueryingAA)
1805 recordDependence(FromAA: *FnLivenessAA, ToAA: *QueryingAA, DepClass);
1806 return true;
1807 }
1808
1809 return false;
1810}
1811
1812bool Attributor::checkForAllCallees(
1813 function_ref<bool(ArrayRef<const Function *>)> Pred,
1814 const AbstractAttribute &QueryingAA, const CallBase &CB) {
1815 if (const Function *Callee = dyn_cast<Function>(Val: CB.getCalledOperand()))
1816 return Pred(Callee);
1817
1818 const auto *CallEdgesAA = getAAFor<AACallEdges>(
1819 QueryingAA, IRP: IRPosition::callsite_function(CB), DepClass: DepClassTy::OPTIONAL);
1820 if (!CallEdgesAA || CallEdgesAA->hasUnknownCallee())
1821 return false;
1822
1823 const auto &Callees = CallEdgesAA->getOptimisticEdges();
1824 return Pred(Callees.getArrayRef());
1825}
1826
1827bool canMarkAsVisited(const User *Usr) {
1828 return isa<PHINode>(Val: Usr) || !isa<Instruction>(Val: Usr);
1829}
1830
1831bool Attributor::checkForAllUses(
1832 function_ref<bool(const Use &, bool &)> Pred,
1833 const AbstractAttribute &QueryingAA, const Value &V,
1834 bool CheckBBLivenessOnly, DepClassTy LivenessDepClass,
1835 bool IgnoreDroppableUses,
1836 function_ref<bool(const Use &OldU, const Use &NewU)> EquivalentUseCB) {
1837
1838 // Check virtual uses first.
1839 for (VirtualUseCallbackTy &CB : VirtualUseCallbacks.lookup(Val: &V))
1840 if (!CB(*this, &QueryingAA))
1841 return false;
1842
1843 if (isa<ConstantData>(Val: V))
1844 return false;
1845
1846 // Check the trivial case first as it catches void values.
1847 if (V.use_empty())
1848 return true;
1849
1850 const IRPosition &IRP = QueryingAA.getIRPosition();
1851 SmallVector<const Use *, 16> Worklist;
1852 SmallPtrSet<const Use *, 16> Visited;
1853
1854 auto AddUsers = [&](const Value &V, const Use *OldUse) {
1855 for (const Use &UU : V.uses()) {
1856 if (OldUse && EquivalentUseCB && !EquivalentUseCB(*OldUse, UU)) {
1857 LLVM_DEBUG(dbgs() << "[Attributor] Potential copy was "
1858 "rejected by the equivalence call back: "
1859 << *UU << "!\n");
1860 return false;
1861 }
1862
1863 Worklist.push_back(Elt: &UU);
1864 }
1865 return true;
1866 };
1867
1868 AddUsers(V, /* OldUse */ nullptr);
1869
1870 LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size()
1871 << " initial uses to check\n");
1872
1873 const Function *ScopeFn = IRP.getAnchorScope();
1874 const auto *LivenessAA =
1875 ScopeFn ? getAAFor<AAIsDead>(QueryingAA, IRP: IRPosition::function(F: *ScopeFn),
1876 DepClass: DepClassTy::NONE)
1877 : nullptr;
1878
1879 while (!Worklist.empty()) {
1880 const Use *U = Worklist.pop_back_val();
1881 if (canMarkAsVisited(Usr: U->getUser()) && !Visited.insert(Ptr: U).second)
1882 continue;
1883 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, {
1884 if (auto *Fn = dyn_cast<Function>(U->getUser()))
1885 dbgs() << "[Attributor] Check use: " << **U << " in " << Fn->getName()
1886 << "\n";
1887 else
1888 dbgs() << "[Attributor] Check use: " << **U << " in " << *U->getUser()
1889 << "\n";
1890 });
1891 bool UsedAssumedInformation = false;
1892 if (isAssumedDead(U: *U, QueryingAA: &QueryingAA, FnLivenessAA: LivenessAA, UsedAssumedInformation,
1893 CheckBBLivenessOnly, DepClass: LivenessDepClass)) {
1894 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
1895 dbgs() << "[Attributor] Dead use, skip!\n");
1896 continue;
1897 }
1898 if (IgnoreDroppableUses && U->getUser()->isDroppable()) {
1899 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
1900 dbgs() << "[Attributor] Droppable user, skip!\n");
1901 continue;
1902 }
1903
1904 if (auto *SI = dyn_cast<StoreInst>(Val: U->getUser())) {
1905 if (&SI->getOperandUse(i: 0) == U) {
1906 if (!Visited.insert(Ptr: U).second)
1907 continue;
1908 SmallSetVector<Value *, 4> PotentialCopies;
1909 if (AA::getPotentialCopiesOfStoredValue(
1910 A&: *this, SI&: *SI, PotentialCopies, QueryingAA, UsedAssumedInformation,
1911 /* OnlyExact */ true)) {
1912 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
1913 dbgs()
1914 << "[Attributor] Value is stored, continue with "
1915 << PotentialCopies.size()
1916 << " potential copies instead!\n");
1917 for (Value *PotentialCopy : PotentialCopies)
1918 if (!AddUsers(*PotentialCopy, U))
1919 return false;
1920 continue;
1921 }
1922 }
1923 }
1924
1925 bool Follow = false;
1926 if (!Pred(*U, Follow))
1927 return false;
1928 if (!Follow)
1929 continue;
1930
1931 User &Usr = *U->getUser();
1932 AddUsers(Usr, /* OldUse */ nullptr);
1933 }
1934
1935 return true;
1936}
1937
1938bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
1939 const AbstractAttribute &QueryingAA,
1940 bool RequireAllCallSites,
1941 bool &UsedAssumedInformation) {
1942 // We can try to determine information from
1943 // the call sites. However, this is only possible all call sites are known,
1944 // hence the function has internal linkage.
1945 const IRPosition &IRP = QueryingAA.getIRPosition();
1946 const Function *AssociatedFunction = IRP.getAssociatedFunction();
1947 if (!AssociatedFunction) {
1948 LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP
1949 << "\n");
1950 return false;
1951 }
1952
1953 return checkForAllCallSites(Pred, Fn: *AssociatedFunction, RequireAllCallSites,
1954 QueryingAA: &QueryingAA, UsedAssumedInformation);
1955}
1956
1957bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred,
1958 const Function &Fn,
1959 bool RequireAllCallSites,
1960 const AbstractAttribute *QueryingAA,
1961 bool &UsedAssumedInformation,
1962 bool CheckPotentiallyDead) {
1963 if (RequireAllCallSites && !Fn.hasLocalLinkage()) {
1964 LLVM_DEBUG(
1965 dbgs()
1966 << "[Attributor] Function " << Fn.getName()
1967 << " has no internal linkage, hence not all call sites are known\n");
1968 return false;
1969 }
1970 // Check virtual uses first.
1971 for (VirtualUseCallbackTy &CB : VirtualUseCallbacks.lookup(Val: &Fn))
1972 if (!CB(*this, QueryingAA))
1973 return false;
1974
1975 SmallVector<const Use *, 8> Uses(make_pointer_range(Range: Fn.uses()));
1976 for (unsigned u = 0; u < Uses.size(); ++u) {
1977 const Use &U = *Uses[u];
1978 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, {
1979 if (auto *Fn = dyn_cast<Function>(U))
1980 dbgs() << "[Attributor] Check use: " << Fn->getName() << " in "
1981 << *U.getUser() << "\n";
1982 else
1983 dbgs() << "[Attributor] Check use: " << *U << " in " << *U.getUser()
1984 << "\n";
1985 });
1986 if (!CheckPotentiallyDead &&
1987 isAssumedDead(U, QueryingAA, FnLivenessAA: nullptr, UsedAssumedInformation,
1988 /* CheckBBLivenessOnly */ true)) {
1989 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
1990 dbgs() << "[Attributor] Dead use, skip!\n");
1991 continue;
1992 }
1993 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: U.getUser())) {
1994 if (CE->isCast() && CE->getType()->isPointerTy()) {
1995 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, {
1996 dbgs() << "[Attributor] Use, is constant cast expression, add "
1997 << CE->getNumUses() << " uses of that expression instead!\n";
1998 });
1999 for (const Use &CEU : CE->uses())
2000 Uses.push_back(Elt: &CEU);
2001 continue;
2002 }
2003 }
2004
2005 AbstractCallSite ACS(&U);
2006 if (!ACS) {
2007 LLVM_DEBUG(dbgs() << "[Attributor] Function " << Fn.getName()
2008 << " has non call site use " << *U.get() << " in "
2009 << *U.getUser() << "\n");
2010 return false;
2011 }
2012
2013 const Use *EffectiveUse =
2014 ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U;
2015 if (!ACS.isCallee(U: EffectiveUse)) {
2016 if (!RequireAllCallSites) {
2017 LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
2018 << " is not a call of " << Fn.getName()
2019 << ", skip use\n");
2020 continue;
2021 }
2022 LLVM_DEBUG(dbgs() << "[Attributor] User " << *EffectiveUse->getUser()
2023 << " is an invalid use of " << Fn.getName() << "\n");
2024 return false;
2025 }
2026
2027 // Make sure the arguments that can be matched between the call site and the
2028 // callee argee on their type. It is unlikely they do not and it doesn't
2029 // make sense for all attributes to know/care about this.
2030 assert(&Fn == ACS.getCalledFunction() && "Expected known callee");
2031 unsigned MinArgsParams =
2032 std::min(a: size_t(ACS.getNumArgOperands()), b: Fn.arg_size());
2033 for (unsigned u = 0; u < MinArgsParams; ++u) {
2034 Value *CSArgOp = ACS.getCallArgOperand(ArgNo: u);
2035 if (CSArgOp && Fn.getArg(i: u)->getType() != CSArgOp->getType()) {
2036 LLVM_DEBUG(
2037 dbgs() << "[Attributor] Call site / callee argument type mismatch ["
2038 << u << "@" << Fn.getName() << ": "
2039 << *Fn.getArg(u)->getType() << " vs. "
2040 << *ACS.getCallArgOperand(u)->getType() << "\n");
2041 return false;
2042 }
2043 }
2044
2045 if (Pred(ACS))
2046 continue;
2047
2048 LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for "
2049 << *ACS.getInstruction() << "\n");
2050 return false;
2051 }
2052
2053 return true;
2054}
2055
2056bool Attributor::shouldPropagateCallBaseContext(const IRPosition &IRP) {
2057 // TODO: Maintain a cache of Values that are
2058 // on the pathway from a Argument to a Instruction that would effect the
2059 // liveness/return state etc.
2060 return EnableCallSiteSpecific;
2061}
2062
2063bool Attributor::checkForAllReturnedValues(function_ref<bool(Value &)> Pred,
2064 const AbstractAttribute &QueryingAA,
2065 AA::ValueScope S,
2066 bool RecurseForSelectAndPHI) {
2067
2068 const IRPosition &IRP = QueryingAA.getIRPosition();
2069 const Function *AssociatedFunction = IRP.getAssociatedFunction();
2070 if (!AssociatedFunction)
2071 return false;
2072
2073 bool UsedAssumedInformation = false;
2074 SmallVector<AA::ValueAndContext> Values;
2075 if (!getAssumedSimplifiedValues(
2076 InitialIRP: IRPosition::returned(F: *AssociatedFunction), AA: &QueryingAA, Values, S,
2077 UsedAssumedInformation, RecurseForSelectAndPHI))
2078 return false;
2079
2080 return llvm::all_of(Range&: Values, P: [&](const AA::ValueAndContext &VAC) {
2081 return Pred(*VAC.getValue());
2082 });
2083}
2084
2085static bool checkForAllInstructionsImpl(
2086 Attributor *A, InformationCache::OpcodeInstMapTy &OpcodeInstMap,
2087 function_ref<bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA,
2088 const AAIsDead *LivenessAA, ArrayRef<unsigned> Opcodes,
2089 bool &UsedAssumedInformation, bool CheckBBLivenessOnly = false,
2090 bool CheckPotentiallyDead = false) {
2091 for (unsigned Opcode : Opcodes) {
2092 // Check if we have instructions with this opcode at all first.
2093 auto *Insts = OpcodeInstMap.lookup(Val: Opcode);
2094 if (!Insts)
2095 continue;
2096
2097 for (Instruction *I : *Insts) {
2098 // Skip dead instructions.
2099 if (A && !CheckPotentiallyDead &&
2100 A->isAssumedDead(IRP: IRPosition::inst(I: *I), QueryingAA, FnLivenessAA: LivenessAA,
2101 UsedAssumedInformation, CheckBBLivenessOnly)) {
2102 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
2103 dbgs() << "[Attributor] Instruction " << *I
2104 << " is potentially dead, skip!\n";);
2105 continue;
2106 }
2107
2108 if (!Pred(*I))
2109 return false;
2110 }
2111 }
2112 return true;
2113}
2114
2115bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred,
2116 const Function *Fn,
2117 const AbstractAttribute *QueryingAA,
2118 ArrayRef<unsigned> Opcodes,
2119 bool &UsedAssumedInformation,
2120 bool CheckBBLivenessOnly,
2121 bool CheckPotentiallyDead) {
2122 // Since we need to provide instructions we have to have an exact definition.
2123 if (!Fn || Fn->isDeclaration())
2124 return false;
2125
2126 const IRPosition &QueryIRP = IRPosition::function(F: *Fn);
2127 const auto *LivenessAA =
2128 CheckPotentiallyDead && QueryingAA
2129 ? (getAAFor<AAIsDead>(QueryingAA: *QueryingAA, IRP: QueryIRP, DepClass: DepClassTy::NONE))
2130 : nullptr;
2131
2132 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F: *Fn);
2133 if (!checkForAllInstructionsImpl(A: this, OpcodeInstMap, Pred, QueryingAA,
2134 LivenessAA, Opcodes, UsedAssumedInformation,
2135 CheckBBLivenessOnly, CheckPotentiallyDead))
2136 return false;
2137
2138 return true;
2139}
2140
2141bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred,
2142 const AbstractAttribute &QueryingAA,
2143 ArrayRef<unsigned> Opcodes,
2144 bool &UsedAssumedInformation,
2145 bool CheckBBLivenessOnly,
2146 bool CheckPotentiallyDead) {
2147 const IRPosition &IRP = QueryingAA.getIRPosition();
2148 const Function *AssociatedFunction = IRP.getAssociatedFunction();
2149 return checkForAllInstructions(Pred, Fn: AssociatedFunction, QueryingAA: &QueryingAA, Opcodes,
2150 UsedAssumedInformation, CheckBBLivenessOnly,
2151 CheckPotentiallyDead);
2152}
2153
2154bool Attributor::checkForAllReadWriteInstructions(
2155 function_ref<bool(Instruction &)> Pred, AbstractAttribute &QueryingAA,
2156 bool &UsedAssumedInformation) {
2157 TimeTraceScope TS("checkForAllReadWriteInstructions");
2158
2159 const Function *AssociatedFunction =
2160 QueryingAA.getIRPosition().getAssociatedFunction();
2161 if (!AssociatedFunction)
2162 return false;
2163
2164 const IRPosition &QueryIRP = IRPosition::function(F: *AssociatedFunction);
2165 const auto *LivenessAA =
2166 getAAFor<AAIsDead>(QueryingAA, IRP: QueryIRP, DepClass: DepClassTy::NONE);
2167
2168 for (Instruction *I :
2169 InfoCache.getReadOrWriteInstsForFunction(F: *AssociatedFunction)) {
2170 // Skip dead instructions.
2171 if (isAssumedDead(IRP: IRPosition::inst(I: *I), QueryingAA: &QueryingAA, FnLivenessAA: LivenessAA,
2172 UsedAssumedInformation))
2173 continue;
2174
2175 if (!Pred(*I))
2176 return false;
2177 }
2178
2179 return true;
2180}
2181
2182void Attributor::runTillFixpoint() {
2183 TimeTraceScope TimeScope("Attributor::runTillFixpoint");
2184 LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized "
2185 << DG.SyntheticRoot.Deps.size()
2186 << " abstract attributes.\n");
2187
2188 // Now that all abstract attributes are collected and initialized we start
2189 // the abstract analysis.
2190
2191 unsigned IterationCounter = 1;
2192 unsigned MaxIterations =
2193 Configuration.MaxFixpointIterations.value_or(u&: SetFixpointIterations);
2194
2195 SmallVector<AbstractAttribute *, 32> ChangedAAs;
2196 SetVector<AbstractAttribute *> Worklist, InvalidAAs;
2197 Worklist.insert_range(R&: DG.SyntheticRoot);
2198
2199 do {
2200 // Remember the size to determine new attributes.
2201 size_t NumAAs = DG.SyntheticRoot.Deps.size();
2202 LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter
2203 << ", Worklist size: " << Worklist.size() << "\n");
2204
2205 // For invalid AAs we can fix dependent AAs that have a required dependence,
2206 // thereby folding long dependence chains in a single step without the need
2207 // to run updates.
2208 for (unsigned u = 0; u < InvalidAAs.size(); ++u) {
2209 AbstractAttribute *InvalidAA = InvalidAAs[u];
2210
2211 // Check the dependences to fast track invalidation.
2212 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
2213 dbgs() << "[Attributor] InvalidAA: " << *InvalidAA
2214 << " has " << InvalidAA->Deps.size()
2215 << " required & optional dependences\n");
2216 for (auto &DepIt : InvalidAA->Deps) {
2217 AbstractAttribute *DepAA = cast<AbstractAttribute>(Val: DepIt.getPointer());
2218 if (DepIt.getInt() == unsigned(DepClassTy::OPTIONAL)) {
2219 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE,
2220 dbgs() << " - recompute: " << *DepAA);
2221 Worklist.insert(X: DepAA);
2222 continue;
2223 }
2224 DEBUG_WITH_TYPE(VERBOSE_DEBUG_TYPE, dbgs()
2225 << " - invalidate: " << *DepAA);
2226 DepAA->getState().indicatePessimisticFixpoint();
2227 assert(DepAA->getState().isAtFixpoint() && "Expected fixpoint state!");
2228 if (!DepAA->getState().isValidState())
2229 InvalidAAs.insert(X: DepAA);
2230 else
2231 ChangedAAs.push_back(Elt: DepAA);
2232 }
2233 InvalidAA->Deps.clear();
2234 }
2235
2236 // Add all abstract attributes that are potentially dependent on one that
2237 // changed to the work list.
2238 for (AbstractAttribute *ChangedAA : ChangedAAs) {
2239 for (auto &DepIt : ChangedAA->Deps)
2240 Worklist.insert(X: cast<AbstractAttribute>(Val: DepIt.getPointer()));
2241 ChangedAA->Deps.clear();
2242 }
2243
2244 LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter
2245 << ", Worklist+Dependent size: " << Worklist.size()
2246 << "\n");
2247
2248 // Reset the changed and invalid set.
2249 ChangedAAs.clear();
2250 InvalidAAs.clear();
2251
2252 // Update all abstract attribute in the work list and record the ones that
2253 // changed.
2254 for (AbstractAttribute *AA : Worklist) {
2255 const auto &AAState = AA->getState();
2256 if (!AAState.isAtFixpoint())
2257 if (updateAA(AA&: *AA) == ChangeStatus::CHANGED)
2258 ChangedAAs.push_back(Elt: AA);
2259
2260 // Use the InvalidAAs vector to propagate invalid states fast transitively
2261 // without requiring updates.
2262 if (!AAState.isValidState())
2263 InvalidAAs.insert(X: AA);
2264 }
2265
2266 // Add attributes to the changed set if they have been created in the last
2267 // iteration.
2268 ChangedAAs.append(in_start: DG.SyntheticRoot.begin() + NumAAs,
2269 in_end: DG.SyntheticRoot.end());
2270
2271 // Reset the work list and repopulate with the changed abstract attributes.
2272 // Note that dependent ones are added above.
2273 Worklist.clear();
2274 Worklist.insert_range(R&: ChangedAAs);
2275 Worklist.insert_range(R&: QueryAAsAwaitingUpdate);
2276 QueryAAsAwaitingUpdate.clear();
2277
2278 } while (!Worklist.empty() && (IterationCounter++ < MaxIterations));
2279
2280 if (IterationCounter > MaxIterations && !Functions.empty()) {
2281 auto Remark = [&](OptimizationRemarkMissed ORM) {
2282 return ORM << "Attributor did not reach a fixpoint after "
2283 << ore::NV("Iterations", MaxIterations) << " iterations.";
2284 };
2285 Function *F = Functions.front();
2286 emitRemark<OptimizationRemarkMissed>(F, RemarkName: "FixedPoint", RemarkCB&: Remark);
2287 }
2288
2289 LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: "
2290 << IterationCounter << "/" << MaxIterations
2291 << " iterations\n");
2292
2293 // Reset abstract arguments not settled in a sound fixpoint by now. This
2294 // happens when we stopped the fixpoint iteration early. Note that only the
2295 // ones marked as "changed" *and* the ones transitively depending on them
2296 // need to be reverted to a pessimistic state. Others might not be in a
2297 // fixpoint state but we can use the optimistic results for them anyway.
2298 SmallPtrSet<AbstractAttribute *, 32> Visited;
2299 for (unsigned u = 0; u < ChangedAAs.size(); u++) {
2300 AbstractAttribute *ChangedAA = ChangedAAs[u];
2301 if (!Visited.insert(Ptr: ChangedAA).second)
2302 continue;
2303
2304 AbstractState &State = ChangedAA->getState();
2305 if (!State.isAtFixpoint()) {
2306 State.indicatePessimisticFixpoint();
2307
2308 NumAttributesTimedOut++;
2309 }
2310
2311 for (auto &DepIt : ChangedAA->Deps)
2312 ChangedAAs.push_back(Elt: cast<AbstractAttribute>(Val: DepIt.getPointer()));
2313 ChangedAA->Deps.clear();
2314 }
2315
2316 LLVM_DEBUG({
2317 if (!Visited.empty())
2318 dbgs() << "\n[Attributor] Finalized " << Visited.size()
2319 << " abstract attributes.\n";
2320 });
2321}
2322
2323void Attributor::registerForUpdate(AbstractAttribute &AA) {
2324 assert(AA.isQueryAA() &&
2325 "Non-query AAs should not be required to register for updates!");
2326 QueryAAsAwaitingUpdate.insert(X: &AA);
2327}
2328
2329ChangeStatus Attributor::manifestAttributes() {
2330 TimeTraceScope TimeScope("Attributor::manifestAttributes");
2331 size_t NumFinalAAs = DG.SyntheticRoot.Deps.size();
2332
2333 unsigned NumManifested = 0;
2334 unsigned NumAtFixpoint = 0;
2335 ChangeStatus ManifestChange = ChangeStatus::UNCHANGED;
2336 for (auto &DepAA : DG.SyntheticRoot.Deps) {
2337 AbstractAttribute *AA = cast<AbstractAttribute>(Val: DepAA.getPointer());
2338 AbstractState &State = AA->getState();
2339
2340 // If there is not already a fixpoint reached, we can now take the
2341 // optimistic state. This is correct because we enforced a pessimistic one
2342 // on abstract attributes that were transitively dependent on a changed one
2343 // already above.
2344 if (!State.isAtFixpoint())
2345 State.indicateOptimisticFixpoint();
2346
2347 // We must not manifest Attributes that use Callbase info.
2348 if (AA->hasCallBaseContext())
2349 continue;
2350 // If the state is invalid, we do not try to manifest it.
2351 if (!State.isValidState())
2352 continue;
2353
2354 if (AA->getCtxI() && !isRunOn(Fn&: *AA->getAnchorScope()))
2355 continue;
2356
2357 // Skip dead code.
2358 bool UsedAssumedInformation = false;
2359 if (isAssumedDead(AA: *AA, FnLivenessAA: nullptr, UsedAssumedInformation,
2360 /* CheckBBLivenessOnly */ true))
2361 continue;
2362 // Check if the manifest debug counter that allows skipping manifestation of
2363 // AAs
2364 if (!DebugCounter::shouldExecute(Counter&: ManifestDBGCounter))
2365 continue;
2366 // Manifest the state and record if we changed the IR.
2367 ChangeStatus LocalChange = AA->manifest(A&: *this);
2368 if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled())
2369 AA->trackStatistics();
2370 LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA
2371 << "\n");
2372
2373 ManifestChange = ManifestChange | LocalChange;
2374
2375 NumAtFixpoint++;
2376 NumManifested += (LocalChange == ChangeStatus::CHANGED);
2377 }
2378
2379 (void)NumManifested;
2380 (void)NumAtFixpoint;
2381 LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested
2382 << " arguments while " << NumAtFixpoint
2383 << " were in a valid fixpoint state\n");
2384
2385 NumAttributesManifested += NumManifested;
2386 NumAttributesValidFixpoint += NumAtFixpoint;
2387
2388 (void)NumFinalAAs;
2389 if (NumFinalAAs != DG.SyntheticRoot.Deps.size()) {
2390 auto DepIt = DG.SyntheticRoot.Deps.begin();
2391 for (unsigned u = 0; u < NumFinalAAs; ++u)
2392 ++DepIt;
2393 for (unsigned u = NumFinalAAs; u < DG.SyntheticRoot.Deps.size();
2394 ++u, ++DepIt) {
2395 errs() << "Unexpected abstract attribute: "
2396 << cast<AbstractAttribute>(Val: DepIt->getPointer()) << " :: "
2397 << cast<AbstractAttribute>(Val: DepIt->getPointer())
2398 ->getIRPosition()
2399 .getAssociatedValue()
2400 << "\n";
2401 }
2402 llvm_unreachable("Expected the final number of abstract attributes to "
2403 "remain unchanged!");
2404 }
2405
2406 for (auto &It : AttrsMap) {
2407 AttributeList &AL = It.getSecond();
2408 const IRPosition &IRP =
2409 isa<Function>(Val: It.getFirst())
2410 ? IRPosition::function(F: *cast<Function>(Val: It.getFirst()))
2411 : IRPosition::callsite_function(CB: *cast<CallBase>(Val: It.getFirst()));
2412 IRP.setAttrList(AL);
2413 }
2414
2415 return ManifestChange;
2416}
2417
2418void Attributor::identifyDeadInternalFunctions() {
2419 // Early exit if we don't intend to delete functions.
2420 if (!Configuration.DeleteFns)
2421 return;
2422
2423 // To avoid triggering an assertion in the lazy call graph we will not delete
2424 // any internal library functions. We should modify the assertion though and
2425 // allow internals to be deleted.
2426 const auto *TLI =
2427 isModulePass()
2428 ? nullptr
2429 : getInfoCache().getTargetLibraryInfoForFunction(F: *Functions.back());
2430 LibFunc LF;
2431
2432 // Identify dead internal functions and delete them. This happens outside
2433 // the other fixpoint analysis as we might treat potentially dead functions
2434 // as live to lower the number of iterations. If they happen to be dead, the
2435 // below fixpoint loop will identify and eliminate them.
2436
2437 SmallVector<Function *, 8> InternalFns;
2438 for (Function *F : Functions)
2439 if (F->hasLocalLinkage() && (isModulePass() || !TLI->getLibFunc(FDecl: *F, F&: LF)))
2440 InternalFns.push_back(Elt: F);
2441
2442 SmallPtrSet<Function *, 8> LiveInternalFns;
2443 bool FoundLiveInternal = true;
2444 while (FoundLiveInternal) {
2445 FoundLiveInternal = false;
2446 for (Function *&F : InternalFns) {
2447 if (!F)
2448 continue;
2449
2450 bool UsedAssumedInformation = false;
2451 if (checkForAllCallSites(
2452 Pred: [&](AbstractCallSite ACS) {
2453 Function *Callee = ACS.getInstruction()->getFunction();
2454 return ToBeDeletedFunctions.count(key: Callee) ||
2455 (Functions.count(key: Callee) && Callee->hasLocalLinkage() &&
2456 !LiveInternalFns.count(Ptr: Callee));
2457 },
2458 Fn: *F, RequireAllCallSites: true, QueryingAA: nullptr, UsedAssumedInformation)) {
2459 continue;
2460 }
2461
2462 LiveInternalFns.insert(Ptr: F);
2463 F = nullptr;
2464 FoundLiveInternal = true;
2465 }
2466 }
2467
2468 for (Function *F : InternalFns)
2469 if (F)
2470 ToBeDeletedFunctions.insert(X: F);
2471}
2472
2473ChangeStatus Attributor::cleanupIR() {
2474 TimeTraceScope TimeScope("Attributor::cleanupIR");
2475 // Delete stuff at the end to avoid invalid references and a nice order.
2476 LLVM_DEBUG(dbgs() << "\n[Attributor] Delete/replace at least "
2477 << ToBeDeletedFunctions.size() << " functions and "
2478 << ToBeDeletedBlocks.size() << " blocks and "
2479 << ToBeDeletedInsts.size() << " instructions and "
2480 << ToBeChangedValues.size() << " values and "
2481 << ToBeChangedUses.size() << " uses. To insert "
2482 << ToBeChangedToUnreachableInsts.size()
2483 << " unreachables.\n"
2484 << "Preserve manifest added " << ManifestAddedBlocks.size()
2485 << " blocks\n");
2486
2487 SmallVector<WeakTrackingVH, 32> DeadInsts;
2488 SmallVector<Instruction *, 32> TerminatorsToFold;
2489
2490 auto ReplaceUse = [&](Use *U, Value *NewV) {
2491 Value *OldV = U->get();
2492
2493 // If we plan to replace NewV we need to update it at this point.
2494 do {
2495 const auto &Entry = ToBeChangedValues.lookup(Key: NewV);
2496 if (!get<0>(Pair: Entry))
2497 break;
2498 NewV = get<0>(Pair: Entry);
2499 } while (true);
2500
2501 Instruction *I = dyn_cast<Instruction>(Val: U->getUser());
2502 assert((!I || isRunOn(*I->getFunction())) &&
2503 "Cannot replace an instruction outside the current SCC!");
2504
2505 // Do not replace uses in returns if the value is a must-tail call we will
2506 // not delete.
2507 if (auto *RI = dyn_cast_or_null<ReturnInst>(Val: I)) {
2508 if (auto *CI = dyn_cast<CallInst>(Val: OldV->stripPointerCasts()))
2509 if (CI->isMustTailCall() && !ToBeDeletedInsts.count(key: CI))
2510 return;
2511 // If we rewrite a return and the new value is not an argument, strip the
2512 // `returned` attribute as it is wrong now.
2513 if (!isa<Argument>(Val: NewV))
2514 for (auto &Arg : RI->getFunction()->args())
2515 Arg.removeAttr(Kind: Attribute::Returned);
2516 }
2517
2518 LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser()
2519 << " instead of " << *OldV << "\n");
2520 U->set(NewV);
2521
2522 if (Instruction *I = dyn_cast<Instruction>(Val: OldV)) {
2523 CGModifiedFunctions.insert(X: I->getFunction());
2524 if (!isa<PHINode>(Val: I) && !ToBeDeletedInsts.count(key: I) &&
2525 isInstructionTriviallyDead(I))
2526 DeadInsts.push_back(Elt: I);
2527 }
2528 if (isa<UndefValue>(Val: NewV) && isa<CallBase>(Val: U->getUser())) {
2529 auto *CB = cast<CallBase>(Val: U->getUser());
2530 if (CB->isArgOperand(U)) {
2531 unsigned Idx = CB->getArgOperandNo(U);
2532 CB->removeParamAttr(ArgNo: Idx, Kind: Attribute::NoUndef);
2533 auto *Callee = dyn_cast_if_present<Function>(Val: CB->getCalledOperand());
2534 if (Callee && Callee->arg_size() > Idx)
2535 Callee->removeParamAttr(ArgNo: Idx, Kind: Attribute::NoUndef);
2536 }
2537 }
2538 if (isa<Constant>(Val: NewV) && isa<CondBrInst>(Val: U->getUser())) {
2539 Instruction *UserI = cast<Instruction>(Val: U->getUser());
2540 if (isa<UndefValue>(Val: NewV)) {
2541 ToBeChangedToUnreachableInsts.insert(X: UserI);
2542 } else {
2543 TerminatorsToFold.push_back(Elt: UserI);
2544 }
2545 }
2546 };
2547
2548 for (auto &It : ToBeChangedUses) {
2549 Use *U = It.first;
2550 Value *NewV = It.second;
2551 ReplaceUse(U, NewV);
2552 }
2553
2554 SmallVector<Use *, 4> Uses;
2555 for (auto &It : ToBeChangedValues) {
2556 Value *OldV = It.first;
2557 auto [NewV, Done] = It.second;
2558 Uses.clear();
2559 for (auto &U : OldV->uses())
2560 if (Done || !U.getUser()->isDroppable())
2561 Uses.push_back(Elt: &U);
2562 for (Use *U : Uses) {
2563 if (auto *I = dyn_cast<Instruction>(Val: U->getUser()))
2564 if (!isRunOn(Fn&: *I->getFunction()))
2565 continue;
2566 ReplaceUse(U, NewV);
2567 }
2568 }
2569
2570 for (const auto &V : InvokeWithDeadSuccessor)
2571 if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(Val: V)) {
2572 assert(isRunOn(*II->getFunction()) &&
2573 "Cannot replace an invoke outside the current SCC!");
2574 bool UnwindBBIsDead = II->hasFnAttr(Kind: Attribute::NoUnwind);
2575 bool NormalBBIsDead = II->hasFnAttr(Kind: Attribute::NoReturn);
2576 bool Invoke2CallAllowed =
2577 !AAIsDead::mayCatchAsynchronousExceptions(F: *II->getFunction());
2578 assert((UnwindBBIsDead || NormalBBIsDead) &&
2579 "Invoke does not have dead successors!");
2580 BasicBlock *BB = II->getParent();
2581 BasicBlock *NormalDestBB = II->getNormalDest();
2582 if (UnwindBBIsDead) {
2583 Instruction *NormalNextIP = &NormalDestBB->front();
2584 if (Invoke2CallAllowed) {
2585 changeToCall(II);
2586 NormalNextIP = BB->getTerminator();
2587 }
2588 if (NormalBBIsDead)
2589 ToBeChangedToUnreachableInsts.insert(X: NormalNextIP);
2590 } else {
2591 assert(NormalBBIsDead && "Broken invariant!");
2592 if (!NormalDestBB->getUniquePredecessor())
2593 NormalDestBB = SplitBlockPredecessors(BB: NormalDestBB, Preds: {BB}, Suffix: ".dead");
2594 ToBeChangedToUnreachableInsts.insert(X: &NormalDestBB->front());
2595 }
2596 }
2597 for (Instruction *I : TerminatorsToFold) {
2598 assert(isRunOn(*I->getFunction()) &&
2599 "Cannot replace a terminator outside the current SCC!");
2600 CGModifiedFunctions.insert(X: I->getFunction());
2601 ConstantFoldTerminator(BB: I->getParent());
2602 }
2603 for (const auto &V : ToBeChangedToUnreachableInsts)
2604 if (Instruction *I = dyn_cast_or_null<Instruction>(Val: V)) {
2605 LLVM_DEBUG(dbgs() << "[Attributor] Change to unreachable: " << *I
2606 << "\n");
2607 assert(isRunOn(*I->getFunction()) &&
2608 "Cannot replace an instruction outside the current SCC!");
2609 CGModifiedFunctions.insert(X: I->getFunction());
2610 changeToUnreachable(I);
2611 }
2612
2613 for (const auto &V : ToBeDeletedInsts) {
2614 if (Instruction *I = dyn_cast_or_null<Instruction>(Val: V)) {
2615 assert((!isa<CallBase>(I) || isa<IntrinsicInst>(I) ||
2616 isRunOn(*I->getFunction())) &&
2617 "Cannot delete an instruction outside the current SCC!");
2618 I->dropDroppableUses();
2619 CGModifiedFunctions.insert(X: I->getFunction());
2620 if (!I->getType()->isVoidTy())
2621 I->replaceAllUsesWith(V: UndefValue::get(T: I->getType()));
2622 if (!isa<PHINode>(Val: I) && isInstructionTriviallyDead(I))
2623 DeadInsts.push_back(Elt: I);
2624 else
2625 I->eraseFromParent();
2626 }
2627 }
2628
2629 llvm::erase_if(C&: DeadInsts, P: [&](WeakTrackingVH I) { return !I; });
2630
2631 LLVM_DEBUG({
2632 dbgs() << "[Attributor] DeadInsts size: " << DeadInsts.size() << "\n";
2633 for (auto &I : DeadInsts)
2634 if (I)
2635 dbgs() << " - " << *I << "\n";
2636 });
2637
2638 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts);
2639
2640 if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) {
2641 SmallVector<BasicBlock *, 8> ToBeDeletedBBs;
2642 ToBeDeletedBBs.reserve(N: NumDeadBlocks);
2643 for (BasicBlock *BB : ToBeDeletedBlocks) {
2644 assert(isRunOn(*BB->getParent()) &&
2645 "Cannot delete a block outside the current SCC!");
2646 CGModifiedFunctions.insert(X: BB->getParent());
2647 // Do not delete BBs added during manifests of AAs.
2648 if (ManifestAddedBlocks.contains(Ptr: BB))
2649 continue;
2650 ToBeDeletedBBs.push_back(Elt: BB);
2651 }
2652 // Actually we do not delete the blocks but squash them into a single
2653 // unreachable but untangling branches that jump here is something we need
2654 // to do in a more generic way.
2655 detachDeadBlocks(BBs: ToBeDeletedBBs, Updates: nullptr);
2656 }
2657
2658 identifyDeadInternalFunctions();
2659
2660 // Rewrite the functions as requested during manifest.
2661 ChangeStatus ManifestChange = rewriteFunctionSignatures(ModifiedFns&: CGModifiedFunctions);
2662
2663 for (Function *Fn : CGModifiedFunctions)
2664 if (!ToBeDeletedFunctions.count(key: Fn) && Functions.count(key: Fn))
2665 Configuration.CGUpdater.reanalyzeFunction(Fn&: *Fn);
2666
2667 for (Function *Fn : ToBeDeletedFunctions) {
2668 if (!Functions.count(key: Fn))
2669 continue;
2670 Configuration.CGUpdater.removeFunction(Fn&: *Fn);
2671 }
2672
2673 if (!ToBeChangedUses.empty())
2674 ManifestChange = ChangeStatus::CHANGED;
2675
2676 if (!ToBeChangedToUnreachableInsts.empty())
2677 ManifestChange = ChangeStatus::CHANGED;
2678
2679 if (!ToBeDeletedFunctions.empty())
2680 ManifestChange = ChangeStatus::CHANGED;
2681
2682 if (!ToBeDeletedBlocks.empty())
2683 ManifestChange = ChangeStatus::CHANGED;
2684
2685 if (!ToBeDeletedInsts.empty())
2686 ManifestChange = ChangeStatus::CHANGED;
2687
2688 if (!InvokeWithDeadSuccessor.empty())
2689 ManifestChange = ChangeStatus::CHANGED;
2690
2691 if (!DeadInsts.empty())
2692 ManifestChange = ChangeStatus::CHANGED;
2693
2694 NumFnDeleted += ToBeDeletedFunctions.size();
2695
2696 LLVM_DEBUG(dbgs() << "[Attributor] Deleted " << ToBeDeletedFunctions.size()
2697 << " functions after manifest.\n");
2698
2699#ifdef EXPENSIVE_CHECKS
2700 for (Function *F : Functions) {
2701 if (ToBeDeletedFunctions.count(F))
2702 continue;
2703 assert(!verifyFunction(*F, &errs()) && "Module verification failed!");
2704 }
2705#endif
2706
2707 return ManifestChange;
2708}
2709
2710ChangeStatus Attributor::run() {
2711 TimeTraceScope TimeScope("Attributor::run");
2712 AttributorCallGraph ACallGraph(*this);
2713
2714 if (PrintCallGraph)
2715 ACallGraph.populateAll();
2716
2717 Phase = AttributorPhase::UPDATE;
2718 runTillFixpoint();
2719
2720 // dump graphs on demand
2721 if (DumpDepGraph)
2722 DG.dumpGraph();
2723
2724 if (ViewDepGraph)
2725 DG.viewGraph();
2726
2727 if (PrintDependencies)
2728 DG.print();
2729
2730 Phase = AttributorPhase::MANIFEST;
2731 ChangeStatus ManifestChange = manifestAttributes();
2732
2733 Phase = AttributorPhase::CLEANUP;
2734 ChangeStatus CleanupChange = cleanupIR();
2735
2736 if (PrintCallGraph)
2737 ACallGraph.print();
2738
2739 return ManifestChange | CleanupChange;
2740}
2741
2742ChangeStatus Attributor::updateAA(AbstractAttribute &AA) {
2743 TimeTraceScope TimeScope("updateAA", [&]() {
2744 return AA.getName().str() +
2745 std::to_string(val: AA.getIRPosition().getPositionKind());
2746 });
2747 assert(Phase == AttributorPhase::UPDATE &&
2748 "We can update AA only in the update stage!");
2749
2750 // Use a new dependence vector for this update.
2751 DependenceVector DV;
2752 DependenceStack.push_back(Elt: &DV);
2753
2754 auto &AAState = AA.getState();
2755 ChangeStatus CS = ChangeStatus::UNCHANGED;
2756 bool UsedAssumedInformation = false;
2757 if (!isAssumedDead(AA, FnLivenessAA: nullptr, UsedAssumedInformation,
2758 /* CheckBBLivenessOnly */ true))
2759 CS = AA.update(A&: *this);
2760
2761 if (!AA.isQueryAA() && DV.empty() && !AA.getState().isAtFixpoint()) {
2762 // If the AA did not rely on outside information but changed, we run it
2763 // again to see if it found a fixpoint. Most AAs do but we don't require
2764 // them to. Hence, it might take the AA multiple iterations to get to a
2765 // fixpoint even if it does not rely on outside information, which is fine.
2766 ChangeStatus RerunCS = ChangeStatus::UNCHANGED;
2767 if (CS == ChangeStatus::CHANGED)
2768 RerunCS = AA.update(A&: *this);
2769
2770 // If the attribute did not change during the run or rerun, and it still did
2771 // not query any non-fix information, the state will not change and we can
2772 // indicate that right at this point.
2773 if (RerunCS == ChangeStatus::UNCHANGED && !AA.isQueryAA() && DV.empty())
2774 AAState.indicateOptimisticFixpoint();
2775 }
2776
2777 if (!AAState.isAtFixpoint())
2778 rememberDependences();
2779
2780 // Verify the stack was used properly, that is we pop the dependence vector we
2781 // put there earlier.
2782 DependenceVector *PoppedDV = DependenceStack.pop_back_val();
2783 (void)PoppedDV;
2784 assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!");
2785
2786 return CS;
2787}
2788
2789void Attributor::createShallowWrapper(Function &F) {
2790 assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!");
2791
2792 Module &M = *F.getParent();
2793 LLVMContext &Ctx = M.getContext();
2794 FunctionType *FnTy = F.getFunctionType();
2795
2796 Function *Wrapper =
2797 Function::Create(Ty: FnTy, Linkage: F.getLinkage(), AddrSpace: F.getAddressSpace(), N: F.getName());
2798 F.setName(""); // set the inside function anonymous
2799 M.getFunctionList().insert(where: F.getIterator(), New: Wrapper);
2800
2801 F.setLinkage(GlobalValue::InternalLinkage);
2802
2803 F.replaceAllUsesWith(V: Wrapper);
2804 assert(F.use_empty() && "Uses remained after wrapper was created!");
2805
2806 // Move the COMDAT section to the wrapper.
2807 // TODO: Check if we need to keep it for F as well.
2808 Wrapper->setComdat(F.getComdat());
2809 F.setComdat(nullptr);
2810
2811 // Copy all metadata and attributes but keep them on F as well.
2812 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
2813 F.getAllMetadata(MDs);
2814 for (auto MDIt : MDs)
2815 Wrapper->addMetadata(KindID: MDIt.first, MD&: *MDIt.second);
2816 Wrapper->setAttributes(F.getAttributes());
2817
2818 // Create the call in the wrapper.
2819 BasicBlock *EntryBB = BasicBlock::Create(Context&: Ctx, Name: "entry", Parent: Wrapper);
2820
2821 SmallVector<Value *, 8> Args;
2822 Argument *FArgIt = F.arg_begin();
2823 for (Argument &Arg : Wrapper->args()) {
2824 Args.push_back(Elt: &Arg);
2825 Arg.setName((FArgIt++)->getName());
2826 }
2827
2828 CallInst *CI = CallInst::Create(Func: &F, Args, NameStr: "", InsertBefore: EntryBB);
2829 CI->setTailCall(true);
2830 CI->addFnAttr(Kind: Attribute::NoInline);
2831 ReturnInst::Create(C&: Ctx, retVal: CI->getType()->isVoidTy() ? nullptr : CI, InsertBefore: EntryBB);
2832
2833 NumFnShallowWrappersCreated++;
2834}
2835
2836bool Attributor::isInternalizable(Function &F) {
2837 if (F.isDeclaration() || F.hasLocalLinkage() ||
2838 GlobalValue::isInterposableLinkage(Linkage: F.getLinkage()))
2839 return false;
2840 return true;
2841}
2842
2843Function *Attributor::internalizeFunction(Function &F, bool Force) {
2844 if (!AllowDeepWrapper && !Force)
2845 return nullptr;
2846 if (!isInternalizable(F))
2847 return nullptr;
2848
2849 SmallPtrSet<Function *, 2> FnSet = {&F};
2850 DenseMap<Function *, Function *> InternalizedFns;
2851 internalizeFunctions(FnSet, FnMap&: InternalizedFns);
2852
2853 return InternalizedFns[&F];
2854}
2855
2856bool Attributor::internalizeFunctions(SmallPtrSetImpl<Function *> &FnSet,
2857 DenseMap<Function *, Function *> &FnMap) {
2858 for (Function *F : FnSet)
2859 if (!Attributor::isInternalizable(F&: *F))
2860 return false;
2861
2862 FnMap.clear();
2863 // Generate the internalized version of each function.
2864 for (Function *F : FnSet) {
2865 Module &M = *F->getParent();
2866 FunctionType *FnTy = F->getFunctionType();
2867
2868 // Create a copy of the current function
2869 Function *Copied =
2870 Function::Create(Ty: FnTy, Linkage: F->getLinkage(), AddrSpace: F->getAddressSpace(),
2871 N: F->getName() + ".internalized");
2872 ValueToValueMapTy VMap;
2873 auto *NewFArgIt = Copied->arg_begin();
2874 for (auto &Arg : F->args()) {
2875 auto ArgName = Arg.getName();
2876 NewFArgIt->setName(ArgName);
2877 VMap[&Arg] = &(*NewFArgIt++);
2878 }
2879 SmallVector<ReturnInst *, 8> Returns;
2880
2881 // Copy the body of the original function to the new one
2882 CloneFunctionInto(NewFunc: Copied, OldFunc: F, VMap,
2883 Changes: CloneFunctionChangeType::LocalChangesOnly, Returns);
2884
2885 // Set the linakage and visibility late as CloneFunctionInto has some
2886 // implicit requirements.
2887 Copied->setVisibility(GlobalValue::DefaultVisibility);
2888 Copied->setLinkage(GlobalValue::PrivateLinkage);
2889
2890 // Copy metadata
2891 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
2892 F->getAllMetadata(MDs);
2893 for (auto MDIt : MDs)
2894 if (!Copied->hasMetadata())
2895 Copied->addMetadata(KindID: MDIt.first, MD&: *MDIt.second);
2896
2897 M.getFunctionList().insert(where: F->getIterator(), New: Copied);
2898 Copied->setDSOLocal(true);
2899 FnMap[F] = Copied;
2900 }
2901
2902 // Replace all uses of the old function with the new internalized function
2903 // unless the caller is a function that was just internalized.
2904 for (Function *F : FnSet) {
2905 auto &InternalizedFn = FnMap[F];
2906 auto IsNotInternalized = [&](Use &U) -> bool {
2907 if (auto *CB = dyn_cast<CallBase>(Val: U.getUser()))
2908 return !FnMap.lookup(Val: CB->getCaller());
2909 return false;
2910 };
2911 F->replaceUsesWithIf(New: InternalizedFn, ShouldReplace: IsNotInternalized);
2912 }
2913
2914 return true;
2915}
2916
2917bool Attributor::isValidFunctionSignatureRewrite(
2918 Argument &Arg, ArrayRef<Type *> ReplacementTypes) {
2919
2920 if (!Configuration.RewriteSignatures)
2921 return false;
2922
2923 Function *Fn = Arg.getParent();
2924 auto CallSiteCanBeChanged = [Fn](AbstractCallSite ACS) {
2925 // Forbid the call site to cast the function return type. If we need to
2926 // rewrite these functions we need to re-create a cast for the new call site
2927 // (if the old had uses).
2928 if (!ACS.getCalledFunction() ||
2929 ACS.getInstruction()->getType() !=
2930 ACS.getCalledFunction()->getReturnType())
2931 return false;
2932 if (cast<CallBase>(Val: ACS.getInstruction())->getCalledOperand()->getType() !=
2933 Fn->getType())
2934 return false;
2935 if (ACS.getNumArgOperands() != Fn->arg_size())
2936 return false;
2937 // Forbid must-tail calls for now.
2938 return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall();
2939 };
2940
2941 // Avoid var-arg functions for now.
2942 if (Fn->isVarArg()) {
2943 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n");
2944 return false;
2945 }
2946
2947 // Avoid functions with complicated argument passing semantics.
2948 AttributeList FnAttributeList = Fn->getAttributes();
2949 if (FnAttributeList.hasAttrSomewhere(Kind: Attribute::Nest) ||
2950 FnAttributeList.hasAttrSomewhere(Kind: Attribute::StructRet) ||
2951 FnAttributeList.hasAttrSomewhere(Kind: Attribute::InAlloca) ||
2952 FnAttributeList.hasAttrSomewhere(Kind: Attribute::Preallocated)) {
2953 LLVM_DEBUG(
2954 dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n");
2955 return false;
2956 }
2957
2958 // Avoid callbacks for now.
2959 bool UsedAssumedInformation = false;
2960 if (!checkForAllCallSites(Pred: CallSiteCanBeChanged, Fn: *Fn, RequireAllCallSites: true, QueryingAA: nullptr,
2961 UsedAssumedInformation,
2962 /* CheckPotentiallyDead */ true)) {
2963 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n");
2964 return false;
2965 }
2966
2967 auto InstPred = [](Instruction &I) {
2968 if (auto *CI = dyn_cast<CallInst>(Val: &I))
2969 return !CI->isMustTailCall();
2970 return true;
2971 };
2972
2973 // Forbid must-tail calls for now.
2974 // TODO:
2975 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F: *Fn);
2976 if (!checkForAllInstructionsImpl(A: nullptr, OpcodeInstMap, Pred: InstPred, QueryingAA: nullptr,
2977 LivenessAA: nullptr, Opcodes: {Instruction::Call},
2978 UsedAssumedInformation)) {
2979 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n");
2980 return false;
2981 }
2982
2983 return true;
2984}
2985
2986bool Attributor::registerFunctionSignatureRewrite(
2987 Argument &Arg, ArrayRef<Type *> ReplacementTypes,
2988 ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB,
2989 ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB) {
2990 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
2991 << Arg.getParent()->getName() << " with "
2992 << ReplacementTypes.size() << " replacements\n");
2993 assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) &&
2994 "Cannot register an invalid rewrite");
2995
2996 Function *Fn = Arg.getParent();
2997 SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
2998 ArgumentReplacementMap[Fn];
2999 if (ARIs.empty())
3000 ARIs.resize(N: Fn->arg_size());
3001
3002 // If we have a replacement already with less than or equal new arguments,
3003 // ignore this request.
3004 std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()];
3005 if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) {
3006 LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n");
3007 return false;
3008 }
3009
3010 // If we have a replacement already but we like the new one better, delete
3011 // the old.
3012 ARI.reset();
3013
3014 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in "
3015 << Arg.getParent()->getName() << " with "
3016 << ReplacementTypes.size() << " replacements\n");
3017
3018 // Remember the replacement.
3019 ARI.reset(p: new ArgumentReplacementInfo(*this, Arg, ReplacementTypes,
3020 std::move(CalleeRepairCB),
3021 std::move(ACSRepairCB)));
3022
3023 return true;
3024}
3025
3026bool Attributor::shouldSeedAttribute(AbstractAttribute &AA) {
3027 bool Result = true;
3028#ifndef NDEBUG
3029 if (SeedAllowList.size() != 0)
3030 Result = llvm::is_contained(SeedAllowList, AA.getName());
3031 Function *Fn = AA.getAnchorScope();
3032 if (FunctionSeedAllowList.size() != 0 && Fn)
3033 Result &= llvm::is_contained(FunctionSeedAllowList, Fn->getName());
3034#endif
3035 return Result;
3036}
3037
3038ChangeStatus Attributor::rewriteFunctionSignatures(
3039 SmallSetVector<Function *, 8> &ModifiedFns) {
3040 ChangeStatus Changed = ChangeStatus::UNCHANGED;
3041
3042 for (auto &It : ArgumentReplacementMap) {
3043 Function *OldFn = It.getFirst();
3044
3045 // Deleted functions do not require rewrites.
3046 if (!Functions.count(key: OldFn) || ToBeDeletedFunctions.count(key: OldFn))
3047 continue;
3048
3049 const SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs =
3050 It.getSecond();
3051 assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!");
3052
3053 SmallVector<Type *, 16> NewArgumentTypes;
3054 SmallVector<AttributeSet, 16> NewArgumentAttributes;
3055
3056 // Collect replacement argument types and copy over existing attributes.
3057 AttributeList OldFnAttributeList = OldFn->getAttributes();
3058 for (Argument &Arg : OldFn->args()) {
3059 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3060 ARIs[Arg.getArgNo()]) {
3061 NewArgumentTypes.append(in_start: ARI->ReplacementTypes.begin(),
3062 in_end: ARI->ReplacementTypes.end());
3063 NewArgumentAttributes.append(NumInputs: ARI->getNumReplacementArgs(),
3064 Elt: AttributeSet());
3065 } else {
3066 NewArgumentTypes.push_back(Elt: Arg.getType());
3067 NewArgumentAttributes.push_back(
3068 Elt: OldFnAttributeList.getParamAttrs(ArgNo: Arg.getArgNo()));
3069 }
3070 }
3071
3072 uint64_t LargestVectorWidth = 0;
3073 for (auto *I : NewArgumentTypes)
3074 if (auto *VT = dyn_cast<llvm::VectorType>(Val: I))
3075 LargestVectorWidth =
3076 std::max(a: LargestVectorWidth,
3077 b: VT->getPrimitiveSizeInBits().getKnownMinValue());
3078
3079 FunctionType *OldFnTy = OldFn->getFunctionType();
3080 Type *RetTy = OldFnTy->getReturnType();
3081
3082 // Construct the new function type using the new arguments types.
3083 FunctionType *NewFnTy =
3084 FunctionType::get(Result: RetTy, Params: NewArgumentTypes, isVarArg: OldFnTy->isVarArg());
3085
3086 LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName()
3087 << "' from " << *OldFn->getFunctionType() << " to "
3088 << *NewFnTy << "\n");
3089
3090 // Create the new function body and insert it into the module.
3091 Function *NewFn = Function::Create(Ty: NewFnTy, Linkage: OldFn->getLinkage(),
3092 AddrSpace: OldFn->getAddressSpace(), N: "");
3093 Functions.insert(X: NewFn);
3094 OldFn->getParent()->getFunctionList().insert(where: OldFn->getIterator(), New: NewFn);
3095 NewFn->takeName(V: OldFn);
3096 NewFn->copyAttributesFrom(Src: OldFn);
3097
3098 // Patch the pointer to LLVM function in debug info descriptor.
3099 NewFn->setSubprogram(OldFn->getSubprogram());
3100 OldFn->setSubprogram(nullptr);
3101
3102 // Recompute the parameter attributes list based on the new arguments for
3103 // the function.
3104 LLVMContext &Ctx = OldFn->getContext();
3105 NewFn->setAttributes(AttributeList::get(
3106 C&: Ctx, FnAttrs: OldFnAttributeList.getFnAttrs(), RetAttrs: OldFnAttributeList.getRetAttrs(),
3107 ArgAttrs: NewArgumentAttributes));
3108 AttributeFuncs::updateMinLegalVectorWidthAttr(Fn&: *NewFn, Width: LargestVectorWidth);
3109
3110 // Remove argmem from the memory effects if we have no more pointer
3111 // arguments, or they are readnone.
3112 MemoryEffects ME = NewFn->getMemoryEffects();
3113 int ArgNo = -1;
3114 if (ME.doesAccessArgPointees() && all_of(Range&: NewArgumentTypes, P: [&](Type *T) {
3115 ++ArgNo;
3116 return !T->isPtrOrPtrVectorTy() ||
3117 NewFn->hasParamAttribute(ArgNo, Kind: Attribute::ReadNone);
3118 })) {
3119 NewFn->setMemoryEffects(ME - MemoryEffects::argMemOnly());
3120 }
3121
3122 // Since we have now created the new function, splice the body of the old
3123 // function right into the new function, leaving the old rotting hulk of the
3124 // function empty.
3125 NewFn->splice(ToIt: NewFn->begin(), FromF: OldFn);
3126
3127 // Set of all "call-like" instructions that invoke the old function mapped
3128 // to their new replacements.
3129 SmallVector<std::pair<CallBase *, CallBase *>, 8> CallSitePairs;
3130
3131 // Callback to create a new "call-like" instruction for a given one.
3132 auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) {
3133 CallBase *OldCB = cast<CallBase>(Val: ACS.getInstruction());
3134 const AttributeList &OldCallAttributeList = OldCB->getAttributes();
3135
3136 // Collect the new argument operands for the replacement call site.
3137 SmallVector<Value *, 16> NewArgOperands;
3138 SmallVector<AttributeSet, 16> NewArgOperandAttributes;
3139 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) {
3140 unsigned NewFirstArgNum = NewArgOperands.size();
3141 (void)NewFirstArgNum; // only used inside assert.
3142 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3143 ARIs[OldArgNum]) {
3144 if (ARI->ACSRepairCB)
3145 ARI->ACSRepairCB(*ARI, ACS, NewArgOperands);
3146 assert(ARI->getNumReplacementArgs() + NewFirstArgNum ==
3147 NewArgOperands.size() &&
3148 "ACS repair callback did not provide as many operand as new "
3149 "types were registered!");
3150 // TODO: Exose the attribute set to the ACS repair callback
3151 NewArgOperandAttributes.append(NumInputs: ARI->ReplacementTypes.size(),
3152 Elt: AttributeSet());
3153 } else {
3154 NewArgOperands.push_back(Elt: ACS.getCallArgOperand(ArgNo: OldArgNum));
3155 NewArgOperandAttributes.push_back(
3156 Elt: OldCallAttributeList.getParamAttrs(ArgNo: OldArgNum));
3157 }
3158 }
3159
3160 assert(NewArgOperands.size() == NewArgOperandAttributes.size() &&
3161 "Mismatch # argument operands vs. # argument operand attributes!");
3162 assert(NewArgOperands.size() == NewFn->arg_size() &&
3163 "Mismatch # argument operands vs. # function arguments!");
3164
3165 SmallVector<OperandBundleDef, 4> OperandBundleDefs;
3166 OldCB->getOperandBundlesAsDefs(Defs&: OperandBundleDefs);
3167
3168 // Create a new call or invoke instruction to replace the old one.
3169 CallBase *NewCB;
3170 if (InvokeInst *II = dyn_cast<InvokeInst>(Val: OldCB)) {
3171 NewCB = InvokeInst::Create(Func: NewFn, IfNormal: II->getNormalDest(),
3172 IfException: II->getUnwindDest(), Args: NewArgOperands,
3173 Bundles: OperandBundleDefs, NameStr: "", InsertBefore: OldCB->getIterator());
3174 } else {
3175 auto *NewCI = CallInst::Create(Func: NewFn, Args: NewArgOperands, Bundles: OperandBundleDefs,
3176 NameStr: "", InsertBefore: OldCB->getIterator());
3177 NewCI->setTailCallKind(cast<CallInst>(Val: OldCB)->getTailCallKind());
3178 NewCB = NewCI;
3179 }
3180
3181 // Copy over various properties and the new attributes.
3182 NewCB->copyMetadata(SrcInst: *OldCB, WL: {LLVMContext::MD_prof, LLVMContext::MD_dbg});
3183 NewCB->setCallingConv(OldCB->getCallingConv());
3184 NewCB->takeName(V: OldCB);
3185 NewCB->setAttributes(AttributeList::get(
3186 C&: Ctx, FnAttrs: OldCallAttributeList.getFnAttrs(),
3187 RetAttrs: OldCallAttributeList.getRetAttrs(), ArgAttrs: NewArgOperandAttributes));
3188
3189 AttributeFuncs::updateMinLegalVectorWidthAttr(Fn&: *NewCB->getCaller(),
3190 Width: LargestVectorWidth);
3191
3192 CallSitePairs.push_back(Elt: {OldCB, NewCB});
3193 return true;
3194 };
3195
3196 // Use the CallSiteReplacementCreator to create replacement call sites.
3197 bool UsedAssumedInformation = false;
3198 bool Success = checkForAllCallSites(Pred: CallSiteReplacementCreator, Fn: *OldFn,
3199 RequireAllCallSites: true, QueryingAA: nullptr, UsedAssumedInformation,
3200 /* CheckPotentiallyDead */ true);
3201 (void)Success;
3202 assert(Success && "Assumed call site replacement to succeed!");
3203
3204 // Rewire the arguments.
3205 Argument *OldFnArgIt = OldFn->arg_begin();
3206 Argument *NewFnArgIt = NewFn->arg_begin();
3207 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size();
3208 ++OldArgNum, ++OldFnArgIt) {
3209 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI =
3210 ARIs[OldArgNum]) {
3211 if (ARI->CalleeRepairCB)
3212 ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt);
3213 if (ARI->ReplacementTypes.empty())
3214 OldFnArgIt->replaceAllUsesWith(
3215 V: PoisonValue::get(T: OldFnArgIt->getType()));
3216 NewFnArgIt += ARI->ReplacementTypes.size();
3217 } else {
3218 NewFnArgIt->takeName(V: &*OldFnArgIt);
3219 OldFnArgIt->replaceAllUsesWith(V: &*NewFnArgIt);
3220 ++NewFnArgIt;
3221 }
3222 }
3223
3224 // Eliminate the instructions *after* we visited all of them.
3225 for (auto &CallSitePair : CallSitePairs) {
3226 CallBase &OldCB = *CallSitePair.first;
3227 CallBase &NewCB = *CallSitePair.second;
3228 assert(OldCB.getType() == NewCB.getType() &&
3229 "Cannot handle call sites with different types!");
3230 ModifiedFns.insert(X: OldCB.getFunction());
3231 OldCB.replaceAllUsesWith(V: &NewCB);
3232 OldCB.eraseFromParent();
3233 }
3234
3235 // Replace the function in the call graph (if any).
3236 Configuration.CGUpdater.replaceFunctionWith(OldFn&: *OldFn, NewFn&: *NewFn);
3237
3238 // If the old function was modified and needed to be reanalyzed, the new one
3239 // does now.
3240 if (ModifiedFns.remove(X: OldFn))
3241 ModifiedFns.insert(X: NewFn);
3242
3243 Changed = ChangeStatus::CHANGED;
3244 }
3245
3246 return Changed;
3247}
3248
3249void InformationCache::initializeInformationCache(const Function &CF,
3250 FunctionInfo &FI) {
3251 // As we do not modify the function here we can remove the const
3252 // withouth breaking implicit assumptions. At the end of the day, we could
3253 // initialize the cache eagerly which would look the same to the users.
3254 Function &F = const_cast<Function &>(CF);
3255
3256 FI.IsKernel = F.hasFnAttribute(Kind: "kernel");
3257
3258 // Walk all instructions to find interesting instructions that might be
3259 // queried by abstract attributes during their initialization or update.
3260 // This has to happen before we create attributes.
3261
3262 DenseMap<const Value *, std::optional<short>> AssumeUsesMap;
3263
3264 // Add \p V to the assume uses map which track the number of uses outside of
3265 // "visited" assumes. If no outside uses are left the value is added to the
3266 // assume only use vector.
3267 auto AddToAssumeUsesMap = [&](const Value &V) -> void {
3268 SmallVector<const Instruction *> Worklist;
3269 if (auto *I = dyn_cast<Instruction>(Val: &V))
3270 Worklist.push_back(Elt: I);
3271 while (!Worklist.empty()) {
3272 const Instruction *I = Worklist.pop_back_val();
3273 std::optional<short> &NumUses = AssumeUsesMap[I];
3274 if (!NumUses)
3275 NumUses = I->getNumUses();
3276 NumUses = *NumUses - /* this assume */ 1;
3277 if (*NumUses != 0)
3278 continue;
3279 AssumeOnlyValues.insert(X: I);
3280 for (const Value *Op : I->operands())
3281 if (auto *OpI = dyn_cast<Instruction>(Val: Op))
3282 Worklist.push_back(Elt: OpI);
3283 }
3284 };
3285
3286 for (Instruction &I : instructions(F: &F)) {
3287 bool IsInterestingOpcode = false;
3288
3289 // To allow easy access to all instructions in a function with a given
3290 // opcode we store them in the InfoCache. As not all opcodes are interesting
3291 // to concrete attributes we only cache the ones that are as identified in
3292 // the following switch.
3293 // Note: There are no concrete attributes now so this is initially empty.
3294 switch (I.getOpcode()) {
3295 default:
3296 assert(!isa<CallBase>(&I) &&
3297 "New call base instruction type needs to be known in the "
3298 "Attributor.");
3299 break;
3300 case Instruction::Call:
3301 // Calls are interesting on their own, additionally:
3302 // For `llvm.assume` calls we also fill the KnowledgeMap as we find them.
3303 // For `must-tail` calls we remember the caller and callee.
3304 if (auto *Assume = dyn_cast<AssumeInst>(Val: &I)) {
3305 AssumeOnlyValues.insert(X: Assume);
3306 fillMapFromAssume(Assume&: *Assume, Result&: KnowledgeMap);
3307 AddToAssumeUsesMap(*Assume->getArgOperand(i: 0));
3308 } else if (cast<CallInst>(Val&: I).isMustTailCall()) {
3309 FI.ContainsMustTailCall = true;
3310 if (auto *Callee = dyn_cast_if_present<Function>(
3311 Val: cast<CallInst>(Val&: I).getCalledOperand()))
3312 getFunctionInfo(F: *Callee).CalledViaMustTail = true;
3313 }
3314 [[fallthrough]];
3315 case Instruction::CallBr:
3316 case Instruction::Invoke:
3317 case Instruction::CleanupRet:
3318 case Instruction::CatchSwitch:
3319 case Instruction::AtomicRMW:
3320 case Instruction::AtomicCmpXchg:
3321 case Instruction::UncondBr:
3322 case Instruction::CondBr:
3323 case Instruction::Resume:
3324 case Instruction::Ret:
3325 case Instruction::Load:
3326 // The alignment of a pointer is interesting for loads.
3327 case Instruction::Store:
3328 // The alignment of a pointer is interesting for stores.
3329 case Instruction::Alloca:
3330 case Instruction::AddrSpaceCast:
3331 IsInterestingOpcode = true;
3332 }
3333 if (IsInterestingOpcode) {
3334 auto *&Insts = FI.OpcodeInstMap[I.getOpcode()];
3335 if (!Insts)
3336 Insts = new (Allocator) InstructionVectorTy();
3337 Insts->push_back(Elt: &I);
3338 }
3339 if (I.mayReadOrWriteMemory())
3340 FI.RWInsts.push_back(Elt: &I);
3341 }
3342
3343 if (F.hasFnAttribute(Kind: Attribute::AlwaysInline) &&
3344 isInlineViable(Callee&: F).isSuccess())
3345 InlineableFunctions.insert(Ptr: &F);
3346}
3347
3348InformationCache::FunctionInfo::~FunctionInfo() {
3349 // The instruction vectors are allocated using a BumpPtrAllocator, we need to
3350 // manually destroy them.
3351 for (auto &It : OpcodeInstMap)
3352 It.getSecond()->~InstructionVectorTy();
3353}
3354
3355ArrayRef<Function *>
3356InformationCache::getIndirectlyCallableFunctions(Attributor &A) const {
3357 assert(A.isClosedWorldModule() && "Cannot see all indirect callees!");
3358 return IndirectlyCallableFunctions;
3359}
3360
3361std::optional<unsigned> InformationCache::getFlatAddressSpace() const {
3362 if (IsTargetGPU())
3363 return 0;
3364 return std::nullopt;
3365}
3366
3367void Attributor::recordDependence(const AbstractAttribute &FromAA,
3368 const AbstractAttribute &ToAA,
3369 DepClassTy DepClass) {
3370 if (DepClass == DepClassTy::NONE)
3371 return;
3372 // If we are outside of an update, thus before the actual fixpoint iteration
3373 // started (= when we create AAs), we do not track dependences because we will
3374 // put all AAs into the initial worklist anyway.
3375 if (DependenceStack.empty())
3376 return;
3377 if (FromAA.getState().isAtFixpoint())
3378 return;
3379 DependenceStack.back()->push_back(Elt: {.FromAA: &FromAA, .ToAA: &ToAA, .DepClass: DepClass});
3380}
3381
3382void Attributor::rememberDependences() {
3383 assert(!DependenceStack.empty() && "No dependences to remember!");
3384
3385 for (DepInfo &DI : *DependenceStack.back()) {
3386 assert((DI.DepClass == DepClassTy::REQUIRED ||
3387 DI.DepClass == DepClassTy::OPTIONAL) &&
3388 "Expected required or optional dependence (1 bit)!");
3389 auto &DepAAs = const_cast<AbstractAttribute &>(*DI.FromAA).Deps;
3390 DepAAs.insert(X: AbstractAttribute::DepTy(
3391 const_cast<AbstractAttribute *>(DI.ToAA), unsigned(DI.DepClass)));
3392 }
3393}
3394
3395template <Attribute::AttrKind AK, typename AAType>
3396void Attributor::checkAndQueryIRAttr(const IRPosition &IRP, AttributeSet Attrs,
3397 bool SkipHasAttrCheck) {
3398 bool IsKnown;
3399 if (SkipHasAttrCheck || !Attrs.hasAttribute(Kind: AK))
3400 if (!Configuration.Allowed || Configuration.Allowed->count(V: &AAType::ID))
3401 if (!AA::hasAssumedIRAttr<AK>(*this, nullptr, IRP, DepClassTy::NONE,
3402 IsKnown))
3403 getOrCreateAAFor<AAType>(IRP);
3404}
3405
3406void Attributor::identifyDefaultAbstractAttributes(Function &F) {
3407 assert(!F.isDeclaration());
3408
3409 if (!VisitedFunctions.insert(V: &F).second)
3410 return;
3411
3412 // In non-module runs we need to look at the call sites of a function to
3413 // determine if it is part of a must-tail call edge. This will influence what
3414 // attributes we can derive.
3415 InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F);
3416 if (!isModulePass() && !FI.CalledViaMustTail) {
3417 for (const Use &U : F.uses())
3418 if (const auto *CB = dyn_cast<CallBase>(Val: U.getUser()))
3419 if (CB->isCallee(U: &U) && CB->isMustTailCall())
3420 FI.CalledViaMustTail = true;
3421 }
3422
3423 IRPosition FPos = IRPosition::function(F);
3424 bool IsIPOAmendable = isFunctionIPOAmendable(F);
3425 auto Attrs = F.getAttributes();
3426 auto FnAttrs = Attrs.getFnAttrs();
3427
3428 // Check for dead BasicBlocks in every function.
3429 // We need dead instruction detection because we do not want to deal with
3430 // broken IR in which SSA rules do not apply.
3431 getOrCreateAAFor<AAIsDead>(IRP: FPos);
3432
3433 // Every function might contain instructions that cause "undefined
3434 // behavior".
3435 getOrCreateAAFor<AAUndefinedBehavior>(IRP: FPos);
3436
3437 // Every function might be applicable for Heap-To-Stack conversion.
3438 if (EnableHeapToStack)
3439 getOrCreateAAFor<AAHeapToStack>(IRP: FPos);
3440
3441 // Every function might be "must-progress".
3442 checkAndQueryIRAttr<Attribute::MustProgress, AAMustProgress>(IRP: FPos, Attrs: FnAttrs);
3443
3444 // Every function might be "no-free".
3445 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(IRP: FPos, Attrs: FnAttrs);
3446
3447 // Every function might be "will-return".
3448 checkAndQueryIRAttr<Attribute::WillReturn, AAWillReturn>(IRP: FPos, Attrs: FnAttrs);
3449
3450 // Every function might be marked "nosync"
3451 checkAndQueryIRAttr<Attribute::NoSync, AANoSync>(IRP: FPos, Attrs: FnAttrs);
3452
3453 // Everything that is visible from the outside (=function, argument, return
3454 // positions), cannot be changed if the function is not IPO amendable. We can
3455 // however analyse the code inside.
3456 if (IsIPOAmendable) {
3457
3458 // Every function can be nounwind.
3459 checkAndQueryIRAttr<Attribute::NoUnwind, AANoUnwind>(IRP: FPos, Attrs: FnAttrs);
3460
3461 // Every function might be "no-return".
3462 checkAndQueryIRAttr<Attribute::NoReturn, AANoReturn>(IRP: FPos, Attrs: FnAttrs);
3463
3464 // Every function might be "no-recurse".
3465 checkAndQueryIRAttr<Attribute::NoRecurse, AANoRecurse>(IRP: FPos, Attrs: FnAttrs);
3466
3467 // Every function can be "non-convergent".
3468 if (Attrs.hasFnAttr(Kind: Attribute::Convergent))
3469 getOrCreateAAFor<AANonConvergent>(IRP: FPos);
3470
3471 // Every function might be "readnone/readonly/writeonly/...".
3472 getOrCreateAAFor<AAMemoryBehavior>(IRP: FPos);
3473
3474 // Every function can be "readnone/argmemonly/inaccessiblememonly/...".
3475 getOrCreateAAFor<AAMemoryLocation>(IRP: FPos);
3476
3477 // Every function can track active assumptions.
3478 getOrCreateAAFor<AAAssumptionInfo>(IRP: FPos);
3479
3480 // If we're not using a dynamic mode for float, there's nothing worthwhile
3481 // to infer. This misses the edge case denormal-fp-math="dynamic" and
3482 // denormal-fp-math-f32=something, but that likely has no real world use.
3483 DenormalMode Mode = F.getDenormalMode(FPType: APFloat::IEEEsingle());
3484 if (Mode.Input == DenormalMode::Dynamic ||
3485 Mode.Output == DenormalMode::Dynamic)
3486 getOrCreateAAFor<AADenormalFPMath>(IRP: FPos);
3487
3488 // Return attributes are only appropriate if the return type is non void.
3489 Type *ReturnType = F.getReturnType();
3490 if (!ReturnType->isVoidTy()) {
3491 IRPosition RetPos = IRPosition::returned(F);
3492 AttributeSet RetAttrs = Attrs.getRetAttrs();
3493
3494 // Every returned value might be dead.
3495 getOrCreateAAFor<AAIsDead>(IRP: RetPos);
3496
3497 // Every function might be simplified.
3498 bool UsedAssumedInformation = false;
3499 getAssumedSimplified(IRP: RetPos, AA: nullptr, UsedAssumedInformation,
3500 S: AA::Intraprocedural);
3501
3502 // Every returned value might be marked noundef.
3503 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(IRP: RetPos, Attrs: RetAttrs);
3504
3505 if (ReturnType->isPointerTy()) {
3506
3507 // Every function with pointer return type might be marked align.
3508 getOrCreateAAFor<AAAlign>(IRP: RetPos);
3509
3510 // Every function with pointer return type might be marked nonnull.
3511 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(IRP: RetPos, Attrs: RetAttrs);
3512
3513 // Every function with pointer return type might be marked noalias.
3514 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(IRP: RetPos, Attrs: RetAttrs);
3515
3516 // Every function with pointer return type might be marked
3517 // dereferenceable.
3518 getOrCreateAAFor<AADereferenceable>(IRP: RetPos);
3519 } else if (AttributeFuncs::isNoFPClassCompatibleType(Ty: ReturnType)) {
3520 getOrCreateAAFor<AANoFPClass>(IRP: RetPos);
3521 }
3522 }
3523 }
3524
3525 for (Argument &Arg : F.args()) {
3526 IRPosition ArgPos = IRPosition::argument(Arg);
3527 auto ArgNo = Arg.getArgNo();
3528 AttributeSet ArgAttrs = Attrs.getParamAttrs(ArgNo);
3529
3530 if (!IsIPOAmendable) {
3531 if (Arg.getType()->isPointerTy())
3532 // Every argument with pointer type might be marked nofree.
3533 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(IRP: ArgPos, Attrs: ArgAttrs);
3534 continue;
3535 }
3536
3537 // Every argument might be simplified. We have to go through the
3538 // Attributor interface though as outside AAs can register custom
3539 // simplification callbacks.
3540 bool UsedAssumedInformation = false;
3541 getAssumedSimplified(IRP: ArgPos, /* AA */ nullptr, UsedAssumedInformation,
3542 S: AA::Intraprocedural);
3543
3544 // Every argument might be dead.
3545 getOrCreateAAFor<AAIsDead>(IRP: ArgPos);
3546
3547 // Every argument might be marked noundef.
3548 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(IRP: ArgPos, Attrs: ArgAttrs);
3549
3550 if (Arg.getType()->isPointerTy()) {
3551 // Every argument with pointer type might be marked nonnull.
3552 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(IRP: ArgPos, Attrs: ArgAttrs);
3553
3554 // Every argument with pointer type might be marked noalias.
3555 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(IRP: ArgPos, Attrs: ArgAttrs);
3556
3557 // Every argument with pointer type might be marked dereferenceable.
3558 getOrCreateAAFor<AADereferenceable>(IRP: ArgPos);
3559
3560 // Every argument with pointer type might be marked align.
3561 getOrCreateAAFor<AAAlign>(IRP: ArgPos);
3562
3563 // Every argument with pointer type might be marked nocapture.
3564 checkAndQueryIRAttr<Attribute::Captures, AANoCapture>(
3565 IRP: ArgPos, Attrs: ArgAttrs, /*SkipHasAttrCheck=*/true);
3566
3567 // Every argument with pointer type might be marked
3568 // "readnone/readonly/writeonly/..."
3569 getOrCreateAAFor<AAMemoryBehavior>(IRP: ArgPos);
3570
3571 // Every argument with pointer type might be marked nofree.
3572 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(IRP: ArgPos, Attrs: ArgAttrs);
3573
3574 // Every argument with pointer type might be privatizable (or
3575 // promotable)
3576 getOrCreateAAFor<AAPrivatizablePtr>(IRP: ArgPos);
3577 } else if (AttributeFuncs::isNoFPClassCompatibleType(Ty: Arg.getType())) {
3578 getOrCreateAAFor<AANoFPClass>(IRP: ArgPos);
3579 }
3580 }
3581
3582 auto CallSitePred = [&](Instruction &I) -> bool {
3583 auto &CB = cast<CallBase>(Val&: I);
3584 IRPosition CBInstPos = IRPosition::inst(I: CB);
3585 IRPosition CBFnPos = IRPosition::callsite_function(CB);
3586
3587 // Call sites might be dead if they do not have side effects and no live
3588 // users. The return value might be dead if there are no live users.
3589 getOrCreateAAFor<AAIsDead>(IRP: CBInstPos);
3590
3591 Function *Callee = dyn_cast_if_present<Function>(Val: CB.getCalledOperand());
3592 // TODO: Even if the callee is not known now we might be able to simplify
3593 // the call/callee.
3594 if (!Callee) {
3595 getOrCreateAAFor<AAIndirectCallInfo>(IRP: CBFnPos);
3596 return true;
3597 }
3598
3599 // Every call site can track active assumptions.
3600 getOrCreateAAFor<AAAssumptionInfo>(IRP: CBFnPos);
3601
3602 // Skip declarations except if annotations on their call sites were
3603 // explicitly requested.
3604 if (!AnnotateDeclarationCallSites && Callee->isDeclaration() &&
3605 !Callee->hasMetadata(KindID: LLVMContext::MD_callback))
3606 return true;
3607
3608 if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) {
3609 IRPosition CBRetPos = IRPosition::callsite_returned(CB);
3610 bool UsedAssumedInformation = false;
3611 getAssumedSimplified(IRP: CBRetPos, AA: nullptr, UsedAssumedInformation,
3612 S: AA::Intraprocedural);
3613
3614 if (AttributeFuncs::isNoFPClassCompatibleType(Ty: Callee->getReturnType()))
3615 getOrCreateAAFor<AANoFPClass>(IRP: CBInstPos);
3616 }
3617
3618 const AttributeList &CBAttrs = CBFnPos.getAttrList();
3619 for (int I = 0, E = CB.arg_size(); I < E; ++I) {
3620
3621 IRPosition CBArgPos = IRPosition::callsite_argument(CB, ArgNo: I);
3622 AttributeSet CBArgAttrs = CBAttrs.getParamAttrs(ArgNo: I);
3623
3624 // Every call site argument might be dead.
3625 getOrCreateAAFor<AAIsDead>(IRP: CBArgPos);
3626
3627 // Call site argument might be simplified. We have to go through the
3628 // Attributor interface though as outside AAs can register custom
3629 // simplification callbacks.
3630 bool UsedAssumedInformation = false;
3631 getAssumedSimplified(IRP: CBArgPos, /* AA */ nullptr, UsedAssumedInformation,
3632 S: AA::Intraprocedural);
3633
3634 // Every call site argument might be marked "noundef".
3635 checkAndQueryIRAttr<Attribute::NoUndef, AANoUndef>(IRP: CBArgPos, Attrs: CBArgAttrs);
3636
3637 Type *ArgTy = CB.getArgOperand(i: I)->getType();
3638
3639 if (!ArgTy->isPointerTy()) {
3640 if (AttributeFuncs::isNoFPClassCompatibleType(Ty: ArgTy))
3641 getOrCreateAAFor<AANoFPClass>(IRP: CBArgPos);
3642
3643 continue;
3644 }
3645
3646 // Call site argument attribute "non-null".
3647 checkAndQueryIRAttr<Attribute::NonNull, AANonNull>(IRP: CBArgPos, Attrs: CBArgAttrs);
3648
3649 // Call site argument attribute "captures(none)".
3650 checkAndQueryIRAttr<Attribute::Captures, AANoCapture>(
3651 IRP: CBArgPos, Attrs: CBArgAttrs, /*SkipHasAttrCheck=*/true);
3652
3653 // Call site argument attribute "no-alias".
3654 checkAndQueryIRAttr<Attribute::NoAlias, AANoAlias>(IRP: CBArgPos, Attrs: CBArgAttrs);
3655
3656 // Call site argument attribute "dereferenceable".
3657 getOrCreateAAFor<AADereferenceable>(IRP: CBArgPos);
3658
3659 // Call site argument attribute "align".
3660 getOrCreateAAFor<AAAlign>(IRP: CBArgPos);
3661
3662 // Call site argument attribute
3663 // "readnone/readonly/writeonly/..."
3664 if (!CBAttrs.hasParamAttr(ArgNo: I, Kind: Attribute::ReadNone))
3665 getOrCreateAAFor<AAMemoryBehavior>(IRP: CBArgPos);
3666
3667 // Call site argument attribute "nofree".
3668 checkAndQueryIRAttr<Attribute::NoFree, AANoFree>(IRP: CBArgPos, Attrs: CBArgAttrs);
3669 }
3670 return true;
3671 };
3672
3673 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F);
3674 [[maybe_unused]] bool Success;
3675 bool UsedAssumedInformation = false;
3676 Success = checkForAllInstructionsImpl(
3677 A: nullptr, OpcodeInstMap, Pred: CallSitePred, QueryingAA: nullptr, LivenessAA: nullptr,
3678 Opcodes: {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr,
3679 (unsigned)Instruction::Call},
3680 UsedAssumedInformation);
3681 assert(Success && "Expected the check call to be successful!");
3682
3683 auto LoadStorePred = [&](Instruction &I) -> bool {
3684 if (auto *LI = dyn_cast<LoadInst>(Val: &I)) {
3685 getOrCreateAAFor<AAAlign>(IRP: IRPosition::value(V: *LI->getPointerOperand()));
3686 if (SimplifyAllLoads)
3687 getAssumedSimplified(IRP: IRPosition::value(V: I), AA: nullptr,
3688 UsedAssumedInformation, S: AA::Intraprocedural);
3689 getOrCreateAAFor<AAInvariantLoadPointer>(
3690 IRP: IRPosition::value(V: *LI->getPointerOperand()));
3691 getOrCreateAAFor<AAAddressSpace>(
3692 IRP: IRPosition::value(V: *LI->getPointerOperand()));
3693 } else {
3694 auto &SI = cast<StoreInst>(Val&: I);
3695 getOrCreateAAFor<AAIsDead>(IRP: IRPosition::inst(I));
3696 getAssumedSimplified(IRP: IRPosition::value(V: *SI.getValueOperand()), AA: nullptr,
3697 UsedAssumedInformation, S: AA::Intraprocedural);
3698 getOrCreateAAFor<AAAlign>(IRP: IRPosition::value(V: *SI.getPointerOperand()));
3699 getOrCreateAAFor<AAAddressSpace>(
3700 IRP: IRPosition::value(V: *SI.getPointerOperand()));
3701 }
3702 return true;
3703 };
3704 Success = checkForAllInstructionsImpl(
3705 A: nullptr, OpcodeInstMap, Pred: LoadStorePred, QueryingAA: nullptr, LivenessAA: nullptr,
3706 Opcodes: {(unsigned)Instruction::Load, (unsigned)Instruction::Store},
3707 UsedAssumedInformation);
3708 assert(Success && "Expected the check call to be successful!");
3709
3710 // AllocaInstPredicate
3711 auto AAAllocationInfoPred = [&](Instruction &I) -> bool {
3712 getOrCreateAAFor<AAAllocationInfo>(IRP: IRPosition::value(V: I));
3713 return true;
3714 };
3715
3716 Success = checkForAllInstructionsImpl(
3717 A: nullptr, OpcodeInstMap, Pred: AAAllocationInfoPred, QueryingAA: nullptr, LivenessAA: nullptr,
3718 Opcodes: {(unsigned)Instruction::Alloca}, UsedAssumedInformation);
3719 assert(Success && "Expected the check call to be successful!");
3720}
3721
3722bool Attributor::isClosedWorldModule() const {
3723 if (CloseWorldAssumption.getNumOccurrences())
3724 return CloseWorldAssumption;
3725 return isModulePass() && Configuration.IsClosedWorldModule;
3726}
3727
3728/// Helpers to ease debugging through output streams and print calls.
3729///
3730///{
3731raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) {
3732 return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged");
3733}
3734
3735raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) {
3736 switch (AP) {
3737 case IRPosition::IRP_INVALID:
3738 return OS << "inv";
3739 case IRPosition::IRP_FLOAT:
3740 return OS << "flt";
3741 case IRPosition::IRP_RETURNED:
3742 return OS << "fn_ret";
3743 case IRPosition::IRP_CALL_SITE_RETURNED:
3744 return OS << "cs_ret";
3745 case IRPosition::IRP_FUNCTION:
3746 return OS << "fn";
3747 case IRPosition::IRP_CALL_SITE:
3748 return OS << "cs";
3749 case IRPosition::IRP_ARGUMENT:
3750 return OS << "arg";
3751 case IRPosition::IRP_CALL_SITE_ARGUMENT:
3752 return OS << "cs_arg";
3753 }
3754 llvm_unreachable("Unknown attribute position!");
3755}
3756
3757raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) {
3758 const Value &AV = Pos.getAssociatedValue();
3759 OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " ["
3760 << Pos.getAnchorValue().getName() << "@" << Pos.getCallSiteArgNo() << "]";
3761
3762 if (Pos.hasCallBaseContext())
3763 OS << "[cb_context:" << *Pos.getCallBaseContext() << "]";
3764 return OS << "}";
3765}
3766
3767raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerRangeState &S) {
3768 OS << "range-state(" << S.getBitWidth() << ")<";
3769 S.getKnown().print(OS);
3770 OS << " / ";
3771 S.getAssumed().print(OS);
3772 OS << ">";
3773
3774 return OS << static_cast<const AbstractState &>(S);
3775}
3776
3777raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) {
3778 return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : ""));
3779}
3780
3781raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) {
3782 AA.print(OS);
3783 return OS;
3784}
3785
3786raw_ostream &llvm::operator<<(raw_ostream &OS,
3787 const PotentialConstantIntValuesState &S) {
3788 OS << "set-state(< {";
3789 if (!S.isValidState())
3790 OS << "full-set";
3791 else {
3792 for (const auto &It : S.getAssumedSet())
3793 OS << It << ", ";
3794 if (S.undefIsContained())
3795 OS << "undef ";
3796 }
3797 OS << "} >)";
3798
3799 return OS;
3800}
3801
3802raw_ostream &llvm::operator<<(raw_ostream &OS,
3803 const PotentialLLVMValuesState &S) {
3804 OS << "set-state(< {";
3805 if (!S.isValidState())
3806 OS << "full-set";
3807 else {
3808 for (const auto &It : S.getAssumedSet()) {
3809 if (auto *F = dyn_cast<Function>(Val: It.first.getValue()))
3810 OS << "@" << F->getName() << "[" << int(It.second) << "], ";
3811 else
3812 OS << *It.first.getValue() << "[" << int(It.second) << "], ";
3813 }
3814 if (S.undefIsContained())
3815 OS << "undef ";
3816 }
3817 OS << "} >)";
3818
3819 return OS;
3820}
3821
3822void AbstractAttribute::print(Attributor *A, raw_ostream &OS) const {
3823 OS << "[";
3824 OS << getName();
3825 OS << "] for CtxI ";
3826
3827 if (auto *I = getCtxI()) {
3828 OS << "'";
3829 I->print(O&: OS);
3830 OS << "'";
3831 } else
3832 OS << "<<null inst>>";
3833
3834 OS << " at position " << getIRPosition() << " with state " << getAsStr(A)
3835 << '\n';
3836}
3837
3838void AbstractAttribute::printWithDeps(raw_ostream &OS) const {
3839 print(OS);
3840
3841 for (const auto &DepAA : Deps) {
3842 auto *AA = DepAA.getPointer();
3843 OS << " updates ";
3844 AA->print(OS);
3845 }
3846
3847 OS << '\n';
3848}
3849
3850raw_ostream &llvm::operator<<(raw_ostream &OS,
3851 const AAPointerInfo::Access &Acc) {
3852 OS << " [" << Acc.getKind() << "] " << *Acc.getRemoteInst();
3853 if (Acc.getLocalInst() != Acc.getRemoteInst())
3854 OS << " via " << *Acc.getLocalInst();
3855 if (Acc.getContent()) {
3856 if (*Acc.getContent())
3857 OS << " [" << **Acc.getContent() << "]";
3858 else
3859 OS << " [ <unknown> ]";
3860 }
3861 return OS;
3862}
3863///}
3864
3865/// ----------------------------------------------------------------------------
3866/// Pass (Manager) Boilerplate
3867/// ----------------------------------------------------------------------------
3868
3869static bool runAttributorOnFunctions(InformationCache &InfoCache,
3870 SetVector<Function *> &Functions,
3871 AnalysisGetter &AG,
3872 CallGraphUpdater &CGUpdater,
3873 bool DeleteFns, bool IsModulePass) {
3874 if (Functions.empty())
3875 return false;
3876
3877 LLVM_DEBUG({
3878 dbgs() << "[Attributor] Run on module with " << Functions.size()
3879 << " functions:\n";
3880 for (Function *Fn : Functions)
3881 dbgs() << " - " << Fn->getName() << "\n";
3882 });
3883
3884 // Create an Attributor and initially empty information cache that is filled
3885 // while we identify default attribute opportunities.
3886 AttributorConfig AC(CGUpdater);
3887 AC.IsModulePass = IsModulePass;
3888 AC.DeleteFns = DeleteFns;
3889
3890 /// Tracking callback for specialization of indirect calls.
3891 DenseMap<CallBase *, std::unique_ptr<SmallPtrSet<Function *, 8>>>
3892 IndirectCalleeTrackingMap;
3893 if (MaxSpecializationPerCB.getNumOccurrences()) {
3894 AC.IndirectCalleeSpecializationCallback =
3895 [&](Attributor &, const AbstractAttribute &AA, CallBase &CB,
3896 Function &Callee, unsigned) {
3897 if (MaxSpecializationPerCB == 0)
3898 return false;
3899 auto &Set = IndirectCalleeTrackingMap[&CB];
3900 if (!Set)
3901 Set = std::make_unique<SmallPtrSet<Function *, 8>>();
3902 if (Set->size() >= MaxSpecializationPerCB)
3903 return Set->contains(Ptr: &Callee);
3904 Set->insert(Ptr: &Callee);
3905 return true;
3906 };
3907 }
3908
3909 Attributor A(Functions, InfoCache, AC);
3910
3911 // Create shallow wrappers for all functions that are not IPO amendable
3912 if (AllowShallowWrappers)
3913 for (Function *F : Functions)
3914 if (!A.isFunctionIPOAmendable(F: *F))
3915 Attributor::createShallowWrapper(F&: *F);
3916
3917 // Internalize non-exact functions
3918 // TODO: for now we eagerly internalize functions without calculating the
3919 // cost, we need a cost interface to determine whether internalizing
3920 // a function is "beneficial"
3921 if (AllowDeepWrapper) {
3922 unsigned FunSize = Functions.size();
3923 for (unsigned u = 0; u < FunSize; u++) {
3924 Function *F = Functions[u];
3925 if (!F->isDeclaration() && !F->isDefinitionExact() && !F->use_empty() &&
3926 !GlobalValue::isInterposableLinkage(Linkage: F->getLinkage())) {
3927 Function *NewF = Attributor::internalizeFunction(F&: *F);
3928 assert(NewF && "Could not internalize function.");
3929 Functions.insert(X: NewF);
3930
3931 // Update call graph
3932 CGUpdater.replaceFunctionWith(OldFn&: *F, NewFn&: *NewF);
3933 for (const Use &U : NewF->uses())
3934 if (CallBase *CB = dyn_cast<CallBase>(Val: U.getUser())) {
3935 auto *CallerF = CB->getCaller();
3936 CGUpdater.reanalyzeFunction(Fn&: *CallerF);
3937 }
3938 }
3939 }
3940 }
3941
3942 for (Function *F : Functions) {
3943 if (F->isDeclaration())
3944 continue;
3945
3946 if (F->hasExactDefinition())
3947 NumFnWithExactDefinition++;
3948 else
3949 NumFnWithoutExactDefinition++;
3950
3951 // We look at internal functions only on-demand but if any use is not a
3952 // direct call or outside the current set of analyzed functions, we have
3953 // to do it eagerly.
3954 if (F->hasLocalLinkage()) {
3955 if (llvm::all_of(Range: F->uses(), P: [&Functions](const Use &U) {
3956 const auto *CB = dyn_cast<CallBase>(Val: U.getUser());
3957 return CB && CB->isCallee(U: &U) &&
3958 Functions.count(key: const_cast<Function *>(CB->getCaller()));
3959 }))
3960 continue;
3961 }
3962
3963 // Populate the Attributor with abstract attribute opportunities in the
3964 // function and the information cache with IR information.
3965 A.identifyDefaultAbstractAttributes(F&: *F);
3966 }
3967
3968 ChangeStatus Changed = A.run();
3969
3970 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size()
3971 << " functions, result: " << Changed << ".\n");
3972 return Changed == ChangeStatus::CHANGED;
3973}
3974
3975static bool runAttributorLightOnFunctions(InformationCache &InfoCache,
3976 SetVector<Function *> &Functions,
3977 AnalysisGetter &AG,
3978 CallGraphUpdater &CGUpdater,
3979 FunctionAnalysisManager &FAM,
3980 bool IsModulePass) {
3981 if (Functions.empty())
3982 return false;
3983
3984 LLVM_DEBUG({
3985 dbgs() << "[AttributorLight] Run on module with " << Functions.size()
3986 << " functions:\n";
3987 for (Function *Fn : Functions)
3988 dbgs() << " - " << Fn->getName() << "\n";
3989 });
3990
3991 // Create an Attributor and initially empty information cache that is filled
3992 // while we identify default attribute opportunities.
3993 AttributorConfig AC(CGUpdater);
3994 AC.IsModulePass = IsModulePass;
3995 AC.DeleteFns = false;
3996 DenseSet<const char *> Allowed(
3997 {&AAWillReturn::ID, &AANoUnwind::ID, &AANoRecurse::ID, &AANoSync::ID,
3998 &AANoFree::ID, &AANoReturn::ID, &AAMemoryLocation::ID,
3999 &AAMemoryBehavior::ID, &AAUnderlyingObjects::ID, &AANoCapture::ID,
4000 &AAInterFnReachability::ID, &AAIntraFnReachability::ID, &AACallEdges::ID,
4001 &AANoFPClass::ID, &AAMustProgress::ID, &AANonNull::ID,
4002 &AADenormalFPMath::ID});
4003 AC.Allowed = &Allowed;
4004 AC.UseLiveness = false;
4005
4006 Attributor A(Functions, InfoCache, AC);
4007
4008 for (Function *F : Functions) {
4009 if (F->isDeclaration())
4010 continue;
4011
4012 if (F->hasExactDefinition())
4013 NumFnWithExactDefinition++;
4014 else
4015 NumFnWithoutExactDefinition++;
4016
4017 // We look at internal functions only on-demand but if any use is not a
4018 // direct call or outside the current set of analyzed functions, we have
4019 // to do it eagerly.
4020 if (AC.UseLiveness && F->hasLocalLinkage()) {
4021 if (llvm::all_of(Range: F->uses(), P: [&Functions](const Use &U) {
4022 const auto *CB = dyn_cast<CallBase>(Val: U.getUser());
4023 return CB && CB->isCallee(U: &U) &&
4024 Functions.count(key: const_cast<Function *>(CB->getCaller()));
4025 }))
4026 continue;
4027 }
4028
4029 // Populate the Attributor with abstract attribute opportunities in the
4030 // function and the information cache with IR information.
4031 A.identifyDefaultAbstractAttributes(F&: *F);
4032 }
4033
4034 ChangeStatus Changed = A.run();
4035
4036 if (Changed == ChangeStatus::CHANGED) {
4037 // Invalidate analyses for modified functions so that we don't have to
4038 // invalidate all analyses for all functions in this SCC.
4039 PreservedAnalyses FuncPA;
4040 // We haven't changed the CFG for modified functions.
4041 FuncPA.preserveSet<CFGAnalyses>();
4042 for (Function *Changed : A.getModifiedFunctions()) {
4043 FAM.invalidate(IR&: *Changed, PA: FuncPA);
4044 // Also invalidate any direct callers of changed functions since analyses
4045 // may care about attributes of direct callees. For example, MemorySSA
4046 // cares about whether or not a call's callee modifies memory and queries
4047 // that through function attributes.
4048 for (auto *U : Changed->users()) {
4049 if (auto *Call = dyn_cast<CallBase>(Val: U)) {
4050 if (Call->getCalledFunction() == Changed)
4051 FAM.invalidate(IR&: *Call->getFunction(), PA: FuncPA);
4052 }
4053 }
4054 }
4055 }
4056 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size()
4057 << " functions, result: " << Changed << ".\n");
4058 return Changed == ChangeStatus::CHANGED;
4059}
4060
4061void AADepGraph::viewGraph() { llvm::ViewGraph(G: this, Name: "Dependency Graph"); }
4062
4063void AADepGraph::dumpGraph() {
4064 static std::atomic<int> CallTimes;
4065 std::string Prefix;
4066
4067 if (!DepGraphDotFileNamePrefix.empty())
4068 Prefix = DepGraphDotFileNamePrefix;
4069 else
4070 Prefix = "dep_graph";
4071 std::string Filename =
4072 Prefix + "_" + std::to_string(val: CallTimes.load()) + ".dot";
4073
4074 outs() << "Dependency graph dump to " << Filename << ".\n";
4075
4076 std::error_code EC;
4077
4078 raw_fd_ostream File(Filename, EC, sys::fs::OF_TextWithCRLF);
4079 if (!EC)
4080 llvm::WriteGraph(O&: File, G: this);
4081
4082 CallTimes++;
4083}
4084
4085void AADepGraph::print() {
4086 for (auto DepAA : SyntheticRoot.Deps)
4087 cast<AbstractAttribute>(Val: DepAA.getPointer())->printWithDeps(OS&: outs());
4088}
4089
4090PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) {
4091 FunctionAnalysisManager &FAM =
4092 AM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: M).getManager();
4093 AnalysisGetter AG(FAM);
4094
4095 SetVector<Function *> Functions;
4096 for (Function &F : M)
4097 Functions.insert(X: &F);
4098
4099 CallGraphUpdater CGUpdater;
4100 BumpPtrAllocator Allocator;
4101 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
4102 if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
4103 /* DeleteFns */ true, /* IsModulePass */ true)) {
4104 // FIXME: Think about passes we will preserve and add them here.
4105 return PreservedAnalyses::none();
4106 }
4107 return PreservedAnalyses::all();
4108}
4109
4110PreservedAnalyses AttributorCGSCCPass::run(LazyCallGraph::SCC &C,
4111 CGSCCAnalysisManager &AM,
4112 LazyCallGraph &CG,
4113 CGSCCUpdateResult &UR) {
4114 FunctionAnalysisManager &FAM =
4115 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(IR&: C, ExtraArgs&: CG).getManager();
4116 AnalysisGetter AG(FAM);
4117
4118 SetVector<Function *> Functions;
4119 for (LazyCallGraph::Node &N : C)
4120 Functions.insert(X: &N.getFunction());
4121
4122 if (Functions.empty())
4123 return PreservedAnalyses::all();
4124
4125 Module &M = *Functions.back()->getParent();
4126 CallGraphUpdater CGUpdater;
4127 CGUpdater.initialize(LCG&: CG, SCC&: C, AM, UR);
4128 BumpPtrAllocator Allocator;
4129 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
4130 if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater,
4131 /* DeleteFns */ false,
4132 /* IsModulePass */ false)) {
4133 // FIXME: Think about passes we will preserve and add them here.
4134 PreservedAnalyses PA;
4135 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
4136 return PA;
4137 }
4138 return PreservedAnalyses::all();
4139}
4140
4141PreservedAnalyses AttributorLightPass::run(Module &M,
4142 ModuleAnalysisManager &AM) {
4143 FunctionAnalysisManager &FAM =
4144 AM.getResult<FunctionAnalysisManagerModuleProxy>(IR&: M).getManager();
4145 AnalysisGetter AG(FAM, /* CachedOnly */ true);
4146
4147 SetVector<Function *> Functions;
4148 for (Function &F : M)
4149 Functions.insert(X: &F);
4150
4151 CallGraphUpdater CGUpdater;
4152 BumpPtrAllocator Allocator;
4153 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr);
4154 if (runAttributorLightOnFunctions(InfoCache, Functions, AG, CGUpdater, FAM,
4155 /* IsModulePass */ true)) {
4156 PreservedAnalyses PA;
4157 // We have not added or removed functions.
4158 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
4159 // We already invalidated all relevant function analyses above.
4160 PA.preserveSet<AllAnalysesOn<Function>>();
4161 return PA;
4162 }
4163 return PreservedAnalyses::all();
4164}
4165
4166PreservedAnalyses AttributorLightCGSCCPass::run(LazyCallGraph::SCC &C,
4167 CGSCCAnalysisManager &AM,
4168 LazyCallGraph &CG,
4169 CGSCCUpdateResult &UR) {
4170 FunctionAnalysisManager &FAM =
4171 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(IR&: C, ExtraArgs&: CG).getManager();
4172 AnalysisGetter AG(FAM);
4173
4174 SetVector<Function *> Functions;
4175 for (LazyCallGraph::Node &N : C)
4176 Functions.insert(X: &N.getFunction());
4177
4178 if (Functions.empty())
4179 return PreservedAnalyses::all();
4180
4181 Module &M = *Functions.back()->getParent();
4182 CallGraphUpdater CGUpdater;
4183 CGUpdater.initialize(LCG&: CG, SCC&: C, AM, UR);
4184 BumpPtrAllocator Allocator;
4185 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions);
4186 if (runAttributorLightOnFunctions(InfoCache, Functions, AG, CGUpdater, FAM,
4187 /* IsModulePass */ false)) {
4188 PreservedAnalyses PA;
4189 // We have not added or removed functions.
4190 PA.preserve<FunctionAnalysisManagerCGSCCProxy>();
4191 // We already invalidated all relevant function analyses above.
4192 PA.preserveSet<AllAnalysesOn<Function>>();
4193 return PA;
4194 }
4195 return PreservedAnalyses::all();
4196}
4197namespace llvm {
4198
4199template <> struct GraphTraits<AADepGraphNode *> {
4200 using NodeRef = AADepGraphNode *;
4201 using DepTy = PointerIntPair<AADepGraphNode *, 1>;
4202 using EdgeRef = PointerIntPair<AADepGraphNode *, 1>;
4203
4204 static NodeRef getEntryNode(AADepGraphNode *DGN) { return DGN; }
4205 static NodeRef DepGetVal(const DepTy &DT) { return DT.getPointer(); }
4206
4207 using ChildIteratorType =
4208 mapped_iterator<AADepGraphNode::DepSetTy::iterator, decltype(&DepGetVal)>;
4209 using ChildEdgeIteratorType = AADepGraphNode::DepSetTy::iterator;
4210
4211 static ChildIteratorType child_begin(NodeRef N) { return N->child_begin(); }
4212
4213 static ChildIteratorType child_end(NodeRef N) { return N->child_end(); }
4214};
4215
4216template <>
4217struct GraphTraits<AADepGraph *> : public GraphTraits<AADepGraphNode *> {
4218 static NodeRef getEntryNode(AADepGraph *DG) { return DG->GetEntryNode(); }
4219
4220 using nodes_iterator =
4221 mapped_iterator<AADepGraphNode::DepSetTy::iterator, decltype(&DepGetVal)>;
4222
4223 static nodes_iterator nodes_begin(AADepGraph *DG) { return DG->begin(); }
4224
4225 static nodes_iterator nodes_end(AADepGraph *DG) { return DG->end(); }
4226};
4227
4228template <> struct DOTGraphTraits<AADepGraph *> : public DefaultDOTGraphTraits {
4229 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
4230
4231 static std::string getNodeLabel(const AADepGraphNode *Node,
4232 const AADepGraph *DG) {
4233 std::string AAString;
4234 raw_string_ostream O(AAString);
4235 Node->print(OS&: O);
4236 return AAString;
4237 }
4238};
4239
4240} // end namespace llvm
4241