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