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