58#include "llvm/IR/IntrinsicsAMDGPU.h"
59#include "llvm/IR/IntrinsicsNVPTX.h"
85#define DEBUG_TYPE "attributor"
87STATISTIC(NumAAs,
"Number of abstract attributes created");
88STATISTIC(NumIndirectCallsPromoted,
"Number of indirect calls promoted");
103#define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME) \
104 ("Number of " #TYPE " marked '" #NAME "'")
105#define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME
106#define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG);
107#define STATS_DECL(NAME, TYPE, MSG) \
108 STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG);
109#define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE));
110#define STATS_DECLTRACK(NAME, TYPE, MSG) \
111 {STATS_DECL(NAME, TYPE, MSG) STATS_TRACK(NAME, TYPE)}
112#define STATS_DECLTRACK_ARG_ATTR(NAME) \
113 STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME))
114#define STATS_DECLTRACK_CSARG_ATTR(NAME) \
115 STATS_DECLTRACK(NAME, CSArguments, \
116 BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME))
117#define STATS_DECLTRACK_FN_ATTR(NAME) \
118 STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME))
119#define STATS_DECLTRACK_CS_ATTR(NAME) \
120 STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME))
121#define STATS_DECLTRACK_FNRET_ATTR(NAME) \
122 STATS_DECLTRACK(NAME, FunctionReturn, \
123 BUILD_STAT_MSG_IR_ATTR(function returns, NAME))
124#define STATS_DECLTRACK_CSRET_ATTR(NAME) \
125 STATS_DECLTRACK(NAME, CSReturn, \
126 BUILD_STAT_MSG_IR_ATTR(call site returns, NAME))
127#define STATS_DECLTRACK_FLOATING_ATTR(NAME) \
128 STATS_DECLTRACK(NAME, Floating, \
129 ("Number of floating values known to be '" #NAME "'"))
134#define PIPE_OPERATOR(CLASS) \
135 raw_ostream &operator<<(raw_ostream &OS, const CLASS &AA) { \
136 return OS << static_cast<const AbstractAttribute &>(AA); \
193 bool HeaderOnly,
CycleRef *CPtr =
nullptr) {
196 auto *BB =
I->getParent();
213 if (
DL.getTypeSizeInBits(Ty) !=
DL.getTypeAllocSizeInBits(Ty))
238 StartPos +=
DL.getTypeAllocSizeInBits(ElTy);
249 bool AllowVolatile) {
250 if (!AllowVolatile &&
I->isVolatile())
254 return LI->getPointerOperand();
258 return SI->getPointerOperand();
262 return CXI->getPointerOperand();
266 return RMWI->getPointerOperand();
288 bool GetMinOffset,
bool AllowNonInbounds,
289 bool UseAssumed =
false) {
291 auto AttributorAnalysis = [&](
Value &
V,
APInt &ROffset) ->
bool {
298 if (!ValueConstantRangeAA)
302 if (
Range.isFullSet())
308 ROffset =
Range.getSignedMin();
310 ROffset =
Range.getSignedMax();
321 const Value *Ptr, int64_t &BytesOffset,
326 true, AllowNonInbounds);
334template <
typename AAType,
typename StateType =
typename AAType::StateType,
336 bool RecurseForSelectAndPHI =
true>
338 Attributor &
A,
const AAType &QueryingAA, StateType &S,
340 LLVM_DEBUG(
dbgs() <<
"[Attributor] Clamp return value states for "
341 << QueryingAA <<
" into " << S <<
"\n");
343 assert((QueryingAA.getIRPosition().getPositionKind() ==
345 QueryingAA.getIRPosition().getPositionKind() ==
347 "Can only clamp returned value states for a function returned or call "
348 "site returned position!");
352 std::optional<StateType>
T;
355 auto CheckReturnValue = [&](
Value &RV) ->
bool {
369 <<
" AA: " <<
AA->getAsStr(&
A) <<
" @ " << RVPos <<
"\n");
370 const StateType &AAS =
AA->getState();
372 T = StateType::getBestState(AAS);
374 LLVM_DEBUG(
dbgs() <<
"[Attributor] AA State: " << AAS <<
" RV State: " <<
T
376 return T->isValidState();
379 if (!
A.checkForAllReturnedValues(CheckReturnValue, QueryingAA,
381 RecurseForSelectAndPHI))
382 S.indicatePessimisticFixpoint();
389template <
typename AAType,
typename BaseType,
390 typename StateType =
typename BaseType::StateType,
391 bool PropagateCallBaseContext =
false,
393 bool RecurseForSelectAndPHI =
true>
394struct AAReturnedFromReturnedValues :
public BaseType {
395 AAReturnedFromReturnedValues(
const IRPosition &IRP, Attributor &
A)
399 StateType S(StateType::getBestState(this->getState()));
401 RecurseForSelectAndPHI>(
403 PropagateCallBaseContext ? this->getCallBaseContext() : nullptr);
412template <
typename AAType,
typename StateType =
typename AAType::StateType,
414static void clampCallSiteArgumentStates(
Attributor &
A,
const AAType &QueryingAA,
416 LLVM_DEBUG(
dbgs() <<
"[Attributor] Clamp call site argument states for "
417 << QueryingAA <<
" into " << S <<
"\n");
419 assert(QueryingAA.getIRPosition().getPositionKind() ==
421 "Can only clamp call site argument states for an argument position!");
425 std::optional<StateType>
T;
428 unsigned ArgNo = QueryingAA.getIRPosition().getCallSiteArgNo();
448 LLVM_DEBUG(
dbgs() <<
"[Attributor] ACS: " << *ACS.getInstruction()
449 <<
" AA: " <<
AA->getAsStr(&
A) <<
" @" << ACSArgPos
451 const StateType &AAS =
AA->getState();
453 T = StateType::getBestState(AAS);
455 LLVM_DEBUG(
dbgs() <<
"[Attributor] AA State: " << AAS <<
" CSA State: " <<
T
457 return T->isValidState();
460 bool UsedAssumedInformation =
false;
461 if (!
A.checkForAllCallSites(CallSiteCheck, QueryingAA,
true,
462 UsedAssumedInformation))
463 S.indicatePessimisticFixpoint();
470template <
typename AAType,
typename BaseType,
471 typename StateType =
typename AAType::StateType,
473bool getArgumentStateFromCallBaseContext(
Attributor &
A,
477 "Expected an 'argument' position !");
483 assert(ArgNo >= 0 &&
"Invalid Arg No!");
497 const StateType &CBArgumentState =
498 static_cast<const StateType &
>(
AA->getState());
500 LLVM_DEBUG(
dbgs() <<
"[Attributor] Briding Call site context to argument"
501 <<
"Position:" << Pos <<
"CB Arg state:" << CBArgumentState
505 State ^= CBArgumentState;
510template <
typename AAType,
typename BaseType,
511 typename StateType =
typename AAType::StateType,
512 bool BridgeCallBaseContext =
false,
514struct AAArgumentFromCallSiteArguments :
public BaseType {
515 AAArgumentFromCallSiteArguments(
const IRPosition &IRP, Attributor &
A)
519 StateType S = StateType::getBestState(this->getState());
521 if (BridgeCallBaseContext) {
523 getArgumentStateFromCallBaseContext<AAType,
BaseType, StateType,
525 A, *
this, this->getIRPosition(), S);
529 clampCallSiteArgumentStates<AAType, StateType, IRAttributeKind>(
A, *
this,
539template <
typename AAType,
typename BaseType,
540 typename StateType =
typename BaseType::StateType,
541 bool IntroduceCallBaseContext =
false,
543struct AACalleeToCallSite :
public BaseType {
544 AACalleeToCallSite(
const IRPosition &IRP, Attributor &
A) :
BaseType(IRP,
A) {}
547 auto IRPKind = this->getIRPosition().getPositionKind();
550 "Can only wrap function returned positions for call site "
551 "returned positions!");
552 auto &S = this->getState();
555 if (IntroduceCallBaseContext)
556 LLVM_DEBUG(
dbgs() <<
"[Attributor] Introducing call base context:" << CB
561 for (
const Function *Callee : Callees) {
570 IntroduceCallBaseContext ? &CB :
nullptr)
572 *
Callee, IntroduceCallBaseContext ? &CB : nullptr);
574 if (Attribute::isEnumAttrKind(IRAttributeKind)) {
577 A,
this, FnPos, DepClassTy::REQUIRED, IsKnown))
583 A.getAAFor<AAType>(*
this, FnPos, DepClassTy::REQUIRED);
587 if (S.isAtFixpoint())
588 return S.isValidState();
592 if (!
A.checkForAllCallees(CalleePred, *
this, CB))
593 return S.indicatePessimisticFixpoint();
599template <
class AAType,
typename StateType =
typename AAType::StateType>
605 for (
unsigned u = 0;
u <
Uses.size(); ++
u) {
609 if (Found &&
AA.followUseInMBEC(
A, U, UserI, State))
624template <
class AAType,
typename StateType =
typename AAType::StateType>
625static void followUsesInMBEC(AAType &
AA,
Attributor &
A, StateType &S,
627 if (!
A.canUseBodyFor(
AA.getIRPosition()))
630 const Value &Val =
AA.getIRPosition().getAssociatedValue();
635 A.getInfoCache().getMustBeExecutedContextExplorer();
641 for (
const Use &U : Val.
uses())
644 followUsesInContext<AAType>(
AA,
A, *Explorer, &CtxI,
Uses, S);
646 if (S.isAtFixpoint())
690 StateType ParentState;
694 ParentState.indicateOptimisticFixpoint();
696 for (
const BasicBlock *BB : Br->successors()) {
697 StateType ChildState;
699 size_t BeforeSize =
Uses.size();
700 followUsesInContext(
AA,
A, *Explorer, &BB->front(),
Uses, ChildState);
703 for (
auto It =
Uses.begin() + BeforeSize; It !=
Uses.end();)
706 ParentState &= ChildState;
757 R.indicatePessimisticFixpoint();
771 BS.indicateOptimisticFixpoint();
776 BS.indicatePessimisticFixpoint();
846 template <
typename F>
853 if (!
Range.mayOverlap(ItRange))
855 bool IsExact =
Range == ItRange && !
Range.offsetOrSizeAreUnknown();
856 for (
auto Index : It.getSecond()) {
866 template <
typename F>
877 for (
unsigned Index : LocalList->getSecond()) {
880 if (
Range.offsetAndSizeAreUnknown())
896 RemoteI = RemoteI ? RemoteI : &
I;
900 bool AccExists =
false;
902 for (
auto Index : LocalList) {
904 if (
A.getLocalInst() == &
I) {
913 <<
"[AAPointerInfo] Inserting access in new offset bins\n";);
915 for (
auto Key : ToAdd) {
922 AccessList.emplace_back(&
I, RemoteI, Ranges, Content, Kind, Ty);
924 "New Access should have been at AccIndex");
925 LocalList.push_back(AccIndex);
934 auto Before = Current;
936 if (Current == Before)
939 auto &ExistingRanges = Before.getRanges();
940 auto &NewRanges = Current.getRanges();
947 <<
"[AAPointerInfo] Removing access from old offset bins\n";);
954 "Expected bin to actually contain the Access.");
976struct AAPointerInfoImpl
977 :
public StateWrapper<AA::PointerInfo::State, AAPointerInfo> {
981 const std::string getAsStr(
Attributor *
A)
const override {
982 return std::string(
"PointerInfo ") +
983 (isValidState() ? (std::string(
"#") +
984 std::to_string(OffsetBins.size()) +
" bins")
989 [](int64_t O) {
return std::to_string(O); }),
996 return AAPointerInfo::manifest(
A);
999 const_bin_iterator
begin()
const override {
return State::begin(); }
1000 const_bin_iterator
end()
const override {
return State::end(); }
1001 int64_t numOffsetBins()
const override {
return State::numOffsetBins(); }
1002 bool reachesReturn()
const override {
1003 return !ReturnedOffsets.isUnassigned();
1005 void addReturnedOffsetsTo(OffsetInfo &OI)
const override {
1006 if (ReturnedOffsets.isUnknown()) {
1011 OffsetInfo MergedOI;
1012 for (
auto Offset : ReturnedOffsets) {
1013 OffsetInfo TmpOI = OI;
1015 MergedOI.merge(TmpOI);
1017 OI = std::move(MergedOI);
1020 ChangeStatus setReachesReturn(
const OffsetInfo &ReachedReturnedOffsets) {
1021 if (ReturnedOffsets.isUnknown())
1022 return ChangeStatus::UNCHANGED;
1023 if (ReachedReturnedOffsets.isUnknown()) {
1024 ReturnedOffsets.setUnknown();
1025 return ChangeStatus::CHANGED;
1027 if (ReturnedOffsets.merge(ReachedReturnedOffsets))
1028 return ChangeStatus::CHANGED;
1029 return ChangeStatus::UNCHANGED;
1032 bool forallInterferingAccesses(
1034 function_ref<
bool(
const AAPointerInfo::Access &,
bool)> CB)
1036 return State::forallInterferingAccesses(
Range, CB);
1039 bool forallInterferingAccesses(
1040 Attributor &
A,
const AbstractAttribute &QueryingAA, Instruction &
I,
1041 bool FindInterferingWrites,
bool FindInterferingReads,
1042 function_ref<
bool(
const Access &,
bool)> UserCB,
bool &HasBeenWrittenTo,
1044 function_ref<
bool(
const Access &)> SkipCB)
const override {
1045 HasBeenWrittenTo =
false;
1047 SmallPtrSet<const Access *, 8> DominatingWrites;
1055 const auto *ExecDomainAA =
A.lookupAAFor<AAExecutionDomain>(
1057 bool AllInSameNoSyncFn = IsAssumedNoSync;
1058 bool InstIsExecutedByInitialThreadOnly =
1059 ExecDomainAA && ExecDomainAA->isExecutedByInitialThreadOnly(
I);
1066 bool InstIsExecutedInAlignedRegion =
1067 FindInterferingReads && ExecDomainAA &&
1068 ExecDomainAA->isExecutedInAlignedRegion(
A,
I);
1070 if (InstIsExecutedInAlignedRegion || InstIsExecutedByInitialThreadOnly)
1071 A.recordDependence(*ExecDomainAA, QueryingAA, DepClassTy::OPTIONAL);
1073 InformationCache &InfoCache =
A.getInfoCache();
1074 bool IsThreadLocalObj =
1083 auto CanIgnoreThreadingForInst = [&](
const Instruction &
I) ->
bool {
1084 if (IsThreadLocalObj || AllInSameNoSyncFn)
1086 const auto *FnExecDomainAA =
1087 I.getFunction() == &
Scope
1089 :
A.lookupAAFor<AAExecutionDomain>(
1092 if (!FnExecDomainAA)
1094 if (InstIsExecutedInAlignedRegion ||
1095 (FindInterferingWrites &&
1096 FnExecDomainAA->isExecutedInAlignedRegion(
A,
I))) {
1097 A.recordDependence(*FnExecDomainAA, QueryingAA, DepClassTy::OPTIONAL);
1100 if (InstIsExecutedByInitialThreadOnly &&
1101 FnExecDomainAA->isExecutedByInitialThreadOnly(
I)) {
1102 A.recordDependence(*FnExecDomainAA, QueryingAA, DepClassTy::OPTIONAL);
1111 auto CanIgnoreThreading = [&](
const Access &Acc) ->
bool {
1112 return CanIgnoreThreadingForInst(*Acc.getRemoteInst()) ||
1113 (Acc.getRemoteInst() != Acc.getLocalInst() &&
1114 CanIgnoreThreadingForInst(*Acc.getLocalInst()));
1118 bool IsKnownNoRecurse;
1126 bool InstInKernel =
A.getInfoCache().isKernel(Scope);
1127 bool ObjHasKernelLifetime =
false;
1128 const bool UseDominanceReasoning =
1129 FindInterferingWrites && IsKnownNoRecurse;
1130 const DominatorTree *DT =
1139 unsigned VAS =
V->getType()->getPointerAddressSpace();
1150 std::function<bool(
const Function &)> IsLiveInCalleeCB;
1155 const Function *AIFn = AI->getFunction();
1156 ObjHasKernelLifetime =
A.getInfoCache().isKernel(*AIFn);
1157 bool IsKnownNoRecurse;
1160 IsKnownNoRecurse)) {
1161 IsLiveInCalleeCB = [AIFn](
const Function &Fn) {
return AIFn != &Fn; };
1166 ObjHasKernelLifetime = HasKernelLifetime(GV, *GV->getParent());
1167 if (ObjHasKernelLifetime)
1168 IsLiveInCalleeCB = [&
A](
const Function &Fn) {
1169 return !
A.getInfoCache().isKernel(Fn);
1177 auto AccessCB = [&](
const Access &Acc,
bool Exact) {
1178 Function *AccScope = Acc.getRemoteInst()->getFunction();
1179 bool AccInSameScope = AccScope == &
Scope;
1183 if (InstInKernel && ObjHasKernelLifetime && !AccInSameScope &&
1184 A.getInfoCache().isKernel(*AccScope))
1187 if (Exact && Acc.isMustAccess() && Acc.getRemoteInst() != &
I) {
1188 if (Acc.isWrite() || (
isa<LoadInst>(
I) && Acc.isWriteOrAssumption()))
1189 ExclusionSet.
insert(Acc.getRemoteInst());
1192 if ((!FindInterferingWrites || !Acc.isWriteOrAssumption()) &&
1193 (!FindInterferingReads || !Acc.isRead()))
1196 bool Dominates = FindInterferingWrites && DT &&
Exact &&
1197 Acc.isMustAccess() && AccInSameScope &&
1200 DominatingWrites.
insert(&Acc);
1204 AllInSameNoSyncFn &= Acc.getRemoteInst()->getFunction() == &
Scope;
1209 if (!State::forallInterferingAccesses(
I, AccessCB,
Range))
1212 HasBeenWrittenTo = !DominatingWrites.
empty();
1216 for (
const Access *Acc : DominatingWrites) {
1217 if (!LeastDominatingWriteInst) {
1218 LeastDominatingWriteInst = Acc->getRemoteInst();
1219 }
else if (DT->
dominates(LeastDominatingWriteInst,
1220 Acc->getRemoteInst())) {
1221 LeastDominatingWriteInst = Acc->getRemoteInst();
1226 auto CanSkipAccess = [&](
const Access &Acc,
bool Exact) {
1227 if (SkipCB && SkipCB(Acc))
1229 if (!CanIgnoreThreading(Acc))
1235 bool ReadChecked = !FindInterferingReads;
1236 bool WriteChecked = !FindInterferingWrites;
1242 &ExclusionSet, IsLiveInCalleeCB))
1247 if (!WriteChecked) {
1249 &ExclusionSet, IsLiveInCalleeCB))
1250 WriteChecked =
true;
1264 if (!WriteChecked && HasBeenWrittenTo &&
1265 Acc.getRemoteInst()->getFunction() != &Scope) {
1267 const auto *FnReachabilityAA =
A.getAAFor<AAInterFnReachability>(
1269 if (FnReachabilityAA) {
1275 if (!FnReachabilityAA->instructionCanReach(
1276 A, *LeastDominatingWriteInst,
1277 *Acc.getRemoteInst()->getFunction()))
1278 WriteChecked =
true;
1282 if (ReadChecked && WriteChecked)
1285 if (!DT || !UseDominanceReasoning)
1287 if (!DominatingWrites.count(&Acc))
1289 return LeastDominatingWriteInst != Acc.getRemoteInst();
1294 for (
auto &It : InterferingAccesses) {
1295 if ((!AllInSameNoSyncFn && !IsThreadLocalObj && !ExecDomainAA) ||
1296 !CanSkipAccess(*It.first, It.second)) {
1297 if (!UserCB(*It.first, It.second))
1305 const AAPointerInfo &OtherAA,
1307 using namespace AA::PointerInfo;
1309 return indicatePessimisticFixpoint();
1312 const auto &OtherAAImpl =
static_cast<const AAPointerInfoImpl &
>(OtherAA);
1313 bool IsByval = OtherAAImpl.getAssociatedArgument()->hasByValAttr();
1314 Changed |= setReachesReturn(OtherAAImpl.ReturnedOffsets);
1317 const auto &State = OtherAAImpl.getState();
1318 for (
const auto &It : State) {
1319 for (
auto Index : It.getSecond()) {
1320 const auto &RAcc = State.getAccess(Index);
1321 if (IsByval && !RAcc.isRead())
1323 bool UsedAssumedInformation =
false;
1325 auto Content =
A.translateArgumentToCallSiteContent(
1326 RAcc.getContent(), CB, *
this, UsedAssumedInformation);
1327 AK =
AccessKind(AK & (IsByval ? AccessKind::AK_R : AccessKind::AK_RW));
1328 AK =
AccessKind(AK | (RAcc.isMayAccess() ? AK_MAY : AK_MUST));
1330 Changed |= addAccess(
A, RAcc.getRanges(), CB, Content, AK,
1331 RAcc.getType(), RAcc.getRemoteInst());
1337 ChangeStatus translateAndAddState(Attributor &
A,
const AAPointerInfo &OtherAA,
1338 const OffsetInfo &Offsets, CallBase &CB,
1340 using namespace AA::PointerInfo;
1342 return indicatePessimisticFixpoint();
1344 const auto &OtherAAImpl =
static_cast<const AAPointerInfoImpl &
>(OtherAA);
1348 const auto &State = OtherAAImpl.getState();
1349 for (
const auto &It : State) {
1350 for (
auto Index : It.getSecond()) {
1351 const auto &RAcc = State.getAccess(Index);
1352 if (!IsMustAcc && RAcc.isAssumption())
1354 for (
auto Offset : Offsets) {
1358 if (!NewRanges.isUnknown()) {
1359 NewRanges.addToAllOffsets(Offset);
1364 Changed |= addAccess(
A, NewRanges, CB, RAcc.getContent(), AK,
1365 RAcc.getType(), RAcc.getRemoteInst());
1373 void trackPointerInfoStatistics(
const IRPosition &IRP)
const {}
1376 void dumpState(raw_ostream &O) {
1377 for (
auto &It : OffsetBins) {
1378 O <<
"[" << It.first.Offset <<
"-" << It.first.Offset + It.first.Size
1379 <<
"] : " << It.getSecond().size() <<
"\n";
1380 for (
auto AccIndex : It.getSecond()) {
1381 auto &Acc = AccessList[AccIndex];
1382 O <<
" - " << Acc.getKind() <<
" - " << *Acc.getLocalInst() <<
"\n";
1383 if (Acc.getLocalInst() != Acc.getRemoteInst())
1384 O <<
" --> " << *Acc.getRemoteInst()
1386 if (!Acc.isWrittenValueYetUndetermined()) {
1388 O <<
" - c: func " << Acc.getWrittenValue()->getName()
1390 else if (Acc.getWrittenValue())
1391 O <<
" - c: " << *Acc.getWrittenValue() <<
"\n";
1393 O <<
" - c: <unknown>\n";
1400struct AAPointerInfoFloating :
public AAPointerInfoImpl {
1402 AAPointerInfoFloating(
const IRPosition &IRP, Attributor &
A)
1403 : AAPointerInfoImpl(IRP,
A) {}
1406 bool handleAccess(Attributor &
A, Instruction &
I,
1407 std::optional<Value *> Content,
AccessKind Kind,
1410 using namespace AA::PointerInfo;
1412 const DataLayout &
DL =
A.getDataLayout();
1413 TypeSize AccessSize =
DL.getTypeStoreSize(&Ty);
1422 if (!VT || VT->getElementCount().isScalable() ||
1424 (*Content)->getType() != VT ||
1425 DL.getTypeStoreSize(VT->getElementType()).isScalable()) {
1436 int64_t ElementSize =
DL.getTypeStoreSize(ElementType).getFixedValue();
1440 OffsetsSorted.end());
1442 for (
int i = 0, e = VT->getElementCount().getFixedValue(); i != e; ++i) {
1444 ConstContent, ConstantInt::get(Int32Ty, i));
1451 for (
auto &ElementOffset : ElementOffsets)
1452 ElementOffset += ElementSize;
1464 bool collectConstantsForGEP(Attributor &
A,
const DataLayout &
DL,
1465 OffsetInfo &UsrOI,
const OffsetInfo &PtrOI,
1466 const GEPOperator *
GEP);
1468 void trackStatistics()
const override {
1469 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1473bool AAPointerInfoFloating::collectConstantsForGEP(Attributor &
A,
1474 const DataLayout &
DL,
1476 const OffsetInfo &PtrOI,
1477 const GEPOperator *
GEP) {
1478 unsigned BitWidth =
DL.getIndexTypeSizeInBits(
GEP->getType());
1479 SmallMapVector<Value *, APInt, 4> VariableOffsets;
1482 assert(!UsrOI.isUnknown() && !PtrOI.isUnknown() &&
1483 "Don't look for constant values if the offset has already been "
1484 "determined to be unknown.");
1486 if (!
GEP->collectOffset(
DL,
BitWidth, VariableOffsets, ConstantOffset)) {
1492 << (VariableOffsets.
empty() ?
"" :
"not") <<
" constant "
1496 Union.addToAll(ConstantOffset.getSExtValue());
1501 for (
const auto &VI : VariableOffsets) {
1502 auto *PotentialConstantsAA =
A.getAAFor<AAPotentialConstantValues>(
1504 if (!PotentialConstantsAA || !PotentialConstantsAA->isValidState()) {
1510 if (PotentialConstantsAA->undefIsContained())
1517 auto &AssumedSet = PotentialConstantsAA->getAssumedSet();
1518 if (AssumedSet.empty())
1522 for (
const auto &ConstOffset : AssumedSet) {
1523 auto CopyPerOffset =
Union;
1524 CopyPerOffset.addToAll(ConstOffset.getSExtValue() *
1525 VI.second.getZExtValue());
1526 Product.merge(CopyPerOffset);
1531 UsrOI = std::move(Union);
1535ChangeStatus AAPointerInfoFloating::updateImpl(Attributor &
A) {
1536 using namespace AA::PointerInfo;
1538 const DataLayout &
DL =
A.getDataLayout();
1539 Value &AssociatedValue = getAssociatedValue();
1541 DenseMap<Value *, OffsetInfo> OffsetInfoMap;
1542 OffsetInfoMap[&AssociatedValue].
insert(0);
1544 auto HandlePassthroughUser = [&](
Value *Usr,
Value *CurPtr,
bool &Follow) {
1555 "CurPtr does not exist in the map!");
1557 auto &UsrOI = OffsetInfoMap[Usr];
1558 auto &PtrOI = OffsetInfoMap[CurPtr];
1559 assert(!PtrOI.isUnassigned() &&
1560 "Cannot pass through if the input Ptr was not visited!");
1566 auto UsePred = [&](
const Use &
U,
bool &Follow) ->
bool {
1568 User *Usr =
U.getUser();
1569 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] Analyze " << *CurPtr <<
" in " << *Usr
1572 "The current pointer offset should have been seeded!");
1573 assert(!OffsetInfoMap[CurPtr].isUnassigned() &&
1574 "Current pointer should be assigned");
1580 return HandlePassthroughUser(Usr, CurPtr, Follow);
1585 auto &UsrOI = OffsetInfoMap[Usr];
1586 auto &PtrOI = OffsetInfoMap[CurPtr];
1588 if (UsrOI.isUnknown())
1591 if (PtrOI.isUnknown()) {
1597 Follow = collectConstantsForGEP(
A,
DL, UsrOI, PtrOI,
GEP);
1601 return HandlePassthroughUser(Usr, CurPtr, Follow);
1606 if (RI->getFunction() == getAssociatedFunction()) {
1607 auto &PtrOI = OffsetInfoMap[CurPtr];
1608 Changed |= setReachesReturn(PtrOI);
1621 auto &UsrOI = PhiIt->second;
1622 auto &PtrOI = OffsetInfoMap[CurPtr];
1626 if (PtrOI.isUnknown()) {
1627 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] PHI operand offset unknown "
1628 << *CurPtr <<
" in " << *
PHI <<
"\n");
1629 Follow = !UsrOI.isUnknown();
1635 if (UsrOI == PtrOI) {
1636 assert(!PtrOI.isUnassigned() &&
1637 "Cannot assign if the current Ptr was not visited!");
1638 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] PHI is invariant (so far)");
1648 auto It = OffsetInfoMap.
find(CurPtrBase);
1649 if (It == OffsetInfoMap.
end()) {
1650 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] PHI operand is too complex "
1651 << *CurPtr <<
" in " << *
PHI
1652 <<
" (base: " << *CurPtrBase <<
")\n");
1666 A.getInfoCache().getAnalysisResultForFunction<CycleAnalysis>(
1667 *
PHI->getFunction());
1669 auto BaseOI = It->getSecond();
1670 BaseOI.addToAll(
Offset.getZExtValue());
1671 if (IsFirstPHIUser || BaseOI == UsrOI) {
1672 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] PHI is invariant " << *CurPtr
1673 <<
" in " << *Usr <<
"\n");
1674 return HandlePassthroughUser(Usr, CurPtr, Follow);
1678 dbgs() <<
"[AAPointerInfo] PHI operand pointer offset mismatch "
1679 << *CurPtr <<
" in " << *
PHI <<
"\n");
1698 if (!handleAccess(
A, *LoadI,
nullptr, AK,
1699 OffsetInfoMap[CurPtr].Offsets,
Changed,
1705 return II->isAssumeLikeIntrinsic();
1716 }
while (FromI && FromI != ToI);
1721 auto IsValidAssume = [&](IntrinsicInst &IntrI) {
1722 if (IntrI.getIntrinsicID() != Intrinsic::assume)
1725 if (IntrI.getParent() == BB) {
1726 if (IsImpactedInRange(LoadI->getNextNode(), &IntrI))
1732 if ((*PredIt) != BB)
1737 if (SuccBB == IntrBB)
1743 if (IsImpactedInRange(LoadI->getNextNode(), BB->
getTerminator()))
1745 if (IsImpactedInRange(&IntrBB->
front(), &IntrI))
1751 std::pair<Value *, IntrinsicInst *>
Assumption;
1752 for (
const Use &LoadU : LoadI->uses()) {
1754 if (!CmpI->isEquality() || !CmpI->isTrueWhenEqual())
1756 for (Instruction *CmpUser : CmpI->users()) {
1758 if (!IsValidAssume(*IntrI))
1760 int Idx = CmpI->getOperandUse(0) == LoadU;
1777 bool UsedAssumedInformation =
false;
1778 std::optional<Value *> Content =
nullptr;
1783 return handleAccess(
1784 A, *
Assumption.second, Content, AccessKind::AK_ASSUMPTION,
1785 OffsetInfoMap[CurPtr].Offsets,
Changed, *LoadI->getType());
1790 for (
auto *OtherOp : OtherOps) {
1791 if (OtherOp == CurPtr) {
1794 <<
"[AAPointerInfo] Escaping use in store like instruction " <<
I
1806 bool UsedAssumedInformation =
false;
1807 std::optional<Value *> Content =
nullptr;
1809 Content =
A.getAssumedSimplified(
1811 return handleAccess(
A,
I, Content, AK, OffsetInfoMap[CurPtr].Offsets,
1816 return HandleStoreLike(*StoreI, StoreI->getValueOperand(),
1817 *StoreI->getValueOperand()->getType(),
1818 {StoreI->getValueOperand()}, AccessKind::AK_W);
1820 return HandleStoreLike(*RMWI,
nullptr, *RMWI->getValOperand()->getType(),
1821 {RMWI->getValOperand()}, AccessKind::AK_RW);
1823 return HandleStoreLike(
1824 *CXI,
nullptr, *CXI->getNewValOperand()->getType(),
1825 {CXI->getCompareOperand(), CXI->getNewValOperand()},
1835 const auto *CSArgPI =
A.getAAFor<AAPointerInfo>(
1841 Changed = translateAndAddState(
A, *CSArgPI, OffsetInfoMap[CurPtr], *CB,
1844 if (!CSArgPI->reachesReturn())
1845 return isValidState();
1848 if (!Callee ||
Callee->arg_size() <= ArgNo)
1850 bool UsedAssumedInformation =
false;
1851 auto ReturnedValue =
A.getAssumedSimplified(
1856 auto *Arg =
Callee->getArg(ArgNo);
1857 if (ReturnedArg && Arg != ReturnedArg)
1859 bool IsRetMustAcc = IsArgMustAcc && (ReturnedArg == Arg);
1860 const auto *CSRetPI =
A.getAAFor<AAPointerInfo>(
1864 OffsetInfo OI = OffsetInfoMap[CurPtr];
1865 CSArgPI->addReturnedOffsetsTo(OI);
1867 translateAndAddState(
A, *CSRetPI, OI, *CB, IsRetMustAcc) |
Changed;
1868 return isValidState();
1870 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] Call user not handled " << *CB
1875 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] User not handled " << *Usr <<
"\n");
1878 auto EquivalentUseCB = [&](
const Use &OldU,
const Use &NewU) {
1879 assert(OffsetInfoMap.
count(OldU) &&
"Old use should be known already!");
1880 assert(!OffsetInfoMap[OldU].isUnassigned() &&
"Old use should be assinged");
1881 if (OffsetInfoMap.
count(NewU)) {
1883 if (!(OffsetInfoMap[NewU] == OffsetInfoMap[OldU])) {
1884 dbgs() <<
"[AAPointerInfo] Equivalent use callback failed: "
1885 << OffsetInfoMap[NewU] <<
" vs " << OffsetInfoMap[OldU]
1889 return OffsetInfoMap[NewU] == OffsetInfoMap[OldU];
1892 return HandlePassthroughUser(NewU.get(), OldU.
get(), Unused);
1894 if (!
A.checkForAllUses(UsePred, *
this, AssociatedValue,
1896 true, EquivalentUseCB)) {
1897 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] Check for all uses failed, abort!\n");
1898 return indicatePessimisticFixpoint();
1902 dbgs() <<
"Accesses by bin after update:\n";
1909struct AAPointerInfoReturned final : AAPointerInfoImpl {
1910 AAPointerInfoReturned(
const IRPosition &IRP, Attributor &
A)
1911 : AAPointerInfoImpl(IRP,
A) {}
1914 return indicatePessimisticFixpoint();
1917 void trackStatistics()
const override {
1918 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1922struct AAPointerInfoArgument final : AAPointerInfoFloating {
1923 AAPointerInfoArgument(
const IRPosition &IRP, Attributor &
A)
1924 : AAPointerInfoFloating(IRP,
A) {}
1926 void trackStatistics()
const override {
1927 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1931struct AAPointerInfoCallSiteArgument final : AAPointerInfoFloating {
1932 AAPointerInfoCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
1933 : AAPointerInfoFloating(IRP,
A) {}
1936 using namespace AA::PointerInfo;
1942 if (
auto Length =
MI->getLengthInBytes())
1943 LengthVal =
Length->getSExtValue();
1944 unsigned ArgNo = getIRPosition().getCallSiteArgNo();
1947 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] Unhandled memory intrinsic "
1949 return indicatePessimisticFixpoint();
1952 ArgNo == 0 ? AccessKind::AK_MUST_WRITE : AccessKind::AK_MUST_READ;
1954 Changed | addAccess(
A, {0, LengthVal}, *
MI,
nullptr,
Kind,
nullptr);
1957 dbgs() <<
"Accesses by bin after update:\n";
1968 Argument *Arg = getAssociatedArgument();
1972 A.getAAFor<AAPointerInfo>(*
this, ArgPos, DepClassTy::REQUIRED);
1973 if (ArgAA && ArgAA->getState().isValidState())
1974 return translateAndAddStateFromCallee(
A, *ArgAA,
1977 return indicatePessimisticFixpoint();
1980 bool IsKnownNoCapture;
1982 A,
this, getIRPosition(), DepClassTy::OPTIONAL, IsKnownNoCapture))
1983 return indicatePessimisticFixpoint();
1985 bool IsKnown =
false;
1987 return ChangeStatus::UNCHANGED;
1990 ReadOnly ? AccessKind::AK_MAY_READ : AccessKind::AK_MAY_READ_WRITE;
1995 void trackStatistics()
const override {
1996 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
2000struct AAPointerInfoCallSiteReturned final : AAPointerInfoFloating {
2001 AAPointerInfoCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
2002 : AAPointerInfoFloating(IRP,
A) {}
2004 void trackStatistics()
const override {
2005 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
2013struct AANoUnwindImpl : AANoUnwind {
2014 AANoUnwindImpl(
const IRPosition &IRP, Attributor &
A) : AANoUnwind(IRP,
A) {}
2019 A,
nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2023 const std::string getAsStr(Attributor *
A)
const override {
2024 return getAssumed() ?
"nounwind" :
"may-unwind";
2029 (unsigned)Instruction::Invoke, (
unsigned)Instruction::CallBr,
2030 (unsigned)Instruction::Call, (
unsigned)Instruction::CleanupRet,
2031 (unsigned)Instruction::CatchSwitch, (
unsigned)Instruction::Resume};
2034 if (!
I.mayThrow(
true))
2038 bool IsKnownNoUnwind;
2046 bool UsedAssumedInformation =
false;
2047 if (!
A.checkForAllInstructions(CheckForNoUnwind, *
this, Opcodes,
2048 UsedAssumedInformation))
2049 return indicatePessimisticFixpoint();
2051 return ChangeStatus::UNCHANGED;
2055struct AANoUnwindFunction final :
public AANoUnwindImpl {
2056 AANoUnwindFunction(
const IRPosition &IRP, Attributor &
A)
2057 : AANoUnwindImpl(IRP,
A) {}
2063struct AANoUnwindCallSite final
2064 : AACalleeToCallSite<AANoUnwind, AANoUnwindImpl> {
2065 AANoUnwindCallSite(
const IRPosition &IRP, Attributor &
A)
2066 : AACalleeToCallSite<AANoUnwind, AANoUnwindImpl>(IRP,
A) {}
2076 case Intrinsic::nvvm_barrier_cta_sync_aligned_all:
2077 case Intrinsic::nvvm_barrier_cta_sync_aligned_count:
2078 case Intrinsic::nvvm_barrier_cta_red_and_aligned_all:
2079 case Intrinsic::nvvm_barrier_cta_red_and_aligned_count:
2080 case Intrinsic::nvvm_barrier_cta_red_or_aligned_all:
2081 case Intrinsic::nvvm_barrier_cta_red_or_aligned_count:
2082 case Intrinsic::nvvm_barrier_cta_red_popc_aligned_all:
2083 case Intrinsic::nvvm_barrier_cta_red_popc_aligned_count:
2085 case Intrinsic::amdgcn_s_barrier:
2086 if (ExecutedAligned)
2109 switch (
I->getOpcode()) {
2110 case Instruction::AtomicRMW:
2113 case Instruction::Store:
2116 case Instruction::Load:
2121 "New atomic operations need to be known in the attributor.");
2139 const std::string getAsStr(Attributor *
A)
const override {
2140 return getAssumed() ?
"nosync" :
"may-sync";
2155 if (
I.mayReadOrWriteMemory())
2169 bool UsedAssumedInformation =
false;
2170 if (!
A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *
this,
2171 UsedAssumedInformation) ||
2172 !
A.checkForAllCallLikeInstructions(CheckForNoSync, *
this,
2173 UsedAssumedInformation))
2174 return indicatePessimisticFixpoint();
2179struct AANoSyncFunction final :
public AANoSyncImpl {
2180 AANoSyncFunction(
const IRPosition &IRP, Attributor &
A)
2181 : AANoSyncImpl(IRP,
A) {}
2187struct AANoSyncCallSite final : AACalleeToCallSite<AANoSync, AANoSyncImpl> {
2188 AANoSyncCallSite(
const IRPosition &IRP, Attributor &
A)
2189 : AACalleeToCallSite<AANoSync, AANoSyncImpl>(IRP,
A) {}
2198struct AANoFreeImpl :
public AANoFree {
2199 AANoFreeImpl(
const IRPosition &IRP, Attributor &
A) : AANoFree(IRP,
A) {}
2204 DepClassTy::NONE, IsKnown));
2221 bool UsedAssumedInformation =
false;
2222 if (!
A.checkForAllReadWriteInstructions(CheckForNoFree, *
this,
2223 UsedAssumedInformation) ||
2224 !
A.checkForAllCallLikeInstructions(CheckForNoFree, *
this,
2225 UsedAssumedInformation))
2226 return indicatePessimisticFixpoint();
2228 return ChangeStatus::UNCHANGED;
2231 const std::string getAsStr(Attributor *
A)
const override {
2232 return getAssumed() ?
"nofree" :
"may-free";
2236struct AANoFreeFunction final :
public AANoFreeImpl {
2237 AANoFreeFunction(
const IRPosition &IRP, Attributor &
A)
2238 : AANoFreeImpl(IRP,
A) {}
2244struct AANoFreeCallSite final : AACalleeToCallSite<AANoFree, AANoFreeImpl> {
2245 AANoFreeCallSite(
const IRPosition &IRP, Attributor &
A)
2246 : AACalleeToCallSite<AANoFree, AANoFreeImpl>(IRP,
A) {}
2252struct AANoFreeFloating : AANoFreeImpl {
2253 AANoFreeFloating(
const IRPosition &IRP, Attributor &
A)
2254 : AANoFreeImpl(IRP,
A) {}
2260 const IRPosition &IRP = getIRPosition();
2265 DepClassTy::OPTIONAL, IsKnown))
2266 return ChangeStatus::UNCHANGED;
2268 Value &AssociatedValue = getIRPosition().getAssociatedValue();
2269 auto Pred = [&](
const Use &
U,
bool &Follow) ->
bool {
2284 DepClassTy::REQUIRED, IsKnown))
2287 const AANoCapture *NoCaptureAA =
nullptr;
2290 DepClassTy::REQUIRED, IsKnown,
2291 false, &NoCaptureAA)) {
2316 if (!
A.checkForAllUses(
Pred, *
this, AssociatedValue))
2317 return indicatePessimisticFixpoint();
2319 return ChangeStatus::UNCHANGED;
2324struct AANoFreeArgument final : AANoFreeFloating {
2325 AANoFreeArgument(
const IRPosition &IRP, Attributor &
A)
2326 : AANoFreeFloating(IRP,
A) {}
2332struct AANoFreeCallSiteArgument final : AANoFreeFloating {
2333 AANoFreeCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
2334 : AANoFreeFloating(IRP,
A) {}
2341 Argument *Arg = getAssociatedArgument();
2343 return indicatePessimisticFixpoint();
2347 DepClassTy::REQUIRED, IsKnown))
2348 return ChangeStatus::UNCHANGED;
2349 return indicatePessimisticFixpoint();
2356struct AANoFreeReturned final : AANoFreeFloating {
2357 AANoFreeReturned(
const IRPosition &IRP, Attributor &
A)
2358 : AANoFreeFloating(IRP,
A) {
2370 void trackStatistics()
const override {}
2374struct AANoFreeCallSiteReturned final : AANoFreeFloating {
2375 AANoFreeCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
2376 : AANoFreeFloating(IRP,
A) {}
2379 return ChangeStatus::UNCHANGED;
2389 bool IgnoreSubsumingPositions) {
2391 AttrKinds.
push_back(Attribute::NonNull);
2394 AttrKinds.
push_back(Attribute::Dereferenceable);
2395 if (
A.hasAttr(IRP, AttrKinds, IgnoreSubsumingPositions, Attribute::NonNull))
2398 if (!
A.canUseBodyFor(IRP))
2405 if (!Fn->isDeclaration()) {
2415 bool UsedAssumedInformation =
false;
2416 if (!
A.checkForAllInstructions(
2418 Worklist.push_back({*cast<ReturnInst>(I).getReturnValue(), &I});
2422 UsedAssumedInformation,
false,
true))
2434 Attribute::NonNull)});
2439static int64_t getKnownNonNullAndDerefBytesForUse(
2440 Attributor &
A,
const AbstractAttribute &QueryingAA,
Value &AssociatedValue,
2441 const Use *U,
const Instruction *
I,
bool &IsNonNull,
bool &TrackUse) {
2444 const Value *UseV =
U->get();
2465 const DataLayout &
DL =
A.getInfoCache().getDL();
2470 case BundleAttr::NonNull:
2473 case BundleAttr::Dereferenceable: {
2477 return CI->getZExtValue();
2494 bool IsKnownNonNull;
2497 IsNonNull |= IsKnownNonNull;
2500 return DerefAA ? DerefAA->getKnownDereferenceableBytes() : 0;
2504 if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() ||
2505 Loc->Size.isScalable() ||
I->isVolatile())
2511 if (
Base &&
Base == &AssociatedValue) {
2512 int64_t DerefBytes = Loc->Size.getValue() +
Offset;
2514 return std::max(int64_t(0), DerefBytes);
2521 int64_t DerefBytes = Loc->Size.getValue();
2523 return std::max(int64_t(0), DerefBytes);
2529struct AANonNullImpl : AANonNull {
2530 AANonNullImpl(
const IRPosition &IRP, Attributor &
A) : AANonNull(IRP,
A) {}
2533 Value &
V = *getAssociatedValue().stripPointerCasts();
2535 indicatePessimisticFixpoint();
2539 if (Instruction *CtxI = getCtxI())
2540 followUsesInMBEC(*
this,
A, getState(), *CtxI);
2544 bool followUseInMBEC(Attributor &
A,
const Use *U,
const Instruction *
I,
2545 AANonNull::StateType &State) {
2546 bool IsNonNull =
false;
2547 bool TrackUse =
false;
2548 getKnownNonNullAndDerefBytesForUse(
A, *
this, getAssociatedValue(), U,
I,
2549 IsNonNull, TrackUse);
2550 State.setKnown(IsNonNull);
2554 const std::string getAsStr(Attributor *
A)
const override {
2555 return getAssumed() ?
"nonnull" :
"may-null";
2560struct AANonNullFloating :
public AANonNullImpl {
2561 AANonNullFloating(
const IRPosition &IRP, Attributor &
A)
2562 : AANonNullImpl(IRP,
A) {}
2565 auto CheckIRP = [&](
const IRPosition &IRP) {
2566 bool IsKnownNonNull;
2568 A, *
this, IRP, DepClassTy::OPTIONAL, IsKnownNonNull);
2572 bool UsedAssumedInformation =
false;
2573 Value *AssociatedValue = &getAssociatedValue();
2575 if (!
A.getAssumedSimplifiedValues(getIRPosition(), *
this,
Values,
2580 Values.size() != 1 ||
Values.front().getValue() != AssociatedValue;
2586 return AA::hasAssumedIRAttr<Attribute::NonNull>(
2587 A, this, IRPosition::value(*Op), DepClassTy::OPTIONAL,
2590 return ChangeStatus::UNCHANGED;
2594 DepClassTy::OPTIONAL, IsKnown) &&
2597 DepClassTy::OPTIONAL, IsKnown))
2598 return ChangeStatus::UNCHANGED;
2605 if (AVIRP == getIRPosition() || !CheckIRP(AVIRP))
2606 return indicatePessimisticFixpoint();
2607 return ChangeStatus::UNCHANGED;
2610 for (
const auto &VAC :
Values)
2612 return indicatePessimisticFixpoint();
2614 return ChangeStatus::UNCHANGED;
2621struct AANonNullReturned final
2622 : AAReturnedFromReturnedValues<AANonNull, AANonNull, AANonNull::StateType,
2623 false, AANonNull::IRAttributeKind, false> {
2624 AANonNullReturned(
const IRPosition &IRP, Attributor &
A)
2625 : AAReturnedFromReturnedValues<AANonNull, AANonNull, AANonNull::StateType,
2629 const std::string getAsStr(Attributor *
A)
const override {
2630 return getAssumed() ?
"nonnull" :
"may-null";
2637struct AANonNullArgument final
2638 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> {
2639 AANonNullArgument(
const IRPosition &IRP, Attributor &
A)
2640 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP,
A) {}
2645struct AANonNullCallSiteArgument final : AANonNullFloating {
2646 AANonNullCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
2647 : AANonNullFloating(IRP,
A) {}
2653struct AANonNullCallSiteReturned final
2654 : AACalleeToCallSite<AANonNull, AANonNullImpl> {
2655 AANonNullCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
2656 : AACalleeToCallSite<AANonNull, AANonNullImpl>(IRP,
A) {}
2664struct AAMustProgressImpl :
public AAMustProgress {
2665 AAMustProgressImpl(
const IRPosition &IRP, Attributor &
A)
2666 : AAMustProgress(IRP,
A) {}
2671 A,
nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2675 const std::string getAsStr(Attributor *
A)
const override {
2676 return getAssumed() ?
"mustprogress" :
"may-not-progress";
2680struct AAMustProgressFunction final : AAMustProgressImpl {
2681 AAMustProgressFunction(
const IRPosition &IRP, Attributor &
A)
2682 : AAMustProgressImpl(IRP,
A) {}
2687 A,
this, getIRPosition(), DepClassTy::OPTIONAL, IsKnown)) {
2689 return indicateOptimisticFixpoint();
2690 return ChangeStatus::UNCHANGED;
2693 auto CheckForMustProgress = [&](AbstractCallSite ACS) {
2695 bool IsKnownMustProgress;
2697 A,
this, IPos, DepClassTy::REQUIRED, IsKnownMustProgress,
2701 bool AllCallSitesKnown =
true;
2702 if (!
A.checkForAllCallSites(CheckForMustProgress, *
this,
2705 return indicatePessimisticFixpoint();
2707 return ChangeStatus::UNCHANGED;
2710 void trackStatistics()
const override {
2716struct AAMustProgressCallSite final : AAMustProgressImpl {
2717 AAMustProgressCallSite(
const IRPosition &IRP, Attributor &
A)
2718 : AAMustProgressImpl(IRP,
A) {}
2726 bool IsKnownMustProgress;
2728 A,
this, FnPos, DepClassTy::REQUIRED, IsKnownMustProgress))
2729 return indicatePessimisticFixpoint();
2730 return ChangeStatus::UNCHANGED;
2733 void trackStatistics()
const override {
2742struct AANoRecurseImpl :
public AANoRecurse {
2743 AANoRecurseImpl(
const IRPosition &IRP, Attributor &
A) : AANoRecurse(IRP,
A) {}
2748 A,
nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2752 const std::string getAsStr(Attributor *
A)
const override {
2753 return getAssumed() ?
"norecurse" :
"may-recurse";
2757struct AANoRecurseFunction final : AANoRecurseImpl {
2758 AANoRecurseFunction(
const IRPosition &IRP, Attributor &
A)
2759 : AANoRecurseImpl(IRP,
A) {}
2764 auto CallSitePred = [&](AbstractCallSite ACS) {
2765 bool IsKnownNoRecurse;
2769 DepClassTy::NONE, IsKnownNoRecurse))
2771 return IsKnownNoRecurse;
2773 bool UsedAssumedInformation =
false;
2774 if (
A.checkForAllCallSites(CallSitePred, *
this,
true,
2775 UsedAssumedInformation)) {
2781 if (!UsedAssumedInformation)
2782 indicateOptimisticFixpoint();
2783 return ChangeStatus::UNCHANGED;
2786 const AAInterFnReachability *EdgeReachability =
2787 A.getAAFor<AAInterFnReachability>(*
this, getIRPosition(),
2788 DepClassTy::REQUIRED);
2789 if (EdgeReachability && EdgeReachability->
canReach(
A, *getAnchorScope()))
2790 return indicatePessimisticFixpoint();
2791 return ChangeStatus::UNCHANGED;
2798struct AANoRecurseCallSite final
2799 : AACalleeToCallSite<AANoRecurse, AANoRecurseImpl> {
2800 AANoRecurseCallSite(
const IRPosition &IRP, Attributor &
A)
2801 : AACalleeToCallSite<AANoRecurse, AANoRecurseImpl>(IRP,
A) {}
2810struct AANonConvergentImpl :
public AANonConvergent {
2811 AANonConvergentImpl(
const IRPosition &IRP, Attributor &
A)
2812 : AANonConvergent(IRP,
A) {}
2814 const std::string getAsStr(Attributor *
A)
const override {
2815 return getAssumed() ?
"non-convergent" :
"may-be-convergent";
2819struct AANonConvergentFunction final : AANonConvergentImpl {
2820 AANonConvergentFunction(
const IRPosition &IRP, Attributor &
A)
2821 : AANonConvergentImpl(IRP,
A) {}
2826 auto CalleeIsNotConvergent = [&](
Instruction &Inst) {
2829 if (!Callee ||
Callee->isIntrinsic()) {
2832 if (
Callee->isDeclaration()) {
2833 return !
Callee->hasFnAttribute(Attribute::Convergent);
2835 const auto *ConvergentAA =
A.getAAFor<AANonConvergent>(
2837 return ConvergentAA && ConvergentAA->isAssumedNotConvergent();
2840 bool UsedAssumedInformation =
false;
2841 if (!
A.checkForAllCallLikeInstructions(CalleeIsNotConvergent, *
this,
2842 UsedAssumedInformation)) {
2843 return indicatePessimisticFixpoint();
2845 return ChangeStatus::UNCHANGED;
2849 if (isKnownNotConvergent() &&
2850 A.hasAttr(getIRPosition(), Attribute::Convergent)) {
2851 A.removeAttrs(getIRPosition(), {Attribute::Convergent});
2852 return ChangeStatus::CHANGED;
2854 return ChangeStatus::UNCHANGED;
2864struct AAUndefinedBehaviorImpl :
public AAUndefinedBehavior {
2865 AAUndefinedBehaviorImpl(
const IRPosition &IRP, Attributor &
A)
2866 : AAUndefinedBehavior(IRP,
A) {}
2872 UndefBranchCondition,
2874 NullReturnViolatesNonNull,
2876 NullArgViolatesNonNull,
2880 std::optional<unsigned> ArgNo;
2882 UBInfo(Kind K) :
K(
K), ArgNo(std::nullopt) {}
2884 UBInfo(Kind K, std::optional<unsigned> ArgNo) :
K(
K), ArgNo(ArgNo) {}
2888 const size_t UBPrevSize = KnownUBInsts.size();
2889 const size_t NoUBPrevSize = AssumedNoUBInsts.size();
2897 if (AssumedNoUBInsts.count(&
I) || KnownUBInsts.count(&
I))
2906 "Expected pointer operand of memory accessing instruction");
2910 std::optional<Value *> SimplifiedPtrOp =
2911 stopOnUndefOrAssumed(
A, PtrOp, &
I, UBInfo::UndefPtrAccess);
2912 if (!SimplifiedPtrOp || !*SimplifiedPtrOp)
2914 const Value *PtrOpVal = *SimplifiedPtrOp;
2920 AssumedNoUBInsts.insert(&
I);
2932 AssumedNoUBInsts.insert(&
I);
2934 KnownUBInsts.try_emplace(&
I, UBInfo::NullPtrAccess);
2943 if (AssumedNoUBInsts.count(&
I) || KnownUBInsts.count(&
I))
2951 std::optional<Value *> SimplifiedCond = stopOnUndefOrAssumed(
2952 A, BrInst->getCondition(), BrInst, UBInfo::UndefBranchCondition);
2953 if (!SimplifiedCond || !*SimplifiedCond)
2955 AssumedNoUBInsts.insert(&
I);
2963 if (AssumedNoUBInsts.count(&
I) || KnownUBInsts.count(&
I))
2972 for (
unsigned idx = 0; idx < CB.
arg_size(); idx++) {
2978 if (idx >=
Callee->arg_size())
2990 bool IsKnownNoUndef;
2992 A,
this, CalleeArgumentIRP, DepClassTy::NONE, IsKnownNoUndef);
2993 if (!IsKnownNoUndef)
2995 bool UsedAssumedInformation =
false;
2996 std::optional<Value *> SimplifiedVal =
2999 if (UsedAssumedInformation)
3001 if (SimplifiedVal && !*SimplifiedVal)
3004 KnownUBInsts.try_emplace(&
I, UBInfo(UBInfo::UndefCallArgument, idx));
3010 bool IsKnownNonNull;
3012 A,
this, CalleeArgumentIRP, DepClassTy::NONE, IsKnownNonNull);
3014 KnownUBInsts.try_emplace(&
I,
3015 UBInfo(UBInfo::NullArgViolatesNonNull, idx));
3024 std::optional<Value *> SimplifiedRetValue = stopOnUndefOrAssumed(
3025 A, RI.getReturnValue(), &
I, UBInfo::UndefReturnValue);
3026 if (!SimplifiedRetValue || !*SimplifiedRetValue)
3044 bool IsKnownNonNull;
3049 KnownUBInsts.try_emplace(&
I, UBInfo::NullReturnViolatesNonNull);
3055 bool UsedAssumedInformation =
false;
3056 A.checkForAllInstructions(InspectMemAccessInstForUB, *
this,
3057 {Instruction::Load, Instruction::Store,
3058 Instruction::AtomicCmpXchg,
3059 Instruction::AtomicRMW},
3060 UsedAssumedInformation,
3062 A.checkForAllInstructions(InspectBrInstForUB, *
this, {Instruction::CondBr},
3063 UsedAssumedInformation,
3065 A.checkForAllCallLikeInstructions(InspectCallSiteForUB, *
this,
3066 UsedAssumedInformation);
3070 if (!getAnchorScope()->getReturnType()->isVoidTy()) {
3072 if (!
A.isAssumedDead(ReturnIRP,
this,
nullptr, UsedAssumedInformation)) {
3073 bool IsKnownNoUndef;
3075 A,
this, ReturnIRP, DepClassTy::NONE, IsKnownNoUndef);
3077 A.checkForAllInstructions(InspectReturnInstForUB, *
this,
3078 {Instruction::Ret}, UsedAssumedInformation,
3083 if (NoUBPrevSize != AssumedNoUBInsts.size() ||
3084 UBPrevSize != KnownUBInsts.size())
3085 return ChangeStatus::CHANGED;
3086 return ChangeStatus::UNCHANGED;
3089 bool isKnownToCauseUB(Instruction *
I)
const override {
3090 return KnownUBInsts.count(
I);
3093 bool isAssumedToCauseUB(Instruction *
I)
const override {
3100 switch (
I->getOpcode()) {
3101 case Instruction::Load:
3102 case Instruction::Store:
3103 case Instruction::AtomicCmpXchg:
3104 case Instruction::AtomicRMW:
3105 case Instruction::CondBr:
3106 return !AssumedNoUBInsts.count(
I);
3115 static void emitUBRemark(Attributor &
A, Instruction *
I,
const UBInfo &Info) {
3116 auto Remark = [&](OptimizationRemark
OR) {
3118 case UBInfo::NullPtrAccess:
3119 case UBInfo::UndefPtrAccess: {
3120 return OR <<
"Memory access through a pointer known to be "
3123 <<
" is undefined behavior; replacing with 'unreachable'.";
3125 case UBInfo::UndefBranchCondition:
3126 return OR <<
"Branch condition known to be "
3128 <<
" is undefined behavior; replacing with 'unreachable'.";
3129 case UBInfo::UndefReturnValue:
3130 case UBInfo::NullReturnViolatesNonNull:
3131 return OR <<
"Value returned known to be "
3134 <<
" is undefined behavior; replacing with 'unreachable'.";
3135 case UBInfo::UndefCallArgument:
3136 case UBInfo::NullArgViolatesNonNull: {
3137 bool IsUndef =
Info.K == UBInfo::UndefCallArgument;
3140 <<
" passed to parameter of ";
3145 return OR <<
" known to be "
3146 <<
ore::NV(
"Argument", IsUndef ?
"undef" :
"null")
3147 <<
" is undefined behavior; replacing with 'unreachable'.";
3152 A.emitRemark<OptimizationRemark>(
I,
"UndefinedBehavior",
Remark);
3156 if (KnownUBInsts.empty())
3157 return ChangeStatus::UNCHANGED;
3158 for (
const auto &[
I, Info] : KnownUBInsts) {
3159 emitUBRemark(
A,
I, Info);
3160 A.changeToUnreachableAfterManifest(
I);
3162 return ChangeStatus::CHANGED;
3165 const std::string getAsStr(Attributor *
A)
const override {
3166 return getAssumed() ?
"undefined-behavior" :
"no-ub";
3195 MapVector<Instruction *, UBInfo> KnownUBInsts;
3199 SmallPtrSet<Instruction *, 8> AssumedNoUBInsts;
3210 std::optional<Value *> stopOnUndefOrAssumed(Attributor &
A,
Value *
V,
3211 Instruction *
I, UBInfo::Kind K) {
3212 bool UsedAssumedInformation =
false;
3213 std::optional<Value *> SimplifiedV =
3216 if (!UsedAssumedInformation) {
3221 KnownUBInsts.try_emplace(
I, K);
3222 return std::nullopt;
3229 KnownUBInsts.try_emplace(
I, K);
3230 return std::nullopt;
3236struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl {
3237 AAUndefinedBehaviorFunction(
const IRPosition &IRP, Attributor &
A)
3238 : AAUndefinedBehaviorImpl(IRP,
A) {}
3240 void trackStatistics()
const override {
3241 STATS_DECL(UndefinedBehaviorInstruction, Instruction,
3242 "Number of instructions known to have UB");
3244 KnownUBInsts.size();
3255static bool mayContainUnboundedCycle(
Function &
F, Attributor &
A) {
3256 ScalarEvolution *SE =
3257 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
F);
3258 LoopInfo *LI =
A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
F);
3264 for (scc_iterator<Function *> SCCI =
scc_begin(&
F); !SCCI.isAtEnd(); ++SCCI)
3265 if (SCCI.hasCycle())
3275 for (
auto *L : LI->getLoopsInPreorder()) {
3282struct AAWillReturnImpl :
public AAWillReturn {
3283 AAWillReturnImpl(
const IRPosition &IRP, Attributor &
A)
3284 : AAWillReturn(IRP,
A) {}
3289 A,
nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
3294 bool isImpliedByMustprogressAndReadonly(Attributor &
A,
bool KnownOnly) {
3295 if (!
A.hasAttr(getIRPosition(), {Attribute::MustProgress}))
3300 return IsKnown || !KnownOnly;
3305 if (isImpliedByMustprogressAndReadonly(
A,
false))
3306 return ChangeStatus::UNCHANGED;
3312 A,
this, IPos, DepClassTy::REQUIRED, IsKnown)) {
3318 bool IsKnownNoRecurse;
3320 A,
this, IPos, DepClassTy::REQUIRED, IsKnownNoRecurse);
3323 bool UsedAssumedInformation =
false;
3324 if (!
A.checkForAllCallLikeInstructions(CheckForWillReturn, *
this,
3325 UsedAssumedInformation))
3326 return indicatePessimisticFixpoint();
3330 return !
I.isVolatile();
3332 if (!
A.checkForAllInstructions(CheckForVolatile, *
this,
3333 {Instruction::Load, Instruction::Store,
3334 Instruction::AtomicCmpXchg,
3335 Instruction::AtomicRMW},
3336 UsedAssumedInformation))
3337 return indicatePessimisticFixpoint();
3339 return ChangeStatus::UNCHANGED;
3342 const std::string getAsStr(Attributor *
A)
const override {
3343 return getAssumed() ?
"willreturn" :
"may-noreturn";
3347struct AAWillReturnFunction final : AAWillReturnImpl {
3348 AAWillReturnFunction(
const IRPosition &IRP, Attributor &
A)
3349 : AAWillReturnImpl(IRP,
A) {}
3352 AAWillReturnImpl::initialize(
A);
3355 assert(
F &&
"Did expect an anchor function");
3356 if (
F->isDeclaration() || mayContainUnboundedCycle(*
F,
A))
3357 indicatePessimisticFixpoint();
3364struct AAWillReturnCallSite final
3365 : AACalleeToCallSite<AAWillReturn, AAWillReturnImpl> {
3366 AAWillReturnCallSite(
const IRPosition &IRP, Attributor &
A)
3367 : AACalleeToCallSite<AAWillReturn, AAWillReturnImpl>(IRP,
A) {}
3370 if (isImpliedByMustprogressAndReadonly(
A,
false))
3371 return ChangeStatus::UNCHANGED;
3373 return AACalleeToCallSite::updateImpl(
A);
3394 const ToTy *
To =
nullptr;
3421 if (!ES || ES->
empty()) {
3422 ExclusionSet = nullptr;
3423 }
else if (MakeUnique) {
3424 ExclusionSet =
A.getInfoCache().getOrCreateUniqueBlockExecutionSet(ES);
3442 if (!PairDMI::isEqual({LHS->From, LHS->To}, {RHS->From, RHS->To}))
3444 return InstSetDMI::isEqual(LHS->ExclusionSet, RHS->ExclusionSet);
3452template <
typename BaseTy,
typename ToTy>
3453struct CachedReachabilityAA :
public BaseTy {
3454 using RQITy = ReachabilityQueryInfo<ToTy>;
3456 CachedReachabilityAA(
const IRPosition &IRP, Attributor &
A) : BaseTy(IRP,
A) {}
3458 bool isQueryAA()
const override {
return true; }
3462 for (
unsigned u = 0, e = QueryVector.size(); u < e; ++u) {
3463 RQITy *RQI = QueryVector[
u];
3464 if (RQI->Result == RQITy::Reachable::No &&
3466 Changed = ChangeStatus::CHANGED;
3472 bool IsTemporaryRQI) = 0;
3474 bool rememberResult(Attributor &
A,
typename RQITy::Reachable Result,
3475 RQITy &RQI,
bool UsedExclusionSet,
bool IsTemporaryRQI) {
3480 QueryCache.erase(&RQI);
3486 if (Result == RQITy::Reachable::Yes || !UsedExclusionSet) {
3487 RQITy PlainRQI(RQI.From, RQI.To);
3488 if (!QueryCache.count(&PlainRQI)) {
3489 RQITy *RQIPtr =
new (
A.Allocator) RQITy(RQI.From, RQI.To);
3491 QueryVector.push_back(RQIPtr);
3492 QueryCache.insert(RQIPtr);
3497 if (IsTemporaryRQI && Result != RQITy::Reachable::Yes && UsedExclusionSet) {
3498 assert((!RQI.ExclusionSet || !RQI.ExclusionSet->empty()) &&
3499 "Did not expect empty set!");
3500 RQITy *RQIPtr =
new (
A.Allocator)
3501 RQITy(
A, *RQI.From, *RQI.To, RQI.ExclusionSet,
true);
3502 assert(RQIPtr->Result == RQITy::Reachable::No &&
"Already reachable?");
3504 assert(!QueryCache.count(RQIPtr));
3505 QueryVector.push_back(RQIPtr);
3506 QueryCache.insert(RQIPtr);
3509 if (Result == RQITy::Reachable::No && IsTemporaryRQI)
3510 A.registerForUpdate(*
this);
3511 return Result == RQITy::Reachable::Yes;
3514 const std::string getAsStr(Attributor *
A)
const override {
3516 return "#queries(" + std::to_string(QueryVector.size()) +
")";
3519 bool checkQueryCache(Attributor &
A, RQITy &StackRQI,
3520 typename RQITy::Reachable &Result) {
3521 if (!this->getState().isValidState()) {
3522 Result = RQITy::Reachable::Yes;
3528 if (StackRQI.ExclusionSet) {
3529 RQITy PlainRQI(StackRQI.From, StackRQI.To);
3530 auto It = QueryCache.find(&PlainRQI);
3531 if (It != QueryCache.end() && (*It)->Result == RQITy::Reachable::No) {
3532 Result = RQITy::Reachable::No;
3537 auto It = QueryCache.find(&StackRQI);
3538 if (It != QueryCache.end()) {
3545 QueryCache.insert(&StackRQI);
3551 DenseSet<RQITy *> QueryCache;
3554struct AAIntraFnReachabilityFunction final
3555 :
public CachedReachabilityAA<AAIntraFnReachability, Instruction> {
3556 using Base = CachedReachabilityAA<AAIntraFnReachability, Instruction>;
3557 AAIntraFnReachabilityFunction(
const IRPosition &IRP, Attributor &
A)
3559 DT =
A.getInfoCache().getAnalysisResultForFunction<DominatorTreeAnalysis>(
3563 bool isAssumedReachable(
3564 Attributor &
A,
const Instruction &From,
const Instruction &To,
3566 auto *NonConstThis =
const_cast<AAIntraFnReachabilityFunction *
>(
this);
3570 RQITy StackRQI(
A, From, To, ExclusionSet,
false);
3572 if (!NonConstThis->checkQueryCache(
A, StackRQI, Result))
3573 return NonConstThis->isReachableImpl(
A, StackRQI,
3575 return Result == RQITy::Reachable::Yes;
3582 A.getAAFor<AAIsDead>(*
this, getIRPosition(), DepClassTy::OPTIONAL);
3585 [&](
const auto &DeadEdge) {
3586 return LivenessAA->isEdgeDead(DeadEdge.first,
3590 return LivenessAA->isAssumedDead(BB);
3592 return ChangeStatus::UNCHANGED;
3596 return Base::updateImpl(
A);
3600 bool IsTemporaryRQI)
override {
3602 bool UsedExclusionSet =
false;
3607 while (IP && IP != &To) {
3608 if (ExclusionSet && IP != Origin && ExclusionSet->
count(IP)) {
3609 UsedExclusionSet =
true;
3617 const BasicBlock *FromBB = RQI.From->getParent();
3618 const BasicBlock *ToBB = RQI.To->getParent();
3620 "Not an intra-procedural query!");
3624 if (FromBB == ToBB &&
3625 WillReachInBlock(*RQI.From, *RQI.To, RQI.ExclusionSet))
3626 return rememberResult(
A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3631 if (!WillReachInBlock(ToBB->
front(), *RQI.To, RQI.ExclusionSet))
3632 return rememberResult(
A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3636 SmallPtrSet<const BasicBlock *, 16> ExclusionBlocks;
3637 if (RQI.ExclusionSet)
3638 for (
auto *
I : *RQI.ExclusionSet)
3639 if (
I->getFunction() == Fn)
3640 ExclusionBlocks.
insert(
I->getParent());
3643 if (ExclusionBlocks.
count(FromBB) &&
3646 return rememberResult(
A, RQITy::Reachable::No, RQI,
true, IsTemporaryRQI);
3649 A.getAAFor<AAIsDead>(*
this, getIRPosition(), DepClassTy::OPTIONAL);
3650 if (LivenessAA && LivenessAA->isAssumedDead(ToBB)) {
3651 DeadBlocks.insert(ToBB);
3652 return rememberResult(
A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3656 SmallPtrSet<const BasicBlock *, 16> Visited;
3660 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> LocalDeadEdges;
3661 while (!Worklist.
empty()) {
3663 if (!Visited.
insert(BB).second)
3665 for (
const BasicBlock *SuccBB :
successors(BB)) {
3666 if (LivenessAA && LivenessAA->isEdgeDead(BB, SuccBB)) {
3667 LocalDeadEdges.
insert({BB, SuccBB});
3672 return rememberResult(
A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3675 return rememberResult(
A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3678 if (ExclusionBlocks.
count(SuccBB)) {
3679 UsedExclusionSet =
true;
3686 DeadEdges.insert_range(LocalDeadEdges);
3687 return rememberResult(
A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3691 void trackStatistics()
const override {}
3696 DenseSet<const BasicBlock *> DeadBlocks;
3700 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> DeadEdges;
3703 const DominatorTree *DT =
nullptr;
3711 bool IgnoreSubsumingPositions) {
3712 assert(ImpliedAttributeKind == Attribute::NoAlias &&
3713 "Unexpected attribute kind");
3719 IgnoreSubsumingPositions =
true;
3730 if (
A.hasAttr(IRP, {Attribute::ByVal, Attribute::NoAlias},
3731 IgnoreSubsumingPositions, Attribute::NoAlias))
3741 "Noalias is a pointer attribute");
3744 const std::string getAsStr(
Attributor *
A)
const override {
3745 return getAssumed() ?
"noalias" :
"may-alias";
3750struct AANoAliasFloating final : AANoAliasImpl {
3751 AANoAliasFloating(
const IRPosition &IRP, Attributor &
A)
3752 : AANoAliasImpl(IRP,
A) {}
3756 return indicatePessimisticFixpoint();
3759 void trackStatistics()
const override {
3765struct AANoAliasArgument final
3766 : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> {
3767 using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>;
3768 AANoAliasArgument(
const IRPosition &IRP, Attributor &
A) :
Base(IRP,
A) {}
3780 DepClassTy::OPTIONAL, IsKnownNoSycn))
3781 return Base::updateImpl(
A);
3786 return Base::updateImpl(
A);
3790 bool UsedAssumedInformation =
false;
3791 if (
A.checkForAllCallSites(
3792 [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *
this,
3793 true, UsedAssumedInformation))
3794 return Base::updateImpl(
A);
3802 return indicatePessimisticFixpoint();
3808struct AANoAliasCallSiteArgument final : AANoAliasImpl {
3809 AANoAliasCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
3810 : AANoAliasImpl(IRP,
A) {}
3814 bool mayAliasWithArgument(Attributor &
A, AAResults *&AAR,
3815 const AAMemoryBehavior &MemBehaviorAA,
3816 const CallBase &CB,
unsigned OtherArgNo) {
3818 if (this->getCallSiteArgNo() == (
int)OtherArgNo)
3826 auto *CBArgMemBehaviorAA =
A.getAAFor<AAMemoryBehavior>(
3830 if (CBArgMemBehaviorAA && CBArgMemBehaviorAA->isAssumedReadNone()) {
3831 A.recordDependence(*CBArgMemBehaviorAA, *
this, DepClassTy::OPTIONAL);
3838 if (CBArgMemBehaviorAA && CBArgMemBehaviorAA->isAssumedReadOnly() &&
3840 A.recordDependence(MemBehaviorAA, *
this, DepClassTy::OPTIONAL);
3841 A.recordDependence(*CBArgMemBehaviorAA, *
this, DepClassTy::OPTIONAL);
3847 AAR =
A.getInfoCache().getAnalysisResultForFunction<AAManager>(
3851 bool IsAliasing = !AAR || !AAR->
isNoAlias(&getAssociatedValue(), ArgOp);
3853 "callsite arguments: "
3854 << getAssociatedValue() <<
" " << *ArgOp <<
" => "
3855 << (IsAliasing ?
"" :
"no-") <<
"alias \n");
3860 bool isKnownNoAliasDueToNoAliasPreservation(
3861 Attributor &
A, AAResults *&AAR,
const AAMemoryBehavior &MemBehaviorAA) {
3874 auto UsePred = [&](
const Use &
U,
bool &Follow) ->
bool {
3890 bool IsKnownNoCapture;
3893 DepClassTy::OPTIONAL, IsKnownNoCapture))
3899 A, *UserI, *getCtxI(), *
this,
nullptr,
3900 [ScopeFn](
const Function &Fn) {
return &Fn != ScopeFn; }))
3915 LLVM_DEBUG(
dbgs() <<
"[AANoAliasCSArg] Unknown user: " << *UserI <<
"\n");
3919 bool IsKnownNoCapture;
3920 const AANoCapture *NoCaptureAA =
nullptr;
3922 A,
this, VIRP, DepClassTy::NONE, IsKnownNoCapture,
false, &NoCaptureAA);
3923 if (!IsAssumedNoCapture &&
3925 if (!
A.checkForAllUses(UsePred, *
this, getAssociatedValue())) {
3927 dbgs() <<
"[AANoAliasCSArg] " << getAssociatedValue()
3928 <<
" cannot be noalias as it is potentially captured\n");
3933 A.recordDependence(*NoCaptureAA, *
this, DepClassTy::OPTIONAL);
3939 for (
unsigned OtherArgNo = 0; OtherArgNo < CB.
arg_size(); OtherArgNo++)
3940 if (mayAliasWithArgument(
A, AAR, MemBehaviorAA, CB, OtherArgNo))
3949 auto *MemBehaviorAA =
3950 A.getAAFor<AAMemoryBehavior>(*
this, getIRPosition(), DepClassTy::NONE);
3952 A.recordDependence(*MemBehaviorAA, *
this, DepClassTy::OPTIONAL);
3953 return ChangeStatus::UNCHANGED;
3956 bool IsKnownNoAlias;
3959 A,
this, VIRP, DepClassTy::REQUIRED, IsKnownNoAlias)) {
3961 <<
" is not no-alias at the definition\n");
3962 return indicatePessimisticFixpoint();
3965 AAResults *AAR =
nullptr;
3966 if (MemBehaviorAA &&
3967 isKnownNoAliasDueToNoAliasPreservation(
A, AAR, *MemBehaviorAA)) {
3969 dbgs() <<
"[AANoAlias] No-Alias deduced via no-alias preservation\n");
3970 return ChangeStatus::UNCHANGED;
3973 return indicatePessimisticFixpoint();
3980struct AANoAliasReturned final : AANoAliasImpl {
3981 AANoAliasReturned(
const IRPosition &IRP, Attributor &
A)
3982 : AANoAliasImpl(IRP,
A) {}
3986 auto CheckReturnValue = [&](
Value &RV) ->
bool {
3997 bool IsKnownNoAlias;
3999 A,
this, RVPos, DepClassTy::REQUIRED, IsKnownNoAlias))
4002 bool IsKnownNoCapture;
4003 const AANoCapture *NoCaptureAA =
nullptr;
4005 A,
this, RVPos, DepClassTy::REQUIRED, IsKnownNoCapture,
false,
4007 return IsAssumedNoCapture ||
4011 if (!
A.checkForAllReturnedValues(CheckReturnValue, *
this))
4012 return indicatePessimisticFixpoint();
4014 return ChangeStatus::UNCHANGED;
4021struct AANoAliasCallSiteReturned final
4022 : AACalleeToCallSite<AANoAlias, AANoAliasImpl> {
4023 AANoAliasCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
4024 : AACalleeToCallSite<AANoAlias, AANoAliasImpl>(IRP,
A) {}
4033struct AAIsDeadValueImpl :
public AAIsDead {
4034 AAIsDeadValueImpl(
const IRPosition &IRP, Attributor &
A) : AAIsDead(IRP,
A) {}
4036 bool isAssumedDead()
const override {
return isAssumed(IS_DEAD); }
4038 bool isKnownDead()
const override {
return isKnown(IS_DEAD); }
4040 bool isAssumedDead(
const BasicBlock *BB)
const override {
return false; }
4042 bool isKnownDead(
const BasicBlock *BB)
const override {
return false; }
4044 bool isAssumedDead(
const Instruction *
I)
const override {
4045 return I == getCtxI() && isAssumedDead();
4048 bool isKnownDead(
const Instruction *
I)
const override {
4049 return isAssumedDead(
I) && isKnownDead();
4052 const std::string getAsStr(Attributor *
A)
const override {
4053 return isAssumedDead() ?
"assumed-dead" :
"assumed-live";
4057 bool areAllUsesAssumedDead(Attributor &
A,
Value &
V) {
4059 if (
V.getType()->isVoidTy() ||
V.use_empty())
4065 if (!
A.isRunOn(*
I->getFunction()))
4067 bool UsedAssumedInformation =
false;
4068 std::optional<Constant *>
C =
4069 A.getAssumedConstant(
V, *
this, UsedAssumedInformation);
4074 auto UsePred = [&](
const Use &
U,
bool &Follow) {
return false; };
4079 return A.checkForAllUses(UsePred, *
this,
V,
false,
4080 DepClassTy::REQUIRED,
4085 bool isAssumedSideEffectFree(Attributor &
A, Instruction *
I) {
4089 if (!
I->isTerminator() && !
I->mayHaveSideEffects())
4098 bool IsKnownNoUnwind;
4100 A,
this, CallIRP, DepClassTy::OPTIONAL, IsKnownNoUnwind))
4108struct AAIsDeadFloating :
public AAIsDeadValueImpl {
4109 AAIsDeadFloating(
const IRPosition &IRP, Attributor &
A)
4110 : AAIsDeadValueImpl(IRP,
A) {}
4113 AAIsDeadValueImpl::initialize(
A);
4116 indicatePessimisticFixpoint();
4121 if (!isAssumedSideEffectFree(
A,
I)) {
4123 indicatePessimisticFixpoint();
4125 removeAssumedBits(HAS_NO_EFFECT);
4129 bool isDeadFence(Attributor &
A, FenceInst &FI) {
4130 const auto *ExecDomainAA =
A.lookupAAFor<AAExecutionDomain>(
4132 if (!ExecDomainAA || !ExecDomainAA->isNoOpFence(FI))
4134 A.recordDependence(*ExecDomainAA, *
this, DepClassTy::OPTIONAL);
4138 bool isDeadStore(Attributor &
A, StoreInst &SI,
4139 SmallSetVector<Instruction *, 8> *AssumeOnlyInst =
nullptr) {
4141 if (
SI.isVolatile())
4147 bool UsedAssumedInformation =
false;
4148 if (!AssumeOnlyInst) {
4149 PotentialCopies.clear();
4151 UsedAssumedInformation)) {
4154 <<
"[AAIsDead] Could not determine potential copies of store!\n");
4158 LLVM_DEBUG(
dbgs() <<
"[AAIsDead] Store has " << PotentialCopies.size()
4159 <<
" potential copies.\n");
4161 InformationCache &InfoCache =
A.getInfoCache();
4164 UsedAssumedInformation))
4168 auto &UserI = cast<Instruction>(*U.getUser());
4169 if (InfoCache.isOnlyUsedByAssume(UserI)) {
4171 AssumeOnlyInst->insert(&UserI);
4174 return A.isAssumedDead(U,
this,
nullptr, UsedAssumedInformation);
4180 <<
" is assumed live!\n");
4185 const std::string getAsStr(Attributor *
A)
const override {
4189 return "assumed-dead-store";
4192 return "assumed-dead-fence";
4193 return AAIsDeadValueImpl::getAsStr(
A);
4199 if (!isDeadStore(
A, *SI))
4200 return indicatePessimisticFixpoint();
4202 if (!isDeadFence(
A, *FI))
4203 return indicatePessimisticFixpoint();
4205 if (!isAssumedSideEffectFree(
A,
I))
4206 return indicatePessimisticFixpoint();
4207 if (!areAllUsesAssumedDead(
A, getAssociatedValue()))
4208 return indicatePessimisticFixpoint();
4213 bool isRemovableStore()
const override {
4214 return isAssumed(IS_REMOVABLE) &&
isa<StoreInst>(&getAssociatedValue());
4218 Value &
V = getAssociatedValue();
4225 SmallSetVector<Instruction *, 8> AssumeOnlyInst;
4226 bool IsDead = isDeadStore(
A, *SI, &AssumeOnlyInst);
4229 A.deleteAfterManifest(*
I);
4230 for (
size_t i = 0; i < AssumeOnlyInst.
size(); ++i) {
4232 for (Instruction *Usr : AOI->
users())
4233 AssumeOnlyInst.
insert(Usr);
4234 A.deleteAfterManifest(*AOI);
4240 A.deleteAfterManifest(*FI);
4243 if (isAssumedSideEffectFree(
A,
I) && !
I->isTerminator()) {
4244 A.deleteAfterManifest(*
I);
4251 void trackStatistics()
const override {
4257 SmallSetVector<Value *, 4> PotentialCopies;
4260struct AAIsDeadArgument :
public AAIsDeadFloating {
4261 AAIsDeadArgument(
const IRPosition &IRP, Attributor &
A)
4262 : AAIsDeadFloating(IRP,
A) {}
4265 Argument &Arg = *getAssociatedArgument();
4266 if (
A.isValidFunctionSignatureRewrite(Arg, {}))
4267 if (
A.registerFunctionSignatureRewrite(
4271 return ChangeStatus::CHANGED;
4273 return ChangeStatus::UNCHANGED;
4279struct AAIsDeadCallSiteArgument :
public AAIsDeadValueImpl {
4280 AAIsDeadCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
4281 : AAIsDeadValueImpl(IRP,
A) {}
4284 AAIsDeadValueImpl::initialize(
A);
4286 indicatePessimisticFixpoint();
4294 Argument *Arg = getAssociatedArgument();
4296 return indicatePessimisticFixpoint();
4298 auto *ArgAA =
A.getAAFor<AAIsDead>(*
this, ArgPos, DepClassTy::REQUIRED);
4300 return indicatePessimisticFixpoint();
4308 "Expected undef values to be filtered out!");
4310 if (
A.changeUseAfterManifest(U, UV))
4311 return ChangeStatus::CHANGED;
4312 return ChangeStatus::UNCHANGED;
4318struct AAIsDeadCallSiteReturned :
public AAIsDeadFloating {
4319 AAIsDeadCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
4320 : AAIsDeadFloating(IRP,
A) {}
4322 bool isAssumedDead()
const override {
4323 return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree;
4327 AAIsDeadFloating::initialize(
A);
4329 indicatePessimisticFixpoint();
4334 IsAssumedSideEffectFree = isAssumedSideEffectFree(
A, getCtxI());
4339 if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(
A, getCtxI())) {
4340 IsAssumedSideEffectFree =
false;
4341 Changed = ChangeStatus::CHANGED;
4343 if (!areAllUsesAssumedDead(
A, getAssociatedValue()))
4344 return indicatePessimisticFixpoint();
4348 void trackStatistics()
const override {
4349 if (IsAssumedSideEffectFree)
4355 const std::string getAsStr(Attributor *
A)
const override {
4356 return isAssumedDead()
4358 : (getAssumed() ?
"assumed-dead-users" :
"assumed-live");
4362 bool IsAssumedSideEffectFree =
true;
4365struct AAIsDeadReturned :
public AAIsDeadValueImpl {
4366 AAIsDeadReturned(
const IRPosition &IRP, Attributor &
A)
4367 : AAIsDeadValueImpl(IRP,
A) {}
4371 bool UsedAssumedInformation =
false;
4372 A.checkForAllInstructions([](Instruction &) {
return true; }, *
this,
4373 {Instruction::Ret}, UsedAssumedInformation);
4375 auto PredForCallSite = [&](AbstractCallSite ACS) {
4376 if (ACS.isCallbackCall() || !ACS.getInstruction())
4378 return areAllUsesAssumedDead(
A, *ACS.getInstruction());
4381 if (!
A.checkForAllCallSites(PredForCallSite, *
this,
true,
4382 UsedAssumedInformation))
4383 return indicatePessimisticFixpoint();
4385 return ChangeStatus::UNCHANGED;
4390 bool AnyChange =
false;
4391 UndefValue &UV = *
UndefValue::get(getAssociatedFunction()->getReturnType());
4398 bool UsedAssumedInformation =
false;
4399 A.checkForAllInstructions(RetInstPred, *
this, {Instruction::Ret},
4400 UsedAssumedInformation);
4401 return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
4407struct AAIsDeadFunction :
public AAIsDead {
4408 AAIsDeadFunction(
const IRPosition &IRP, Attributor &
A) : AAIsDead(IRP,
A) {}
4412 assert(
F &&
"Did expect an anchor function");
4413 if (!isAssumedDeadInternalFunction(
A)) {
4414 ToBeExploredFrom.insert(&
F->getEntryBlock().front());
4415 assumeLive(
A,
F->getEntryBlock());
4419 bool isAssumedDeadInternalFunction(Attributor &
A) {
4420 if (!getAnchorScope()->hasLocalLinkage())
4426 if (!
A.shouldUpdateAA<AAIsDead>(getIRPosition()))
4428 bool UsedAssumedInformation =
false;
4429 return A.checkForAllCallSites([](AbstractCallSite) {
return false; }, *
this,
4430 true, UsedAssumedInformation);
4433 const std::string getAsStr(Attributor *
A)
const override {
4434 return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) +
"/" +
4435 std::to_string(getAnchorScope()->
size()) +
"][#TBEP " +
4436 std::to_string(ToBeExploredFrom.size()) +
"][#KDE " +
4437 std::to_string(KnownDeadEnds.size()) +
"]";
4441 assert(getState().isValidState() &&
4442 "Attempted to manifest an invalid state!");
4447 if (AssumedLiveBlocks.empty()) {
4448 A.deleteAfterManifest(
F);
4449 return ChangeStatus::CHANGED;
4455 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(
F);
4457 KnownDeadEnds.set_union(ToBeExploredFrom);
4458 for (
const Instruction *DeadEndI : KnownDeadEnds) {
4462 bool IsKnownNoReturn;
4470 A.registerInvokeWithDeadSuccessor(
const_cast<InvokeInst &
>(*
II));
4472 A.changeToUnreachableAfterManifest(
4473 const_cast<Instruction *
>(DeadEndI->getNextNode()));
4474 HasChanged = ChangeStatus::CHANGED;
4477 STATS_DECL(AAIsDead, BasicBlock,
"Number of dead basic blocks deleted.");
4478 for (BasicBlock &BB :
F)
4479 if (!AssumedLiveBlocks.count(&BB)) {
4480 A.deleteAfterManifest(BB);
4482 HasChanged = ChangeStatus::CHANGED;
4490 bool isEdgeDead(
const BasicBlock *From,
const BasicBlock *To)
const override {
4493 "Used AAIsDead of the wrong function");
4494 return isValidState() && !AssumedLiveEdges.count(std::make_pair(From, To));
4497 void trackStatistics()
const override {}
4500 bool isAssumedDead()
const override {
return false; }
4502 bool isKnownDead()
const override {
return false; }
4504 bool isAssumedDead(
const BasicBlock *BB)
const override {
4506 "BB must be in the same anchor scope function.");
4510 return !AssumedLiveBlocks.count(BB);
4513 bool isKnownDead(
const BasicBlock *BB)
const override {
4514 return getKnown() && isAssumedDead(BB);
4517 bool isAssumedDead(
const Instruction *
I)
const override {
4518 assert(
I->getParent()->getParent() == getAnchorScope() &&
4519 "Instruction must be in the same anchor scope function.");
4526 if (!AssumedLiveBlocks.count(
I->getParent()))
4532 if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI))
4539 bool isKnownDead(
const Instruction *
I)
const override {
4540 return getKnown() && isAssumedDead(
I);
4545 bool assumeLive(Attributor &
A,
const BasicBlock &BB) {
4546 if (!AssumedLiveBlocks.insert(&BB).second)
4549 if (!
A.isDuringDeduction())
4556 for (
const Instruction &
I : BB)
4559 if (
F->hasLocalLinkage()) {
4561 dbgs() <<
"[AAIsDead] Seeding live internal callee ";
4562 F->printAsOperand(
dbgs(),
false);
4564 BB.getParent()->printAsOperand(
dbgs(),
false);
4567 A.markLiveInternalFunction(*
F);
4574 SmallSetVector<const Instruction *, 8> ToBeExploredFrom;
4577 SmallSetVector<const Instruction *, 8> KnownDeadEnds;
4580 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> AssumedLiveEdges;
4583 DenseSet<const BasicBlock *> AssumedLiveBlocks;
4587identifyAliveSuccessors(Attributor &
A,
const CallBase &CB,
4588 AbstractAttribute &AA,
4589 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4592 bool IsKnownNoReturn;
4595 return !IsKnownNoReturn;
4604identifyAliveSuccessors(Attributor &
A,
const InvokeInst &
II,
4605 AbstractAttribute &AA,
4606 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4607 bool UsedAssumedInformation =
4613 if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*
II.getFunction())) {
4614 AliveSuccessors.
push_back(&
II.getUnwindDest()->front());
4618 bool IsKnownNoUnwind;
4621 UsedAssumedInformation |= !IsKnownNoUnwind;
4623 AliveSuccessors.
push_back(&
II.getUnwindDest()->front());
4626 return UsedAssumedInformation;
4630identifyAliveSuccessors(Attributor &,
const UncondBrInst &BI,
4631 AbstractAttribute &,
4632 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4638identifyAliveSuccessors(Attributor &
A,
const CondBrInst &BI,
4639 AbstractAttribute &AA,
4640 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4641 bool UsedAssumedInformation =
false;
4642 std::optional<Constant *>
C =
4643 A.getAssumedConstant(*BI.
getCondition(), AA, UsedAssumedInformation);
4653 UsedAssumedInformation =
false;
4655 return UsedAssumedInformation;
4659identifyAliveSuccessors(Attributor &
A,
const SwitchInst &SI,
4660 AbstractAttribute &AA,
4661 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4662 bool UsedAssumedInformation =
false;
4666 UsedAssumedInformation)) {
4668 for (
const BasicBlock *SuccBB :
successors(
SI.getParent()))
4677 return UsedAssumedInformation;
4680 Type &Ty = *
SI.getCondition()->getType();
4681 SmallPtrSet<ConstantInt *, 8>
Constants;
4682 auto CheckForConstantInt = [&](
Value *
V) {
4691 return CheckForConstantInt(VAC.
getValue());
4693 for (
const BasicBlock *SuccBB :
successors(
SI.getParent()))
4695 return UsedAssumedInformation;
4698 unsigned MatchedCases = 0;
4699 for (
const auto &CaseIt :
SI.cases()) {
4700 if (
Constants.count(CaseIt.getCaseValue())) {
4702 AliveSuccessors.
push_back(&CaseIt.getCaseSuccessor()->front());
4709 AliveSuccessors.
push_back(&
SI.getDefaultDest()->front());
4710 return UsedAssumedInformation;
4716 if (AssumedLiveBlocks.empty()) {
4717 if (isAssumedDeadInternalFunction(
A))
4721 ToBeExploredFrom.insert(&
F->getEntryBlock().front());
4722 assumeLive(
A,
F->getEntryBlock());
4726 LLVM_DEBUG(
dbgs() <<
"[AAIsDead] Live [" << AssumedLiveBlocks.size() <<
"/"
4727 << getAnchorScope()->
size() <<
"] BBs and "
4728 << ToBeExploredFrom.size() <<
" exploration points and "
4729 << KnownDeadEnds.size() <<
" known dead ends\n");
4734 ToBeExploredFrom.end());
4735 decltype(ToBeExploredFrom) NewToBeExploredFrom;
4738 while (!Worklist.
empty()) {
4745 I =
I->getNextNode();
4747 AliveSuccessors.
clear();
4749 bool UsedAssumedInformation =
false;
4750 switch (
I->getOpcode()) {
4754 "Expected non-terminators to be handled already!");
4755 for (
const BasicBlock *SuccBB :
successors(
I->getParent()))
4758 case Instruction::Call:
4760 *
this, AliveSuccessors);
4762 case Instruction::Invoke:
4764 *
this, AliveSuccessors);
4766 case Instruction::UncondBr:
4767 UsedAssumedInformation = identifyAliveSuccessors(
4770 case Instruction::CondBr:
4772 *
this, AliveSuccessors);
4774 case Instruction::Switch:
4776 *
this, AliveSuccessors);
4780 if (UsedAssumedInformation) {
4781 NewToBeExploredFrom.insert(
I);
4782 }
else if (AliveSuccessors.
empty() ||
4783 (
I->isTerminator() &&
4784 AliveSuccessors.
size() <
I->getNumSuccessors())) {
4785 if (KnownDeadEnds.insert(
I))
4790 << AliveSuccessors.
size() <<
" UsedAssumedInformation: "
4791 << UsedAssumedInformation <<
"\n");
4793 for (
const Instruction *AliveSuccessor : AliveSuccessors) {
4794 if (!
I->isTerminator()) {
4795 assert(AliveSuccessors.size() == 1 &&
4796 "Non-terminator expected to have a single successor!");
4800 auto Edge = std::make_pair(
I->getParent(), AliveSuccessor->getParent());
4801 if (AssumedLiveEdges.insert(
Edge).second)
4803 if (assumeLive(
A, *AliveSuccessor->getParent()))
4810 if (NewToBeExploredFrom.size() != ToBeExploredFrom.size() ||
4811 llvm::any_of(NewToBeExploredFrom, [&](
const Instruction *
I) {
4812 return !ToBeExploredFrom.count(I);
4815 ToBeExploredFrom = std::move(NewToBeExploredFrom);
4824 if (ToBeExploredFrom.empty() &&
4825 getAnchorScope()->
size() == AssumedLiveBlocks.size() &&
4826 llvm::all_of(KnownDeadEnds, [](
const Instruction *DeadEndI) {
4827 return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0;
4829 return indicatePessimisticFixpoint();
4834struct AAIsDeadCallSite final : AAIsDeadFunction {
4835 AAIsDeadCallSite(
const IRPosition &IRP, Attributor &
A)
4836 : AAIsDeadFunction(IRP,
A) {}
4844 "supported for call sites yet!");
4848 return indicatePessimisticFixpoint();
4851 void trackStatistics()
const override {}
4858struct AADereferenceableImpl : AADereferenceable {
4859 AADereferenceableImpl(
const IRPosition &IRP, Attributor &
A)
4860 : AADereferenceable(IRP,
A) {}
4861 using StateType = DerefState;
4864 Value &
V = *getAssociatedValue().stripPointerCasts();
4866 A.getAttrs(getIRPosition(),
4867 {Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
4870 takeKnownDerefBytesMaximum(Attr.getValueAsInt());
4873 bool IsKnownNonNull;
4875 A,
this, getIRPosition(), DepClassTy::OPTIONAL, IsKnownNonNull);
4878 takeKnownDerefBytesMaximum(
V.getPointerDereferenceableBytes(
4879 A.getDataLayout(), CanBeNull,
nullptr));
4881 if (Instruction *CtxI = getCtxI())
4882 followUsesInMBEC(*
this,
A, getState(), *CtxI);
4885 StateType &getState()
override {
return *
this; }
4886 const StateType &getState()
const override {
return *
this; }
4889 void addAccessedBytesForUse(Attributor &
A,
const Use *U,
const Instruction *
I,
4890 DerefState &State) {
4891 const Value *UseV =
U->get();
4896 if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() ||
I->isVolatile())
4901 Loc->Ptr,
Offset,
A.getDataLayout(),
true);
4902 if (
Base &&
Base == &getAssociatedValue())
4903 State.addAccessedBytes(
Offset, Loc->Size.getValue());
4907 bool followUseInMBEC(Attributor &
A,
const Use *U,
const Instruction *
I,
4908 AADereferenceable::StateType &State) {
4909 bool IsNonNull =
false;
4910 bool TrackUse =
false;
4911 int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse(
4912 A, *
this, getAssociatedValue(), U,
I, IsNonNull, TrackUse);
4913 LLVM_DEBUG(
dbgs() <<
"[AADereferenceable] Deref bytes: " << DerefBytes
4914 <<
" for instruction " << *
I <<
"\n");
4916 addAccessedBytesForUse(
A, U,
I, State);
4917 State.takeKnownDerefBytesMaximum(DerefBytes);
4923 bool IsKnownNonNull;
4925 A,
this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4926 if (IsAssumedNonNull &&
4927 A.hasAttr(getIRPosition(), Attribute::DereferenceableOrNull)) {
4928 A.removeAttrs(getIRPosition(), {Attribute::DereferenceableOrNull});
4929 return ChangeStatus::CHANGED;
4934 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
4935 SmallVectorImpl<Attribute> &Attrs)
const override {
4937 bool IsKnownNonNull;
4939 A,
this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4940 if (IsAssumedNonNull)
4941 Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
4942 Ctx, getAssumedDereferenceableBytes()));
4944 Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
4945 Ctx, getAssumedDereferenceableBytes()));
4948 const std::string getAsStr(Attributor *
A)
const override {
4949 if (!getAssumedDereferenceableBytes())
4950 return "unknown-dereferenceable";
4951 bool IsKnownNonNull;
4952 bool IsAssumedNonNull =
false;
4955 *
A,
this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4956 return std::string(
"dereferenceable") +
4957 (IsAssumedNonNull ?
"" :
"_or_null") +
4958 (isAssumedGlobal() ?
"_globally" :
"") +
"<" +
4959 std::to_string(getKnownDereferenceableBytes()) +
"-" +
4960 std::to_string(getAssumedDereferenceableBytes()) +
">" +
4961 (!
A ?
" [non-null is unknown]" :
"");
4966struct AADereferenceableFloating : AADereferenceableImpl {
4967 AADereferenceableFloating(
const IRPosition &IRP, Attributor &
A)
4968 : AADereferenceableImpl(IRP,
A) {}
4972 bool UsedAssumedInformation =
false;
4974 if (!
A.getAssumedSimplifiedValues(getIRPosition(), *
this,
Values,
4976 Values.push_back({getAssociatedValue(), getCtxI()});
4979 Stripped =
Values.size() != 1 ||
4980 Values.front().getValue() != &getAssociatedValue();
4983 const DataLayout &
DL =
A.getDataLayout();
4986 auto VisitValueCB = [&](
const Value &
V) ->
bool {
4988 DL.getIndexSizeInBits(
V.getType()->getPointerAddressSpace());
4989 APInt
Offset(IdxWidth, 0);
4994 const auto *AA =
A.getAAFor<AADereferenceable>(
4996 int64_t DerefBytes = 0;
4997 if (!AA || (!Stripped &&
this == AA)) {
5001 DerefBytes =
Base->getPointerDereferenceableBytes(
5002 DL, CanBeNull,
nullptr);
5003 T.GlobalState.indicatePessimisticFixpoint();
5006 DerefBytes =
DS.DerefBytesState.getAssumed();
5007 T.GlobalState &=
DS.GlobalState;
5013 int64_t OffsetSExt =
Offset.getSExtValue();
5017 T.takeAssumedDerefBytesMinimum(
5018 std::max(int64_t(0), DerefBytes - OffsetSExt));
5023 T.takeKnownDerefBytesMaximum(
5024 std::max(int64_t(0), DerefBytes - OffsetSExt));
5025 T.indicatePessimisticFixpoint();
5026 }
else if (OffsetSExt > 0) {
5032 T.indicatePessimisticFixpoint();
5036 return T.isValidState();
5039 for (
const auto &VAC :
Values)
5040 if (!VisitValueCB(*VAC.
getValue()))
5041 return indicatePessimisticFixpoint();
5046 void trackStatistics()
const override {
5052struct AADereferenceableReturned final
5053 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> {
5055 AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>;
5056 AADereferenceableReturned(
const IRPosition &IRP, Attributor &
A)
5059 void trackStatistics()
const override {
5065struct AADereferenceableArgument final
5066 : AAArgumentFromCallSiteArguments<AADereferenceable,
5067 AADereferenceableImpl> {
5069 AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl>;
5070 AADereferenceableArgument(
const IRPosition &IRP, Attributor &
A)
5073 void trackStatistics()
const override {
5079struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
5080 AADereferenceableCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
5081 : AADereferenceableFloating(IRP,
A) {}
5083 void trackStatistics()
const override {
5089struct AADereferenceableCallSiteReturned final
5090 : AACalleeToCallSite<AADereferenceable, AADereferenceableImpl> {
5091 using Base = AACalleeToCallSite<AADereferenceable, AADereferenceableImpl>;
5092 AADereferenceableCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
5095 void trackStatistics()
const override {
5105static unsigned getKnownAlignForUse(Attributor &
A, AAAlign &QueryingAA,
5106 Value &AssociatedValue,
const Use *U,
5107 const Instruction *
I,
bool &TrackUse) {
5116 if (
GEP->hasAllConstantIndices())
5121 switch (
II->getIntrinsicID()) {
5122 case Intrinsic::ptrmask: {
5124 const auto *ConstVals =
A.getAAFor<AAPotentialConstantValues>(
5126 const auto *AlignAA =
A.getAAFor<AAAlign>(
5128 if (ConstVals && ConstVals->isValidState() && ConstVals->isAtFixpoint()) {
5129 unsigned ShiftValue = std::min(ConstVals->getAssumedMinTrailingZeros(),
5132 if (ConstAlign >= AlignAA->getKnownAlign())
5133 return Align(1).value();
5136 return AlignAA->getKnownAlign().
value();
5139 case Intrinsic::amdgcn_make_buffer_rsrc: {
5140 const auto *AlignAA =
A.getAAFor<AAAlign>(
5143 return AlignAA->getKnownAlign().
value();
5161 MA = MaybeAlign(AlignAA->getKnownAlign());
5164 const DataLayout &
DL =
A.getDataLayout();
5165 const Value *UseV =
U->get();
5167 if (
SI->getPointerOperand() == UseV)
5168 MA =
SI->getAlign();
5170 if (LI->getPointerOperand() == UseV)
5171 MA = LI->getAlign();
5173 if (AI->getPointerOperand() == UseV)
5174 MA = AI->getAlign();
5176 if (AI->getPointerOperand() == UseV)
5177 MA = AI->getAlign();
5187 if (
Base == &AssociatedValue) {
5192 uint32_t
gcd = std::gcd(uint32_t(
abs((int32_t)
Offset)), Alignment);
5200struct AAAlignImpl : AAAlign {
5201 AAAlignImpl(
const IRPosition &IRP, Attributor &
A) : AAAlign(IRP,
A) {}
5205 A.getAttrs(getIRPosition(), {Attribute::Alignment},
Attrs);
5207 takeKnownMaximum(Attr.getValueAsInt());
5209 Value &
V = *getAssociatedValue().stripPointerCasts();
5210 takeKnownMaximum(
V.getPointerAlignment(
A.getDataLayout()).value());
5212 if (Instruction *CtxI = getCtxI())
5213 followUsesInMBEC(*
this,
A, getState(), *CtxI);
5220 Value &AssociatedValue = getAssociatedValue();
5222 return ChangeStatus::UNCHANGED;
5224 for (
const Use &U : AssociatedValue.
uses()) {
5226 if (
SI->getPointerOperand() == &AssociatedValue)
5227 if (
SI->getAlign() < getAssumedAlign()) {
5229 "Number of times alignment added to a store");
5230 SI->setAlignment(getAssumedAlign());
5231 InstrChanged = ChangeStatus::CHANGED;
5234 if (LI->getPointerOperand() == &AssociatedValue)
5235 if (LI->getAlign() < getAssumedAlign()) {
5236 LI->setAlignment(getAssumedAlign());
5238 "Number of times alignment added to a load");
5239 InstrChanged = ChangeStatus::CHANGED;
5242 if (RMW->getPointerOperand() == &AssociatedValue) {
5243 if (RMW->getAlign() < getAssumedAlign()) {
5245 "Number of times alignment added to atomicrmw");
5247 RMW->setAlignment(getAssumedAlign());
5248 InstrChanged = ChangeStatus::CHANGED;
5252 if (CAS->getPointerOperand() == &AssociatedValue) {
5253 if (CAS->getAlign() < getAssumedAlign()) {
5255 "Number of times alignment added to cmpxchg");
5256 CAS->setAlignment(getAssumedAlign());
5257 InstrChanged = ChangeStatus::CHANGED;
5265 Align InheritAlign =
5266 getAssociatedValue().getPointerAlignment(
A.getDataLayout());
5267 if (InheritAlign >= getAssumedAlign())
5268 return InstrChanged;
5269 return Changed | InstrChanged;
5276 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
5277 SmallVectorImpl<Attribute> &Attrs)
const override {
5278 if (getAssumedAlign() > 1)
5280 Attribute::getWithAlignment(Ctx,
Align(getAssumedAlign())));
5284 bool followUseInMBEC(Attributor &
A,
const Use *U,
const Instruction *
I,
5285 AAAlign::StateType &State) {
5286 bool TrackUse =
false;
5288 unsigned int KnownAlign =
5289 getKnownAlignForUse(
A, *
this, getAssociatedValue(), U,
I, TrackUse);
5290 State.takeKnownMaximum(KnownAlign);
5295 const std::string getAsStr(Attributor *
A)
const override {
5296 return "align<" + std::to_string(getKnownAlign().value()) +
"-" +
5297 std::to_string(getAssumedAlign().value()) +
">";
5302struct AAAlignFloating : AAAlignImpl {
5303 AAAlignFloating(
const IRPosition &IRP, Attributor &
A) : AAAlignImpl(IRP,
A) {}
5306 const DataLayout &
DL =
A.getDataLayout();
5309 bool UsedAssumedInformation =
false;
5311 if (!
A.getAssumedSimplifiedValues(getIRPosition(), *
this,
Values,
5313 Values.push_back({getAssociatedValue(), getCtxI()});
5316 Stripped =
Values.size() != 1 ||
5317 Values.front().getValue() != &getAssociatedValue();
5321 auto VisitValueCB = [&](
Value &
V) ->
bool {
5325 DepClassTy::REQUIRED);
5326 if (!AA || (!Stripped &&
this == AA)) {
5344 T.takeKnownMaximum(Alignment);
5345 T.indicatePessimisticFixpoint();
5348 const AAAlign::StateType &
DS = AA->
getState();
5351 return T.isValidState();
5354 for (
const auto &VAC :
Values) {
5355 if (!VisitValueCB(*VAC.
getValue()))
5356 return indicatePessimisticFixpoint();
5368struct AAAlignReturned final
5369 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
5370 using Base = AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>;
5371 AAAlignReturned(
const IRPosition &IRP, Attributor &
A) :
Base(IRP,
A) {}
5377struct AAAlignArgument final
5378 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> {
5379 using Base = AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>;
5380 AAAlignArgument(
const IRPosition &IRP, Attributor &
A) :
Base(IRP,
A) {}
5386 if (
A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument()))
5387 return ChangeStatus::UNCHANGED;
5388 return Base::manifest(
A);
5394struct AAAlignCallSiteArgument final : AAAlignFloating {
5395 AAAlignCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
5396 : AAAlignFloating(IRP,
A) {}
5402 if (Argument *Arg = getAssociatedArgument())
5403 if (
A.getInfoCache().isInvolvedInMustTailCall(*Arg))
5404 return ChangeStatus::UNCHANGED;
5406 Align InheritAlign =
5407 getAssociatedValue().getPointerAlignment(
A.getDataLayout());
5408 if (InheritAlign >= getAssumedAlign())
5409 Changed = ChangeStatus::UNCHANGED;
5415 if (Argument *Arg = getAssociatedArgument()) {
5418 const auto *ArgAlignAA =
A.getAAFor<AAAlign>(
5421 takeKnownMaximum(ArgAlignAA->getKnownAlign().value());
5430struct AAAlignCallSiteReturned final
5431 : AACalleeToCallSite<AAAlign, AAAlignImpl> {
5432 using Base = AACalleeToCallSite<AAAlign, AAAlignImpl>;
5433 AAAlignCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
5439 switch (
II->getIntrinsicID()) {
5440 case Intrinsic::ptrmask: {
5444 const auto *ConstVals =
A.getAAFor<AAPotentialConstantValues>(
5446 if (ConstVals && ConstVals->isValidState()) {
5447 unsigned ShiftValue =
5448 std::min(ConstVals->getAssumedMinTrailingZeros(),
5449 Value::MaxAlignmentExponent);
5454 const auto *AlignAA =
5456 DepClassTy::REQUIRED);
5458 Alignment = std::max(AlignAA->getAssumedAlign(), Alignment);
5465 std::min(this->getAssumedAlign(), Alignment).value());
5471 case Intrinsic::amdgcn_make_buffer_rsrc: {
5472 const auto *AlignAA =
5474 DepClassTy::REQUIRED);
5477 this->getState(), AlignAA->getAssumedAlign().
value());
5484 return Base::updateImpl(
A);
5492struct AANoReturnImpl :
public AANoReturn {
5493 AANoReturnImpl(
const IRPosition &IRP, Attributor &
A) : AANoReturn(IRP,
A) {}
5498 A,
nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
5502 const std::string getAsStr(Attributor *
A)
const override {
5503 return getAssumed() ?
"noreturn" :
"may-return";
5507 auto CheckForNoReturn = [](
Instruction &) {
return false; };
5508 bool UsedAssumedInformation =
false;
5509 if (!
A.checkForAllInstructions(CheckForNoReturn, *
this,
5510 {(unsigned)Instruction::Ret},
5511 UsedAssumedInformation))
5512 return indicatePessimisticFixpoint();
5513 return ChangeStatus::UNCHANGED;
5517struct AANoReturnFunction final : AANoReturnImpl {
5518 AANoReturnFunction(
const IRPosition &IRP, Attributor &
A)
5519 : AANoReturnImpl(IRP,
A) {}
5525struct AANoReturnCallSite final
5526 : AACalleeToCallSite<AANoReturn, AANoReturnImpl> {
5527 AANoReturnCallSite(
const IRPosition &IRP, Attributor &
A)
5528 : AACalleeToCallSite<AANoReturn, AANoReturnImpl>(IRP,
A) {}
5538struct AAInstanceInfoImpl :
public AAInstanceInfo {
5539 AAInstanceInfoImpl(
const IRPosition &IRP, Attributor &
A)
5540 : AAInstanceInfo(IRP,
A) {}
5543 Value &
V = getAssociatedValue();
5545 if (
C->isThreadDependent())
5546 indicatePessimisticFixpoint();
5548 indicateOptimisticFixpoint();
5554 indicateOptimisticFixpoint();
5559 A.getInfoCache().getAnalysisResultForFunction<CycleAnalysis>(
5562 indicatePessimisticFixpoint();
5571 Value &
V = getAssociatedValue();
5574 Scope =
I->getFunction();
5577 if (!
Scope->hasLocalLinkage())
5581 return indicateOptimisticFixpoint();
5583 bool IsKnownNoRecurse;
5589 auto UsePred = [&](
const Use &
U,
bool &Follow) {
5604 if (!Callee || !
Callee->hasLocalLinkage())
5608 const auto *ArgInstanceInfoAA =
A.getAAFor<AAInstanceInfo>(
5610 DepClassTy::OPTIONAL);
5611 if (!ArgInstanceInfoAA ||
5612 !ArgInstanceInfoAA->isAssumedUniqueForAnalysis())
5617 A, *CB, *Scope, *
this,
nullptr,
5625 auto EquivalentUseCB = [&](
const Use &OldU,
const Use &NewU) {
5627 auto *Ptr =
SI->getPointerOperand()->stripPointerCasts();
5635 if (!
A.checkForAllUses(UsePred, *
this,
V,
true,
5636 DepClassTy::OPTIONAL,
5637 true, EquivalentUseCB))
5638 return indicatePessimisticFixpoint();
5643 const std::string getAsStr(Attributor *
A)
const override {
5644 return isAssumedUniqueForAnalysis() ?
"<unique [fAa]>" :
"<unknown>";
5647 void trackStatistics()
const override {}
5651struct AAInstanceInfoFloating : AAInstanceInfoImpl {
5652 AAInstanceInfoFloating(
const IRPosition &IRP, Attributor &
A)
5653 : AAInstanceInfoImpl(IRP,
A) {}
5657struct AAInstanceInfoArgument final : AAInstanceInfoFloating {
5658 AAInstanceInfoArgument(
const IRPosition &IRP, Attributor &
A)
5659 : AAInstanceInfoFloating(IRP,
A) {}
5663struct AAInstanceInfoCallSiteArgument final : AAInstanceInfoImpl {
5664 AAInstanceInfoCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
5665 : AAInstanceInfoImpl(IRP,
A) {}
5672 Argument *Arg = getAssociatedArgument();
5674 return indicatePessimisticFixpoint();
5677 A.getAAFor<AAInstanceInfo>(*
this, ArgPos, DepClassTy::REQUIRED);
5679 return indicatePessimisticFixpoint();
5685struct AAInstanceInfoReturned final : AAInstanceInfoImpl {
5686 AAInstanceInfoReturned(
const IRPosition &IRP, Attributor &
A)
5687 : AAInstanceInfoImpl(IRP,
A) {
5701struct AAInstanceInfoCallSiteReturned final : AAInstanceInfoFloating {
5702 AAInstanceInfoCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
5703 : AAInstanceInfoFloating(IRP,
A) {}
5710 bool IgnoreSubsumingPositions) {
5711 assert(ImpliedAttributeKind == Attribute::Captures &&
5712 "Unexpected attribute kind");
5726 A.getAttrs(IRP, {Attribute::Captures}, Attrs,
5736 {Attribute::Captures, Attribute::ByVal}, Attrs,
5775 bool NoThrow =
F.doesNotThrow();
5776 bool WillReturn =
F.willReturn();
5777 bool IsVoidReturn =
F.getReturnType()->isVoidTy();
5778 if (
ReadOnly && NoThrow && WillReturn && IsVoidReturn) {
5791 if (NoThrow && IsVoidReturn)
5796 if (!NoThrow || ArgNo < 0 ||
5797 !
F.getAttributes().hasAttrSomewhere(Attribute::Returned))
5800 for (
unsigned U = 0, E =
F.arg_size(); U < E; ++U)
5801 if (
F.hasParamAttribute(U, Attribute::Returned)) {
5802 if (U ==
unsigned(ArgNo))
5826 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
5827 SmallVectorImpl<Attribute> &Attrs)
const override {
5828 if (!isAssumedNoCaptureMaybeReturned())
5831 if (isArgumentPosition()) {
5832 if (isAssumedNoCapture())
5833 Attrs.emplace_back(Attribute::get(Ctx, Attribute::Captures));
5834 else if (
A.Opts.attributor_manifest_internal)
5835 Attrs.emplace_back(Attribute::get(Ctx,
"no-capture-maybe-returned"));
5839 const std::string getAsStr(Attributor *
A)
const override {
5840 if (isKnownNoCapture())
5841 return "known not-captured";
5842 if (isAssumedNoCapture())
5843 return "assumed not-captured";
5844 if (isKnownNoCaptureMaybeReturned())
5845 return "known not-captured-maybe-returned";
5846 if (isAssumedNoCaptureMaybeReturned())
5847 return "assumed not-captured-maybe-returned";
5848 return "assumed-captured";
5853 bool checkUse(Attributor &
A, AANoCapture::StateType &State,
const Use &U,
5856 LLVM_DEBUG(
dbgs() <<
"[AANoCapture] Check use: " << *
U.get() <<
" in "
5862 return isCapturedIn(State,
true,
true,
5869 return isCapturedIn(State,
true,
true,
5875 return isCapturedIn(State,
false,
false,
5877 return isCapturedIn(State,
true,
true,
5885 return isCapturedIn(State,
true,
true,
5892 bool IsKnownNoCapture;
5893 const AANoCapture *ArgNoCaptureAA =
nullptr;
5895 A,
this, CSArgPos, DepClassTy::REQUIRED, IsKnownNoCapture,
false,
5897 if (IsAssumedNoCapture)
5898 return isCapturedIn(State,
false,
false,
5902 return isCapturedIn(State,
false,
false,
5907 return isCapturedIn(State,
true,
true,
5914 static bool isCapturedIn(AANoCapture::StateType &State,
bool CapturedInMem,
5915 bool CapturedInInt,
bool CapturedInRet) {
5916 LLVM_DEBUG(
dbgs() <<
" - captures [Mem " << CapturedInMem <<
"|Int "
5917 << CapturedInInt <<
"|Ret " << CapturedInRet <<
"]\n");
5929 const IRPosition &IRP = getIRPosition();
5933 return indicatePessimisticFixpoint();
5940 return indicatePessimisticFixpoint();
5948 T.addKnownBits(NOT_CAPTURED_IN_MEM);
5950 addKnownBits(NOT_CAPTURED_IN_MEM);
5957 auto CheckReturnedArgs = [&](
bool &UsedAssumedInformation) {
5961 UsedAssumedInformation))
5963 bool SeenConstant =
false;
5964 for (
const AA::ValueAndContext &VAC :
Values) {
5968 SeenConstant =
true;
5970 VAC.
getValue() == getAssociatedArgument())
5976 bool IsKnownNoUnwind;
5979 bool IsVoidTy =
F->getReturnType()->isVoidTy();
5980 bool UsedAssumedInformation =
false;
5981 if (IsVoidTy || CheckReturnedArgs(UsedAssumedInformation)) {
5982 T.addKnownBits(NOT_CAPTURED_IN_RET);
5985 bool IsKnownWillReturn;
5988 if (IsAssumedWillReturn &&
T.isKnown(NOT_CAPTURED_IN_MEM))
5990 if (IsKnownNoUnwind && (IsVoidTy || !UsedAssumedInformation)) {
5991 addKnownBits(NOT_CAPTURED_IN_RET);
5992 if (IsKnownWillReturn && isKnown(NOT_CAPTURED_IN_MEM))
5993 return indicateOptimisticFixpoint();
5998 auto UseCheck = [&](
const Use &
U,
bool &Follow) ->
bool {
6007 return checkUse(
A,
T, U, Follow);
6010 if (!
A.checkForAllUses(UseCheck, *
this, *
V))
6011 return indicatePessimisticFixpoint();
6014 auto Assumed = S.getAssumed();
6015 S.intersectAssumedBits(
T.getAssumed());
6016 if (!isAssumedNoCaptureMaybeReturned())
6017 return indicatePessimisticFixpoint();
6023struct AANoCaptureArgument final : AANoCaptureImpl {
6024 AANoCaptureArgument(
const IRPosition &IRP, Attributor &
A)
6025 : AANoCaptureImpl(IRP,
A) {}
6031struct AANoCaptureCallSiteArgument final : AANoCaptureImpl {
6032 AANoCaptureCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
6033 : AANoCaptureImpl(IRP,
A) {}
6040 Argument *Arg = getAssociatedArgument();
6042 return indicatePessimisticFixpoint();
6044 bool IsKnownNoCapture;
6045 const AANoCapture *ArgAA =
nullptr;
6047 A,
this, ArgPos, DepClassTy::REQUIRED, IsKnownNoCapture,
false,
6049 return ChangeStatus::UNCHANGED;
6051 return indicatePessimisticFixpoint();
6055 void trackStatistics()
const override {
6061struct AANoCaptureFloating final : AANoCaptureImpl {
6062 AANoCaptureFloating(
const IRPosition &IRP, Attributor &
A)
6063 : AANoCaptureImpl(IRP,
A) {}
6065 void trackStatistics()
const override {
6071struct AANoCaptureReturned final : AANoCaptureImpl {
6072 AANoCaptureReturned(
const IRPosition &IRP, Attributor &
A)
6073 : AANoCaptureImpl(IRP,
A) {
6085 void trackStatistics()
const override {}
6089struct AANoCaptureCallSiteReturned final : AANoCaptureImpl {
6090 AANoCaptureCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
6091 : AANoCaptureImpl(IRP,
A) {}
6096 determineFunctionCaptureCapabilities(getIRPosition(), *
F, *
this);
6099 void trackStatistics()
const override {
6116 dbgs() <<
"[ValueSimplify] is assumed to be "
6119 dbgs() <<
"[ValueSimplify] is assumed to be <none>\n";
6130 if (getAssociatedValue().
getType()->isVoidTy())
6131 indicatePessimisticFixpoint();
6132 if (
A.hasSimplificationCallback(getIRPosition()))
6133 indicatePessimisticFixpoint();
6136 const std::string getAsStr(Attributor *
A)
const override {
6138 dbgs() <<
"SAV: " << (bool)SimplifiedAssociatedValue <<
" ";
6139 if (SimplifiedAssociatedValue && *SimplifiedAssociatedValue)
6140 dbgs() <<
"SAV: " << **SimplifiedAssociatedValue <<
" ";
6142 return isValidState() ? (isAtFixpoint() ?
"simplified" :
"maybe-simple")
6146 void trackStatistics()
const override {}
6148 std::optional<Value *>
6149 getAssumedSimplifiedValue(Attributor &
A)
const override {
6150 return SimplifiedAssociatedValue;
6157 static Value *ensureType(Attributor &
A,
Value &
V,
Type &Ty, Instruction *CtxI,
6161 if (CtxI &&
V.getType()->canLosslesslyBitCastTo(&Ty))
6163 : BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6172 static Value *reproduceInst(Attributor &
A,
6173 const AbstractAttribute &QueryingAA,
6174 Instruction &
I,
Type &Ty, Instruction *CtxI,
6176 assert(CtxI &&
"Cannot reproduce an instruction without context!");
6177 if (
Check && (
I.mayReadFromMemory() ||
6182 Value *NewOp = reproduceValue(
A, QueryingAA, *
Op, Ty, CtxI,
Check, VMap);
6184 assert(
Check &&
"Manifest of new value unexpectedly failed!");
6206 static Value *reproduceValue(Attributor &
A,
6207 const AbstractAttribute &QueryingAA,
Value &
V,
6208 Type &Ty, Instruction *CtxI,
bool Check,
6210 if (
const auto &NewV = VMap.
lookup(&
V))
6212 bool UsedAssumedInformation =
false;
6213 std::optional<Value *> SimpleV =
A.getAssumedSimplified(
6215 if (!SimpleV.has_value())
6219 EffectiveV = *SimpleV;
6224 return ensureType(
A, *EffectiveV, Ty, CtxI,
Check);
6226 if (
Value *NewV = reproduceInst(
A, QueryingAA, *
I, Ty, CtxI,
Check, VMap))
6227 return ensureType(
A, *NewV, Ty, CtxI,
Check);
6233 Value *manifestReplacementValue(Attributor &
A, Instruction *CtxI)
const {
6234 Value *NewV = SimplifiedAssociatedValue
6235 ? *SimplifiedAssociatedValue
6237 if (NewV && NewV != &getAssociatedValue()) {
6241 if (reproduceValue(
A, *
this, *NewV, *getAssociatedType(), CtxI,
6243 return reproduceValue(
A, *
this, *NewV, *getAssociatedType(), CtxI,
6251 bool checkAndUpdate(Attributor &
A,
const AbstractAttribute &QueryingAA,
6252 const IRPosition &IRP,
bool Simplify =
true) {
6253 bool UsedAssumedInformation =
false;
6256 QueryingValueSimplified =
A.getAssumedSimplified(
6258 return unionAssumed(QueryingValueSimplified);
6262 template <
typename AAType>
bool askSimplifiedValueFor(Attributor &
A) {
6263 if (!getAssociatedValue().
getType()->isIntegerTy())
6268 A.getAAFor<AAType>(*
this, getIRPosition(), DepClassTy::NONE);
6272 std::optional<Constant *> COpt = AA->getAssumedConstant(
A);
6275 SimplifiedAssociatedValue = std::nullopt;
6276 A.recordDependence(*AA, *
this, DepClassTy::OPTIONAL);
6279 if (
auto *
C = *COpt) {
6280 SimplifiedAssociatedValue =
C;
6281 A.recordDependence(*AA, *
this, DepClassTy::OPTIONAL);
6287 bool askSimplifiedValueForOtherAAs(Attributor &
A) {
6288 if (askSimplifiedValueFor<AAValueConstantRange>(
A))
6290 if (askSimplifiedValueFor<AAPotentialConstantValues>(
A))
6297 for (
auto &U : getAssociatedValue().uses()) {
6302 IP =
PHI->getIncomingBlock(U)->getTerminator();
6303 if (
auto *NewV = manifestReplacementValue(
A, IP)) {
6305 <<
" -> " << *NewV <<
" :: " << *
this <<
"\n");
6306 if (
A.changeUseAfterManifest(U, *NewV))
6307 Changed = ChangeStatus::CHANGED;
6311 return Changed | AAValueSimplify::manifest(
A);
6315 SimplifiedAssociatedValue = &getAssociatedValue();
6316 return AAValueSimplify::indicatePessimisticFixpoint();
6320struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
6321 AAValueSimplifyArgument(
const IRPosition &IRP, Attributor &
A)
6322 : AAValueSimplifyImpl(IRP,
A) {}
6325 AAValueSimplifyImpl::initialize(
A);
6326 if (
A.hasAttr(getIRPosition(),
6327 {Attribute::InAlloca, Attribute::Preallocated,
6328 Attribute::StructRet, Attribute::Nest, Attribute::ByVal},
6330 indicatePessimisticFixpoint();
6336 Argument *Arg = getAssociatedArgument();
6342 return indicatePessimisticFixpoint();
6345 auto Before = SimplifiedAssociatedValue;
6347 auto PredForCallSite = [&](AbstractCallSite ACS) {
6348 const IRPosition &ACSArgPos =
6359 bool UsedAssumedInformation =
false;
6360 std::optional<Constant *> SimpleArgOp =
6361 A.getAssumedConstant(ACSArgPos, *
this, UsedAssumedInformation);
6368 return unionAssumed(*SimpleArgOp);
6373 bool UsedAssumedInformation =
false;
6374 if (hasCallBaseContext() &&
6375 getCallBaseContext()->getCalledOperand() == Arg->
getParent())
6377 AbstractCallSite(&getCallBaseContext()->getCalledOperandUse()));
6379 Success =
A.checkForAllCallSites(PredForCallSite, *
this,
true,
6380 UsedAssumedInformation);
6383 if (!askSimplifiedValueForOtherAAs(
A))
6384 return indicatePessimisticFixpoint();
6387 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6388 : ChangeStatus ::CHANGED;
6391 void trackStatistics()
const override {
6396struct AAValueSimplifyReturned : AAValueSimplifyImpl {
6397 AAValueSimplifyReturned(
const IRPosition &IRP, Attributor &
A)
6398 : AAValueSimplifyImpl(IRP,
A) {}
6400 std::optional<Value *>
6401 getAssumedSimplifiedValue(Attributor &
A)
const override {
6402 if (!isValidState())
6404 return SimplifiedAssociatedValue;
6408 auto Before = SimplifiedAssociatedValue;
6412 return checkAndUpdate(
6417 bool UsedAssumedInformation =
false;
6418 if (!
A.checkForAllInstructions(ReturnInstCB, *
this, {Instruction::Ret},
6419 UsedAssumedInformation))
6420 if (!askSimplifiedValueForOtherAAs(
A))
6421 return indicatePessimisticFixpoint();
6424 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6425 : ChangeStatus ::CHANGED;
6431 return ChangeStatus::UNCHANGED;
6434 void trackStatistics()
const override {
6439struct AAValueSimplifyFloating : AAValueSimplifyImpl {
6440 AAValueSimplifyFloating(
const IRPosition &IRP, Attributor &
A)
6441 : AAValueSimplifyImpl(IRP,
A) {}
6444 AAValueSimplifyImpl::initialize(
A);
6445 Value &
V = getAnchorValue();
6449 indicatePessimisticFixpoint();
6453 auto Before = SimplifiedAssociatedValue;
6454 if (!askSimplifiedValueForOtherAAs(
A))
6455 return indicatePessimisticFixpoint();
6458 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6459 : ChangeStatus ::CHANGED;
6462 void trackStatistics()
const override {
6467struct AAValueSimplifyFunction : AAValueSimplifyImpl {
6468 AAValueSimplifyFunction(
const IRPosition &IRP, Attributor &
A)
6469 : AAValueSimplifyImpl(IRP,
A) {}
6472 SimplifiedAssociatedValue =
nullptr;
6473 indicateOptimisticFixpoint();
6477 "AAValueSimplify(Function|CallSite)::updateImpl will not be called");
6479 void trackStatistics()
const override {
6484struct AAValueSimplifyCallSite : AAValueSimplifyFunction {
6485 AAValueSimplifyCallSite(
const IRPosition &IRP, Attributor &
A)
6486 : AAValueSimplifyFunction(IRP,
A) {}
6487 void trackStatistics()
const override {
6492struct AAValueSimplifyCallSiteReturned : AAValueSimplifyImpl {
6493 AAValueSimplifyCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
6494 : AAValueSimplifyImpl(IRP,
A) {}
6497 AAValueSimplifyImpl::initialize(
A);
6498 Function *Fn = getAssociatedFunction();
6499 assert(Fn &&
"Did expect an associted function");
6500 for (Argument &Arg : Fn->
args()) {
6505 checkAndUpdate(
A, *
this, IRP))
6506 indicateOptimisticFixpoint();
6508 indicatePessimisticFixpoint();
6515 return indicatePessimisticFixpoint();
6518 void trackStatistics()
const override {
6523struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating {
6524 AAValueSimplifyCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
6525 : AAValueSimplifyFloating(IRP,
A) {}
6530 auto *FloatAA =
A.lookupAAFor<AAValueSimplify>(
6532 if (FloatAA && FloatAA->getState().isValidState())
6535 if (
auto *NewV = manifestReplacementValue(
A, getCtxI())) {
6537 ->getArgOperandUse(getCallSiteArgNo());
6538 if (
A.changeUseAfterManifest(U, *NewV))
6539 Changed = ChangeStatus::CHANGED;
6542 return Changed | AAValueSimplify::manifest(
A);
6545 void trackStatistics()
const override {
6556 bool UsedAssumedInformation =
false;
6557 return A.checkForAllInstructions(
6560 if (CI.isTailCall() && !CI.isMustTailCall())
6564 QueryingAA, {Instruction::Call}, UsedAssumedInformation);
6569struct AAHeapToStackFunction final :
public AAHeapToStack {
6571 static bool isGlobalizedLocal(
const CallBase &CB) {
6573 return A.
isValid() &&
A.getValueAsString() ==
"__kmpc_alloc_shared";
6576 struct AllocationInfo {
6581 bool IsGlobalizedLocal =
false;
6588 } Status = STACK_DUE_TO_USE;
6592 bool HasPotentiallyFreeingUnknownUses =
false;
6596 bool MoveAllocaIntoEntry =
true;
6599 SmallSetVector<CallBase *, 1> PotentialFreeCalls{};
6602 struct DeallocationInfo {
6610 bool MightFreeUnknownObjects =
false;
6613 SmallSetVector<CallBase *, 1> PotentialAllocationCalls{};
6616 AAHeapToStackFunction(
const IRPosition &IRP, Attributor &
A)
6617 : AAHeapToStack(IRP,
A) {}
6619 ~AAHeapToStackFunction()
override {
6622 for (
auto &It : AllocationInfos)
6623 It.second->~AllocationInfo();
6624 for (
auto &It : DeallocationInfos)
6625 It.second->~DeallocationInfo();
6629 AAHeapToStack::initialize(
A);
6636 DeallocationInfos[CB] =
new (
A.Allocator) DeallocationInfo{CB, FreedOp};
6643 auto *I8Ty = Type::getInt8Ty(CB->
getParent()->getContext());
6645 AllocationInfo *AI =
new (
A.Allocator) AllocationInfo{CB};
6646 AllocationInfos[CB] = AI;
6647 AI->IsGlobalizedLocal = isGlobalizedLocal(*CB);
6653 bool UsedAssumedInformation =
false;
6654 bool Success =
A.checkForAllCallLikeInstructions(
6655 AllocationIdentifierCB, *
this, UsedAssumedInformation,
6659 assert(
Success &&
"Did not expect the call base visit callback to fail!");
6662 [](
const IRPosition &,
const AbstractAttribute *,
6663 bool &) -> std::optional<Value *> {
return nullptr; };
6664 for (
const auto &It : AllocationInfos)
6667 for (
const auto &It : DeallocationInfos)
6672 const std::string getAsStr(Attributor *
A)
const override {
6673 unsigned NumH2SMallocs = 0, NumInvalidMallocs = 0;
6674 for (
const auto &It : AllocationInfos) {
6675 if (It.second->Status == AllocationInfo::INVALID)
6676 ++NumInvalidMallocs;
6680 return "[H2S] Mallocs Good/Bad: " + std::to_string(NumH2SMallocs) +
"/" +
6681 std::to_string(NumInvalidMallocs);
6684 void trackStatistics()
const override {
6687 "Number of malloc/calloc/aligned_alloc calls converted to allocas");
6688 for (
const auto &It : AllocationInfos)
6689 if (It.second->Status != AllocationInfo::INVALID)
6693 bool isAssumedHeapToStack(
const CallBase &CB)
const override {
6695 if (AllocationInfo *AI =
6696 AllocationInfos.lookup(
const_cast<CallBase *
>(&CB)))
6697 return AI->Status != AllocationInfo::INVALID;
6701 bool isAssumedHeapToStackRemovedFree(CallBase &CB)
const override {
6702 if (!isValidState())
6705 for (
const auto &It : AllocationInfos) {
6706 AllocationInfo &AI = *It.second;
6707 if (AI.Status == AllocationInfo::INVALID)
6710 if (AI.PotentialFreeCalls.count(&CB))
6718 assert(getState().isValidState() &&
6719 "Attempted to manifest an invalid state!");
6723 const auto *
TLI =
A.getInfoCache().getTargetLibraryInfoForFunction(*
F);
6727 if (
any_of(AllocationInfos,
6728 [](
const std::pair<CallBase *, AllocationInfo *> &It) {
6729 return It.second->Status != AllocationInfo::INVALID;
6732 return ChangeStatus::UNCHANGED;
6734 for (
auto &It : AllocationInfos) {
6735 AllocationInfo &AI = *It.second;
6736 if (AI.Status == AllocationInfo::INVALID)
6739 for (CallBase *FreeCall : AI.PotentialFreeCalls) {
6740 LLVM_DEBUG(
dbgs() <<
"H2S: Removing free call: " << *FreeCall <<
"\n");
6744 A.deleteAfterManifest(*FreeCall);
6745 HasChanged = ChangeStatus::CHANGED;
6748 LLVM_DEBUG(
dbgs() <<
"H2S: Removing malloc-like call: " << *AI.CB
6751 auto Remark = [&](OptimizationRemark
OR) {
6752 if (AI.IsGlobalizedLocal)
6753 return OR <<
"Moving globalized variable to the stack.";
6754 return OR <<
"Moving memory allocation from the heap to the stack.";
6756 if (AI.IsGlobalizedLocal)
6757 A.emitRemark<OptimizationRemark>(AI.CB,
"OMP110",
Remark);
6759 A.emitRemark<OptimizationRemark>(AI.CB,
"HeapToStack",
Remark);
6761 const DataLayout &
DL =
A.getInfoCache().getDL();
6763 std::optional<APInt> SizeAPI =
getSize(
A, *
this, AI);
6765 Size = ConstantInt::get(AI.CB->getContext(), *SizeAPI);
6767 ObjectSizeOpts Opts;
6768 ObjectSizeOffsetEvaluator Eval(*AI.CB->getModule(),
TLI, Opts);
6769 SizeOffsetValue SizeOffsetPair = Eval.compute(AI.CB);
6776 ?
F->getEntryBlock().begin()
6777 : AI.CB->getIterator();
6780 if (MaybeAlign RetAlign = AI.CB->getRetAlign())
6781 Alignment = std::max(Alignment, *RetAlign);
6783 std::optional<APInt> AlignmentAPI = getAPInt(
A, *
this, *Align);
6784 assert(AlignmentAPI && AlignmentAPI->getZExtValue() > 0 &&
6785 "Expected an alignment during manifest!");
6787 std::max(Alignment,
assumeAligned(AlignmentAPI->getZExtValue()));
6791 unsigned AS =
DL.getAllocaAddrSpace();
6793 new AllocaInst(Type::getInt8Ty(
F->getContext()), AS,
Size, Alignment,
6794 AI.CB->getName() +
".h2s", IP);
6796 if (Alloca->
getType() != AI.CB->getType())
6797 Alloca = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6798 Alloca, AI.CB->getType(),
"malloc_cast", AI.CB->getIterator());
6800 auto *I8Ty = Type::getInt8Ty(
F->getContext());
6803 "Must be able to materialize initial memory state of allocation");
6808 auto *NBB =
II->getNormalDest();
6810 A.deleteAfterManifest(*AI.CB);
6812 A.deleteAfterManifest(*AI.CB);
6821 Builder.CreateMemSet(Alloca, InitVal,
Size, std::nullopt);
6823 HasChanged = ChangeStatus::CHANGED;
6826 for (CallInst *CI : TailCalls)
6827 CI->setTailCall(
false);
6832 std::optional<APInt> getAPInt(Attributor &
A,
const AbstractAttribute &AA,
6834 bool UsedAssumedInformation =
false;
6835 std::optional<Constant *> SimpleV =
6836 A.getAssumedConstant(
V, AA, UsedAssumedInformation);
6838 return APInt(64, 0);
6840 return CI->getValue();
6841 return std::nullopt;
6844 std::optional<APInt>
getSize(Attributor &
A,
const AbstractAttribute &AA,
6845 AllocationInfo &AI) {
6847 bool UsedAssumedInformation =
false;
6848 if (std::optional<Constant *> SimpleV =
6849 A.getAssumedConstant(*
V, AA, UsedAssumedInformation))
6856 const auto *
TLI =
A.getInfoCache().getTargetLibraryInfoForFunction(*
F);
6862 MapVector<CallBase *, AllocationInfo *> AllocationInfos;
6866 MapVector<CallBase *, DeallocationInfo *> DeallocationInfos;
6871ChangeStatus AAHeapToStackFunction::updateImpl(Attributor &
A) {
6875 const auto *LivenessAA =
6878 MustBeExecutedContextExplorer *Explorer =
6879 A.getInfoCache().getMustBeExecutedContextExplorer();
6881 bool StackIsAccessibleByOtherThreads =
6882 A.getInfoCache().stackIsAccessibleByOtherThreads();
6885 A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(*F);
6886 std::optional<bool> MayContainIrreducibleControl;
6888 if (&
F->getEntryBlock() == &BB)
6890 if (!MayContainIrreducibleControl.has_value())
6892 if (*MayContainIrreducibleControl)
6901 bool HasUpdatedFrees =
false;
6903 auto UpdateFrees = [&]() {
6904 HasUpdatedFrees =
true;
6906 for (
auto &It : DeallocationInfos) {
6907 DeallocationInfo &DI = *It.second;
6910 if (DI.MightFreeUnknownObjects)
6914 bool UsedAssumedInformation =
false;
6915 if (
A.isAssumedDead(*DI.CB,
this, LivenessAA, UsedAssumedInformation,
6922 LLVM_DEBUG(
dbgs() <<
"[H2S] Unknown underlying object for free!\n");
6923 DI.MightFreeUnknownObjects =
true;
6936 DI.MightFreeUnknownObjects =
true;
6940 AllocationInfo *AI = AllocationInfos.lookup(ObjCB);
6942 LLVM_DEBUG(
dbgs() <<
"[H2S] Free of a non-allocation object: " << *Obj
6944 DI.MightFreeUnknownObjects =
true;
6948 DI.PotentialAllocationCalls.insert(ObjCB);
6952 auto FreeCheck = [&](AllocationInfo &AI) {
6956 if (!StackIsAccessibleByOtherThreads) {
6961 dbgs() <<
"[H2S] found an escaping use, stack is not accessible by "
6962 "other threads and function is not nosync:\n");
6966 if (!HasUpdatedFrees)
6970 if (AI.PotentialFreeCalls.size() != 1) {
6972 << AI.PotentialFreeCalls.size() <<
"\n");
6975 CallBase *UniqueFree = *AI.PotentialFreeCalls.begin();
6976 DeallocationInfo *DI = DeallocationInfos.lookup(UniqueFree);
6979 dbgs() <<
"[H2S] unique free call was not known as deallocation call "
6980 << *UniqueFree <<
"\n");
6983 if (DI->MightFreeUnknownObjects) {
6985 dbgs() <<
"[H2S] unique free call might free unknown allocations\n");
6988 if (DI->PotentialAllocationCalls.empty())
6990 if (DI->PotentialAllocationCalls.size() > 1) {
6992 << DI->PotentialAllocationCalls.size()
6993 <<
" different allocations\n");
6996 if (*DI->PotentialAllocationCalls.begin() != AI.CB) {
6999 <<
"[H2S] unique free call not known to free this allocation but "
7000 << **DI->PotentialAllocationCalls.begin() <<
"\n");
7005 if (!AI.IsGlobalizedLocal) {
7007 if (!Explorer || !Explorer->isInContextOf(UniqueFree, CtxI)) {
7008 LLVM_DEBUG(
dbgs() <<
"[H2S] unique free call might not be executed "
7009 "with the allocation "
7010 << *UniqueFree <<
"\n");
7017 auto UsesCheck = [&](AllocationInfo &AI) {
7018 bool ValidUsesOnly =
true;
7020 auto Pred = [&](
const Use &
U,
bool &Follow) ->
bool {
7025 if (
SI->getValueOperand() ==
U.get()) {
7027 <<
"[H2S] escaping store to memory: " << *UserI <<
"\n");
7028 ValidUsesOnly =
false;
7039 ValidUsesOnly =
false;
7045 if (DeallocationInfos.count(CB)) {
7046 AI.PotentialFreeCalls.insert(CB);
7053 bool IsKnownNoCapture;
7062 if (!IsAssumedNoCapture ||
7063 (!AI.IsGlobalizedLocal && !IsAssumedNoFree)) {
7064 AI.HasPotentiallyFreeingUnknownUses |= !IsAssumedNoFree;
7067 auto Remark = [&](OptimizationRemarkMissed ORM) {
7069 <<
"Could not move globalized variable to the stack. "
7070 "Variable is potentially captured in call. Mark "
7071 "parameter as `__attribute__((noescape))` to override.";
7074 if (ValidUsesOnly && AI.IsGlobalizedLocal)
7075 A.emitRemark<OptimizationRemarkMissed>(CB,
"OMP113",
Remark);
7078 ValidUsesOnly =
false;
7091 ValidUsesOnly =
false;
7094 if (!
A.checkForAllUses(
Pred, *
this, *AI.CB,
false,
7096 [&](
const Use &OldU,
const Use &NewU) {
7097 auto *SI = dyn_cast<StoreInst>(OldU.getUser());
7098 return !SI || StackIsAccessibleByOtherThreads ||
7099 AA::isAssumedThreadLocalObject(
7100 A, *SI->getPointerOperand(), *this);
7103 return ValidUsesOnly;
7108 for (
auto &It : AllocationInfos) {
7109 AllocationInfo &AI = *It.second;
7110 if (AI.Status == AllocationInfo::INVALID)
7114 std::optional<APInt> APAlign = getAPInt(
A, *
this, *Align);
7118 LLVM_DEBUG(
dbgs() <<
"[H2S] Unknown allocation alignment: " << *AI.CB
7120 AI.Status = AllocationInfo::INVALID;
7125 !APAlign->isPowerOf2()) {
7126 LLVM_DEBUG(
dbgs() <<
"[H2S] Invalid allocation alignment: " << APAlign
7128 AI.Status = AllocationInfo::INVALID;
7135 if (!AI.IsGlobalizedLocal &&
A.Opts.max_heap_to_stack_size != -1) {
7136 if (!
Size ||
Size->ugt(
A.Opts.max_heap_to_stack_size)) {
7139 dbgs() <<
"[H2S] Unknown allocation size: " << *AI.CB <<
"\n";
7141 dbgs() <<
"[H2S] Allocation size too large: " << *AI.CB <<
" vs. "
7142 <<
A.Opts.max_heap_to_stack_size <<
"\n";
7145 AI.Status = AllocationInfo::INVALID;
7151 switch (AI.Status) {
7152 case AllocationInfo::STACK_DUE_TO_USE:
7155 AI.Status = AllocationInfo::STACK_DUE_TO_FREE;
7157 case AllocationInfo::STACK_DUE_TO_FREE:
7160 AI.Status = AllocationInfo::INVALID;
7163 case AllocationInfo::INVALID:
7170 bool IsGlobalizedLocal = AI.IsGlobalizedLocal;
7171 if (AI.MoveAllocaIntoEntry &&
7172 (!
Size.has_value() ||
7173 (!IsGlobalizedLocal && IsInLoop(*AI.CB->getParent()))))
7174 AI.MoveAllocaIntoEntry =
false;
7183struct AAPrivatizablePtrImpl :
public AAPrivatizablePtr {
7184 AAPrivatizablePtrImpl(
const IRPosition &IRP, Attributor &
A)
7185 : AAPrivatizablePtr(IRP,
A), PrivatizableType(std::nullopt) {}
7188 AAPrivatizablePtr::indicatePessimisticFixpoint();
7189 PrivatizableType =
nullptr;
7190 return ChangeStatus::CHANGED;
7196 virtual std::optional<Type *> identifyPrivatizableType(Attributor &
A) = 0;
7200 std::optional<Type *> combineTypes(std::optional<Type *> T0,
7201 std::optional<Type *>
T1) {
7211 std::optional<Type *> getPrivatizableType()
const override {
7212 return PrivatizableType;
7215 const std::string getAsStr(Attributor *
A)
const override {
7216 return isAssumedPrivatizablePtr() ?
"[priv]" :
"[no-priv]";
7220 std::optional<Type *> PrivatizableType;
7225struct AAPrivatizablePtrArgument final :
public AAPrivatizablePtrImpl {
7226 AAPrivatizablePtrArgument(
const IRPosition &IRP, Attributor &
A)
7227 : AAPrivatizablePtrImpl(IRP,
A) {}
7229 std::optional<Type *> identifyPrivatizableType(Attributor &
A)
override {
7232 bool UsedAssumedInformation =
false;
7234 A.getAttrs(getIRPosition(), {Attribute::ByVal},
Attrs,
7236 if (!
Attrs.empty() &&
7237 A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *
this,
7238 true, UsedAssumedInformation))
7239 return Attrs[0].getValueAsType();
7241 std::optional<Type *> Ty;
7242 unsigned ArgNo = getIRPosition().getCallSiteArgNo();
7250 auto CallSiteCheck = [&](AbstractCallSite ACS) {
7259 A.getAAFor<AAPrivatizablePtr>(*
this, ACSArgPos, DepClassTy::REQUIRED);
7262 std::optional<Type *> CSTy = PrivCSArgAA->getPrivatizableType();
7265 dbgs() <<
"[AAPrivatizablePtr] ACSPos: " << ACSArgPos <<
", CSTy: ";
7269 dbgs() <<
"<nullptr>";
7274 Ty = combineTypes(Ty, CSTy);
7277 dbgs() <<
" : New Type: ";
7279 (*Ty)->print(
dbgs());
7281 dbgs() <<
"<nullptr>";
7290 if (!
A.checkForAllCallSites(CallSiteCheck, *
this,
true,
7291 UsedAssumedInformation))
7297 PrivatizableType = identifyPrivatizableType(
A);
7298 if (!PrivatizableType)
7299 return ChangeStatus::UNCHANGED;
7300 if (!*PrivatizableType)
7301 return indicatePessimisticFixpoint();
7306 DepClassTy::OPTIONAL);
7309 if (!
A.hasAttr(getIRPosition(), Attribute::ByVal) &&
7312 return indicatePessimisticFixpoint();
7318 identifyReplacementTypes(*PrivatizableType, ReplacementTypes);
7322 Function &Fn = *getIRPosition().getAnchorScope();
7324 A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn);
7326 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] Missing TTI for function "
7328 return indicatePessimisticFixpoint();
7331 auto CallSiteCheck = [&](AbstractCallSite ACS) {
7338 bool UsedAssumedInformation =
false;
7339 if (!
A.checkForAllCallSites(CallSiteCheck, *
this,
true,
7340 UsedAssumedInformation)) {
7342 dbgs() <<
"[AAPrivatizablePtr] ABI incompatibility detected for "
7344 return indicatePessimisticFixpoint();
7348 Argument *Arg = getAssociatedArgument();
7349 if (!
A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) {
7351 return indicatePessimisticFixpoint();
7358 auto IsCompatiblePrivArgOfCallback = [&](CallBase &CB) {
7361 for (
const Use *U : CallbackUses) {
7362 AbstractCallSite CBACS(U);
7363 assert(CBACS && CBACS.isCallbackCall());
7364 for (Argument &CBArg : CBACS.getCalledFunction()->args()) {
7365 int CBArgNo = CBACS.getCallArgOperandNo(CBArg);
7369 <<
"[AAPrivatizablePtr] Argument " << *Arg
7370 <<
"check if can be privatized in the context of its parent ("
7372 <<
")\n[AAPrivatizablePtr] because it is an argument in a "
7374 << CBArgNo <<
"@" << CBACS.getCalledFunction()->getName()
7375 <<
")\n[AAPrivatizablePtr] " << CBArg <<
" : "
7376 << CBACS.getCallArgOperand(CBArg) <<
" vs "
7378 <<
"[AAPrivatizablePtr] " << CBArg <<
" : "
7379 << CBACS.getCallArgOperandNo(CBArg) <<
" vs " << ArgNo <<
"\n";
7382 if (CBArgNo !=
int(ArgNo))
7384 const auto *CBArgPrivAA =
A.getAAFor<AAPrivatizablePtr>(
7386 if (CBArgPrivAA && CBArgPrivAA->isValidState()) {
7387 auto CBArgPrivTy = CBArgPrivAA->getPrivatizableType();
7390 if (*CBArgPrivTy == PrivatizableType)
7395 dbgs() <<
"[AAPrivatizablePtr] Argument " << *Arg
7396 <<
" cannot be privatized in the context of its parent ("
7398 <<
")\n[AAPrivatizablePtr] because it is an argument in a "
7400 << CBArgNo <<
"@" << CBACS.getCalledFunction()->getName()
7401 <<
").\n[AAPrivatizablePtr] for which the argument "
7402 "privatization is not compatible.\n";
7412 auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) {
7416 "Expected a direct call operand for callback call operand");
7421 dbgs() <<
"[AAPrivatizablePtr] Argument " << *Arg
7422 <<
" check if be privatized in the context of its parent ("
7424 <<
")\n[AAPrivatizablePtr] because it is an argument in a "
7426 << DCArgNo <<
"@" << DCCallee->
getName() <<
").\n";
7429 if (
unsigned(DCArgNo) < DCCallee->
arg_size()) {
7430 const auto *DCArgPrivAA =
A.getAAFor<AAPrivatizablePtr>(
7432 DepClassTy::REQUIRED);
7433 if (DCArgPrivAA && DCArgPrivAA->isValidState()) {
7434 auto DCArgPrivTy = DCArgPrivAA->getPrivatizableType();
7437 if (*DCArgPrivTy == PrivatizableType)
7443 dbgs() <<
"[AAPrivatizablePtr] Argument " << *Arg
7444 <<
" cannot be privatized in the context of its parent ("
7446 <<
")\n[AAPrivatizablePtr] because it is an argument in a "
7449 <<
").\n[AAPrivatizablePtr] for which the argument "
7450 "privatization is not compatible.\n";
7458 auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) {
7462 return IsCompatiblePrivArgOfDirectCS(ACS);
7466 if (!
A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *
this,
true,
7467 UsedAssumedInformation))
7468 return indicatePessimisticFixpoint();
7470 return ChangeStatus::UNCHANGED;
7476 identifyReplacementTypes(
Type *PrivType,
7477 SmallVectorImpl<Type *> &ReplacementTypes) {
7480 assert(PrivType &&
"Expected privatizable type!");
7484 for (
unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++)
7485 ReplacementTypes.
push_back(PrivStructType->getElementType(u));
7487 ReplacementTypes.
append(PrivArrayType->getNumElements(),
7488 PrivArrayType->getElementType());
7499 assert(PrivType &&
"Expected privatizable type!");
7502 const DataLayout &
DL =
F.getDataLayout();
7506 const StructLayout *PrivStructLayout =
DL.getStructLayout(PrivStructType);
7507 for (
unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
7510 new StoreInst(
F.getArg(ArgNo + u), Ptr, IP);
7513 Type *PointeeTy = PrivArrayType->getElementType();
7514 uint64_t PointeeTySize =
DL.getTypeStoreSize(PointeeTy);
7515 for (
unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
7517 new StoreInst(
F.getArg(ArgNo + u), Ptr, IP);
7520 new StoreInst(
F.getArg(ArgNo), &
Base, IP);
7526 void createReplacementValues(Align Alignment,
Type *PrivType,
7528 SmallVectorImpl<Value *> &ReplacementValues) {
7530 assert(PrivType &&
"Expected privatizable type!");
7538 const StructLayout *PrivStructLayout =
DL.getStructLayout(PrivStructType);
7539 for (
unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
7540 Type *PointeeTy = PrivStructType->getElementType(u);
7543 LoadInst *
L =
new LoadInst(PointeeTy, Ptr,
"", IP->
getIterator());
7544 L->setAlignment(Alignment);
7548 Type *PointeeTy = PrivArrayType->getElementType();
7549 uint64_t PointeeTySize =
DL.getTypeStoreSize(PointeeTy);
7550 for (
unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
7552 LoadInst *
L =
new LoadInst(PointeeTy, Ptr,
"", IP->
getIterator());
7553 L->setAlignment(Alignment);
7558 L->setAlignment(Alignment);
7564 if (!PrivatizableType)
7565 return ChangeStatus::UNCHANGED;
7566 assert(*PrivatizableType &&
"Expected privatizable type!");
7568 Argument *Arg = getAssociatedArgument();
7571 const auto *AlignAA =
7578 [=](
const Attributor::ArgumentReplacementInfo &ARI,
7580 BasicBlock &EntryBB = ReplacementFn.getEntryBlock();
7582 const DataLayout &
DL = IP->getDataLayout();
7583 unsigned AS =
DL.getAllocaAddrSpace();
7584 Instruction *AI =
new AllocaInst(*PrivatizableType, AS,
7585 Arg->
getName() +
".priv", IP);
7586 createInitialization(*PrivatizableType, *AI, ReplacementFn,
7587 ArgIt->getArgNo(), IP);
7590 AI = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
7598 if (CI && CI->isTailCall() && !CI->isMustTailCall())
7599 CI->setTailCall(
false);
7607 [=](
const Attributor::ArgumentReplacementInfo &ARI,
7608 AbstractCallSite ACS, SmallVectorImpl<Value *> &NewArgOperands) {
7611 createReplacementValues(
7612 AlignAA ? AlignAA->getAssumedAlign() :
Align(0),
7613 *PrivatizableType, ACS,
7621 identifyReplacementTypes(*PrivatizableType, ReplacementTypes);
7624 if (
A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes,
7625 std::move(FnRepairCB),
7626 std::move(ACSRepairCB)))
7627 return ChangeStatus::CHANGED;
7628 return ChangeStatus::UNCHANGED;
7631 void trackStatistics()
const override {
7636struct AAPrivatizablePtrFloating :
public AAPrivatizablePtrImpl {
7637 AAPrivatizablePtrFloating(
const IRPosition &IRP, Attributor &
A)
7638 : AAPrivatizablePtrImpl(IRP,
A) {}
7642 indicatePessimisticFixpoint();
7647 "updateImpl will not be called");
7650 std::optional<Type *> identifyPrivatizableType(Attributor &
A)
override {
7653 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] No underlying object found!\n");
7660 return AI->getAllocatedType();
7662 auto *PrivArgAA =
A.getAAFor<AAPrivatizablePtr>(
7664 if (PrivArgAA && PrivArgAA->isAssumedPrivatizablePtr())
7665 return PrivArgAA->getPrivatizableType();
7668 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] Underlying object neither valid "
7669 "alloca nor privatizable argument: "
7674 void trackStatistics()
const override {
7679struct AAPrivatizablePtrCallSiteArgument final
7680 :
public AAPrivatizablePtrFloating {
7681 AAPrivatizablePtrCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
7682 : AAPrivatizablePtrFloating(IRP,
A) {}
7685 if (
A.hasAttr(getIRPosition(), Attribute::ByVal))
7686 indicateOptimisticFixpoint();
7690 PrivatizableType = identifyPrivatizableType(
A);
7691 if (!PrivatizableType)
7692 return ChangeStatus::UNCHANGED;
7693 if (!*PrivatizableType)
7694 return indicatePessimisticFixpoint();
7696 const IRPosition &IRP = getIRPosition();
7697 bool IsKnownNoCapture;
7699 A,
this, IRP, DepClassTy::REQUIRED, IsKnownNoCapture);
7700 if (!IsAssumedNoCapture) {
7701 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] pointer might be captured!\n");
7702 return indicatePessimisticFixpoint();
7705 bool IsKnownNoAlias;
7707 A,
this, IRP, DepClassTy::REQUIRED, IsKnownNoAlias)) {
7708 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] pointer might alias!\n");
7709 return indicatePessimisticFixpoint();
7714 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] pointer is written!\n");
7715 return indicatePessimisticFixpoint();
7718 return ChangeStatus::UNCHANGED;
7721 void trackStatistics()
const override {
7726struct AAPrivatizablePtrCallSiteReturned final
7727 :
public AAPrivatizablePtrFloating {
7728 AAPrivatizablePtrCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
7729 : AAPrivatizablePtrFloating(IRP,
A) {}
7733 indicatePessimisticFixpoint();
7736 void trackStatistics()
const override {
7741struct AAPrivatizablePtrReturned final :
public AAPrivatizablePtrFloating {
7742 AAPrivatizablePtrReturned(
const IRPosition &IRP, Attributor &
A)
7743 : AAPrivatizablePtrFloating(IRP,
A) {}
7747 indicatePessimisticFixpoint();
7750 void trackStatistics()
const override {
7760struct AAMemoryBehaviorImpl :
public AAMemoryBehavior {
7761 AAMemoryBehaviorImpl(
const IRPosition &IRP, Attributor &
A)
7762 : AAMemoryBehavior(IRP,
A) {}
7765 intersectAssumedBits(BEST_STATE);
7766 getKnownStateFromValue(
A, getIRPosition(), getState());
7767 AAMemoryBehavior::initialize(
A);
7771 static void getKnownStateFromValue(Attributor &
A,
const IRPosition &IRP,
7772 BitIntegerState &State,
7773 bool IgnoreSubsumingPositions =
false) {
7775 A.getAttrs(IRP, AttrKinds, Attrs, IgnoreSubsumingPositions);
7777 switch (Attr.getKindAsEnum()) {
7778 case Attribute::ReadNone:
7781 case Attribute::ReadOnly:
7784 case Attribute::WriteOnly:
7808 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
7809 SmallVectorImpl<Attribute> &Attrs)
const override {
7812 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
7814 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly));
7815 else if (isAssumedWriteOnly())
7816 Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly));
7821 const IRPosition &IRP = getIRPosition();
7823 if (
A.hasAttr(IRP, Attribute::ReadNone,
7825 return ChangeStatus::UNCHANGED;
7834 return ChangeStatus::UNCHANGED;
7837 A.removeAttrs(IRP, AttrKinds);
7840 A.removeAttrs(IRP, Attribute::Writable);
7846 const std::string getAsStr(Attributor *
A)
const override {
7851 if (isAssumedWriteOnly())
7853 return "may-read/write";
7857 static const Attribute::AttrKind AttrKinds[3];
7861 Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly};
7864struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl {
7865 AAMemoryBehaviorFloating(
const IRPosition &IRP, Attributor &
A)
7866 : AAMemoryBehaviorImpl(IRP,
A) {}
7870 void trackStatistics()
const override {
7875 else if (isAssumedWriteOnly())
7882 bool followUsersOfUseIn(Attributor &
A,
const Use &U,
7883 const Instruction *UserI);
7886 void analyzeUseIn(Attributor &
A,
const Use &U,
const Instruction *UserI);
7890struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating {
7891 AAMemoryBehaviorArgument(
const IRPosition &IRP, Attributor &
A)
7892 : AAMemoryBehaviorFloating(IRP,
A) {}
7895 intersectAssumedBits(BEST_STATE);
7896 const IRPosition &IRP = getIRPosition();
7900 bool HasByVal =
A.hasAttr(IRP, {Attribute::ByVal},
7902 getKnownStateFromValue(
A, IRP, getState(),
7909 return ChangeStatus::UNCHANGED;
7913 if (
A.hasAttr(getIRPosition(),
7914 {Attribute::InAlloca, Attribute::Preallocated})) {
7915 removeKnownBits(NO_WRITES);
7916 removeAssumedBits(NO_WRITES);
7918 A.removeAttrs(getIRPosition(), AttrKinds);
7919 return AAMemoryBehaviorFloating::manifest(
A);
7922 void trackStatistics()
const override {
7927 else if (isAssumedWriteOnly())
7932struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument {
7933 AAMemoryBehaviorCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
7934 : AAMemoryBehaviorArgument(IRP,
A) {}
7939 Argument *Arg = getAssociatedArgument();
7941 indicatePessimisticFixpoint();
7945 addKnownBits(NO_WRITES);
7946 removeKnownBits(NO_READS);
7947 removeAssumedBits(NO_READS);
7949 AAMemoryBehaviorArgument::initialize(
A);
7950 if (getAssociatedFunction()->isDeclaration())
7951 indicatePessimisticFixpoint();
7959 Argument *Arg = getAssociatedArgument();
7962 A.getAAFor<AAMemoryBehavior>(*
this, ArgPos, DepClassTy::REQUIRED);
7964 return indicatePessimisticFixpoint();
7968 void trackStatistics()
const override {
7973 else if (isAssumedWriteOnly())
7979struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating {
7980 AAMemoryBehaviorCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
7981 : AAMemoryBehaviorFloating(IRP,
A) {}
7984 AAMemoryBehaviorImpl::initialize(
A);
7988 return ChangeStatus::UNCHANGED;
7991 void trackStatistics()
const override {}
7995struct AAMemoryBehaviorFunction final :
public AAMemoryBehaviorImpl {
7996 AAMemoryBehaviorFunction(
const IRPosition &IRP, Attributor &
A)
7997 : AAMemoryBehaviorImpl(IRP,
A) {}
8011 else if (isAssumedWriteOnly())
8014 A.removeAttrs(getIRPosition(), AttrKinds);
8017 for (Argument &Arg :
F.args())
8019 return A.manifestAttrs(getIRPosition(),
8020 Attribute::getWithMemoryEffects(
F.getContext(), ME));
8023 void trackStatistics()
const override {
8028 else if (isAssumedWriteOnly())
8034struct AAMemoryBehaviorCallSite final
8035 : AACalleeToCallSite<AAMemoryBehavior, AAMemoryBehaviorImpl> {
8036 AAMemoryBehaviorCallSite(
const IRPosition &IRP, Attributor &
A)
8037 : AACalleeToCallSite<AAMemoryBehavior, AAMemoryBehaviorImpl>(IRP,
A) {}
8047 else if (isAssumedWriteOnly())
8050 A.removeAttrs(getIRPosition(), AttrKinds);
8053 for (Use &U : CB.
args())
8055 Attribute::Writable);
8056 return A.manifestAttrs(
8057 getIRPosition(), Attribute::getWithMemoryEffects(CB.
getContext(), ME));
8060 void trackStatistics()
const override {
8065 else if (isAssumedWriteOnly())
8070ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &
A) {
8073 auto AssumedState = getAssumed();
8080 const auto *MemBehaviorAA =
A.getAAFor<AAMemoryBehavior>(
8082 if (MemBehaviorAA) {
8083 intersectAssumedBits(MemBehaviorAA->
getAssumed());
8084 return !isAtFixpoint();
8089 if (
I.mayReadFromMemory())
8090 removeAssumedBits(NO_READS);
8091 if (
I.mayWriteToMemory())
8092 removeAssumedBits(NO_WRITES);
8093 return !isAtFixpoint();
8096 bool UsedAssumedInformation =
false;
8097 if (!
A.checkForAllReadWriteInstructions(CheckRWInst, *
this,
8098 UsedAssumedInformation))
8099 return indicatePessimisticFixpoint();
8105ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &
A) {
8107 const IRPosition &IRP = getIRPosition();
8118 const auto *FnMemAA =
8121 FnMemAssumedState = FnMemAA->getAssumed();
8122 S.addKnownBits(FnMemAA->getKnown());
8123 if ((S.getAssumed() & FnMemAA->getAssumed()) == S.getAssumed())
8129 auto AssumedState = S.getAssumed();
8135 bool IsKnownNoCapture;
8136 const AANoCapture *ArgNoCaptureAA =
nullptr;
8141 if (!IsAssumedNoCapture &&
8143 S.intersectAssumedBits(FnMemAssumedState);
8149 auto UsePred = [&](
const Use &
U,
bool &Follow) ->
bool {
8151 LLVM_DEBUG(
dbgs() <<
"[AAMemoryBehavior] Use: " << *U <<
" in " << *UserI
8159 Follow = followUsersOfUseIn(
A, U, UserI);
8163 analyzeUseIn(
A, U, UserI);
8165 return !isAtFixpoint();
8168 if (!
A.checkForAllUses(UsePred, *
this, getAssociatedValue()))
8169 return indicatePessimisticFixpoint();
8175bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &
A,
const Use &U,
8176 const Instruction *UserI) {
8194 if (
U.get()->getType()->isPointerTy()) {
8196 bool IsKnownNoCapture;
8205void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &
A,
const Use &U,
8206 const Instruction *UserI) {
8213 case Instruction::Load:
8215 removeAssumedBits(NO_READS);
8218 case Instruction::Store:
8223 removeAssumedBits(NO_WRITES);
8225 indicatePessimisticFixpoint();
8228 case Instruction::Call:
8229 case Instruction::CallBr:
8230 case Instruction::Invoke: {
8237 indicatePessimisticFixpoint();
8244 removeAssumedBits(NO_READS);
8251 if (
U.get()->getType()->isPointerTy())
8255 const auto *MemBehaviorAA =
8261 intersectAssumedBits(MemBehaviorAA->
getAssumed());
8269 removeAssumedBits(NO_READS);
8271 removeAssumedBits(NO_WRITES);
8283 return "all memory";
8286 std::string S =
"memory:";
8292 S +=
"internal global,";
8294 S +=
"external global,";
8298 S +=
"inaccessible,";
8312 AccessKind2Accesses.fill(
nullptr);
8315 ~AAMemoryLocationImpl()
override {
8318 for (AccessSet *AS : AccessKind2Accesses)
8324 intersectAssumedBits(BEST_STATE);
8325 getKnownStateFromValue(
A, getIRPosition(), getState());
8326 AAMemoryLocation::initialize(
A);
8330 static void getKnownStateFromValue(Attributor &
A,
const IRPosition &IRP,
8331 BitIntegerState &State,
8332 bool IgnoreSubsumingPositions =
false) {
8341 bool UseArgMemOnly =
true;
8343 if (AnchorFn &&
A.isRunOn(*AnchorFn))
8347 A.getAttrs(IRP, {Attribute::Memory},
Attrs, IgnoreSubsumingPositions);
8356 State.
addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM,
true,
true));
8361 State.
addKnownBits(inverseLocation(NO_ARGUMENT_MEM,
true,
true));
8365 A.manifestAttrs(IRP,
8366 Attribute::getWithMemoryEffects(
8375 NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM,
true,
true));
8379 A.manifestAttrs(IRP,
8380 Attribute::getWithMemoryEffects(
8389 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
8390 SmallVectorImpl<Attribute> &Attrs)
const override {
8397 else if (isAssumedInaccessibleMemOnly())
8398 Attrs.push_back(Attribute::getWithMemoryEffects(
8400 else if (isAssumedArgMemOnly())
8403 else if (isAssumedInaccessibleOrArgMemOnly())
8404 Attrs.push_back(Attribute::getWithMemoryEffects(
8413 const IRPosition &IRP = getIRPosition();
8417 if (DeducedAttrs.
size() != 1)
8418 return ChangeStatus::UNCHANGED;
8428 return A.manifestAttrs(IRP, Attribute::getWithMemoryEffects(
8432 bool checkForAllAccessesToMemoryKind(
8434 MemoryLocationsKind)>
8436 MemoryLocationsKind RequestedMLK)
const override {
8437 if (!isValidState())
8440 MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation();
8441 if (AssumedMLK == NO_LOCATIONS)
8445 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS;
8446 CurMLK *= 2, ++
Idx) {
8447 if (CurMLK & RequestedMLK)
8450 if (
const AccessSet *
Accesses = AccessKind2Accesses[Idx])
8451 for (
const AccessInfo &AI : *
Accesses)
8452 if (!
Pred(AI.I, AI.Ptr, AI.Kind, CurMLK))
8465 MemoryLocationsKind KnownMLK = getKnown();
8467 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2)
8468 if (!(CurMLK & KnownMLK))
8469 updateStateAndAccessesMap(getState(), CurMLK,
I,
nullptr,
Changed,
8470 getAccessKindFromInst(
I));
8471 return AAMemoryLocation::indicatePessimisticFixpoint();
8491 bool operator()(
const AccessInfo &
LHS,
const AccessInfo &
RHS)
const {
8495 return LHS.Ptr <
RHS.Ptr;
8496 if (
LHS.Kind !=
RHS.Kind)
8497 return LHS.Kind <
RHS.Kind;
8504 using AccessSet = SmallSet<AccessInfo, 2, AccessInfo>;
8505 std::array<AccessSet *, llvm::ConstantLog2<VALID_STATE>()>
8506 AccessKind2Accesses;
8511 categorizeArgumentPointerLocations(Attributor &
A, CallBase &CB,
8512 AAMemoryLocation::StateType &AccessedLocs,
8517 categorizeAccessedLocations(Attributor &
A, Instruction &
I,
bool &
Changed);
8520 AccessKind getAccessKindFromInst(
const Instruction *
I) {
8523 AK =
I->mayReadFromMemory() ? READ :
NONE;
8532 void updateStateAndAccessesMap(AAMemoryLocation::StateType &State,
8533 MemoryLocationsKind MLK,
const Instruction *
I,
8542 if (MLK == NO_UNKOWN_MEM)
8544 State.removeAssumedBits(MLK);
8549 void categorizePtrValue(Attributor &
A,
const Instruction &
I,
const Value &Ptr,
8550 AAMemoryLocation::StateType &State,
bool &
Changed,
8551 unsigned AccessAS = 0);
8557void AAMemoryLocationImpl::categorizePtrValue(
8558 Attributor &
A,
const Instruction &
I,
const Value &Ptr,
8560 LLVM_DEBUG(
dbgs() <<
"[AAMemoryLocation] Categorize pointer locations for "
8565 unsigned ObjectAS =
Obj.getType()->getPointerAddressSpace();
8567 MemoryLocationsKind MLK = NO_LOCATIONS;
8587 MLK = NO_ARGUMENT_MEM;
8593 if (GVar->isConstant())
8596 if (GV->hasLocalLinkage())
8597 MLK = NO_GLOBAL_INTERNAL_MEM;
8599 MLK = NO_GLOBAL_EXTERNAL_MEM;
8608 bool IsKnownNoAlias;
8612 MLK = NO_MALLOCED_MEM;
8614 MLK = NO_UNKOWN_MEM;
8616 MLK = NO_UNKOWN_MEM;
8619 assert(MLK != NO_LOCATIONS &&
"No location specified!");
8620 LLVM_DEBUG(
dbgs() <<
"[AAMemoryLocation] Ptr value can be categorized: "
8621 << Obj <<
" -> " << getMemoryLocationsAsStr(MLK) <<
"\n");
8623 getAccessKindFromInst(&
I));
8628 const auto *AA =
A.getAAFor<AAUnderlyingObjects>(
8632 dbgs() <<
"[AAMemoryLocation] Pointer locations not categorized\n");
8633 updateStateAndAccessesMap(
State, NO_UNKOWN_MEM, &
I,
nullptr,
Changed,
8634 getAccessKindFromInst(&
I));
8639 dbgs() <<
"[AAMemoryLocation] Accessed locations with pointer locations: "
8643void AAMemoryLocationImpl::categorizeArgumentPointerLocations(
8646 for (
unsigned ArgNo = 0,
E = CB.
arg_size(); ArgNo <
E; ++ArgNo) {
8655 const auto *ArgOpMemLocationAA =
8658 if (ArgOpMemLocationAA && ArgOpMemLocationAA->isAssumedReadNone())
8663 categorizePtrValue(
A, CB, *ArgOp, AccessedLocs,
Changed);
8668AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &
A, Instruction &
I,
8670 LLVM_DEBUG(
dbgs() <<
"[AAMemoryLocation] Categorize accessed locations for "
8674 AccessedLocs.intersectAssumedBits(NO_LOCATIONS);
8679 const auto *CBMemLocationAA =
A.getAAFor<AAMemoryLocation>(
8682 <<
" [" << CBMemLocationAA <<
"]\n");
8683 if (!CBMemLocationAA) {
8684 updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &
I,
nullptr,
8685 Changed, getAccessKindFromInst(&
I));
8686 return NO_UNKOWN_MEM;
8689 if (CBMemLocationAA->isAssumedReadNone())
8690 return NO_LOCATIONS;
8692 if (CBMemLocationAA->isAssumedInaccessibleMemOnly()) {
8693 updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &
I,
nullptr,
8694 Changed, getAccessKindFromInst(&
I));
8695 return AccessedLocs.getAssumed();
8698 uint32_t CBAssumedNotAccessedLocs =
8699 CBMemLocationAA->getAssumedNotAccessedLocation();
8702 uint32_t CBAssumedNotAccessedLocsNoArgMem =
8703 CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM;
8705 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
8706 if (CBAssumedNotAccessedLocsNoArgMem & CurMLK)
8708 updateStateAndAccessesMap(AccessedLocs, CurMLK, &
I,
nullptr,
Changed,
8709 getAccessKindFromInst(&
I));
8714 bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM);
8715 if (HasGlobalAccesses) {
8718 updateStateAndAccessesMap(AccessedLocs, MLK, &
I, Ptr,
Changed,
8719 getAccessKindFromInst(&
I));
8722 if (!CBMemLocationAA->checkForAllAccessesToMemoryKind(
8723 AccessPred, inverseLocation(NO_GLOBAL_MEM,
false,
false)))
8724 return AccessedLocs.getWorstState();
8728 dbgs() <<
"[AAMemoryLocation] Accessed state before argument handling: "
8729 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) <<
"\n");
8732 bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM);
8734 categorizeArgumentPointerLocations(
A, *CB, AccessedLocs,
Changed);
8737 dbgs() <<
"[AAMemoryLocation] Accessed state after argument handling: "
8738 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) <<
"\n");
8740 return AccessedLocs.getAssumed();
8745 dbgs() <<
"[AAMemoryLocation] Categorize memory access with pointer: "
8746 <<
I <<
" [" << *Ptr <<
"]\n");
8747 categorizePtrValue(
A,
I, *Ptr, AccessedLocs,
Changed,
8748 Ptr->getType()->getPointerAddressSpace());
8749 return AccessedLocs.getAssumed();
8752 LLVM_DEBUG(
dbgs() <<
"[AAMemoryLocation] Failed to categorize instruction: "
8754 updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &
I,
nullptr,
Changed,
8755 getAccessKindFromInst(&
I));
8756 return AccessedLocs.getAssumed();
8760struct AAMemoryLocationFunction final :
public AAMemoryLocationImpl {
8761 AAMemoryLocationFunction(
const IRPosition &IRP, Attributor &
A)
8762 : AAMemoryLocationImpl(IRP,
A) {}
8766 const auto *MemBehaviorAA =
8767 A.getAAFor<AAMemoryBehavior>(*
this, getIRPosition(), DepClassTy::NONE);
8770 return indicateOptimisticFixpoint();
8772 "AAMemoryLocation was not read-none but AAMemoryBehavior was!");
8773 A.recordDependence(*MemBehaviorAA, *
this, DepClassTy::OPTIONAL);
8774 return ChangeStatus::UNCHANGED;
8778 auto AssumedState = getAssumed();
8782 MemoryLocationsKind MLK = categorizeAccessedLocations(
A,
I,
Changed);
8783 LLVM_DEBUG(
dbgs() <<
"[AAMemoryLocation] Accessed locations for " <<
I
8784 <<
": " << getMemoryLocationsAsStr(MLK) <<
"\n");
8785 removeAssumedBits(inverseLocation(MLK,
false,
false));
8788 return getAssumedNotAccessedLocation() != VALID_STATE;
8791 bool UsedAssumedInformation =
false;
8792 if (!
A.checkForAllReadWriteInstructions(CheckRWInst, *
this,
8793 UsedAssumedInformation))
8794 return indicatePessimisticFixpoint();
8796 Changed |= AssumedState != getAssumed();
8797 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
8800 void trackStatistics()
const override {
8803 else if (isAssumedArgMemOnly())
8805 else if (isAssumedInaccessibleMemOnly())
8807 else if (isAssumedInaccessibleOrArgMemOnly())
8813struct AAMemoryLocationCallSite final : AAMemoryLocationImpl {
8814 AAMemoryLocationCallSite(
const IRPosition &IRP, Attributor &
A)
8815 : AAMemoryLocationImpl(IRP,
A) {}
8818 AAMemoryLocationImpl::initialize(
A);
8825 removeKnownBits(NO_INACCESSIBLE_MEM);
8826 updateStateAndAccessesMap(getState(), NO_INACCESSIBLE_MEM, &CB,
nullptr,
8827 Changed, getAccessKindFromInst(&CB));
8839 A.getAAFor<AAMemoryLocation>(*
this, FnPos, DepClassTy::REQUIRED);
8841 return indicatePessimisticFixpoint();
8845 updateStateAndAccessesMap(getState(), MLK,
I, Ptr,
Changed,
8846 getAccessKindFromInst(
I));
8849 if (!FnAA->checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS))
8850 return indicatePessimisticFixpoint();
8851 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
8854 void trackStatistics()
const override {
8864struct AADenormalFPMathImpl :
public AADenormalFPMath {
8865 AADenormalFPMathImpl(
const IRPosition &IRP, Attributor &
A)
8866 : AADenormalFPMath(IRP,
A) {}
8868 const std::string getAsStr(Attributor *
A)
const override {
8869 std::string Str(
"AADenormalFPMath[");
8870 raw_string_ostream OS(Str);
8872 DenormalState
Known = getKnown();
8873 if (
Known.Mode.isValid())
8874 OS <<
"denormal-fp-math=" <<
Known.Mode;
8878 if (
Known.ModeF32.isValid())
8879 OS <<
" denormal-fp-math-f32=" <<
Known.ModeF32;
8885struct AADenormalFPMathFunction final : AADenormalFPMathImpl {
8886 AADenormalFPMathFunction(
const IRPosition &IRP, Attributor &
A)
8887 : AADenormalFPMathImpl(IRP,
A) {}
8891 DenormalFPEnv DenormEnv =
F->getDenormalFPEnv();
8901 auto CheckCallSite = [=, &Change, &
A](AbstractCallSite CS) {
8904 <<
"->" << getAssociatedFunction()->
getName() <<
'\n');
8906 const auto *CallerInfo =
A.getAAFor<AADenormalFPMath>(
8912 CallerInfo->getState());
8916 bool AllCallSitesKnown =
true;
8917 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
true, AllCallSitesKnown))
8918 return indicatePessimisticFixpoint();
8920 if (Change == ChangeStatus::CHANGED && isModeFixed())
8926 LLVMContext &Ctx = getAssociatedFunction()->getContext();
8932 DenormalFPEnv KnownEnv(
Known.Mode,
Known.ModeF32);
8935 AttrToRemove.
push_back(Attribute::DenormalFPEnv);
8938 Ctx, Attribute::DenormalFPEnv,
8939 DenormalFPEnv(
Known.Mode,
Known.ModeF32).toIntValue()));
8942 auto &IRP = getIRPosition();
8945 return A.removeAttrs(IRP, AttrToRemove) |
8946 A.manifestAttrs(IRP, AttrToAdd,
true);
8949 void trackStatistics()
const override {
8958struct AAValueConstantRangeImpl : AAValueConstantRange {
8959 using StateType = IntegerRangeState;
8960 AAValueConstantRangeImpl(
const IRPosition &IRP, Attributor &
A)
8961 : AAValueConstantRange(IRP,
A) {}
8964 if (
A.hasSimplificationCallback(getIRPosition())) {
8965 indicatePessimisticFixpoint();
8970 intersectKnown(getConstantRangeFromSCEV(
A, getCtxI()));
8973 intersectKnown(getConstantRangeFromLVI(
A, getCtxI()));
8976 const std::string getAsStr(Attributor *
A)
const override {
8978 llvm::raw_string_ostream OS(Str);
8980 getKnown().print(OS);
8982 getAssumed().print(OS);
8989 const SCEV *getSCEV(Attributor &
A,
const Instruction *
I =
nullptr)
const {
8990 if (!getAnchorScope())
8993 ScalarEvolution *SE =
8994 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
8997 LoopInfo *LI =
A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
9003 const SCEV *S = SE->
getSCEV(&getAssociatedValue());
9012 ConstantRange getConstantRangeFromSCEV(Attributor &
A,
9013 const Instruction *
I =
nullptr)
const {
9014 if (!getAnchorScope())
9017 ScalarEvolution *SE =
9018 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
9021 const SCEV *S = getSCEV(
A,
I);
9031 getConstantRangeFromLVI(Attributor &
A,
9032 const Instruction *CtxI =
nullptr)
const {
9033 if (!getAnchorScope())
9036 LazyValueInfo *LVI =
9037 A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>(
9052 bool isValidCtxInstructionForOutsideAnalysis(Attributor &
A,
9053 const Instruction *CtxI,
9054 bool AllowAACtxI)
const {
9055 if (!CtxI || (!AllowAACtxI && CtxI == getCtxI()))
9067 InformationCache &InfoCache =
A.getInfoCache();
9068 const DominatorTree *DT =
9078 getAssumedConstantRange(Attributor &
A,
9079 const Instruction *CtxI =
nullptr)
const override {
9084 if (!isValidCtxInstructionForOutsideAnalysis(
A, CtxI,
9086 return getAssumed();
9088 ConstantRange LVIR = getConstantRangeFromLVI(
A, CtxI);
9089 ConstantRange SCEVR = getConstantRangeFromSCEV(
A, CtxI);
9090 return getAssumed().intersectWith(SCEVR).intersectWith(LVIR);
9095 getMDNodeForConstantRange(
Type *Ty, LLVMContext &Ctx,
9096 const ConstantRange &AssumedConstantRange) {
9098 Ty, AssumedConstantRange.
getLower())),
9100 Ty, AssumedConstantRange.
getUpper()))};
9105 static bool isBetterRange(
const ConstantRange &Assumed,
9106 const Instruction &
I) {
9110 std::optional<ConstantRange>
Known;
9114 }
else if (MDNode *KnownRanges =
I.getMetadata(LLVMContext::MD_range)) {
9120 if (KnownRanges->getNumOperands() > 2)
9123 ConstantInt *
Lower =
9125 ConstantInt *
Upper =
9135 setRangeMetadataIfisBetterRange(Instruction *
I,
9136 const ConstantRange &AssumedConstantRange) {
9137 if (isBetterRange(AssumedConstantRange, *
I)) {
9138 I->setMetadata(LLVMContext::MD_range,
9139 getMDNodeForConstantRange(
I->getType(),
I->getContext(),
9140 AssumedConstantRange));
9147 setRangeRetAttrIfisBetterRange(Attributor &
A,
const IRPosition &IRP,
9149 const ConstantRange &AssumedConstantRange) {
9150 if (isBetterRange(AssumedConstantRange, *
I)) {
9151 A.manifestAttrs(IRP,
9152 Attribute::get(
I->getContext(), Attribute::Range,
9153 AssumedConstantRange),
9162 ConstantRange AssumedConstantRange = getAssumedConstantRange(
A);
9165 auto &
V = getAssociatedValue();
9169 assert(
I == getCtxI() &&
"Should not annotate an instruction which is "
9170 "not the context instruction");
9172 if (setRangeMetadataIfisBetterRange(
I, AssumedConstantRange))
9173 Changed = ChangeStatus::CHANGED;
9175 if (setRangeRetAttrIfisBetterRange(
A, getIRPosition(),
I,
9176 AssumedConstantRange))
9177 Changed = ChangeStatus::CHANGED;
9185struct AAValueConstantRangeArgument final
9186 : AAArgumentFromCallSiteArguments<
9187 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
9189 using Base = AAArgumentFromCallSiteArguments<
9190 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
9192 AAValueConstantRangeArgument(
const IRPosition &IRP, Attributor &
A)
9195 void trackStatistics()
const override {
9200struct AAValueConstantRangeReturned
9201 : AAReturnedFromReturnedValues<AAValueConstantRange,
9202 AAValueConstantRangeImpl,
9203 AAValueConstantRangeImpl::StateType,
9206 AAReturnedFromReturnedValues<AAValueConstantRange,
9207 AAValueConstantRangeImpl,
9208 AAValueConstantRangeImpl::StateType,
9210 AAValueConstantRangeReturned(
const IRPosition &IRP, Attributor &
A)
9214 if (!
A.isFunctionIPOAmendable(*getAssociatedFunction()))
9215 indicatePessimisticFixpoint();
9218 void trackStatistics()
const override {
9223struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
9224 AAValueConstantRangeFloating(
const IRPosition &IRP, Attributor &
A)
9225 : AAValueConstantRangeImpl(IRP,
A) {}
9228 AAValueConstantRangeImpl::initialize(
A);
9232 Value &
V = getAssociatedValue();
9235 unionAssumed(ConstantRange(
C->getValue()));
9236 indicateOptimisticFixpoint();
9242 unionAssumed(ConstantRange(APInt(
getBitWidth(), 0)));
9243 indicateOptimisticFixpoint();
9255 if (
auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) {
9266 indicatePessimisticFixpoint();
9269 << getAssociatedValue() <<
"\n");
9272 bool calculateBinaryOperator(
9273 Attributor &
A, BinaryOperator *BinOp, IntegerRangeState &
T,
9274 const Instruction *CtxI,
9275 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9280 bool UsedAssumedInformation =
false;
9281 const auto &SimplifiedLHS =
A.getAssumedSimplified(
9284 if (!SimplifiedLHS.has_value())
9286 if (!*SimplifiedLHS)
9288 LHS = *SimplifiedLHS;
9290 const auto &SimplifiedRHS =
A.getAssumedSimplified(
9293 if (!SimplifiedRHS.has_value())
9295 if (!*SimplifiedRHS)
9297 RHS = *SimplifiedRHS;
9303 auto *LHSAA =
A.getAAFor<AAValueConstantRange>(
9305 DepClassTy::REQUIRED);
9309 auto LHSAARange = LHSAA->getAssumedConstantRange(
A, CtxI);
9311 auto *RHSAA =
A.getAAFor<AAValueConstantRange>(
9313 DepClassTy::REQUIRED);
9317 auto RHSAARange = RHSAA->getAssumedConstantRange(
A, CtxI);
9319 auto AssumedRange = LHSAARange.binaryOp(BinOp->
getOpcode(), RHSAARange);
9321 T.unionAssumed(AssumedRange);
9325 return T.isValidState();
9328 bool calculateCastInst(
9329 Attributor &
A, CastInst *CastI, IntegerRangeState &
T,
9330 const Instruction *CtxI,
9331 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9337 bool UsedAssumedInformation =
false;
9338 const auto &SimplifiedOpV =
A.getAssumedSimplified(
9341 if (!SimplifiedOpV.has_value())
9343 if (!*SimplifiedOpV)
9345 OpV = *SimplifiedOpV;
9350 auto *OpAA =
A.getAAFor<AAValueConstantRange>(
9352 DepClassTy::REQUIRED);
9356 T.unionAssumed(OpAA->getAssumed().castOp(CastI->
getOpcode(),
9358 return T.isValidState();
9362 calculateCmpInst(Attributor &
A, CmpInst *CmpI, IntegerRangeState &
T,
9363 const Instruction *CtxI,
9364 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9369 bool UsedAssumedInformation =
false;
9370 const auto &SimplifiedLHS =
A.getAssumedSimplified(
9373 if (!SimplifiedLHS.has_value())
9375 if (!*SimplifiedLHS)
9377 LHS = *SimplifiedLHS;
9379 const auto &SimplifiedRHS =
A.getAssumedSimplified(
9382 if (!SimplifiedRHS.has_value())
9384 if (!*SimplifiedRHS)
9386 RHS = *SimplifiedRHS;
9392 auto *LHSAA =
A.getAAFor<AAValueConstantRange>(
9394 DepClassTy::REQUIRED);
9398 auto *RHSAA =
A.getAAFor<AAValueConstantRange>(
9400 DepClassTy::REQUIRED);
9404 auto LHSAARange = LHSAA->getAssumedConstantRange(
A, CtxI);
9405 auto RHSAARange = RHSAA->getAssumedConstantRange(
A, CtxI);
9408 if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet())
9411 bool MustTrue =
false, MustFalse =
false;
9413 auto AllowedRegion =
9416 if (AllowedRegion.intersectWith(LHSAARange).isEmptySet())
9422 assert((!MustTrue || !MustFalse) &&
9423 "Either MustTrue or MustFalse should be false!");
9426 T.unionAssumed(ConstantRange(APInt( 1, 1)));
9428 T.unionAssumed(ConstantRange(APInt( 1, 0)));
9430 T.unionAssumed(ConstantRange( 1,
true));
9432 LLVM_DEBUG(
dbgs() <<
"[AAValueConstantRange] " << *CmpI <<
" after "
9433 << (MustTrue ?
"true" : (MustFalse ?
"false" :
"unknown"))
9434 <<
": " <<
T <<
"\n\t" << *LHSAA <<
"\t<op>\n\t"
9438 return T.isValidState();
9449 bool UsedAssumedInformation =
false;
9450 const auto &SimplifiedOpV =
A.getAssumedSimplified(
9453 if (!SimplifiedOpV.has_value())
9455 if (!*SimplifiedOpV)
9457 Value *VPtr = *SimplifiedOpV;
9460 const auto *AA =
A.getAAFor<AAValueConstantRange>(
9462 DepClassTy::REQUIRED);
9466 T.unionAssumed(AA->getAssumedConstantRange(
A, CtxI));
9470 return T.isValidState();
9475 if (!calculateBinaryOperator(
A, BinOp,
T, CtxI, QuerriedAAs))
9478 if (!calculateCmpInst(
A, CmpI,
T, CtxI, QuerriedAAs))
9481 if (!calculateCastInst(
A, CastI,
T, CtxI, QuerriedAAs))
9487 T.indicatePessimisticFixpoint();
9494 for (
const AAValueConstantRange *QueriedAA : QuerriedAAs) {
9495 if (QueriedAA !=
this)
9498 if (
T.getAssumed() == getState().getAssumed())
9500 T.indicatePessimisticFixpoint();
9503 return T.isValidState();
9506 if (!VisitValueCB(getAssociatedValue(), getCtxI()))
9507 return indicatePessimisticFixpoint();
9512 return ChangeStatus::UNCHANGED;
9513 if (++NumChanges > MaxNumChanges) {
9514 LLVM_DEBUG(
dbgs() <<
"[AAValueConstantRange] performed " << NumChanges
9515 <<
" but only " << MaxNumChanges
9516 <<
" are allowed to avoid cyclic reasoning.");
9517 return indicatePessimisticFixpoint();
9519 return ChangeStatus::CHANGED;
9522 void trackStatistics()
const override {
9531 static constexpr int MaxNumChanges = 5;
9534struct AAValueConstantRangeFunction : AAValueConstantRangeImpl {
9535 AAValueConstantRangeFunction(
const IRPosition &IRP, Attributor &
A)
9536 : AAValueConstantRangeImpl(IRP,
A) {}
9539 llvm_unreachable(
"AAValueConstantRange(Function|CallSite)::updateImpl will "
9546struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction {
9547 AAValueConstantRangeCallSite(
const IRPosition &IRP, Attributor &
A)
9548 : AAValueConstantRangeFunction(IRP,
A) {}
9553struct AAValueConstantRangeCallSiteReturned
9554 : AACalleeToCallSite<AAValueConstantRange, AAValueConstantRangeImpl,
9555 AAValueConstantRangeImpl::StateType,
9557 AAValueConstantRangeCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
9558 : AACalleeToCallSite<AAValueConstantRange, AAValueConstantRangeImpl,
9559 AAValueConstantRangeImpl::StateType,
9565 if (std::optional<ConstantRange>
Range = CI->getRange())
9566 intersectKnown(*
Range);
9569 AAValueConstantRangeImpl::initialize(
A);
9572 void trackStatistics()
const override {
9576struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating {
9577 AAValueConstantRangeCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
9578 : AAValueConstantRangeFloating(IRP,
A) {}
9581 return ChangeStatus::UNCHANGED;
9584 void trackStatistics()
const override {
9594 :
Base(IRP,
true,
A.Opts.attributor_max_potential_values) {}
9604 if (
A.hasSimplificationCallback(getIRPosition()))
9605 indicatePessimisticFixpoint();
9610 bool fillSetWithConstantValues(Attributor &
A,
const IRPosition &IRP, SetTy &S,
9611 bool &ContainsUndef,
bool ForSelf) {
9613 bool UsedAssumedInformation =
false;
9615 UsedAssumedInformation)) {
9622 auto *PotentialValuesAA =
A.getAAFor<AAPotentialConstantValues>(
9623 *
this, IRP, DepClassTy::REQUIRED);
9624 if (!PotentialValuesAA || !PotentialValuesAA->getState().isValidState())
9626 ContainsUndef = PotentialValuesAA->getState().undefIsContained();
9627 S = PotentialValuesAA->getState().getAssumedSet();
9634 ContainsUndef =
false;
9635 for (
auto &It :
Values) {
9637 ContainsUndef =
true;
9643 S.insert(CI->getValue());
9645 ContainsUndef &= S.empty();
9650 const std::string getAsStr(Attributor *
A)
const override {
9652 llvm::raw_string_ostream OS(Str);
9658 return indicatePessimisticFixpoint();
9662struct AAPotentialConstantValuesArgument final
9663 : AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
9664 AAPotentialConstantValuesImpl,
9665 PotentialConstantIntValuesState> {
9666 using Base = AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
9667 AAPotentialConstantValuesImpl,
9669 AAPotentialConstantValuesArgument(
const IRPosition &IRP, Attributor &
A)
9672 void trackStatistics()
const override {
9677struct AAPotentialConstantValuesReturned
9678 : AAReturnedFromReturnedValues<AAPotentialConstantValues,
9679 AAPotentialConstantValuesImpl> {
9680 using Base = AAReturnedFromReturnedValues<AAPotentialConstantValues,
9681 AAPotentialConstantValuesImpl>;
9682 AAPotentialConstantValuesReturned(
const IRPosition &IRP, Attributor &
A)
9686 if (!
A.isFunctionIPOAmendable(*getAssociatedFunction()))
9687 indicatePessimisticFixpoint();
9688 Base::initialize(
A);
9691 void trackStatistics()
const override {
9696struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
9697 AAPotentialConstantValuesFloating(
const IRPosition &IRP, Attributor &
A)
9698 : AAPotentialConstantValuesImpl(IRP,
A) {}
9701 AAPotentialConstantValuesImpl::initialize(
A);
9705 Value &
V = getAssociatedValue();
9708 unionAssumed(
C->getValue());
9709 indicateOptimisticFixpoint();
9714 unionAssumedWithUndef();
9715 indicateOptimisticFixpoint();
9725 indicatePessimisticFixpoint();
9728 << getAssociatedValue() <<
"\n");
9731 static bool calculateICmpInst(
const ICmpInst *ICI,
const APInt &
LHS,
9736 static APInt calculateCastInst(
const CastInst *CI,
const APInt &Src,
9737 uint32_t ResultBitWidth) {
9742 case Instruction::Trunc:
9743 return Src.trunc(ResultBitWidth);
9744 case Instruction::SExt:
9745 return Src.sext(ResultBitWidth);
9746 case Instruction::ZExt:
9747 return Src.zext(ResultBitWidth);
9748 case Instruction::BitCast:
9753 static APInt calculateBinaryOperator(
const BinaryOperator *BinOp,
9754 const APInt &
LHS,
const APInt &
RHS,
9755 bool &SkipOperation,
bool &Unsupported) {
9762 switch (BinOpcode) {
9766 case Instruction::Add:
9768 case Instruction::Sub:
9770 case Instruction::Mul:
9772 case Instruction::UDiv:
9774 SkipOperation =
true;
9778 case Instruction::SDiv:
9780 SkipOperation =
true;
9784 case Instruction::URem:
9786 SkipOperation =
true;
9790 case Instruction::SRem:
9792 SkipOperation =
true;
9796 case Instruction::Shl:
9798 case Instruction::LShr:
9800 case Instruction::AShr:
9802 case Instruction::And:
9804 case Instruction::Or:
9806 case Instruction::Xor:
9811 bool calculateBinaryOperatorAndTakeUnion(
const BinaryOperator *BinOp,
9812 const APInt &
LHS,
const APInt &
RHS) {
9813 bool SkipOperation =
false;
9816 calculateBinaryOperator(BinOp,
LHS,
RHS, SkipOperation, Unsupported);
9821 unionAssumed(Result);
9822 return isValidState();
9825 ChangeStatus updateWithICmpInst(Attributor &
A, ICmpInst *ICI) {
9826 auto AssumedBefore = getAssumed();
9830 bool LHSContainsUndef =
false, RHSContainsUndef =
false;
9831 SetTy LHSAAPVS, RHSAAPVS;
9833 LHSContainsUndef,
false) ||
9835 RHSContainsUndef,
false))
9836 return indicatePessimisticFixpoint();
9839 bool MaybeTrue =
false, MaybeFalse =
false;
9841 if (LHSContainsUndef && RHSContainsUndef) {
9844 unionAssumedWithUndef();
9845 }
else if (LHSContainsUndef) {
9846 for (
const APInt &R : RHSAAPVS) {
9847 bool CmpResult = calculateICmpInst(ICI,
Zero, R);
9848 MaybeTrue |= CmpResult;
9849 MaybeFalse |= !CmpResult;
9850 if (MaybeTrue & MaybeFalse)
9851 return indicatePessimisticFixpoint();
9853 }
else if (RHSContainsUndef) {
9854 for (
const APInt &L : LHSAAPVS) {
9855 bool CmpResult = calculateICmpInst(ICI, L,
Zero);
9856 MaybeTrue |= CmpResult;
9857 MaybeFalse |= !CmpResult;
9858 if (MaybeTrue & MaybeFalse)
9859 return indicatePessimisticFixpoint();
9862 for (
const APInt &L : LHSAAPVS) {
9863 for (
const APInt &R : RHSAAPVS) {
9864 bool CmpResult = calculateICmpInst(ICI, L, R);
9865 MaybeTrue |= CmpResult;
9866 MaybeFalse |= !CmpResult;
9867 if (MaybeTrue & MaybeFalse)
9868 return indicatePessimisticFixpoint();
9873 unionAssumed(APInt( 1, 1));
9875 unionAssumed(APInt( 1, 0));
9876 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9877 : ChangeStatus::CHANGED;
9880 ChangeStatus updateWithSelectInst(Attributor &
A, SelectInst *SI) {
9881 auto AssumedBefore = getAssumed();
9885 bool UsedAssumedInformation =
false;
9886 std::optional<Constant *>
C =
A.getAssumedConstant(
9887 *
SI->getCondition(), *
this, UsedAssumedInformation);
9890 bool OnlyLeft =
false, OnlyRight =
false;
9891 if (
C && *
C && (*C)->isOneValue())
9893 else if (
C && *
C && (*C)->isNullValue())
9896 bool LHSContainsUndef =
false, RHSContainsUndef =
false;
9897 SetTy LHSAAPVS, RHSAAPVS;
9900 LHSContainsUndef,
false))
9901 return indicatePessimisticFixpoint();
9905 RHSContainsUndef,
false))
9906 return indicatePessimisticFixpoint();
9908 if (OnlyLeft || OnlyRight) {
9910 auto *OpAA = OnlyLeft ? &LHSAAPVS : &RHSAAPVS;
9911 auto Undef = OnlyLeft ? LHSContainsUndef : RHSContainsUndef;
9914 unionAssumedWithUndef();
9916 for (
const auto &It : *OpAA)
9920 }
else if (LHSContainsUndef && RHSContainsUndef) {
9922 unionAssumedWithUndef();
9924 for (
const auto &It : LHSAAPVS)
9926 for (
const auto &It : RHSAAPVS)
9929 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9930 : ChangeStatus::CHANGED;
9933 ChangeStatus updateWithCastInst(Attributor &
A, CastInst *CI) {
9934 auto AssumedBefore = getAssumed();
9936 return indicatePessimisticFixpoint();
9941 bool SrcContainsUndef =
false;
9944 SrcContainsUndef,
false))
9945 return indicatePessimisticFixpoint();
9947 if (SrcContainsUndef)
9948 unionAssumedWithUndef();
9950 for (
const APInt &S : SrcPVS) {
9951 APInt
T = calculateCastInst(CI, S, ResultBitWidth);
9955 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9956 : ChangeStatus::CHANGED;
9959 ChangeStatus updateWithBinaryOperator(Attributor &
A, BinaryOperator *BinOp) {
9960 auto AssumedBefore = getAssumed();
9964 bool LHSContainsUndef =
false, RHSContainsUndef =
false;
9965 SetTy LHSAAPVS, RHSAAPVS;
9967 LHSContainsUndef,
false) ||
9969 RHSContainsUndef,
false))
9970 return indicatePessimisticFixpoint();
9975 if (LHSContainsUndef && RHSContainsUndef) {
9976 if (!calculateBinaryOperatorAndTakeUnion(BinOp,
Zero,
Zero))
9977 return indicatePessimisticFixpoint();
9978 }
else if (LHSContainsUndef) {
9979 for (
const APInt &R : RHSAAPVS) {
9980 if (!calculateBinaryOperatorAndTakeUnion(BinOp,
Zero, R))
9981 return indicatePessimisticFixpoint();
9983 }
else if (RHSContainsUndef) {
9984 for (
const APInt &L : LHSAAPVS) {
9985 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L,
Zero))
9986 return indicatePessimisticFixpoint();
9989 for (
const APInt &L : LHSAAPVS) {
9990 for (
const APInt &R : RHSAAPVS) {
9991 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, R))
9992 return indicatePessimisticFixpoint();
9996 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9997 : ChangeStatus::CHANGED;
10000 ChangeStatus updateWithInstruction(Attributor &
A, Instruction *Inst) {
10001 auto AssumedBefore = getAssumed();
10003 bool ContainsUndef;
10005 ContainsUndef,
true))
10006 return indicatePessimisticFixpoint();
10007 if (ContainsUndef) {
10008 unionAssumedWithUndef();
10010 for (
const auto &It : Incoming)
10013 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
10014 : ChangeStatus::CHANGED;
10018 Value &
V = getAssociatedValue();
10022 return updateWithICmpInst(
A, ICI);
10025 return updateWithSelectInst(
A, SI);
10028 return updateWithCastInst(
A, CI);
10031 return updateWithBinaryOperator(
A, BinOp);
10034 return updateWithInstruction(
A,
I);
10036 return indicatePessimisticFixpoint();
10039 void trackStatistics()
const override {
10044struct AAPotentialConstantValuesFunction : AAPotentialConstantValuesImpl {
10045 AAPotentialConstantValuesFunction(
const IRPosition &IRP, Attributor &
A)
10046 : AAPotentialConstantValuesImpl(IRP,
A) {}
10050 "AAPotentialConstantValues(Function|CallSite)::updateImpl will "
10054 void trackStatistics()
const override {
10059struct AAPotentialConstantValuesCallSite : AAPotentialConstantValuesFunction {
10060 AAPotentialConstantValuesCallSite(
const IRPosition &IRP, Attributor &
A)
10061 : AAPotentialConstantValuesFunction(IRP,
A) {}
10063 void trackStatistics()
const override {
10068struct AAPotentialConstantValuesCallSiteReturned
10069 : AACalleeToCallSite<AAPotentialConstantValues,
10070 AAPotentialConstantValuesImpl> {
10071 AAPotentialConstantValuesCallSiteReturned(
const IRPosition &IRP,
10073 : AACalleeToCallSite<AAPotentialConstantValues,
10074 AAPotentialConstantValuesImpl>(IRP,
A) {}
10076 void trackStatistics()
const override {
10081struct AAPotentialConstantValuesCallSiteArgument
10082 : AAPotentialConstantValuesFloating {
10083 AAPotentialConstantValuesCallSiteArgument(
const IRPosition &IRP,
10085 : AAPotentialConstantValuesFloating(IRP,
A) {}
10088 AAPotentialConstantValuesImpl::initialize(
A);
10089 if (isAtFixpoint())
10092 Value &
V = getAssociatedValue();
10095 unionAssumed(
C->getValue());
10096 indicateOptimisticFixpoint();
10101 unionAssumedWithUndef();
10102 indicateOptimisticFixpoint();
10108 Value &
V = getAssociatedValue();
10109 auto AssumedBefore = getAssumed();
10110 auto *AA =
A.getAAFor<AAPotentialConstantValues>(
10113 return indicatePessimisticFixpoint();
10114 const auto &S = AA->getAssumed();
10116 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
10117 : ChangeStatus::CHANGED;
10120 void trackStatistics()
const override {
10129 bool IgnoreSubsumingPositions) {
10130 assert(ImpliedAttributeKind == Attribute::NoUndef &&
10131 "Unexpected attribute kind");
10132 if (
A.hasAttr(IRP, {Attribute::NoUndef}, IgnoreSubsumingPositions,
10133 Attribute::NoUndef))
10152 Value &
V = getAssociatedValue();
10154 indicatePessimisticFixpoint();
10155 assert(!isImpliedByIR(
A, getIRPosition(), Attribute::NoUndef));
10159 bool followUseInMBEC(Attributor &
A,
const Use *U,
const Instruction *
I,
10160 AANoUndef::StateType &State) {
10161 const Value *UseV =
U->get();
10162 const DominatorTree *DT =
nullptr;
10163 AssumptionCache *AC =
nullptr;
10164 InformationCache &InfoCache =
A.getInfoCache();
10170 bool TrackUse =
false;
10178 const std::string getAsStr(Attributor *
A)
const override {
10179 return getAssumed() ?
"noundef" :
"may-undef-or-poison";
10186 bool UsedAssumedInformation =
false;
10187 if (
A.isAssumedDead(getIRPosition(),
nullptr,
nullptr,
10188 UsedAssumedInformation))
10189 return ChangeStatus::UNCHANGED;
10193 if (!
A.getAssumedSimplified(getIRPosition(), *
this, UsedAssumedInformation,
10196 return ChangeStatus::UNCHANGED;
10197 return AANoUndef::manifest(
A);
10201struct AANoUndefFloating :
public AANoUndefImpl {
10202 AANoUndefFloating(
const IRPosition &IRP, Attributor &
A)
10203 : AANoUndefImpl(IRP,
A) {}
10206 AANoUndefImpl::initialize(
A);
10207 if (!getState().isAtFixpoint() && getAnchorScope() &&
10208 !getAnchorScope()->isDeclaration())
10209 if (Instruction *CtxI = getCtxI())
10210 followUsesInMBEC(*
this,
A, getState(), *CtxI);
10214 auto VisitValueCB = [&](
const IRPosition &IRP) ->
bool {
10215 bool IsKnownNoUndef;
10217 A,
this, IRP, DepClassTy::REQUIRED, IsKnownNoUndef);
10221 bool UsedAssumedInformation =
false;
10222 Value *AssociatedValue = &getAssociatedValue();
10224 if (!
A.getAssumedSimplifiedValues(getIRPosition(), *
this,
Values,
10229 Values.size() != 1 ||
Values.front().getValue() != AssociatedValue;
10237 if (AVIRP == getIRPosition() || !VisitValueCB(AVIRP))
10238 return indicatePessimisticFixpoint();
10239 return ChangeStatus::UNCHANGED;
10242 for (
const auto &VAC :
Values)
10244 return indicatePessimisticFixpoint();
10246 return ChangeStatus::UNCHANGED;
10254static bool checkPoisonGeneratingAttrsHold(
Attributor &
A,
10259 AttributeMask AM = AttributeFuncs::getPoisonGeneratingAttributes();
10265 case Attribute::NonNull: {
10272 case Attribute::Alignment: {
10273 const auto *AlignAA =
10275 if (!AlignAA || AlignAA->getAssumedAlign() < *Attr.
getAlignment())
10279 case Attribute::Range: {
10287 case Attribute::NoFPClass: {
10289 const auto *NoFPClassAA =
10291 if (!NoFPClassAA ||
10292 (NoFPClassAA->getAssumedNoFPClass() & NoFPClass) != NoFPClass)
10305struct AANoUndefReturned final
10306 : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl> {
10307 using Base = AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl>;
10308 AANoUndefReturned(
const IRPosition &IRP, Attributor &
A) :
Base(IRP,
A) {}
10311 Base::initialize(
A);
10312 RetAttrs = getAssociatedFunction()->getAttributes().getRetAttrs();
10318 if (RetAttrs.hasAttributes()) {
10321 return checkPoisonGeneratingAttrsHold(
A, *
this, RetAttrs,
10324 bool UsedAssumedInformation =
false;
10325 if (!
A.checkForAllInstructions(AttrsHold, *
this, {Instruction::Ret},
10326 UsedAssumedInformation))
10327 return indicatePessimisticFixpoint();
10330 return Base::updateImpl(
A);
10337 AttributeSet RetAttrs;
10340struct AANoUndefArgument final
10341 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl> {
10342 AANoUndefArgument(
const IRPosition &IRP, Attributor &
A)
10343 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl>(IRP,
A) {}
10348struct AANoUndefCallSiteArgument final : AANoUndefFloating {
10349 AANoUndefCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
10350 : AANoUndefFloating(IRP,
A) {}
10355struct AANoUndefCallSiteReturned final
10356 : AACalleeToCallSite<AANoUndef, AANoUndefImpl> {
10357 using Base = AACalleeToCallSite<AANoUndef, AANoUndefImpl>;
10358 AANoUndefCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
10362 Base::initialize(
A);
10370 if (RetAttrs.hasAttributes()) {
10373 return checkPoisonGeneratingAttrsHold(
10377 if (!
A.checkForAllCallees(AttrsHold, *
this,
10379 return indicatePessimisticFixpoint();
10382 return Base::updateImpl(
A);
10389 AttributeSet RetAttrs;
10395 AANoFPClassImpl(
const IRPosition &IRP, Attributor &
A) : AANoFPClass(IRP,
A) {}
10398 const IRPosition &IRP = getIRPosition();
10402 indicateOptimisticFixpoint();
10407 A.getAttrs(getIRPosition(), {Attribute::NoFPClass},
Attrs,
false);
10408 for (
const auto &Attr : Attrs) {
10415 const DataLayout &
DL =
A.getDataLayout();
10416 InformationCache &InfoCache =
A.getInfoCache();
10418 const DominatorTree *DT =
nullptr;
10419 AssumptionCache *AC =
nullptr;
10420 const TargetLibraryInfo *
TLI =
nullptr;
10424 if (!
F->isDeclaration()) {
10431 SimplifyQuery Q(
DL,
TLI, DT, AC, CtxI);
10438 followUsesInMBEC(*
this,
A, getState(), *CtxI);
10442 bool followUseInMBEC(Attributor &
A,
const Use *U,
const Instruction *
I,
10443 AANoFPClass::StateType &State) {
10454 if (
auto *NoFPAA =
A.getAAFor<AANoFPClass>(*
this, IRP, DepClassTy::NONE))
10455 State.addKnownBits(NoFPAA->getState().getKnown());
10459 const std::string getAsStr(Attributor *
A)
const override {
10460 std::string
Result =
"nofpclass";
10461 raw_string_ostream OS(Result);
10462 OS << getKnownNoFPClass() <<
'/' << getAssumedNoFPClass();
10466 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
10467 SmallVectorImpl<Attribute> &Attrs)
const override {
10468 Attrs.emplace_back(Attribute::getWithNoFPClass(Ctx, getAssumedNoFPClass()));
10472struct AANoFPClassFloating :
public AANoFPClassImpl {
10473 AANoFPClassFloating(
const IRPosition &IRP, Attributor &
A)
10474 : AANoFPClassImpl(IRP,
A) {}
10478 bool UsedAssumedInformation =
false;
10479 if (!
A.getAssumedSimplifiedValues(getIRPosition(), *
this,
Values,
10481 Values.push_back({getAssociatedValue(), getCtxI()});
10487 DepClassTy::REQUIRED);
10488 if (!AA ||
this == AA) {
10489 T.indicatePessimisticFixpoint();
10491 const AANoFPClass::StateType &S =
10492 static_cast<const AANoFPClass::StateType &
>(AA->
getState());
10495 return T.isValidState();
10498 for (
const auto &VAC :
Values)
10500 return indicatePessimisticFixpoint();
10505 void trackStatistics()
const override {
10510struct AANoFPClassReturned final
10511 : AAReturnedFromReturnedValues<AANoFPClass, AANoFPClassImpl,
10512 AANoFPClassImpl::StateType, false,
10513 Attribute::None, false> {
10514 AANoFPClassReturned(
const IRPosition &IRP, Attributor &
A)
10515 : AAReturnedFromReturnedValues<AANoFPClass, AANoFPClassImpl,
10516 AANoFPClassImpl::StateType,
false,
10519 void trackStatistics()
const override {
10524struct AANoFPClassArgument final
10525 : AAArgumentFromCallSiteArguments<AANoFPClass, AANoFPClassImpl> {
10526 AANoFPClassArgument(
const IRPosition &IRP, Attributor &
A)
10527 : AAArgumentFromCallSiteArguments<AANoFPClass, AANoFPClassImpl>(IRP,
A) {}
10532struct AANoFPClassCallSiteArgument final : AANoFPClassFloating {
10533 AANoFPClassCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
10534 : AANoFPClassFloating(IRP,
A) {}
10536 void trackStatistics()
const override {
10541struct AANoFPClassCallSiteReturned final
10542 : AACalleeToCallSite<AANoFPClass, AANoFPClassImpl> {
10543 AANoFPClassCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
10544 : AACalleeToCallSite<AANoFPClass, AANoFPClassImpl>(IRP,
A) {}
10546 void trackStatistics()
const override {
10552 AACallEdgesImpl(
const IRPosition &IRP, Attributor &
A) : AACallEdges(IRP,
A) {}
10554 const SetVector<Function *> &getOptimisticEdges()
const override {
10555 return CalledFunctions;
10558 bool hasUnknownCallee()
const override {
return HasUnknownCallee; }
10560 bool hasNonAsmUnknownCallee()
const override {
10561 return HasUnknownCalleeNonAsm;
10564 const std::string getAsStr(Attributor *
A)
const override {
10565 return "CallEdges[" + std::to_string(HasUnknownCallee) +
"," +
10566 std::to_string(CalledFunctions.size()) +
"]";
10569 void trackStatistics()
const override {}
10574 static Function *getOnlyCallee(
const CallBase &CB) {
10576 if (Callee && !
Callee->hasMetadata(LLVMContext::MD_callback))
10582 if (CalledFunctions.insert(Fn)) {
10583 Change = ChangeStatus::CHANGED;
10589 void setHasUnknownCallee(
bool NonAsm,
ChangeStatus &Change) {
10590 if (!HasUnknownCallee)
10591 Change = ChangeStatus::CHANGED;
10592 if (NonAsm && !HasUnknownCalleeNonAsm)
10593 Change = ChangeStatus::CHANGED;
10594 HasUnknownCalleeNonAsm |= NonAsm;
10595 HasUnknownCallee =
true;
10600 SetVector<Function *> CalledFunctions;
10603 bool HasUnknownCallee =
false;
10606 bool HasUnknownCalleeNonAsm =
false;
10609struct AACallEdgesCallSite :
public AACallEdgesImpl {
10610 AACallEdgesCallSite(
const IRPosition &IRP, Attributor &
A)
10611 : AACallEdgesImpl(IRP,
A) {}
10617 addCalledFunction(Callee, Change);
10618 indicateOptimisticFixpoint();
10627 addCalledFunction(Fn, Change);
10629 LLVM_DEBUG(
dbgs() <<
"[AACallEdges] Unrecognized value: " <<
V <<
"\n");
10630 setHasUnknownCallee(
true, Change);
10641 VisitValue(*
V, CtxI);
10645 bool UsedAssumedInformation =
false;
10649 Values.push_back({*
V, CtxI});
10651 for (
auto &VAC :
Values)
10658 if (
IA->hasSideEffects() &&
10661 setHasUnknownCallee(
false, Change);
10667 if (
auto *IndirectCallAA =
A.getAAFor<AAIndirectCallInfo>(
10668 *
this, getIRPosition(), DepClassTy::OPTIONAL))
10669 if (IndirectCallAA->foreachCallee(
10670 [&](
Function *Fn) { return VisitValue(*Fn, CB); }))
10679 for (
const Use *U : CallbackUses)
10680 ProcessCalledOperand(
U->get(), CB);
10686struct AACallEdgesFunction :
public AACallEdgesImpl {
10687 AACallEdgesFunction(
const IRPosition &IRP, Attributor &
A)
10688 : AACallEdgesImpl(IRP,
A) {}
10692 bool AllCallsDirect =
true;
10699 if (
Function *Callee = getOnlyCallee(CB)) {
10700 addCalledFunction(Callee, Change);
10704 AllCallsDirect =
false;
10705 auto *CBEdges =
A.getAAFor<AACallEdges>(
10709 if (CBEdges->hasNonAsmUnknownCallee())
10710 setHasUnknownCallee(
true, Change);
10711 if (CBEdges->hasUnknownCallee())
10712 setHasUnknownCallee(
false, Change);
10714 for (
Function *
F : CBEdges->getOptimisticEdges())
10715 addCalledFunction(
F, Change);
10721 bool UsedAssumedInformation =
false;
10722 if (!
A.checkForAllCallLikeInstructions(ProcessCallInst, *
this,
10723 UsedAssumedInformation,
10727 setHasUnknownCallee(
true, Change);
10731 if (AllCallsDirect && !UsedAssumedInformation)
10732 indicateOptimisticFixpoint();
10740struct AAInterFnReachabilityFunction
10741 :
public CachedReachabilityAA<AAInterFnReachability, Function> {
10742 using Base = CachedReachabilityAA<AAInterFnReachability, Function>;
10743 AAInterFnReachabilityFunction(
const IRPosition &IRP, Attributor &
A)
10746 bool instructionCanReach(
10747 Attributor &
A,
const Instruction &From,
const Function &To,
10750 auto *NonConstThis =
const_cast<AAInterFnReachabilityFunction *
>(
this);
10752 RQITy StackRQI(
A, From, To, ExclusionSet,
false);
10753 RQITy::Reachable
Result;
10754 if (!NonConstThis->checkQueryCache(
A, StackRQI, Result))
10755 return NonConstThis->isReachableImpl(
A, StackRQI,
10757 return Result == RQITy::Reachable::Yes;
10761 bool IsTemporaryRQI)
override {
10763 &RQI.From->getFunction()->getEntryBlock().front();
10764 if (EntryI != RQI.From &&
10765 !instructionCanReach(
A, *EntryI, *RQI.To,
nullptr))
10766 return rememberResult(
A, RQITy::Reachable::No, RQI,
false,
10769 auto CheckReachableCallBase = [&](CallBase *CB) {
10770 auto *CBEdges =
A.getAAFor<AACallEdges>(
10772 if (!CBEdges || !CBEdges->getState().isValidState())
10775 if (CBEdges->hasUnknownCallee())
10778 for (
Function *Fn : CBEdges->getOptimisticEdges()) {
10789 if (Fn == getAnchorScope()) {
10790 if (EntryI == RQI.From)
10795 const AAInterFnReachability *InterFnReachability =
10797 DepClassTy::OPTIONAL);
10800 if (!InterFnReachability ||
10808 const auto *IntraFnReachability =
A.getAAFor<AAIntraFnReachability>(
10810 DepClassTy::OPTIONAL);
10818 return IntraFnReachability && !IntraFnReachability->isAssumedReachable(
10819 A, *RQI.From, CBInst, RQI.ExclusionSet);
10822 bool UsedExclusionSet =
true;
10823 bool UsedAssumedInformation =
false;
10824 if (!
A.checkForAllCallLikeInstructions(CheckCallBase, *
this,
10825 UsedAssumedInformation,
10827 return rememberResult(
A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
10830 return rememberResult(
A, RQITy::Reachable::No, RQI, UsedExclusionSet,
10834 void trackStatistics()
const override {}
10838template <
typename AAType>
10839static std::optional<Constant *>
10842 if (!Ty.isIntegerTy())
10850 std::optional<Constant *> COpt =
AA->getAssumedConstant(
A);
10852 if (!COpt.has_value()) {
10854 return std::nullopt;
10856 if (
auto *
C = *COpt) {
10867 std::optional<Value *> V;
10868 for (
auto &It :
Values) {
10870 if (V.has_value() && !*V)
10873 if (!V.has_value())
10886 if (
A.hasSimplificationCallback(getIRPosition())) {
10887 indicatePessimisticFixpoint();
10890 Value *Stripped = getAssociatedValue().stripPointerCasts();
10892 addValue(
A, getState(), *Stripped, getCtxI(),
AA::AnyScope,
10894 indicateOptimisticFixpoint();
10897 AAPotentialValues::initialize(
A);
10900 const std::string getAsStr(Attributor *
A)
const override {
10902 llvm::raw_string_ostream OS(Str);
10907 template <
typename AAType>
10908 static std::optional<Value *> askOtherAA(Attributor &
A,
10909 const AbstractAttribute &AA,
10910 const IRPosition &IRP,
Type &Ty) {
10915 return std::nullopt;
10922 virtual void addValue(Attributor &
A, StateType &State,
Value &
V,
10929 for (
const auto &U : CB->
args()) {
10939 Type &Ty = *getAssociatedType();
10940 std::optional<Value *> SimpleV =
10941 askOtherAA<AAValueConstantRange>(
A, *
this, ValIRP, Ty);
10942 if (SimpleV.has_value() && !*SimpleV) {
10943 auto *PotentialConstantsAA =
A.getAAFor<AAPotentialConstantValues>(
10944 *
this, ValIRP, DepClassTy::OPTIONAL);
10945 if (PotentialConstantsAA && PotentialConstantsAA->isValidState()) {
10946 for (
const auto &It : PotentialConstantsAA->getAssumedSet())
10947 State.unionAssumed({{*ConstantInt::get(&Ty, It),
nullptr}, S});
10948 if (PotentialConstantsAA->undefIsContained())
10953 if (!SimpleV.has_value())
10965 State.unionAssumed({{*VPtr, CtxI}, S});
10971 AA::ValueAndContext
I;
10975 return II.I ==
I &&
II.S == S;
10978 return std::tie(
I, S) < std::tie(
II.I,
II.S);
10985 bool recurseForValue(Attributor &
A,
const IRPosition &IRP,
AA::ValueScope S) {
10986 SmallMapVector<AA::ValueAndContext, int, 8> ValueScopeMap;
10991 bool UsedAssumedInformation =
false;
10993 if (!
A.getAssumedSimplifiedValues(IRP,
this,
Values, CS,
10994 UsedAssumedInformation))
10998 ValueScopeMap[It] |= CS;
11005 if (ValueScopeMap.
size() > 7)
11008 for (
auto &It : ValueScopeMap)
11009 addValue(
A, getState(), *It.first.getValue(), It.first.getCtxI(),
11015 void giveUpOnIntraprocedural(Attributor &
A) {
11016 auto NewS = StateType::getBestState(getState());
11017 for (
const auto &It : getAssumedSet()) {
11020 addValue(
A, NewS, *It.first.getValue(), It.first.getCtxI(),
11023 assert(!undefIsContained() &&
"Undef should be an explicit value!");
11030 getState() = StateType::getBestState(getState());
11031 getState().unionAssumed({{getAssociatedValue(), getCtxI()},
AA::AnyScope});
11032 AAPotentialValues::indicateOptimisticFixpoint();
11033 return ChangeStatus::CHANGED;
11037 return indicatePessimisticFixpoint();
11044 if (!getAssumedSimplifiedValues(
A,
Values, S))
11046 Value &OldV = getAssociatedValue();
11049 Value *NewV = getSingleValue(
A, *
this, getIRPosition(),
Values);
11050 if (!NewV || NewV == &OldV)
11055 if (
A.changeAfterManifest(getIRPosition(), *NewV))
11056 return ChangeStatus::CHANGED;
11058 return ChangeStatus::UNCHANGED;
11061 bool getAssumedSimplifiedValues(
11062 Attributor &
A, SmallVectorImpl<AA::ValueAndContext> &
Values,
11063 AA::ValueScope S,
bool RecurseForSelectAndPHI =
false)
const override {
11064 if (!isValidState())
11066 bool UsedAssumedInformation =
false;
11067 for (
const auto &It : getAssumedSet())
11068 if (It.second & S) {
11069 if (RecurseForSelectAndPHI && (
isa<PHINode>(It.first.getValue()) ||
11071 if (
A.getAssumedSimplifiedValues(
11073 this,
Values, S, UsedAssumedInformation))
11076 Values.push_back(It.first);
11078 assert(!undefIsContained() &&
"Undef should be an explicit value!");
11083struct AAPotentialValuesFloating : AAPotentialValuesImpl {
11084 AAPotentialValuesFloating(
const IRPosition &IRP, Attributor &
A)
11085 : AAPotentialValuesImpl(IRP,
A) {}
11088 auto AssumedBefore = getAssumed();
11090 genericValueTraversal(
A, &getAssociatedValue());
11092 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11093 : ChangeStatus::CHANGED;
11097 struct LivenessInfo {
11098 const AAIsDead *LivenessAA =
nullptr;
11099 bool AnyDead =
false;
11109 SmallVectorImpl<ItemInfo> &Worklist) {
11112 bool UsedAssumedInformation =
false;
11114 auto GetSimplifiedValues = [&](
Value &
V,
11116 if (!
A.getAssumedSimplifiedValues(
11120 Values.push_back(AA::ValueAndContext{
V,
II.I.getCtxI()});
11124 if (GetSimplifiedValues(*
LHS, LHSValues))
11126 if (GetSimplifiedValues(*
RHS, RHSValues))
11131 InformationCache &InfoCache =
A.getInfoCache();
11138 F ?
A.getInfoCache().getTargetLibraryInfoForFunction(*
F) :
nullptr;
11143 const DataLayout &
DL =
A.getDataLayout();
11144 SimplifyQuery Q(
DL,
TLI, DT, AC, CmpI);
11146 auto CheckPair = [&](
Value &LHSV,
Value &RHSV) {
11149 nullptr,
II.S, getAnchorScope());
11155 if (&LHSV == &RHSV &&
11157 Constant *NewV = ConstantInt::get(Type::getInt1Ty(Ctx),
11159 addValue(
A, getState(), *NewV,
nullptr,
II.S,
11166 if (TypedLHS && TypedRHS) {
11168 if (NewV && NewV != &Cmp) {
11169 addValue(
A, getState(), *NewV,
nullptr,
II.S,
11181 if (!LHSIsNull && !RHSIsNull)
11187 assert((LHSIsNull || RHSIsNull) &&
11188 "Expected nullptr versus non-nullptr comparison at this point");
11191 unsigned PtrIdx = LHSIsNull;
11192 bool IsKnownNonNull;
11195 DepClassTy::REQUIRED, IsKnownNonNull);
11196 if (!IsAssumedNonNull)
11202 addValue(
A, getState(), *NewV,
nullptr,
II.S,
11207 for (
auto &LHSValue : LHSValues)
11208 for (
auto &RHSValue : RHSValues)
11209 if (!CheckPair(*LHSValue.getValue(), *RHSValue.getValue()))
11214 bool handleSelectInst(Attributor &
A, SelectInst &SI, ItemInfo
II,
11215 SmallVectorImpl<ItemInfo> &Worklist) {
11217 bool UsedAssumedInformation =
false;
11219 std::optional<Constant *>
C =
11220 A.getAssumedConstant(*
SI.getCondition(), *
this, UsedAssumedInformation);
11221 bool NoValueYet = !
C.has_value();
11229 }
else if (&SI == &getAssociatedValue()) {
11234 std::optional<Value *> SimpleV =
A.getAssumedSimplified(
11236 if (!SimpleV.has_value())
11239 addValue(
A, getState(), **SimpleV, CtxI,
II.S, getAnchorScope());
11247 bool handleLoadInst(Attributor &
A, LoadInst &LI, ItemInfo
II,
11248 SmallVectorImpl<ItemInfo> &Worklist) {
11249 SmallSetVector<Value *, 4> PotentialCopies;
11250 SmallSetVector<Instruction *, 4> PotentialValueOrigins;
11251 bool UsedAssumedInformation =
false;
11253 PotentialValueOrigins, *
this,
11254 UsedAssumedInformation,
11256 LLVM_DEBUG(
dbgs() <<
"[AAPotentialValues] Failed to get potentially "
11257 "loaded values for load instruction "
11265 InformationCache &InfoCache =
A.getInfoCache();
11267 if (!
llvm::all_of(PotentialValueOrigins, [&](Instruction *
I) {
11271 return A.isAssumedDead(
SI->getOperandUse(0),
this,
11273 UsedAssumedInformation,
11275 return A.isAssumedDead(*
I,
this,
nullptr,
11276 UsedAssumedInformation,
11279 LLVM_DEBUG(
dbgs() <<
"[AAPotentialValues] Load is onl used by assumes "
11280 "and we cannot delete all the stores: "
11291 bool AllLocal = ScopeIsLocal;
11296 if (!DynamicallyUnique) {
11297 LLVM_DEBUG(
dbgs() <<
"[AAPotentialValues] Not all potentially loaded "
11298 "values are dynamically unique: "
11303 for (
auto *PotentialCopy : PotentialCopies) {
11305 Worklist.
push_back({{*PotentialCopy, CtxI},
II.S});
11310 if (!AllLocal && ScopeIsLocal)
11315 bool handlePHINode(
11316 Attributor &
A, PHINode &
PHI, ItemInfo
II,
11317 SmallVectorImpl<ItemInfo> &Worklist,
11318 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) {
11319 auto GetLivenessInfo = [&](
const Function &
F) -> LivenessInfo & {
11320 LivenessInfo &LI = LivenessAAs[&
F];
11321 if (!LI.LivenessAA)
11327 if (&
PHI == &getAssociatedValue()) {
11328 LivenessInfo &LI = GetLivenessInfo(*
PHI.getFunction());
11330 A.getInfoCache().getAnalysisResultForFunction<CycleAnalysis>(
11331 *
PHI.getFunction());
11335 for (
unsigned u = 0, e =
PHI.getNumIncomingValues(); u < e; u++) {
11337 if (LI.LivenessAA &&
11338 LI.LivenessAA->isEdgeDead(IncomingBB,
PHI.getParent())) {
11357 bool UsedAssumedInformation =
false;
11358 std::optional<Value *> SimpleV =
A.getAssumedSimplified(
11360 if (!SimpleV.has_value())
11364 addValue(
A, getState(), **SimpleV, &
PHI,
II.S, getAnchorScope());
11371 bool handleGenericInst(Attributor &
A, Instruction &
I, ItemInfo
II,
11372 SmallVectorImpl<ItemInfo> &Worklist) {
11373 bool SomeSimplified =
false;
11374 bool UsedAssumedInformation =
false;
11376 SmallVector<Value *, 8> NewOps(
I.getNumOperands());
11379 const auto &SimplifiedOp =
A.getAssumedSimplified(
11384 if (!SimplifiedOp.has_value())
11388 NewOps[
Idx] = *SimplifiedOp;
11392 SomeSimplified |= (NewOps[
Idx] !=
Op);
11398 if (!SomeSimplified)
11401 InformationCache &InfoCache =
A.getInfoCache();
11405 const auto *
TLI =
A.getInfoCache().getTargetLibraryInfoForFunction(*
F);
11408 const DataLayout &
DL =
I.getDataLayout();
11409 SimplifyQuery Q(
DL,
TLI, DT, AC, &
I);
11411 if (!NewV || NewV == &
I)
11414 LLVM_DEBUG(
dbgs() <<
"Generic inst " <<
I <<
" assumed simplified to "
11421 Attributor &
A, Instruction &
I, ItemInfo
II,
11422 SmallVectorImpl<ItemInfo> &Worklist,
11423 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) {
11426 CI->getPredicate(),
II, Worklist);
11428 switch (
I.getOpcode()) {
11429 case Instruction::Select:
11431 case Instruction::PHI:
11433 case Instruction::Load:
11436 return handleGenericInst(
A,
I,
II, Worklist);
11441 void genericValueTraversal(Attributor &
A,
Value *InitialV) {
11442 SmallMapVector<const Function *, LivenessInfo, 4> LivenessAAs;
11444 SmallSet<ItemInfo, 16> Visited;
11462 if (Iteration++ >=
A.Opts.attributor_max_potential_values_iterations) {
11463 LLVM_DEBUG(
dbgs() <<
"Generic value traversal reached iteration limit: "
11464 << Iteration <<
"!\n");
11465 addValue(
A, getState(), *
V, CtxI, S, getAnchorScope());
11471 Value *NewV =
nullptr;
11472 if (
V->getType()->isPointerTy()) {
11478 for (Argument &Arg :
Callee->args())
11485 if (NewV && NewV !=
V) {
11486 Worklist.
push_back({{*NewV, CtxI}, S});
11500 if (
V == InitialV && CtxI == getCtxI()) {
11501 indicatePessimisticFixpoint();
11505 addValue(
A, getState(), *
V, CtxI, S, getAnchorScope());
11506 }
while (!Worklist.
empty());
11510 for (
auto &It : LivenessAAs)
11511 if (It.second.AnyDead)
11512 A.recordDependence(*It.second.LivenessAA, *
this, DepClassTy::OPTIONAL);
11515 void trackStatistics()
const override {
11520struct AAPotentialValuesArgument final : AAPotentialValuesImpl {
11521 using Base = AAPotentialValuesImpl;
11522 AAPotentialValuesArgument(
const IRPosition &IRP, Attributor &
A)
11528 indicatePessimisticFixpoint();
11532 auto AssumedBefore = getAssumed();
11534 unsigned ArgNo = getCalleeArgNo();
11536 bool UsedAssumedInformation =
false;
11538 auto CallSitePred = [&](AbstractCallSite ACS) {
11540 if (CSArgIRP.getPositionKind() == IRP_INVALID)
11543 if (!
A.getAssumedSimplifiedValues(CSArgIRP,
this,
Values,
11545 UsedAssumedInformation))
11548 return isValidState();
11551 if (!
A.checkForAllCallSites(CallSitePred, *
this,
11553 UsedAssumedInformation))
11554 return indicatePessimisticFixpoint();
11556 Function *Fn = getAssociatedFunction();
11557 bool AnyNonLocal =
false;
11558 for (
auto &It :
Values) {
11560 addValue(
A, getState(), *It.getValue(), It.getCtxI(),
AA::AnyScope,
11565 return indicatePessimisticFixpoint();
11569 addValue(
A, getState(), *It.getValue(), It.getCtxI(),
AA::AnyScope,
11575 AnyNonLocal =
true;
11577 assert(!undefIsContained() &&
"Undef should be an explicit value!");
11579 giveUpOnIntraprocedural(
A);
11581 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11582 : ChangeStatus::CHANGED;
11585 void trackStatistics()
const override {
11590struct AAPotentialValuesReturned :
public AAPotentialValuesFloating {
11591 using Base = AAPotentialValuesFloating;
11592 AAPotentialValuesReturned(
const IRPosition &IRP, Attributor &
A)
11597 if (!
F ||
F->isDeclaration() ||
F->getReturnType()->isVoidTy()) {
11598 indicatePessimisticFixpoint();
11602 for (Argument &Arg :
F->args())
11605 ReturnedArg = &Arg;
11608 if (!
A.isFunctionIPOAmendable(*
F) ||
11609 A.hasSimplificationCallback(getIRPosition())) {
11611 indicatePessimisticFixpoint();
11613 indicateOptimisticFixpoint();
11618 auto AssumedBefore = getAssumed();
11619 bool UsedAssumedInformation =
false;
11622 Function *AnchorScope = getAnchorScope();
11628 UsedAssumedInformation,
11634 bool AllInterAreIntra =
false;
11641 for (
const AA::ValueAndContext &VAC :
Values) {
11642 addValue(
A, getState(), *VAC.
getValue(),
11646 if (AllInterAreIntra)
11653 HandleReturnedValue(*ReturnedArg,
nullptr,
true);
11656 bool AddValues =
true;
11659 addValue(
A, getState(), *RetI.getOperand(0), &RetI,
AA::AnyScope,
11663 return HandleReturnedValue(*RetI.getOperand(0), &RetI, AddValues);
11666 if (!
A.checkForAllInstructions(RetInstPred, *
this, {Instruction::Ret},
11667 UsedAssumedInformation,
11669 return indicatePessimisticFixpoint();
11672 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11673 : ChangeStatus::CHANGED;
11678 return ChangeStatus::UNCHANGED;
11680 if (!getAssumedSimplifiedValues(
A,
Values, AA::ValueScope::Intraprocedural,
11682 return ChangeStatus::UNCHANGED;
11683 Value *NewVal = getSingleValue(
A, *
this, getIRPosition(),
Values);
11685 return ChangeStatus::UNCHANGED;
11690 "Number of function with unique return");
11693 {Attribute::get(Arg->
getContext(), Attribute::Returned)});
11698 Value *RetOp = RetI.getOperand(0);
11702 if (
A.changeUseAfterManifest(RetI.getOperandUse(0), *NewVal))
11703 Changed = ChangeStatus::CHANGED;
11706 bool UsedAssumedInformation =
false;
11707 (void)
A.checkForAllInstructions(RetInstPred, *
this, {Instruction::Ret},
11708 UsedAssumedInformation,
11714 return AAPotentialValues::indicatePessimisticFixpoint();
11717 void trackStatistics()
const override{
11724struct AAPotentialValuesFunction : AAPotentialValuesImpl {
11725 AAPotentialValuesFunction(
const IRPosition &IRP, Attributor &
A)
11726 : AAPotentialValuesImpl(IRP,
A) {}
11733 void trackStatistics()
const override {
11738struct AAPotentialValuesCallSite : AAPotentialValuesFunction {
11739 AAPotentialValuesCallSite(
const IRPosition &IRP, Attributor &
A)
11740 : AAPotentialValuesFunction(IRP,
A) {}
11742 void trackStatistics()
const override {
11747struct AAPotentialValuesCallSiteReturned : AAPotentialValuesImpl {
11748 AAPotentialValuesCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
11749 : AAPotentialValuesImpl(IRP,
A) {}
11752 auto AssumedBefore = getAssumed();
11756 return indicatePessimisticFixpoint();
11758 bool UsedAssumedInformation =
false;
11762 UsedAssumedInformation))
11763 return indicatePessimisticFixpoint();
11769 for (
const AA::ValueAndContext &It :
Values) {
11770 Value *
V = It.getValue();
11771 std::optional<Value *> CallerV =
A.translateArgumentToCallSiteContent(
11772 V, *CB, *
this, UsedAssumedInformation);
11773 if (!CallerV.has_value()) {
11777 V = *CallerV ? *CallerV :
V;
11783 giveUpOnIntraprocedural(
A);
11786 addValue(
A, getState(), *
V, CB, S, getAnchorScope());
11793 UsedAssumedInformation))
11794 return indicatePessimisticFixpoint();
11804 bool OnlyArgsAndConstants =
11812 if (!OnlyArgsAndConstants) {
11816 UsedAssumedInformation))
11817 return indicatePessimisticFixpoint();
11821 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11822 : ChangeStatus::CHANGED;
11826 return AAPotentialValues::indicatePessimisticFixpoint();
11829 void trackStatistics()
const override {
11834struct AAPotentialValuesCallSiteArgument : AAPotentialValuesFloating {
11835 AAPotentialValuesCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
11836 : AAPotentialValuesFloating(IRP,
A) {}
11838 void trackStatistics()
const override {
11847 AAAssumptionInfoImpl(
const IRPosition &IRP, Attributor &
A,
11848 const DenseSet<StringRef> &
Known)
11849 : AAAssumptionInfo(IRP,
A,
Known) {}
11853 if (getKnown().isUniversal())
11854 return ChangeStatus::UNCHANGED;
11856 const IRPosition &IRP = getIRPosition();
11858 getAssumed().getSet().
end());
11860 return A.manifestAttrs(IRP,
11867 bool hasAssumption(
const StringRef Assumption)
const override {
11868 return isValidState() && setContains(Assumption);
11871 const std::string getAsStr(Attributor *
A)
const override {
11872 const SetContents &
Known = getKnown();
11873 const SetContents &Assumed = getAssumed();
11877 const std::string KnownStr =
llvm::join(Set,
",");
11879 std::string AssumedStr =
"Universal";
11880 if (!Assumed.isUniversal()) {
11881 Set.assign(Assumed.getSet().begin(), Assumed.getSet().end());
11884 return "Known [" + KnownStr +
"]," +
" Assumed [" + AssumedStr +
"]";
11899struct AAAssumptionInfoFunction final : AAAssumptionInfoImpl {
11900 AAAssumptionInfoFunction(
const IRPosition &IRP, Attributor &
A)
11901 : AAAssumptionInfoImpl(IRP,
A,
11907 auto CallSitePred = [&](AbstractCallSite ACS) {
11908 const auto *AssumptionAA =
A.getAAFor<AAAssumptionInfo>(
11910 DepClassTy::REQUIRED);
11914 Changed |= getIntersection(AssumptionAA->getAssumed());
11915 return !getAssumed().empty() || !getKnown().empty();
11918 bool UsedAssumedInformation =
false;
11923 if (!
A.checkForAllCallSites(CallSitePred, *
this,
true,
11924 UsedAssumedInformation))
11925 return indicatePessimisticFixpoint();
11927 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
11930 void trackStatistics()
const override {}
11934struct AAAssumptionInfoCallSite final : AAAssumptionInfoImpl {
11936 AAAssumptionInfoCallSite(
const IRPosition &IRP, Attributor &
A)
11937 : AAAssumptionInfoImpl(IRP,
A, getInitialAssumptions(IRP)) {}
11941 A.getAAFor<AAAssumptionInfo>(*
this, FnPos, DepClassTy::REQUIRED);
11946 auto *AssumptionAA =
11947 A.getAAFor<AAAssumptionInfo>(*
this, FnPos, DepClassTy::REQUIRED);
11949 return indicatePessimisticFixpoint();
11950 bool Changed = getIntersection(AssumptionAA->getAssumed());
11951 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
11954 void trackStatistics()
const override {}
11959 DenseSet<StringRef> getInitialAssumptions(
const IRPosition &IRP) {
11966 return Assumptions;
11981struct AAUnderlyingObjectsImpl
11986 const std::string getAsStr(
Attributor *
A)
const override {
11987 if (!isValidState())
11988 return "<invalid>";
11991 OS <<
"underlying objects: inter " << InterAssumedUnderlyingObjects.size()
11992 <<
" objects, intra " << IntraAssumedUnderlyingObjects.size()
11994 if (!InterAssumedUnderlyingObjects.empty()) {
11995 OS <<
"inter objects:\n";
11996 for (
auto *Obj : InterAssumedUnderlyingObjects)
11997 OS << *Obj <<
'\n';
11999 if (!IntraAssumedUnderlyingObjects.empty()) {
12000 OS <<
"intra objects:\n";
12001 for (
auto *Obj : IntraAssumedUnderlyingObjects)
12002 OS << *
Obj <<
'\n';
12007 void trackStatistics()
const override {}
12010 auto &Ptr = getAssociatedValue();
12012 bool UsedAssumedInformation =
false;
12013 auto DoUpdate = [&](SmallSetVector<Value *, 8> &UnderlyingObjects,
12015 SmallPtrSet<Value *, 8> SeenObjects;
12019 Scope, UsedAssumedInformation))
12020 return UnderlyingObjects.
insert(&Ptr);
12024 for (
unsigned I = 0;
I <
Values.size(); ++
I) {
12028 if (!SeenObjects.
insert(UO ? UO : Obj).second)
12030 if (UO && UO != Obj) {
12036 const auto *OtherAA =
A.getAAFor<AAUnderlyingObjects>(
12042 Values.emplace_back(
V,
nullptr);
12046 if (!OtherAA || !OtherAA->forallUnderlyingObjects(
Pred, Scope))
12048 "The forall call should not return false at this position");
12054 Changed |= handleIndirect(
A, *Obj, UnderlyingObjects, Scope,
12055 UsedAssumedInformation);
12061 for (
unsigned u = 0, e =
PHI->getNumIncomingValues(); u < e; u++) {
12063 handleIndirect(
A, *
PHI->getIncomingValue(u), UnderlyingObjects,
12064 Scope, UsedAssumedInformation);
12078 if (!UsedAssumedInformation)
12079 indicateOptimisticFixpoint();
12080 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
12083 bool forallUnderlyingObjects(
12086 if (!isValidState())
12087 return Pred(getAssociatedValue());
12090 ? IntraAssumedUnderlyingObjects
12091 : InterAssumedUnderlyingObjects;
12092 for (
Value *Obj : AssumedUnderlyingObjects)
12102 bool handleIndirect(Attributor &
A,
Value &
V,
12103 SmallSetVector<Value *, 8> &UnderlyingObjects,
12106 const auto *AA =
A.getAAFor<AAUnderlyingObjects>(
12112 if (!AA || !AA->forallUnderlyingObjects(
Pred, Scope))
12114 "The forall call should not return false at this position");
12120 SmallSetVector<Value *, 8> IntraAssumedUnderlyingObjects;
12122 SmallSetVector<Value *, 8> InterAssumedUnderlyingObjects;
12125struct AAUnderlyingObjectsFloating final : AAUnderlyingObjectsImpl {
12126 AAUnderlyingObjectsFloating(
const IRPosition &IRP, Attributor &
A)
12127 : AAUnderlyingObjectsImpl(IRP,
A) {}
12130struct AAUnderlyingObjectsArgument final : AAUnderlyingObjectsImpl {
12131 AAUnderlyingObjectsArgument(
const IRPosition &IRP, Attributor &
A)
12132 : AAUnderlyingObjectsImpl(IRP,
A) {}
12135struct AAUnderlyingObjectsCallSite final : AAUnderlyingObjectsImpl {
12136 AAUnderlyingObjectsCallSite(
const IRPosition &IRP, Attributor &
A)
12137 : AAUnderlyingObjectsImpl(IRP,
A) {}
12140struct AAUnderlyingObjectsCallSiteArgument final : AAUnderlyingObjectsImpl {
12141 AAUnderlyingObjectsCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
12142 : AAUnderlyingObjectsImpl(IRP,
A) {}
12145struct AAUnderlyingObjectsReturned final : AAUnderlyingObjectsImpl {
12146 AAUnderlyingObjectsReturned(
const IRPosition &IRP, Attributor &
A)
12147 : AAUnderlyingObjectsImpl(IRP,
A) {}
12150struct AAUnderlyingObjectsCallSiteReturned final : AAUnderlyingObjectsImpl {
12151 AAUnderlyingObjectsCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
12152 : AAUnderlyingObjectsImpl(IRP,
A) {}
12155struct AAUnderlyingObjectsFunction final : AAUnderlyingObjectsImpl {
12156 AAUnderlyingObjectsFunction(
const IRPosition &IRP, Attributor &
A)
12157 : AAUnderlyingObjectsImpl(IRP,
A) {}
12164 AAGlobalValueInfoFloating(
const IRPosition &IRP, Attributor &
A)
12165 : AAGlobalValueInfo(IRP,
A) {}
12169 bool checkUse(Attributor &
A,
const Use &U,
bool &Follow,
12170 SmallVectorImpl<const Value *> &Worklist) {
12176 if (!GV->hasLocalLinkage() && !
A.isClosedWorldModule())
12182 LLVM_DEBUG(
dbgs() <<
"[AAGlobalValueInfo] Check use: " << *
U.get() <<
" in "
12183 << *UInst <<
"\n");
12186 int Idx = &
Cmp->getOperandUse(0) == &
U;
12189 return U == &getAnchorValue();
12194 auto CallSitePred = [&](AbstractCallSite ACS) {
12195 Worklist.
push_back(ACS.getInstruction());
12198 bool UsedAssumedInformation =
false;
12200 if (!
A.checkForAllCallSites(CallSitePred, *UInst->
getFunction(),
12202 UsedAssumedInformation))
12220 if (!Fn || !
A.isFunctionIPOAmendable(*Fn))
12229 unsigned NumUsesBefore =
Uses.size();
12231 SmallPtrSet<const Value *, 8> Visited;
12235 auto UsePred = [&](
const Use &
U,
bool &Follow) ->
bool {
12243 return checkUse(
A, U, Follow, Worklist);
12245 auto EquivalentUseCB = [&](
const Use &OldU,
const Use &NewU) {
12246 Uses.insert(&OldU);
12250 while (!Worklist.
empty()) {
12252 if (!Visited.
insert(
V).second)
12254 if (!
A.checkForAllUses(UsePred, *
this, *
V,
12256 DepClassTy::OPTIONAL,
12257 true, EquivalentUseCB)) {
12258 return indicatePessimisticFixpoint();
12262 return Uses.size() == NumUsesBefore ? ChangeStatus::UNCHANGED
12263 : ChangeStatus::CHANGED;
12266 bool isPotentialUse(
const Use &U)
const override {
12267 return !isValidState() ||
Uses.contains(&U);
12271 return ChangeStatus::UNCHANGED;
12274 const std::string getAsStr(Attributor *
A)
const override {
12275 return "[" + std::to_string(
Uses.size()) +
" uses]";
12278 void trackStatistics()
const override {
12284 SmallPtrSet<const Use *, 8>
Uses;
12291 AAIndirectCallInfoCallSite(
const IRPosition &IRP, Attributor &
A)
12292 : AAIndirectCallInfo(IRP,
A) {}
12295 auto *MD = getCtxI()->getMetadata(LLVMContext::MD_callees);
12296 if (!MD && !
A.isClosedWorldModule())
12300 for (
const auto &
Op : MD->operands())
12302 PotentialCallees.insert(Callee);
12303 }
else if (
A.isClosedWorldModule()) {
12305 A.getInfoCache().getIndirectlyCallableFunctions(
A);
12306 PotentialCallees.insert_range(IndirectlyCallableFunctions);
12309 if (PotentialCallees.empty())
12310 indicateOptimisticFixpoint();
12318 SmallSetVector<Function *, 4> AssumedCalleesNow;
12319 bool AllCalleesKnownNow = AllCalleesKnown;
12321 auto CheckPotentialCalleeUse = [&](
Function &PotentialCallee,
12322 bool &UsedAssumedInformation) {
12323 const auto *GIAA =
A.getAAFor<AAGlobalValueInfo>(
12325 if (!GIAA || GIAA->isPotentialUse(CalleeUse))
12327 UsedAssumedInformation = !GIAA->isAtFixpoint();
12331 auto AddPotentialCallees = [&]() {
12332 for (
auto *PotentialCallee : PotentialCallees) {
12333 bool UsedAssumedInformation =
false;
12334 if (CheckPotentialCalleeUse(*PotentialCallee, UsedAssumedInformation))
12335 AssumedCalleesNow.
insert(PotentialCallee);
12341 bool UsedAssumedInformation =
false;
12344 AA::ValueScope::AnyScope,
12345 UsedAssumedInformation)) {
12346 if (PotentialCallees.empty())
12347 return indicatePessimisticFixpoint();
12348 AddPotentialCallees();
12353 auto CheckPotentialCallee = [&](
Function &Fn) {
12354 if (!PotentialCallees.empty() && !PotentialCallees.count(&Fn))
12357 auto &CachedResult = FilterResults[&Fn];
12358 if (CachedResult.has_value())
12359 return CachedResult.value();
12361 bool UsedAssumedInformation =
false;
12362 if (!CheckPotentialCalleeUse(Fn, UsedAssumedInformation)) {
12363 if (!UsedAssumedInformation)
12364 CachedResult =
false;
12373 for (
int I = NumCBArgs;
I < NumFnArgs; ++
I) {
12374 bool IsKnown =
false;
12377 DepClassTy::OPTIONAL, IsKnown)) {
12379 CachedResult =
false;
12384 CachedResult =
true;
12390 for (
auto &VAC :
Values) {
12398 if (CheckPotentialCallee(*VACFn))
12399 AssumedCalleesNow.
insert(VACFn);
12402 if (!PotentialCallees.empty()) {
12403 AddPotentialCallees();
12406 AllCalleesKnownNow =
false;
12409 if (AssumedCalleesNow == AssumedCallees &&
12410 AllCalleesKnown == AllCalleesKnownNow)
12411 return ChangeStatus::UNCHANGED;
12413 std::swap(AssumedCallees, AssumedCalleesNow);
12414 AllCalleesKnown = AllCalleesKnownNow;
12415 return ChangeStatus::CHANGED;
12420 if (!AllCalleesKnown && AssumedCallees.empty())
12421 return ChangeStatus::UNCHANGED;
12424 bool UsedAssumedInformation =
false;
12425 if (
A.isAssumedDead(*CB,
this,
nullptr,
12426 UsedAssumedInformation))
12427 return ChangeStatus::UNCHANGED;
12432 if (
FP->getType()->getPointerAddressSpace() != ProgramAS)
12433 FP =
new AddrSpaceCastInst(
12434 FP, PointerType::get(
FP->getContext(), ProgramAS),
12435 FP->getName() +
".as" + Twine(ProgramAS), CB->
getIterator());
12444 if (AssumedCallees.empty()) {
12445 assert(AllCalleesKnown &&
12446 "Expected all callees to be known if there are none.");
12447 A.changeToUnreachableAfterManifest(CB);
12448 return ChangeStatus::CHANGED;
12452 if (AllCalleesKnown && AssumedCallees.size() == 1) {
12453 auto *NewCallee = AssumedCallees.front();
12454 if (!
A.shouldSpecializeCallSiteForCallee(*
this, *CB, *NewCallee,
12456 return ChangeStatus::UNCHANGED;
12460 NumIndirectCallsPromoted++;
12461 return ChangeStatus::CHANGED;
12469 A.deleteAfterManifest(*CB);
12470 return ChangeStatus::CHANGED;
12480 bool SpecializedForAnyCallees =
false;
12481 bool SpecializedForAllCallees = AllCalleesKnown;
12482 ICmpInst *LastCmp =
nullptr;
12485 for (
Function *NewCallee : AssumedCallees) {
12486 if (!
A.shouldSpecializeCallSiteForCallee(*
this, *CB, *NewCallee,
12487 AssumedCallees.size())) {
12488 SkippedAssumedCallees.
push_back(NewCallee);
12489 SpecializedForAllCallees =
false;
12492 SpecializedForAnyCallees =
true;
12498 A.registerManifestAddedBasicBlock(*ThenTI->
getParent());
12499 A.registerManifestAddedBasicBlock(*IP->getParent());
12505 A.registerManifestAddedBasicBlock(*ElseBB);
12507 SplitTI->replaceUsesOfWith(CBBB, ElseBB);
12512 CastInst *RetBC =
nullptr;
12513 CallInst *NewCall =
nullptr;
12518 NumIndirectCallsPromoted++;
12527 auto AttachCalleeMetadata = [&](CallBase &IndirectCB) {
12528 if (!AllCalleesKnown)
12529 return ChangeStatus::UNCHANGED;
12530 MDBuilder MDB(IndirectCB.getContext());
12531 MDNode *Callees = MDB.createCallees(SkippedAssumedCallees);
12532 IndirectCB.setMetadata(LLVMContext::MD_callees, Callees);
12533 return ChangeStatus::CHANGED;
12536 if (!SpecializedForAnyCallees)
12537 return AttachCalleeMetadata(*CB);
12540 if (SpecializedForAllCallees) {
12543 new UnreachableInst(IP->getContext(), IP);
12544 IP->eraseFromParent();
12547 CBClone->setName(CB->
getName());
12548 CBClone->insertBefore(*IP->getParent(), IP);
12549 NewCalls.
push_back({CBClone,
nullptr});
12550 AttachCalleeMetadata(*CBClone);
12557 CB->
getParent()->getFirstInsertionPt());
12558 for (
auto &It : NewCalls) {
12559 CallBase *NewCall = It.first;
12560 Instruction *CallRet = It.second ? It.second : It.first;
12572 A.deleteAfterManifest(*CB);
12573 Changed = ChangeStatus::CHANGED;
12578 const std::string getAsStr(Attributor *
A)
const override {
12579 return std::string(AllCalleesKnown ?
"eliminate" :
"specialize") +
12580 " indirect call site with " + std::to_string(AssumedCallees.size()) +
12584 void trackStatistics()
const override {
12585 if (AllCalleesKnown) {
12587 Eliminated, CallSites,
12588 "Number of indirect call sites eliminated via specialization")
12591 "Number of indirect call sites specialized")
12595 bool foreachCallee(function_ref<
bool(
Function *)> CB)
const override {
12596 return isValidState() && AllCalleesKnown &&
all_of(AssumedCallees, CB);
12601 DenseMap<Function *, std::optional<bool>> FilterResults;
12605 SmallSetVector<Function *, 4> PotentialCallees;
12609 SmallSetVector<Function *, 4> AssumedCallees;
12613 bool AllCalleesKnown =
true;
12620struct AAInvariantLoadPointerImpl
12622 AAInvariantLoadPointer> {
12626 IS_NOALIAS = 1 << 0,
12629 IS_NOEFFECT = 1 << 1,
12631 IS_LOCALLY_INVARIANT = 1 << 2,
12633 IS_LOCALLY_CONSTRAINED = 1 << 3,
12635 IS_BEST_STATE = IS_NOALIAS | IS_NOEFFECT | IS_LOCALLY_INVARIANT |
12636 IS_LOCALLY_CONSTRAINED,
12638 static_assert(getBestState() == IS_BEST_STATE,
"Unexpected best state");
12641 StateWrapper<BitIntegerState<uint8_t, 15>, AAInvariantLoadPointer>;
12645 AAInvariantLoadPointerImpl(
const IRPosition &IRP, Attributor &
A)
12648 bool isKnownInvariant()
const final {
12649 return isKnownLocallyInvariant() && isKnown(IS_LOCALLY_CONSTRAINED);
12652 bool isKnownLocallyInvariant()
const final {
12653 if (isKnown(IS_LOCALLY_INVARIANT))
12655 return isKnown(IS_NOALIAS | IS_NOEFFECT);
12658 bool isAssumedInvariant()
const final {
12659 return isAssumedLocallyInvariant() && isAssumed(IS_LOCALLY_CONSTRAINED);
12662 bool isAssumedLocallyInvariant()
const final {
12663 if (isAssumed(IS_LOCALLY_INVARIANT))
12665 return isAssumed(IS_NOALIAS | IS_NOEFFECT);
12672 if (requiresNoAlias() && !isAssumed(IS_NOALIAS))
12673 return indicatePessimisticFixpoint();
12677 Changed |= updateLocalInvariance(
A);
12683 if (!isKnownInvariant())
12684 return ChangeStatus::UNCHANGED;
12687 const Value *Ptr = &getAssociatedValue();
12688 const auto TagInvariantLoads = [&](
const Use &
U,
bool &) {
12689 if (
U.get() != Ptr)
12697 if (!
A.isRunOn(
I->getFunction()))
12700 if (
I->hasMetadata(LLVMContext::MD_invariant_load))
12704 LI->setMetadata(LLVMContext::MD_invariant_load,
12706 Changed = ChangeStatus::CHANGED;
12711 (void)
A.checkForAllUses(TagInvariantLoads, *
this, *Ptr);
12715 const std::string getAsStr(Attributor *)
const override {
12716 if (isKnownInvariant())
12717 return "load-invariant pointer";
12718 return "non-invariant pointer";
12721 void trackStatistics()
const override {}
12725 bool requiresNoAlias()
const {
12726 switch (getPositionKind()) {
12732 case IRP_CALL_SITE:
12734 case IRP_CALL_SITE_RETURNED: {
12739 case IRP_ARGUMENT: {
12740 const Function *
F = getAssociatedFunction();
12741 assert(
F &&
"no associated function for argument");
12747 bool isExternal()
const {
12748 const Function *
F = getAssociatedFunction();
12752 getPositionKind() != IRP_CALL_SITE_RETURNED;
12756 if (isKnown(IS_NOALIAS) || !isAssumed(IS_NOALIAS))
12757 return ChangeStatus::UNCHANGED;
12760 if (
const auto *ANoAlias =
A.getOrCreateAAFor<AANoAlias>(
12761 getIRPosition(),
this, DepClassTy::REQUIRED)) {
12762 if (ANoAlias->isKnownNoAlias()) {
12763 addKnownBits(IS_NOALIAS);
12764 return ChangeStatus::CHANGED;
12767 if (!ANoAlias->isAssumedNoAlias()) {
12768 removeAssumedBits(IS_NOALIAS);
12769 return ChangeStatus::CHANGED;
12772 return ChangeStatus::UNCHANGED;
12777 if (
const Argument *Arg = getAssociatedArgument()) {
12779 addKnownBits(IS_NOALIAS);
12780 return ChangeStatus::UNCHANGED;
12785 removeAssumedBits(IS_NOALIAS);
12786 return ChangeStatus::CHANGED;
12789 return ChangeStatus::UNCHANGED;
12793 if (isKnown(IS_NOEFFECT) || !isAssumed(IS_NOEFFECT))
12794 return ChangeStatus::UNCHANGED;
12796 if (!getAssociatedFunction())
12797 return indicatePessimisticFixpoint();
12800 return indicatePessimisticFixpoint();
12802 const auto HasNoEffectLoads = [&](
const Use &
U,
bool &) {
12804 return !LI || !LI->mayHaveSideEffects();
12806 if (!
A.checkForAllUses(HasNoEffectLoads, *
this, getAssociatedValue()))
12807 return indicatePessimisticFixpoint();
12809 if (
const auto *AMemoryBehavior =
A.getOrCreateAAFor<AAMemoryBehavior>(
12810 getIRPosition(),
this, DepClassTy::REQUIRED)) {
12813 if (!AMemoryBehavior->isAssumedReadOnly())
12814 return indicatePessimisticFixpoint();
12816 if (AMemoryBehavior->isKnownReadOnly()) {
12817 addKnownBits(IS_NOEFFECT);
12818 return ChangeStatus::UNCHANGED;
12821 return ChangeStatus::UNCHANGED;
12824 if (
const Argument *Arg = getAssociatedArgument()) {
12826 addKnownBits(IS_NOEFFECT);
12827 return ChangeStatus::UNCHANGED;
12832 return indicatePessimisticFixpoint();
12835 return ChangeStatus::UNCHANGED;
12839 if (isKnown(IS_LOCALLY_INVARIANT) || !isAssumed(IS_LOCALLY_INVARIANT))
12840 return ChangeStatus::UNCHANGED;
12843 const auto *AUO =
A.getOrCreateAAFor<AAUnderlyingObjects>(
12844 getIRPosition(),
this, DepClassTy::REQUIRED);
12846 return ChangeStatus::UNCHANGED;
12848 bool UsedAssumedInformation =
false;
12849 const auto IsLocallyInvariantLoadIfPointer = [&](
const Value &
V) {
12850 if (!
V.getType()->isPointerTy())
12852 const auto *IsInvariantLoadPointer =
12854 DepClassTy::REQUIRED);
12856 if (!IsInvariantLoadPointer)
12859 if (IsInvariantLoadPointer->isKnownLocallyInvariant())
12861 if (!IsInvariantLoadPointer->isAssumedLocallyInvariant())
12864 UsedAssumedInformation =
true;
12867 if (!AUO->forallUnderlyingObjects(IsLocallyInvariantLoadIfPointer))
12868 return indicatePessimisticFixpoint();
12874 if (!IsLocallyInvariantLoadIfPointer(*Arg))
12875 return indicatePessimisticFixpoint();
12880 if (!UsedAssumedInformation) {
12882 addKnownBits(IS_LOCALLY_INVARIANT);
12883 return ChangeStatus::CHANGED;
12886 return ChangeStatus::UNCHANGED;
12890struct AAInvariantLoadPointerFloating final : AAInvariantLoadPointerImpl {
12891 AAInvariantLoadPointerFloating(
const IRPosition &IRP, Attributor &
A)
12892 : AAInvariantLoadPointerImpl(IRP,
A) {}
12895struct AAInvariantLoadPointerReturned final : AAInvariantLoadPointerImpl {
12896 AAInvariantLoadPointerReturned(
const IRPosition &IRP, Attributor &
A)
12897 : AAInvariantLoadPointerImpl(IRP,
A) {}
12900 removeAssumedBits(IS_LOCALLY_CONSTRAINED);
12904struct AAInvariantLoadPointerCallSiteReturned final
12905 : AAInvariantLoadPointerImpl {
12906 AAInvariantLoadPointerCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
12907 : AAInvariantLoadPointerImpl(IRP,
A) {}
12911 const Function *
F = getAssociatedFunction();
12913 indicatePessimisticFixpoint();
12917 if (!
F->isDeclaration() && !
F->isIntrinsic())
12918 return AAInvariantLoadPointerImpl::initialize(
A);
12923 return AAInvariantLoadPointerImpl::initialize(
A);
12925 if (
F->onlyReadsMemory() &&
F->hasNoSync())
12926 return AAInvariantLoadPointerImpl::initialize(
A);
12930 indicatePessimisticFixpoint();
12934struct AAInvariantLoadPointerArgument final : AAInvariantLoadPointerImpl {
12935 AAInvariantLoadPointerArgument(
const IRPosition &IRP, Attributor &
A)
12936 : AAInvariantLoadPointerImpl(IRP,
A) {}
12939 const Function *
F = getAssociatedFunction();
12940 assert(
F &&
"no associated function for argument");
12943 addKnownBits(IS_LOCALLY_CONSTRAINED);
12947 if (!
F->hasLocalLinkage())
12948 removeAssumedBits(IS_LOCALLY_CONSTRAINED);
12952struct AAInvariantLoadPointerCallSiteArgument final
12953 : AAInvariantLoadPointerImpl {
12954 AAInvariantLoadPointerCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
12955 : AAInvariantLoadPointerImpl(IRP,
A) {}
12962template <
typename InstType>
12963static bool makeChange(
Attributor &
A, InstType *MemInst,
const Use &U,
12965 bool UseOriginalValue) {
12966 if (
U.getOperandNo() != InstType::getPointerOperandIndex())
12969 if (MemInst->isVolatile()) {
12971 *MemInst->getFunction());
12972 unsigned NewAS = NewPtrTy->getPointerAddressSpace();
12973 if (!
TTI || !
TTI->hasVolatileVariant(MemInst, NewAS))
12977 if (UseOriginalValue) {
12978 A.changeUseAfterManifest(
const_cast<Use &
>(U), *OriginalValue);
12984 A.changeUseAfterManifest(
const_cast<Use &
>(U), *
CastInst);
12989 AAAddressSpaceImpl(
const IRPosition &IRP, Attributor &
A)
12990 : AAAddressSpace(IRP,
A) {}
12993 assert(isValidState() &&
"the AA is invalid");
12994 return AssumedAddressSpace;
12998 assert(getAssociatedType()->isPtrOrPtrVectorTy() &&
12999 "Associated value is not a pointer");
13001 if (!
A.getInfoCache().getFlatAddressSpace().has_value()) {
13002 indicatePessimisticFixpoint();
13006 unsigned FlatAS =
A.getInfoCache().getFlatAddressSpace().value();
13007 unsigned AS = getAssociatedType()->getPointerAddressSpace();
13008 if (AS != FlatAS) {
13009 [[maybe_unused]]
bool R = takeAddressSpace(AS);
13010 assert(R &&
"The take should happen");
13011 indicateOptimisticFixpoint();
13016 uint32_t OldAddressSpace = AssumedAddressSpace;
13017 unsigned FlatAS =
A.getInfoCache().getFlatAddressSpace().value();
13019 auto CheckAddressSpace = [&](
Value &
Obj) {
13025 unsigned ObjAS =
Obj.getType()->getPointerAddressSpace();
13026 if (ObjAS != FlatAS)
13027 return takeAddressSpace(ObjAS);
13041 A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(*F);
13043 if (AssumedAS != ~0U)
13044 return takeAddressSpace(AssumedAS);
13048 return takeAddressSpace(FlatAS);
13051 auto *AUO =
A.getOrCreateAAFor<AAUnderlyingObjects>(getIRPosition(),
this,
13052 DepClassTy::REQUIRED);
13053 if (!AUO->forallUnderlyingObjects(CheckAddressSpace))
13054 return indicatePessimisticFixpoint();
13056 return OldAddressSpace == AssumedAddressSpace ? ChangeStatus::UNCHANGED
13057 : ChangeStatus::CHANGED;
13063 if (NewAS == InvalidAddressSpace ||
13065 return ChangeStatus::UNCHANGED;
13067 unsigned FlatAS =
A.getInfoCache().getFlatAddressSpace().value();
13069 Value *AssociatedValue = &getAssociatedValue();
13070 Value *OriginalValue = peelAddrspacecast(AssociatedValue, FlatAS);
13073 PointerType::get(getAssociatedType()->
getContext(), NewAS);
13074 bool UseOriginalValue =
13079 auto Pred = [&](
const Use &
U,
bool &) {
13080 if (
U.get() != AssociatedValue)
13091 makeChange(
A, LI, U, OriginalValue, NewPtrTy, UseOriginalValue);
13094 makeChange(
A, SI, U, OriginalValue, NewPtrTy, UseOriginalValue);
13097 makeChange(
A, RMW, U, OriginalValue, NewPtrTy, UseOriginalValue);
13100 makeChange(
A, CmpX, U, OriginalValue, NewPtrTy, UseOriginalValue);
13107 (void)
A.checkForAllUses(
Pred, *
this, getAssociatedValue(),
13110 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
13113 const std::string getAsStr(Attributor *
A)
const override {
13114 if (!isValidState())
13115 return "addrspace(<invalid>)";
13116 return "addrspace(" +
13117 (AssumedAddressSpace == InvalidAddressSpace
13119 : std::to_string(AssumedAddressSpace)) +
13124 uint32_t AssumedAddressSpace = InvalidAddressSpace;
13126 bool takeAddressSpace(uint32_t AS) {
13127 if (AssumedAddressSpace == InvalidAddressSpace) {
13128 AssumedAddressSpace = AS;
13131 return AssumedAddressSpace == AS;
13134 static Value *peelAddrspacecast(
Value *
V,
unsigned FlatAS) {
13136 assert(
I->getSrcAddressSpace() != FlatAS &&
13137 "there should not be flat AS -> non-flat AS");
13138 return I->getPointerOperand();
13141 if (
C->getOpcode() == Instruction::AddrSpaceCast) {
13142 assert(
C->getOperand(0)->getType()->getPointerAddressSpace() !=
13144 "there should not be flat AS -> non-flat AS X");
13145 return C->getOperand(0);
13151struct AAAddressSpaceFloating final : AAAddressSpaceImpl {
13152 AAAddressSpaceFloating(
const IRPosition &IRP, Attributor &
A)
13153 : AAAddressSpaceImpl(IRP,
A) {}
13155 void trackStatistics()
const override {
13160struct AAAddressSpaceReturned final : AAAddressSpaceImpl {
13161 AAAddressSpaceReturned(
const IRPosition &IRP, Attributor &
A)
13162 : AAAddressSpaceImpl(IRP,
A) {}
13167 (void)indicatePessimisticFixpoint();
13170 void trackStatistics()
const override {
13175struct AAAddressSpaceCallSiteReturned final : AAAddressSpaceImpl {
13176 AAAddressSpaceCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
13177 : AAAddressSpaceImpl(IRP,
A) {}
13179 void trackStatistics()
const override {
13184struct AAAddressSpaceArgument final : AAAddressSpaceImpl {
13185 AAAddressSpaceArgument(
const IRPosition &IRP, Attributor &
A)
13186 : AAAddressSpaceImpl(IRP,
A) {}
13191struct AAAddressSpaceCallSiteArgument final : AAAddressSpaceImpl {
13192 AAAddressSpaceCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
13193 : AAAddressSpaceImpl(IRP,
A) {}
13198 (void)indicatePessimisticFixpoint();
13201 void trackStatistics()
const override {
13217 AANoAliasAddrSpaceImpl(
const IRPosition &IRP, Attributor &
A)
13218 : AANoAliasAddrSpace(IRP,
A) {}
13221 assert(getAssociatedType()->isPtrOrPtrVectorTy() &&
13222 "Associated value is not a pointer");
13226 std::optional<unsigned> FlatAS =
A.getInfoCache().getFlatAddressSpace();
13227 if (!FlatAS.has_value()) {
13228 indicatePessimisticFixpoint();
13234 unsigned AS = getAssociatedType()->getPointerAddressSpace();
13235 if (AS != *FlatAS) {
13237 indicateOptimisticFixpoint();
13242 unsigned FlatAS =
A.getInfoCache().getFlatAddressSpace().value();
13243 uint32_t OldAssumed = getAssumed();
13245 auto CheckAddressSpace = [&](
Value &
Obj) {
13249 unsigned AS =
Obj.getType()->getPointerAddressSpace();
13253 removeAS(
Obj.getType()->getPointerAddressSpace());
13257 const AAUnderlyingObjects *AUO =
A.getOrCreateAAFor<AAUnderlyingObjects>(
13258 getIRPosition(),
this, DepClassTy::REQUIRED);
13260 return indicatePessimisticFixpoint();
13262 return OldAssumed == getAssumed() ? ChangeStatus::UNCHANGED
13263 : ChangeStatus::CHANGED;
13267 unsigned FlatAS =
A.getInfoCache().getFlatAddressSpace().value();
13269 unsigned AS = getAssociatedType()->getPointerAddressSpace();
13270 if (AS != FlatAS ||
Map.empty())
13271 return ChangeStatus::UNCHANGED;
13273 LLVMContext &Ctx = getAssociatedValue().getContext();
13274 MDNode *NoAliasASNode =
nullptr;
13275 MDBuilder MDB(Ctx);
13277 for (RangeMap::const_iterator
I =
Map.begin();
I !=
Map.end();
I++) {
13280 unsigned Upper =
I.stop();
13281 unsigned Lower =
I.start();
13282 if (!NoAliasASNode) {
13283 NoAliasASNode = MDB.createRange(APInt(32,
Lower), APInt(32,
Upper + 1));
13286 MDNode *ASRange = MDB.createRange(APInt(32,
Lower), APInt(32,
Upper + 1));
13290 Value *AssociatedValue = &getAssociatedValue();
13293 auto AddNoAliasAttr = [&](
const Use &
U,
bool &) {
13294 if (
U.get() != AssociatedValue)
13297 if (!Inst || Inst->
hasMetadata(LLVMContext::MD_noalias_addrspace))
13304 Inst->
setMetadata(LLVMContext::MD_noalias_addrspace, NoAliasASNode);
13308 (void)
A.checkForAllUses(AddNoAliasAttr, *
this, *AssociatedValue,
13310 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
13313 const std::string getAsStr(Attributor *
A)
const override {
13314 if (!isValidState())
13315 return "<invalid>";
13317 raw_string_ostream OS(Str);
13318 OS <<
"CanNotBeAddrSpace(";
13319 for (RangeMap::const_iterator
I =
Map.begin();
I !=
Map.end();
I++) {
13320 unsigned Upper =
I.stop();
13321 unsigned Lower =
I.start();
13322 OS <<
' ' <<
'[' <<
Upper <<
',' <<
Lower + 1 <<
')';
13329 void removeAS(
unsigned AS) {
13330 RangeMap::iterator
I =
Map.find(AS);
13332 if (
I !=
Map.end()) {
13333 unsigned Upper =
I.stop();
13334 unsigned Lower =
I.start();
13338 if (AS != ~((
unsigned)0) && AS + 1 <=
Upper)
13340 if (AS != 0 &&
Lower <= AS - 1)
13345 void resetASRanges(Attributor &
A) {
13347 Map.insert(0,
A.getInfoCache().getMaxAddrSpace(),
true);
13351struct AANoAliasAddrSpaceFloating final : AANoAliasAddrSpaceImpl {
13352 AANoAliasAddrSpaceFloating(
const IRPosition &IRP, Attributor &
A)
13353 : AANoAliasAddrSpaceImpl(IRP,
A) {}
13355 void trackStatistics()
const override {
13360struct AANoAliasAddrSpaceReturned final : AANoAliasAddrSpaceImpl {
13361 AANoAliasAddrSpaceReturned(
const IRPosition &IRP, Attributor &
A)
13362 : AANoAliasAddrSpaceImpl(IRP,
A) {}
13364 void trackStatistics()
const override {
13369struct AANoAliasAddrSpaceCallSiteReturned final : AANoAliasAddrSpaceImpl {
13370 AANoAliasAddrSpaceCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
13371 : AANoAliasAddrSpaceImpl(IRP,
A) {}
13373 void trackStatistics()
const override {
13378struct AANoAliasAddrSpaceArgument final : AANoAliasAddrSpaceImpl {
13379 AANoAliasAddrSpaceArgument(
const IRPosition &IRP, Attributor &
A)
13380 : AANoAliasAddrSpaceImpl(IRP,
A) {}
13382 void trackStatistics()
const override {
13387struct AANoAliasAddrSpaceCallSiteArgument final : AANoAliasAddrSpaceImpl {
13388 AANoAliasAddrSpaceCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
13389 : AANoAliasAddrSpaceImpl(IRP,
A) {}
13391 void trackStatistics()
const override {
13399 AAAllocationInfoImpl(
const IRPosition &IRP, Attributor &
A)
13400 : AAAllocationInfo(IRP,
A) {}
13402 std::optional<TypeSize> getAllocatedSize()
const override {
13403 assert(isValidState() &&
"the AA is invalid");
13404 return AssumedAllocatedSize;
13407 std::optional<TypeSize> findInitialAllocationSize(Instruction *
I,
13408 const DataLayout &
DL) {
13411 switch (
I->getOpcode()) {
13412 case Instruction::Alloca: {
13417 return std::nullopt;
13423 const IRPosition &IRP = getIRPosition();
13428 return indicatePessimisticFixpoint();
13430 bool IsKnownNoCapture;
13432 A,
this, IRP, DepClassTy::OPTIONAL, IsKnownNoCapture))
13433 return indicatePessimisticFixpoint();
13435 const AAPointerInfo *PI =
13436 A.getOrCreateAAFor<AAPointerInfo>(IRP, *
this, DepClassTy::REQUIRED);
13439 return indicatePessimisticFixpoint();
13442 return indicatePessimisticFixpoint();
13444 const DataLayout &
DL =
A.getDataLayout();
13445 const auto AllocationSize = findInitialAllocationSize(
I,
DL);
13448 if (!AllocationSize)
13449 return indicatePessimisticFixpoint();
13453 if (*AllocationSize == 0)
13454 return indicatePessimisticFixpoint();
13460 return indicatePessimisticFixpoint();
13462 if (BinSize == 0) {
13463 auto NewAllocationSize = std::make_optional<TypeSize>(0,
false);
13464 if (!changeAllocationSize(NewAllocationSize))
13465 return ChangeStatus::UNCHANGED;
13466 return ChangeStatus::CHANGED;
13470 const auto &It = PI->
begin();
13473 if (It->first.Offset != 0)
13474 return indicatePessimisticFixpoint();
13476 uint64_t SizeOfBin = It->first.Offset + It->first.Size;
13478 if (SizeOfBin >= *AllocationSize)
13479 return indicatePessimisticFixpoint();
13481 auto NewAllocationSize = std::make_optional<TypeSize>(SizeOfBin * 8,
false);
13483 if (!changeAllocationSize(NewAllocationSize))
13484 return ChangeStatus::UNCHANGED;
13486 return ChangeStatus::CHANGED;
13491 assert(isValidState() &&
13492 "Manifest should only be called if the state is valid.");
13496 auto FixedAllocatedSizeInBits = getAllocatedSize()->getFixedValue();
13498 unsigned long NumBytesToAllocate = (FixedAllocatedSizeInBits + 7) / 8;
13500 switch (
I->getOpcode()) {
13502 case Instruction::Alloca: {
13506 Type *CharType = Type::getInt8Ty(
I->getContext());
13508 auto *NumBytesToValue =
13509 ConstantInt::get(
I->getContext(), APInt(32, NumBytesToAllocate));
13512 insertPt = std::next(insertPt);
13513 AllocaInst *NewAllocaInst =
13518 return ChangeStatus::CHANGED;
13526 return ChangeStatus::UNCHANGED;
13529 const std::string getAsStr(Attributor *
A)
const override {
13530 if (!isValidState())
13531 return "allocationinfo(<invalid>)";
13532 return "allocationinfo(" +
13533 (AssumedAllocatedSize == HasNoAllocationSize
13535 : std::to_string(AssumedAllocatedSize->getFixedValue())) +
13540 std::optional<TypeSize> AssumedAllocatedSize = HasNoAllocationSize;
13544 bool changeAllocationSize(std::optional<TypeSize>
Size) {
13545 if (AssumedAllocatedSize == HasNoAllocationSize ||
13546 AssumedAllocatedSize !=
Size) {
13547 AssumedAllocatedSize =
Size;
13554struct AAAllocationInfoFloating : AAAllocationInfoImpl {
13555 AAAllocationInfoFloating(
const IRPosition &IRP, Attributor &
A)
13556 : AAAllocationInfoImpl(IRP,
A) {}
13558 void trackStatistics()
const override {
13563struct AAAllocationInfoReturned : AAAllocationInfoImpl {
13564 AAAllocationInfoReturned(
const IRPosition &IRP, Attributor &
A)
13565 : AAAllocationInfoImpl(IRP,
A) {}
13570 (void)indicatePessimisticFixpoint();
13573 void trackStatistics()
const override {
13578struct AAAllocationInfoCallSiteReturned : AAAllocationInfoImpl {
13579 AAAllocationInfoCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
13580 : AAAllocationInfoImpl(IRP,
A) {}
13582 void trackStatistics()
const override {
13587struct AAAllocationInfoArgument : AAAllocationInfoImpl {
13588 AAAllocationInfoArgument(
const IRPosition &IRP, Attributor &
A)
13589 : AAAllocationInfoImpl(IRP,
A) {}
13591 void trackStatistics()
const override {
13596struct AAAllocationInfoCallSiteArgument : AAAllocationInfoImpl {
13597 AAAllocationInfoCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
13598 : AAAllocationInfoImpl(IRP,
A) {}
13602 (void)indicatePessimisticFixpoint();
13605 void trackStatistics()
const override {
13654#define SWITCH_PK_INV(CLASS, PK, POS_NAME) \
13655 case IRPosition::PK: \
13656 llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!");
13658#define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \
13659 case IRPosition::PK: \
13660 AA = new (A.Allocator) CLASS##SUFFIX(IRP, A); \
13664#define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13665 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13666 CLASS *AA = nullptr; \
13667 switch (IRP.getPositionKind()) { \
13668 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13669 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \
13670 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \
13671 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13672 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \
13673 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \
13674 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13675 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13680#define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13681 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13682 CLASS *AA = nullptr; \
13683 switch (IRP.getPositionKind()) { \
13684 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13685 SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \
13686 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \
13687 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13688 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13689 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \
13690 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13691 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13696#define CREATE_ABSTRACT_ATTRIBUTE_FOR_ONE_POSITION(POS, SUFFIX, CLASS) \
13697 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13698 CLASS *AA = nullptr; \
13699 switch (IRP.getPositionKind()) { \
13700 SWITCH_PK_CREATE(CLASS, IRP, POS, SUFFIX) \
13702 llvm_unreachable("Cannot create " #CLASS " for position otherthan " #POS \
13708#define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13709 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13710 CLASS *AA = nullptr; \
13711 switch (IRP.getPositionKind()) { \
13712 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13713 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13714 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13715 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13716 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13717 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \
13718 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13719 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13724#define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13725 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13726 CLASS *AA = nullptr; \
13727 switch (IRP.getPositionKind()) { \
13728 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13729 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \
13730 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \
13731 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13732 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \
13733 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \
13734 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \
13735 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13740#define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13741 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13742 CLASS *AA = nullptr; \
13743 switch (IRP.getPositionKind()) { \
13744 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13745 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13746 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13747 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13748 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13749 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13750 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13751 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13803#undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION
13804#undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION
13805#undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION
13806#undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION
13807#undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION
13808#undef CREATE_ABSTRACT_ATTRIBUTE_FOR_ONE_POSITION
13809#undef SWITCH_PK_CREATE
13810#undef SWITCH_PK_INV
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
Expand Atomic instructions
This file contains the simple types necessary to represent the attributes associated with functions a...
#define STATS_DECLTRACK(NAME, TYPE, MSG)
static std::optional< Constant * > askForAssumedConstant(Attributor &A, const AbstractAttribute &QueryingAA, const IRPosition &IRP, Type &Ty)
static bool collectTailCalls(Attributor &A, const AbstractAttribute &QueryingAA, SmallVectorImpl< CallInst * > &TailCalls)
Collect the non-musttail tail calls in the function of QueryingAA.
static void clampReturnedValueStates(Attributor &A, const AAType &QueryingAA, StateType &S, const IRPosition::CallBaseContext *CBContext=nullptr)
Clamp the information known for all returned values of a function (identified by QueryingAA) into S.
#define STATS_DECLTRACK_FN_ATTR(NAME)
#define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
#define STATS_DECLTRACK_CS_ATTR(NAME)
#define PIPE_OPERATOR(CLASS)
#define STATS_DECLTRACK_ARG_ATTR(NAME)
static const Value * stripAndAccumulateOffsets(Attributor &A, const AbstractAttribute &QueryingAA, const Value *Val, const DataLayout &DL, APInt &Offset, bool GetMinOffset, bool AllowNonInbounds, bool UseAssumed=false)
#define STATS_DECLTRACK_CSRET_ATTR(NAME)
static Value * constructPointer(Value *Ptr, int64_t Offset, IRBuilder< NoFolder > &IRB)
Helper function to create a pointer based on Ptr, and advanced by Offset bytes.
#define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
#define BUILD_STAT_NAME(NAME, TYPE)
static bool isDenselyPacked(Type *Ty, const DataLayout &DL)
Checks if a type could have padding bytes.
#define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
static const Value * getMinimalBaseOfPointer(Attributor &A, const AbstractAttribute &QueryingAA, const Value *Ptr, int64_t &BytesOffset, const DataLayout &DL, bool AllowNonInbounds=false)
static bool mayBeInCycle(const CycleInfo *CI, const Instruction *I, bool HeaderOnly, CycleRef *CPtr=nullptr)
#define STATS_DECLTRACK_FNRET_ATTR(NAME)
#define STATS_DECLTRACK_CSARG_ATTR(NAME)
#define CREATE_ABSTRACT_ATTRIBUTE_FOR_ONE_POSITION(POS, SUFFIX, CLASS)
#define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
#define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS)
#define STATS_DECLTRACK_FLOATING_ATTR(NAME)
#define STATS_DECL(NAME, TYPE, MSG)
bpf unwind BPF Unwind Lower
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< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool isReachableImpl(SmallVectorImpl< BasicBlock * > &Worklist, const StopSetT &StopSet, const SmallPtrSetImpl< BasicBlock * > *ExclusionSet, const DominatorTree *DT, const LoopInfo *LI, const CycleInfo *CI)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares an analysis pass that computes CycleInfo for LLVM IR, specialized from GenericCycl...
static uint64_t align(uint64_t Size)
DXIL Forward Handle Accesses
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
static Value * getCondition(Instruction *I)
if(!TBB||Cond.size()< 1) return false
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
static unsigned getAddressSpace(const Value *V, unsigned MaxLookup)
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
static StringRef getName(Value *V)
dot regions Print regions of function to dot true view regions View regions of function(with no function bodies)"
Remove Loads Into Fake Uses
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
std::pair< BasicBlock *, BasicBlock * > Edge
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines generic set operations that may be used on set's of different types,...
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static SymbolRef::Type getType(const Symbol *Sym)
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static unsigned getSize(unsigned Kind)
LLVM_ABI AACallGraphNode * operator*() const
bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
A trivial helper function to check to see if the specified pointers are no-alias.
Class for arbitrary precision integers.
int64_t getSExtValue() const
Get sign extended value.
CallBase * getInstruction() const
Return the underlying instruction.
bool isCallbackCall() const
Return true if this ACS represents a callback call.
bool isDirectCall() const
Return true if this ACS represents a direct call.
static LLVM_ABI void getCallbackUses(const CallBase &CB, SmallVectorImpl< const Use * > &CallbackUses)
Add operand uses of CB that represent callback uses into CallbackUses.
int getCallArgOperandNo(Argument &Arg) const
Return the operand index of the underlying instruction associated with Arg.
This class represents a conversion between pointers from one address space to another.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
This class represents an incoming formal argument to a Function.
LLVM_ABI bool hasNoAliasAttr() const
Return true if this argument has the noalias attribute.
LLVM_ABI bool onlyReadsMemory() const
Return true if this argument has the readonly or readnone attribute.
LLVM_ABI bool hasPointeeInMemoryValueAttr() const
Return true if this argument has the byval, sret, inalloca, preallocated, or byref attribute.
LLVM_ABI bool hasReturnedAttr() const
Return true if this argument has the returned attribute.
LLVM_ABI bool hasByValAttr() const
Return true if this argument has the byval attribute.
const Function * getParent() const
unsigned getArgNo() const
Return the index of this formal argument in its containing function.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
This class stores enough information to efficiently remove some attributes from an existing AttrBuild...
bool contains(Attribute::AttrKind A) const
Return true if the builder has the specified attribute.
This class holds the attributes for a particular argument, parameter, function, or return value.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
LLVM_ABI const ConstantRange & getRange() const
Returns the value of the range attribute.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM_ABI FPClassTest getNoFPClass() const
Return the FPClassTest for nofpclass.
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 getWithCaptureInfo(LLVMContext &Context, CaptureInfo CI)
static bool isEnumAttrKind(AttrKind Kind)
bool isValid() const
Return true if the attribute is any kind of attribute.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
LLVM_ABI MaybeAlign getAlignment() const
Returns the alignment field of an attribute as a byte alignment value.
LLVM_ABI CaptureInfo getCaptureInfo() const
Returns information from captures attribute.
LLVM Basic Block Representation.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Instruction & front() const
InstListType::iterator iterator
Instruction iterators...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
BinaryOps getOpcode() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
LLVM_ABI MemoryEffects getMemoryEffects() const
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
Value * getCalledOperand() const
const Use & getCalledOperandUse() const
Attribute getFnAttr(StringRef Kind) const
Get the attribute of a given kind for the function.
const Use & getArgOperandUse(unsigned i) const
Wrappers for getting the Use of a call argument.
LLVM_ABI bool isVolatile() const
Return true if this is a call to an intrinsic with a volatile flag that is set, e....
OperandBundleUse getOperandBundleForOperand(unsigned OpIdx) const
Return the operand bundle for the operand at index OpIdx.
LLVM_ABI std::optional< ConstantRange > getRange() const
If this return value has a range attribute, return the value range of the argument.
Value * getArgOperand(unsigned i) const
bool isBundleOperand(unsigned Idx) const
Return true if the operand at index Idx is a bundle operand.
bool isConvergent() const
Determine if the invoke is convergent.
FunctionType * getFunctionType() const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned getArgOperandNo(const Use *U) const
Given a use for a arg operand, get the arg operand number that corresponds to it.
unsigned arg_size() const
bool isArgOperand(const Use *U) const
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CaptureInfo none()
Create CaptureInfo that does not capture any components of the pointer.
This is the base class for all instructions that perform data casts.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
LLVM_ABI bool isIntegerCast() const
There are several places where we need to know if a cast instruction only deals with integer source a...
Type * getDestTy() const
Return the destination type, as a convenience.
bool isEquality() const
Determine if this is an equals/not equals predicate.
bool isFalseWhenEqual() const
This is just a convenience.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
bool isTrueWhenEqual() const
This is just a convenience.
Predicate getPredicate() const
Return the predicate for this instruction.
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
This class represents a range of values.
const APInt & getLower() const
Return the lower value for this range.
LLVM_ABI bool isFullSet() const
Return true if this set contains all of the elements possible for this data-type.
LLVM_ABI bool isEmptySet() const
Return true if this set contains no members.
bool isSingleElement() const
Return true if this set contains exactly one member.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
const APInt & getUpper() const
Return the upper value for this range.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
Opaque handle to a cycle within a GenericCycleInfo that wraps the cycle's preorder index.
A parsed version of the target data layout string in and methods for querying it.
unsigned getProgramAddressSpace() const
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
const BasicBlock & getEntryBlock() const
iterator_range< arg_iterator > args()
const Function & getFunction() const
Argument * getArg(unsigned i) const
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
BlockT * getHeader(CycleRef C) const
CycleRef getCycle(const BlockT *Block) const
Find the innermost cycle containing Block.
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
bool hasLocalLinkage() const
PointerType * getType() const
Global values are always pointers.
static LLVM_ABI bool compare(const APInt &LHS, const APInt &RHS, ICmpInst::Predicate Pred)
Return result of LHS Pred RHS comparison.
Value * CreatePtrAddWithSignedOffset(Value *Ptr, int64_t Offset, const Twine &Name="", GEPNoWrapFlags NW=GEPNoWrapFlags::none())
Create a ptradd with a signed constant offset.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI bool isLifetimeStartOrEnd() const LLVM_READONLY
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
LLVM_ABI bool mayWriteToMemory() const LLVM_READONLY
Return true if this instruction may modify memory.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
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.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
bool isTerminator() const
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
LLVM_ABI bool mayReadOrWriteMemory() const LLVM_READONLY
Return true if this instruction may read or write memory.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
This is an important class for using LLVM in a threaded context.
LLVM_ABI ConstantRange getConstantRange(Value *V, Instruction *CtxI, bool UndefAllowed)
Return the ConstantRange constraint that is known to hold for the specified value at the specified in...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
static MemoryEffectsBase readOnly()
bool doesNotAccessMemory() const
Whether this function accesses no memory.
static MemoryEffectsBase argMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase inaccessibleMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
bool onlyAccessesInaccessibleMem() const
Whether this function only (at most) accesses inaccessible memory.
ModRefInfo getModRef(Location Loc) const
Get ModRefInfo for the given Location.
bool onlyAccessesArgPointees() const
Whether this function only (at most) accesses argument memory.
bool onlyReadsMemory() const
Whether this function only (at most) reads memory.
static MemoryEffectsBase writeOnly()
static MemoryEffectsBase inaccessibleOrArgMemOnly(ModRefInfo MR=ModRefInfo::ModRef)
static MemoryEffectsBase none()
bool onlyAccessesInaccessibleOrArgMem() const
Whether this function only (at most) accesses argument and inaccessible memory.
static MemoryEffectsBase unknown()
static LLVM_ABI std::optional< MemoryLocation > getOrNone(const Instruction *Inst)
static SizeOffsetValue unknown()
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
Class to represent pointers.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
LLVM_ABI SCEVUse getSCEVAtScope(const SCEV *S, const Loop *L)
Return a SCEV expression for the specified value at the specified scope in the program.
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
LLVM_ABI unsigned getSmallConstantMaxTripCount(const Loop *L, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
Returns the upper bound of the loop trip count as a normal unsigned value.
ConstantRange getUnsignedRange(const SCEV *S)
Determine the unsigned range for a particular SCEV.
A vector that has set insertion semantics.
size_type size() const
Determine the number of elements in the SetVector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
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.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
TypeSize getElementOffset(unsigned Idx) const
TypeSize getSizeInBits() const
TypeSize getElementOffsetInBits(unsigned Idx) const
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Analysis pass providing the TargetTransformInfo.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI unsigned getIntegerBitWidth() const
bool isPointerTy() const
True if this is an instance of PointerType.
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isVoidTy() const
Return true if this is 'void'.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i=0) const
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.
User * getUser() const
Returns the User that contains this Use.
const Use & getOperandUse(unsigned i) const
LLVM_ABI bool isDroppable() const
A droppable user is a user for which uses can be dropped without affecting correctness and should be ...
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Value * getOperand(unsigned i) const
unsigned getNumOperands() const
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
static constexpr uint64_t MaximumAlignment
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
static constexpr unsigned MaxAlignmentExponent
The maximum alignment for instructions.
iterator_range< use_iterator > uses()
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const ValueT &V)
constexpr ScalarTy getFixedValue() const
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
const ParentTy * getParent() const
self_iterator getIterator()
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
SetVector< Function * >::iterator I
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
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.
raw_ostream & operator<<(raw_ostream &OS, const RangeTy &R)
LLVM_ABI std::optional< Value * > combineOptionalValuesInAAValueLatice(const std::optional< Value * > &A, const std::optional< Value * > &B, Type *Ty)
Return the combination of A and B such that the result is a possible value of both.
LLVM_ABI bool isValidAtPosition(const ValueAndContext &VAC, InformationCache &InfoCache)
Return true if the value of VAC is a valid at the position of VAC, that is a constant,...
LLVM_ABI bool isAssumedThreadLocalObject(Attributor &A, Value &Obj, const AbstractAttribute &QueryingAA)
Return true if Obj is assumed to be a thread local object.
LLVM_ABI bool isGPUConstantAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU constant address space for the target triple...
LLVM_ABI bool isDynamicallyUnique(Attributor &A, const AbstractAttribute &QueryingAA, const Value &V, bool ForAnalysisOnly=true)
Return true if V is dynamically unique, that is, there are no two "instances" of V at runtime with di...
LLVM_ABI bool getPotentialCopiesOfStoredValue(Attributor &A, StoreInst &SI, SmallSetVector< Value *, 4 > &PotentialCopies, const AbstractAttribute &QueryingAA, bool &UsedAssumedInformation, bool OnlyExact=false)
Collect all potential values of the one stored by SI into PotentialCopies.
LLVM_ABI bool isGPUSharedAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU shared address space for the target triple i...
LLVM_ABI bool isGPULocalAddressSpace(const Module &M, unsigned AS)
Check if the given address space AS corresponds to a GPU local/private address space for the target t...
SmallPtrSet< Instruction *, 4 > InstExclusionSetTy
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.
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 Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
@ BasicBlock
Various leaf nodes.
@ Unsupported
This operation is completely unsupported on the target.
@ SingleThread
Synchronized with respect to signal handlers executing in the same thread.
@ Valid
The data is already valid.
unsigned combineHashValue(unsigned a, unsigned b)
Simplistic combination of 32-bit hash values into 32-bit hash values.
ElementType
The element type of an SRV or UAV resource.
Scope
Defines the scope in which this symbol should be visible: Default – Visible in the public interface o...
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
@ User
could "use" a pointer
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< UseNode * > Use
friend class Instruction
Iterator for Instructions in a `BasicBlock.
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Value * getAllocAlignment(const CallBase *V)
Gets the alignment argument for an aligned_alloc-like function based on the allocalign attribute.
bool operator<(int64_t V1, const APSInt &V2)
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt gcd(const DynamicAPInt &A, const DynamicAPInt &B)
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isLegalToPromote(const CallBase &CB, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q, SmallVectorImpl< Instruction * > *DropAnnotations=nullptr)
See if we can compute a simplified version of this instruction.
RelativeUniformCounterPtr Values
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
@ Known
Known to have no common set bits.
@ Undef
Value of the register doesn't matter.
auto pred_end(const MachineBasicBlock *BB)
unsigned getPointerAddressSpace(const Type *T)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
APFloat abs(APFloat X)
Returns the absolute value of the argument.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
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 ...
LLVM_ABI Value * simplifyInstructionWithOperands(Instruction *I, ArrayRef< Value * > NewOps, const SimplifyQuery &Q)
Like simplifyInstruction but the operands of I are replaced with NewOps.
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
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.
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
bool isa_and_nonnull(const Y &Val)
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
PotentialValuesState< std::pair< AA::ValueAndContext, AA::ValueScope > > PotentialLLVMValuesState
bool isModSet(const ModRefInfo MRI)
void sort(IteratorTy Start, IteratorTy End)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
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.
bool isPointerTy(const Type *T)
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
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,...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI CallBase & promoteCall(CallBase &CB, Function *Callee, CastInst **RetBitCast=nullptr)
Promote the given indirect call site to unconditionally call Callee.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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...
LLVM_ABI bool hasAssumption(const Function &F, const KnownAssumptionString &AssumptionStr)
Return true if F has the assumption AssumptionStr attached.
@ Success
The lock was released successfully.
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
AtomicOrdering
Atomic ordering for LLVM's memory model.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
PotentialValuesState< APInt > PotentialConstantIntValuesState
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
InterleavedRange< Range > interleaved_array(const Range &R, StringRef Separator=", ")
Output range R as an array of interleaved elements.
ChangeStatus clampStateAndIndicateChange< DerefState >(DerefState &S, const DerefState &R)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
launder.invariant.group and similar intrinsics return a pointer that aliases their argument,...
DWARFExpression::Operation Op
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R)
Helper function to clamp a state S of type StateType with the information in R and indicate/return if...
constexpr unsigned BitWidth
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
LLVM_ABI std::optional< APInt > getAllocSize(const CallBase *CB, const TargetLibraryInfo *TLI, function_ref< const Value *(const Value *)> Mapper=[](const Value *V) { return V;})
Return the size of the requested allocation.
LLVM_ABI DenseSet< StringRef > getAssumptions(const Function &F)
Return the set of all assumptions for the function F.
Align assumeAligned(uint64_t Value)
Treats the value 0 as a 1, so Align is always at least 1.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
@ OPTIONAL
The target may be valid if the source is not.
@ NONE
Do not track a dependence between source and target.
@ REQUIRED
The target cannot be valid if the source is not.
LLVM_ABI UseCaptureInfo DetermineUseCaptureKind(const Use &U, const Value *Base)
Determine what kind of capture behaviour U may exhibit.
LLVM_ABI Value * simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
LLVM_ABI bool mayContainIrreducibleControl(const Function &F, const LoopInfo *LI)
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
LLVM_ABI Constant * getElidedFreeResult(const Value *V)
If this is a call to a free function that returns a value, return the value that will be returned whe...
bool capturesNothing(CaptureComponents CC)
LLVM_ABI AssumeDereferenceableInfo getAssumeDereferenceableInfo(OperandBundleUse)
LLVM_ABI Value * getFreedOperand(const CallBase *CB)
If this if a call to a free function, return the freed operand.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
bool capturesAnyProvenance(CaptureComponents CC)
constexpr StringRef AssumptionAttrKey
The key we use for assumption attributes.
constexpr bool isCallableCC(CallingConv::ID CC)
bool isRefSet(const ModRefInfo MRI)
LLVM_ABI bool isRemovableAlloc(const CallBase *V)
Return true if this is a call to an allocation function that does not have side effects that we are r...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A type to track pointer/struct usage and accesses for AAPointerInfo.
bool forallInterferingAccesses(AA::RangeTy Range, F CB) const
See AAPointerInfo::forallInterferingAccesses.
AAPointerInfo::const_bin_iterator end() const
ChangeStatus addAccess(Attributor &A, const AAPointerInfo::RangeList &Ranges, Instruction &I, std::optional< Value * > Content, AAPointerInfo::AccessKind Kind, Type *Ty, Instruction *RemoteI=nullptr)
Add a new Access to the state at offset Offset and with size Size.
DenseMap< const Instruction *, SmallVector< unsigned > > RemoteIMap
AAPointerInfo::const_bin_iterator begin() const
AAPointerInfo::OffsetInfo ReturnedOffsets
Flag to determine if the underlying pointer is reaching a return statement in the associated function...
State & operator=(State &&R)
State(State &&SIS)=default
const AAPointerInfo::Access & getAccess(unsigned Index) const
SmallVector< AAPointerInfo::Access > AccessList
bool isAtFixpoint() const override
Return if this abstract state is fixed, thus does not need to be updated if information changes as it...
bool forallInterferingAccesses(Instruction &I, F CB, AA::RangeTy &Range) const
See AAPointerInfo::forallInterferingAccesses.
static State getWorstState(const State &SIS)
Return the worst possible representable state.
int64_t numOffsetBins() const
AAPointerInfo::OffsetBinsTy OffsetBins
ChangeStatus indicateOptimisticFixpoint() override
Indicate that the abstract state should converge to the optimistic state.
State & operator=(const State &R)
ChangeStatus indicatePessimisticFixpoint() override
Indicate that the abstract state should converge to the pessimistic state.
const State & getAssumed() const
static State getBestState(const State &SIS)
Return the best possible representable state.
bool isValidState() const override
Return if this abstract state is in a valid state.
----------------—AAIntraFnReachability Attribute-----------------------—
ReachabilityQueryInfo(const ReachabilityQueryInfo &RQI)
unsigned Hash
Precomputed hash for this RQI.
const Instruction * From
Start here,.
Reachable Result
and remember if it worked:
ReachabilityQueryInfo(const Instruction *From, const ToTy *To)
ReachabilityQueryInfo(Attributor &A, const Instruction &From, const ToTy &To, const AA::InstExclusionSetTy *ES, bool MakeUnique)
Constructor replacement to ensure unique and stable sets are used for the cache.
const ToTy * To
reach this place,
const AA::InstExclusionSetTy * ExclusionSet
without going through any of these instructions,
unsigned computeHashValue() const
An abstract interface for address space information.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for all align attributes.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
Align getKnownAlign() const
Return known alignment.
static LLVM_ABI const char ID
An abstract attribute for getting assumption information.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract state for querying live call edges.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract Attribute for specializing "dynamic" components of denormal_fpenv to a known denormal mod...
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for all dereferenceable attribute.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for llvm::GlobalValue information interference.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for indirect call information interference.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface to track if a value leaves it's defining function instance.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract Attribute for computing reachability between functions.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
bool canReach(Attributor &A, const Function &Fn) const
If the function represented by this possition can reach Fn.
virtual bool instructionCanReach(Attributor &A, const Instruction &Inst, const Function &Fn, const AA::InstExclusionSetTy *ExclusionSet=nullptr) const =0
Can Inst reach Fn.
An abstract interface to determine reachability of point A to B.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for identifying pointers from which loads can be marked invariant.
static LLVM_ABI const char ID
Unique ID (due to the unique address).
An abstract interface for liveness abstract attribute.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for memory access kind related attributes (readnone/readonly/writeonly).
bool isAssumedReadOnly() const
Return true if we assume that the underlying value is not accessed (=written) in its respective scope...
bool isKnownReadNone() const
Return true if we know that the underlying value is not read or accessed in its respective scope.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
bool isAssumedReadNone() const
Return true if we assume that the underlying value is not read or accessed in its respective scope.
An abstract interface for all memory location attributes (readnone/argmemonly/inaccessiblememonly/ina...
static LLVM_ABI std::string getMemoryLocationsAsStr(MemoryLocationsKind MLK)
Return the locations encoded by MLK as a readable string.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
StateType::base_t MemoryLocationsKind
An abstract interface for all nonnull attributes.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for potential address space information.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for all noalias attributes.
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
---------------------— NoAlias Argument Attribute ---------------------—
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for all nocapture attributes.
@ NO_CAPTURE_MAYBE_RETURNED
If we do not capture the value in memory or through integers we can only communicate it back as a der...
@ NO_CAPTURE
If we do not capture the value in memory, through integers, or as a derived pointer we know it is not...
static LLVM_ABI const char ID
Unique ID (due to the unique address)
bool isAssumedNoCaptureMaybeReturned() const
Return true if we assume that the underlying value is not captured in its respective scope but we all...
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
--------------------— Variable Capturing ------------------------------—
static LLVM_ABI void determineFunctionCaptureCapabilities(const IRPosition &IRP, const Function &F, BitIntegerState &State)
Update State according to the capture capabilities of F for position IRP.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An AbstractAttribute for nofree.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract attribute for norecurse.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An AbstractAttribute for noreturn.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI bool isAlignedBarrier(const CallBase &CB, bool ExecutedAligned)
Helper function to determine if CB is an aligned (GPU) barrier.
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 noundef attributes.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
---------------------— NoUndef Attribute ------------------------------—
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract Attribute for determining the necessity of the convergent attribute.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for all nonnull attributes.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
static LLVM_ABI bool isImpliedByIR(Attributor &A, const IRPosition &IRP, Attribute::AttrKind ImpliedAttributeKind, bool IgnoreSubsumingPositions=false)
---------------------— NonNull Argument Attribute ---------------------—
A helper containing a list of offsets computed for a Use.
A container for a list of ranges.
static void set_difference(const RangeList &L, const RangeList &R, RangeList &D)
Copy ranges from L that are not in R, into D.
An abstract interface for struct information.
virtual bool reachesReturn() const =0
OffsetBinsTy::const_iterator const_bin_iterator
virtual const_bin_iterator begin() const =0
DenseMap< AA::RangeTy, SmallSet< unsigned, 4 > > OffsetBinsTy
static LLVM_ABI const char ID
Unique ID (due to the unique address)
virtual int64_t numOffsetBins() const =0
An abstract interface for potential values analysis.
StateWrapper< PotentialConstantIntValuesState, AbstractAttribute, bool, unsigned > Base
static LLVM_ABI const char ID
Unique ID (due to the unique address)
LLVM_ABI AAPotentialConstantValues(const IRPosition &IRP, Attributor &A)
---------------— Potential Values Attribute ----------------------—
static LLVM_ABI const char ID
Unique ID (due to the unique address)
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 interface for privatizability.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract attribute for undefined behavior.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract attribute for getting all assumption underlying objects.
virtual bool forallUnderlyingObjects(function_ref< bool(Value &)> Pred, AA::ValueScope Scope=AA::Interprocedural) const =0
Check Pred on all underlying objects in Scope collected so far.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for range value analysis.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract interface for value simplify abstract attribute.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
An abstract attribute for willreturn.
static LLVM_ABI const char ID
Unique ID (due to the unique address)
Helper to represent an access offset and size, with logic to deal with uncertainty and check for over...
static constexpr int64_t Unknown
static RangeTy getUnknown()
const Instruction * getCtxI() const
Base struct for all "concrete attribute" deductions.
void print(raw_ostream &OS) const
Helper functions, for debug purposes only.
virtual StateType & getState()=0
Return the internal abstract state for inspection.
virtual void initialize(Attributor &A)
Initialize the state with the information in the Attributor A.
An interface to query the internal state of an abstract attribute.
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.
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
static constexpr Align fromLog2(unsigned Log2Value)
Returns an alignment of 1 << Log2Value bytes.
std::function< void( const ArgumentReplacementInfo &, Function &, Function::arg_iterator)> CalleeRepairCBTy
Callee repair callback type.
const Argument & getReplacedArg() const
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.
std::function< std::optional< Value * >( const IRPosition &, const AbstractAttribute *, bool &)> SimplifictionCallbackTy
Register CB as a simplification callback.
Specialization of the integer state for a bit-wise encoding.
BitIntegerState & addKnownBits(base_t Bits)
Add the bits in BitsEncoding to the "known bits".
Simple wrapper for a single bit (boolean) state.
static constexpr DenormalFPEnv getDefault()
static unsigned getHashValue(const Access &A)
AAPointerInfo::Access Access
static bool isEqual(const Access &LHS, const Access &RHS)
static bool isEqual(const AA::RangeTy &A, const AA::RangeTy B)
static unsigned getHashValue(const AA::RangeTy &Range)
DenseMapInfo< std::pair< const Instruction *, const ToTy * > > PairDMI
static bool isEqual(const ReachabilityQueryInfo< ToTy > *LHS, const ReachabilityQueryInfo< ToTy > *RHS)
DenseMapInfo< const AA::InstExclusionSetTy * > InstSetDMI
static unsigned getHashValue(const ReachabilityQueryInfo< ToTy > *RQI)
An information struct used to provide DenseMap with the various necessary components for a given valu...
State for dereferenceable attribute.
IncIntegerState DerefBytesState
State representing for dereferenceable bytes.
ChangeStatus manifest(Attributor &A) override
Helper to describe and deal with positions in the LLVM-IR.
Function * getAssociatedFunction() const
Return the associated function, if any.
static const IRPosition callsite_returned(const CallBase &CB)
Create a position describing the returned value of CB.
static const IRPosition returned(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the returned value of F.
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.
int getCalleeArgNo() const
Return the callee argument number of the associated value if it is an argument or call site argument,...
static const IRPosition inst(const Instruction &I, const CallBaseContext *CBContext=nullptr)
Create a position describing the instruction I.
static const IRPosition callsite_argument(const CallBase &CB, unsigned ArgNo)
Create a position describing the argument of CB at position ArgNo.
Kind
The positions we distinguish in the IR.
@ IRP_ARGUMENT
An attribute for a function argument.
@ IRP_RETURNED
An attribute for the function return value.
@ IRP_CALL_SITE
An attribute for a call site (function scope).
@ IRP_CALL_SITE_RETURNED
An attribute for a call site return value.
@ IRP_FUNCTION
An attribute for a function (scope).
@ IRP_CALL_SITE_ARGUMENT
An attribute for a call site argument.
@ IRP_INVALID
An invalid position.
Instruction * getCtxI() const
Return the context instruction, if any.
static const IRPosition argument(const Argument &Arg, const CallBaseContext *CBContext=nullptr)
Create a position describing the argument Arg.
Type * getAssociatedType() const
Return the type this abstract attribute is associated with.
static const IRPosition function(const Function &F, const CallBaseContext *CBContext=nullptr)
Create a position describing the function scope of F.
const CallBaseContext * getCallBaseContext() const
Get the call base context from the position.
Value & getAssociatedValue() const
Return the value this abstract attribute is associated with.
Value & getAnchorValue() const
Return the value this abstract attribute is anchored with.
int getCallSiteArgNo() const
Return the call site argument number of the associated value if it is an argument or call site argume...
static const IRPosition function_scope(const IRPosition &IRP, const CallBaseContext *CBContext=nullptr)
Create a position with function scope matching the "context" of IRP.
Kind getPositionKind() const
Return the associated position kind.
bool isArgumentPosition() const
Return true if the position is an argument or call site argument.
static const IRPosition callsite_function(const CallBase &CB)
Create a position describing the function scope of CB.
Function * getAnchorScope() const
Return the Function surrounding the anchor value.
ConstantRange getKnown() const
Return the known state encoding.
ConstantRange getAssumed() const
Return the assumed state encoding.
base_t getAssumed() const
Return the assumed state encoding.
static constexpr base_t getWorstState()
Helper that allows to insert a new assumption string in the known assumption set by creating a (stati...
A "must be executed context" for a given program point PP is the set of instructions,...
LLVM_ABI bool checkForAllTerminatorsInContext(const Instruction *PP, function_ref< bool(const Instruction *)> Pred)
Check Pred on all terminators in the context of PP and return true if it holds for all of them.
LLVM_ABI bool isInContextOf(const Instruction *I, const Instruction *PP)
}
Helper to tie a abstract state implementation to an abstract attribute.
StateType & getState() override
bool isPassthrough() const
CaptureComponents ResultCC
Components captured by the return value of the user of this Use.
LLVM_ABI bool unionAssumed(std::optional< Value * > Other)
Merge Other into the currently assumed simplified value.
std::optional< Value * > SimplifiedAssociatedValue
An assumed simplified value.
Type * Ty
The type of the original value.