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 (
const Use &CmpU : CmpI->uses()) {
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()},
1832 A.getInfoCache().getTargetLibraryInfoForFunction(*CB->
getFunction());
1837 const auto *CSArgPI =
A.getAAFor<AAPointerInfo>(
1843 Changed = translateAndAddState(
A, *CSArgPI, OffsetInfoMap[CurPtr], *CB,
1846 if (!CSArgPI->reachesReturn())
1847 return isValidState();
1850 if (!Callee ||
Callee->arg_size() <= ArgNo)
1852 bool UsedAssumedInformation =
false;
1853 auto ReturnedValue =
A.getAssumedSimplified(
1858 auto *Arg =
Callee->getArg(ArgNo);
1859 if (ReturnedArg && Arg != ReturnedArg)
1861 bool IsRetMustAcc = IsArgMustAcc && (ReturnedArg == Arg);
1862 const auto *CSRetPI =
A.getAAFor<AAPointerInfo>(
1866 OffsetInfo OI = OffsetInfoMap[CurPtr];
1867 CSArgPI->addReturnedOffsetsTo(OI);
1869 translateAndAddState(
A, *CSRetPI, OI, *CB, IsRetMustAcc) |
Changed;
1870 return isValidState();
1872 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] Call user not handled " << *CB
1877 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] User not handled " << *Usr <<
"\n");
1880 auto EquivalentUseCB = [&](
const Use &OldU,
const Use &NewU) {
1881 assert(OffsetInfoMap.
count(OldU) &&
"Old use should be known already!");
1882 assert(!OffsetInfoMap[OldU].isUnassigned() &&
"Old use should be assinged");
1883 if (OffsetInfoMap.
count(NewU)) {
1885 if (!(OffsetInfoMap[NewU] == OffsetInfoMap[OldU])) {
1886 dbgs() <<
"[AAPointerInfo] Equivalent use callback failed: "
1887 << OffsetInfoMap[NewU] <<
" vs " << OffsetInfoMap[OldU]
1891 return OffsetInfoMap[NewU] == OffsetInfoMap[OldU];
1894 return HandlePassthroughUser(NewU.get(), OldU.
get(), Unused);
1896 if (!
A.checkForAllUses(UsePred, *
this, AssociatedValue,
1898 true, EquivalentUseCB)) {
1899 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] Check for all uses failed, abort!\n");
1900 return indicatePessimisticFixpoint();
1904 dbgs() <<
"Accesses by bin after update:\n";
1911struct AAPointerInfoReturned final : AAPointerInfoImpl {
1912 AAPointerInfoReturned(
const IRPosition &IRP, Attributor &
A)
1913 : AAPointerInfoImpl(IRP,
A) {}
1916 return indicatePessimisticFixpoint();
1919 void trackStatistics()
const override {
1920 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1924struct AAPointerInfoArgument final : AAPointerInfoFloating {
1925 AAPointerInfoArgument(
const IRPosition &IRP, Attributor &
A)
1926 : AAPointerInfoFloating(IRP,
A) {}
1928 void trackStatistics()
const override {
1929 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
1933struct AAPointerInfoCallSiteArgument final : AAPointerInfoFloating {
1934 AAPointerInfoCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
1935 : AAPointerInfoFloating(IRP,
A) {}
1938 using namespace AA::PointerInfo;
1944 if (
auto Length =
MI->getLengthInBytes())
1945 LengthVal =
Length->getSExtValue();
1946 unsigned ArgNo = getIRPosition().getCallSiteArgNo();
1949 LLVM_DEBUG(
dbgs() <<
"[AAPointerInfo] Unhandled memory intrinsic "
1951 return indicatePessimisticFixpoint();
1954 ArgNo == 0 ? AccessKind::AK_MUST_WRITE : AccessKind::AK_MUST_READ;
1956 Changed | addAccess(
A, {0, LengthVal}, *
MI,
nullptr,
Kind,
nullptr);
1959 dbgs() <<
"Accesses by bin after update:\n";
1970 Argument *Arg = getAssociatedArgument();
1974 A.getAAFor<AAPointerInfo>(*
this, ArgPos, DepClassTy::REQUIRED);
1975 if (ArgAA && ArgAA->getState().isValidState())
1976 return translateAndAddStateFromCallee(
A, *ArgAA,
1979 return indicatePessimisticFixpoint();
1982 bool IsKnownNoCapture;
1984 A,
this, getIRPosition(), DepClassTy::OPTIONAL, IsKnownNoCapture))
1985 return indicatePessimisticFixpoint();
1987 bool IsKnown =
false;
1989 return ChangeStatus::UNCHANGED;
1992 ReadOnly ? AccessKind::AK_MAY_READ : AccessKind::AK_MAY_READ_WRITE;
1997 void trackStatistics()
const override {
1998 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
2002struct AAPointerInfoCallSiteReturned final : AAPointerInfoFloating {
2003 AAPointerInfoCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
2004 : AAPointerInfoFloating(IRP,
A) {}
2006 void trackStatistics()
const override {
2007 AAPointerInfoImpl::trackPointerInfoStatistics(getIRPosition());
2015struct AANoUnwindImpl : AANoUnwind {
2016 AANoUnwindImpl(
const IRPosition &IRP, Attributor &
A) : AANoUnwind(IRP,
A) {}
2021 A,
nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2025 const std::string getAsStr(Attributor *
A)
const override {
2026 return getAssumed() ?
"nounwind" :
"may-unwind";
2031 (unsigned)Instruction::Invoke, (
unsigned)Instruction::CallBr,
2032 (unsigned)Instruction::Call, (
unsigned)Instruction::CleanupRet,
2033 (unsigned)Instruction::CatchSwitch, (
unsigned)Instruction::Resume};
2036 if (!
I.mayThrow(
true))
2040 bool IsKnownNoUnwind;
2048 bool UsedAssumedInformation =
false;
2049 if (!
A.checkForAllInstructions(CheckForNoUnwind, *
this, Opcodes,
2050 UsedAssumedInformation))
2051 return indicatePessimisticFixpoint();
2053 return ChangeStatus::UNCHANGED;
2057struct AANoUnwindFunction final :
public AANoUnwindImpl {
2058 AANoUnwindFunction(
const IRPosition &IRP, Attributor &
A)
2059 : AANoUnwindImpl(IRP,
A) {}
2065struct AANoUnwindCallSite final
2066 : AACalleeToCallSite<AANoUnwind, AANoUnwindImpl> {
2067 AANoUnwindCallSite(
const IRPosition &IRP, Attributor &
A)
2068 : AACalleeToCallSite<AANoUnwind, AANoUnwindImpl>(IRP,
A) {}
2078 case Intrinsic::nvvm_barrier_cta_sync_aligned_all:
2079 case Intrinsic::nvvm_barrier_cta_sync_aligned_count:
2080 case Intrinsic::nvvm_barrier_cta_red_and_aligned_all:
2081 case Intrinsic::nvvm_barrier_cta_red_and_aligned_count:
2082 case Intrinsic::nvvm_barrier_cta_red_or_aligned_all:
2083 case Intrinsic::nvvm_barrier_cta_red_or_aligned_count:
2084 case Intrinsic::nvvm_barrier_cta_red_popc_aligned_all:
2085 case Intrinsic::nvvm_barrier_cta_red_popc_aligned_count:
2087 case Intrinsic::amdgcn_s_barrier:
2088 if (ExecutedAligned)
2111 switch (
I->getOpcode()) {
2112 case Instruction::AtomicRMW:
2115 case Instruction::Store:
2118 case Instruction::Load:
2123 "New atomic operations need to be known in the attributor.");
2141 const std::string getAsStr(Attributor *
A)
const override {
2142 return getAssumed() ?
"nosync" :
"may-sync";
2157 if (
I.mayReadOrWriteMemory())
2171 bool UsedAssumedInformation =
false;
2172 if (!
A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *
this,
2173 UsedAssumedInformation) ||
2174 !
A.checkForAllCallLikeInstructions(CheckForNoSync, *
this,
2175 UsedAssumedInformation))
2176 return indicatePessimisticFixpoint();
2181struct AANoSyncFunction final :
public AANoSyncImpl {
2182 AANoSyncFunction(
const IRPosition &IRP, Attributor &
A)
2183 : AANoSyncImpl(IRP,
A) {}
2189struct AANoSyncCallSite final : AACalleeToCallSite<AANoSync, AANoSyncImpl> {
2190 AANoSyncCallSite(
const IRPosition &IRP, Attributor &
A)
2191 : AACalleeToCallSite<AANoSync, AANoSyncImpl>(IRP,
A) {}
2200struct AANoFreeImpl :
public AANoFree {
2201 AANoFreeImpl(
const IRPosition &IRP, Attributor &
A) : AANoFree(IRP,
A) {}
2206 DepClassTy::NONE, IsKnown));
2223 bool UsedAssumedInformation =
false;
2224 if (!
A.checkForAllReadWriteInstructions(CheckForNoFree, *
this,
2225 UsedAssumedInformation) ||
2226 !
A.checkForAllCallLikeInstructions(CheckForNoFree, *
this,
2227 UsedAssumedInformation))
2228 return indicatePessimisticFixpoint();
2230 return ChangeStatus::UNCHANGED;
2233 const std::string getAsStr(Attributor *
A)
const override {
2234 return getAssumed() ?
"nofree" :
"may-free";
2238struct AANoFreeFunction final :
public AANoFreeImpl {
2239 AANoFreeFunction(
const IRPosition &IRP, Attributor &
A)
2240 : AANoFreeImpl(IRP,
A) {}
2246struct AANoFreeCallSite final : AACalleeToCallSite<AANoFree, AANoFreeImpl> {
2247 AANoFreeCallSite(
const IRPosition &IRP, Attributor &
A)
2248 : AACalleeToCallSite<AANoFree, AANoFreeImpl>(IRP,
A) {}
2254struct AANoFreeFloating : AANoFreeImpl {
2255 AANoFreeFloating(
const IRPosition &IRP, Attributor &
A)
2256 : AANoFreeImpl(IRP,
A) {}
2262 const IRPosition &IRP = getIRPosition();
2267 DepClassTy::OPTIONAL, IsKnown))
2268 return ChangeStatus::UNCHANGED;
2270 Value &AssociatedValue = getIRPosition().getAssociatedValue();
2271 auto Pred = [&](
const Use &
U,
bool &Follow) ->
bool {
2286 DepClassTy::REQUIRED, IsKnown))
2289 const AANoCapture *NoCaptureAA =
nullptr;
2292 DepClassTy::REQUIRED, IsKnown,
2293 false, &NoCaptureAA)) {
2318 if (!
A.checkForAllUses(
Pred, *
this, AssociatedValue))
2319 return indicatePessimisticFixpoint();
2321 return ChangeStatus::UNCHANGED;
2326struct AANoFreeArgument final : AANoFreeFloating {
2327 AANoFreeArgument(
const IRPosition &IRP, Attributor &
A)
2328 : AANoFreeFloating(IRP,
A) {}
2334struct AANoFreeCallSiteArgument final : AANoFreeFloating {
2335 AANoFreeCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
2336 : AANoFreeFloating(IRP,
A) {}
2343 Argument *Arg = getAssociatedArgument();
2345 return indicatePessimisticFixpoint();
2349 DepClassTy::REQUIRED, IsKnown))
2350 return ChangeStatus::UNCHANGED;
2351 return indicatePessimisticFixpoint();
2358struct AANoFreeReturned final : AANoFreeFloating {
2359 AANoFreeReturned(
const IRPosition &IRP, Attributor &
A)
2360 : AANoFreeFloating(IRP,
A) {
2372 void trackStatistics()
const override {}
2376struct AANoFreeCallSiteReturned final : AANoFreeFloating {
2377 AANoFreeCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
2378 : AANoFreeFloating(IRP,
A) {}
2381 return ChangeStatus::UNCHANGED;
2391 bool IgnoreSubsumingPositions) {
2393 AttrKinds.
push_back(Attribute::NonNull);
2396 AttrKinds.
push_back(Attribute::Dereferenceable);
2397 if (
A.hasAttr(IRP, AttrKinds, IgnoreSubsumingPositions, Attribute::NonNull))
2400 if (!
A.canUseBodyFor(IRP))
2407 if (!Fn->isDeclaration()) {
2417 bool UsedAssumedInformation =
false;
2418 if (!
A.checkForAllInstructions(
2420 Worklist.push_back({*cast<ReturnInst>(I).getReturnValue(), &I});
2424 UsedAssumedInformation,
false,
true))
2436 Attribute::NonNull)});
2441static int64_t getKnownNonNullAndDerefBytesForUse(
2442 Attributor &
A,
const AbstractAttribute &QueryingAA,
Value &AssociatedValue,
2443 const Use *U,
const Instruction *
I,
bool &IsNonNull,
bool &TrackUse) {
2446 const Value *UseV =
U->get();
2467 const DataLayout &
DL =
A.getInfoCache().getDL();
2472 case BundleAttr::NonNull:
2475 case BundleAttr::Dereferenceable: {
2479 return CI->getZExtValue();
2496 bool IsKnownNonNull;
2499 IsNonNull |= IsKnownNonNull;
2502 return DerefAA ? DerefAA->getKnownDereferenceableBytes() : 0;
2506 if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() ||
2507 Loc->Size.isScalable() ||
I->isVolatile())
2513 if (
Base &&
Base == &AssociatedValue) {
2514 int64_t DerefBytes = Loc->Size.getValue() +
Offset;
2516 return std::max(int64_t(0), DerefBytes);
2523 int64_t DerefBytes = Loc->Size.getValue();
2525 return std::max(int64_t(0), DerefBytes);
2531struct AANonNullImpl : AANonNull {
2532 AANonNullImpl(
const IRPosition &IRP, Attributor &
A) : AANonNull(IRP,
A) {}
2535 Value &
V = *getAssociatedValue().stripPointerCasts();
2537 indicatePessimisticFixpoint();
2541 if (Instruction *CtxI = getCtxI())
2542 followUsesInMBEC(*
this,
A, getState(), *CtxI);
2546 bool followUseInMBEC(Attributor &
A,
const Use *U,
const Instruction *
I,
2547 AANonNull::StateType &State) {
2548 bool IsNonNull =
false;
2549 bool TrackUse =
false;
2550 getKnownNonNullAndDerefBytesForUse(
A, *
this, getAssociatedValue(), U,
I,
2551 IsNonNull, TrackUse);
2552 State.setKnown(IsNonNull);
2556 const std::string getAsStr(Attributor *
A)
const override {
2557 return getAssumed() ?
"nonnull" :
"may-null";
2562struct AANonNullFloating :
public AANonNullImpl {
2563 AANonNullFloating(
const IRPosition &IRP, Attributor &
A)
2564 : AANonNullImpl(IRP,
A) {}
2567 auto CheckIRP = [&](
const IRPosition &IRP) {
2568 bool IsKnownNonNull;
2570 A, *
this, IRP, DepClassTy::OPTIONAL, IsKnownNonNull);
2574 bool UsedAssumedInformation =
false;
2575 Value *AssociatedValue = &getAssociatedValue();
2577 if (!
A.getAssumedSimplifiedValues(getIRPosition(), *
this,
Values,
2582 Values.size() != 1 ||
Values.front().getValue() != AssociatedValue;
2588 return AA::hasAssumedIRAttr<Attribute::NonNull>(
2589 A, this, IRPosition::value(*Op), DepClassTy::OPTIONAL,
2592 return ChangeStatus::UNCHANGED;
2596 DepClassTy::OPTIONAL, IsKnown) &&
2599 DepClassTy::OPTIONAL, IsKnown))
2600 return ChangeStatus::UNCHANGED;
2607 if (AVIRP == getIRPosition() || !CheckIRP(AVIRP))
2608 return indicatePessimisticFixpoint();
2609 return ChangeStatus::UNCHANGED;
2612 for (
const auto &VAC :
Values)
2614 return indicatePessimisticFixpoint();
2616 return ChangeStatus::UNCHANGED;
2623struct AANonNullReturned final
2624 : AAReturnedFromReturnedValues<AANonNull, AANonNull, AANonNull::StateType,
2625 false, AANonNull::IRAttributeKind, false> {
2626 AANonNullReturned(
const IRPosition &IRP, Attributor &
A)
2627 : AAReturnedFromReturnedValues<AANonNull, AANonNull, AANonNull::StateType,
2631 const std::string getAsStr(Attributor *
A)
const override {
2632 return getAssumed() ?
"nonnull" :
"may-null";
2639struct AANonNullArgument final
2640 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> {
2641 AANonNullArgument(
const IRPosition &IRP, Attributor &
A)
2642 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP,
A) {}
2647struct AANonNullCallSiteArgument final : AANonNullFloating {
2648 AANonNullCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
2649 : AANonNullFloating(IRP,
A) {}
2655struct AANonNullCallSiteReturned final
2656 : AACalleeToCallSite<AANonNull, AANonNullImpl> {
2657 AANonNullCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
2658 : AACalleeToCallSite<AANonNull, AANonNullImpl>(IRP,
A) {}
2666struct AAMustProgressImpl :
public AAMustProgress {
2667 AAMustProgressImpl(
const IRPosition &IRP, Attributor &
A)
2668 : AAMustProgress(IRP,
A) {}
2673 A,
nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2677 const std::string getAsStr(Attributor *
A)
const override {
2678 return getAssumed() ?
"mustprogress" :
"may-not-progress";
2682struct AAMustProgressFunction final : AAMustProgressImpl {
2683 AAMustProgressFunction(
const IRPosition &IRP, Attributor &
A)
2684 : AAMustProgressImpl(IRP,
A) {}
2689 A,
this, getIRPosition(), DepClassTy::OPTIONAL, IsKnown)) {
2691 return indicateOptimisticFixpoint();
2692 return ChangeStatus::UNCHANGED;
2695 auto CheckForMustProgress = [&](AbstractCallSite ACS) {
2697 bool IsKnownMustProgress;
2699 A,
this, IPos, DepClassTy::REQUIRED, IsKnownMustProgress,
2703 bool AllCallSitesKnown =
true;
2704 if (!
A.checkForAllCallSites(CheckForMustProgress, *
this,
2707 return indicatePessimisticFixpoint();
2709 return ChangeStatus::UNCHANGED;
2712 void trackStatistics()
const override {
2718struct AAMustProgressCallSite final : AAMustProgressImpl {
2719 AAMustProgressCallSite(
const IRPosition &IRP, Attributor &
A)
2720 : AAMustProgressImpl(IRP,
A) {}
2728 bool IsKnownMustProgress;
2730 A,
this, FnPos, DepClassTy::REQUIRED, IsKnownMustProgress))
2731 return indicatePessimisticFixpoint();
2732 return ChangeStatus::UNCHANGED;
2735 void trackStatistics()
const override {
2744struct AANoRecurseImpl :
public AANoRecurse {
2745 AANoRecurseImpl(
const IRPosition &IRP, Attributor &
A) : AANoRecurse(IRP,
A) {}
2750 A,
nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
2754 const std::string getAsStr(Attributor *
A)
const override {
2755 return getAssumed() ?
"norecurse" :
"may-recurse";
2759struct AANoRecurseFunction final : AANoRecurseImpl {
2760 AANoRecurseFunction(
const IRPosition &IRP, Attributor &
A)
2761 : AANoRecurseImpl(IRP,
A) {}
2766 auto CallSitePred = [&](AbstractCallSite ACS) {
2767 bool IsKnownNoRecurse;
2771 DepClassTy::NONE, IsKnownNoRecurse))
2773 return IsKnownNoRecurse;
2775 bool UsedAssumedInformation =
false;
2776 if (
A.checkForAllCallSites(CallSitePred, *
this,
true,
2777 UsedAssumedInformation)) {
2783 if (!UsedAssumedInformation)
2784 indicateOptimisticFixpoint();
2785 return ChangeStatus::UNCHANGED;
2788 const AAInterFnReachability *EdgeReachability =
2789 A.getAAFor<AAInterFnReachability>(*
this, getIRPosition(),
2790 DepClassTy::REQUIRED);
2791 if (EdgeReachability && EdgeReachability->
canReach(
A, *getAnchorScope()))
2792 return indicatePessimisticFixpoint();
2793 return ChangeStatus::UNCHANGED;
2800struct AANoRecurseCallSite final
2801 : AACalleeToCallSite<AANoRecurse, AANoRecurseImpl> {
2802 AANoRecurseCallSite(
const IRPosition &IRP, Attributor &
A)
2803 : AACalleeToCallSite<AANoRecurse, AANoRecurseImpl>(IRP,
A) {}
2812struct AANonConvergentImpl :
public AANonConvergent {
2813 AANonConvergentImpl(
const IRPosition &IRP, Attributor &
A)
2814 : AANonConvergent(IRP,
A) {}
2816 const std::string getAsStr(Attributor *
A)
const override {
2817 return getAssumed() ?
"non-convergent" :
"may-be-convergent";
2821struct AANonConvergentFunction final : AANonConvergentImpl {
2822 AANonConvergentFunction(
const IRPosition &IRP, Attributor &
A)
2823 : AANonConvergentImpl(IRP,
A) {}
2828 auto CalleeIsNotConvergent = [&](
Instruction &Inst) {
2831 if (!Callee ||
Callee->isIntrinsic()) {
2834 if (
Callee->isDeclaration()) {
2835 return !
Callee->hasFnAttribute(Attribute::Convergent);
2837 const auto *ConvergentAA =
A.getAAFor<AANonConvergent>(
2839 return ConvergentAA && ConvergentAA->isAssumedNotConvergent();
2842 bool UsedAssumedInformation =
false;
2843 if (!
A.checkForAllCallLikeInstructions(CalleeIsNotConvergent, *
this,
2844 UsedAssumedInformation)) {
2845 return indicatePessimisticFixpoint();
2847 return ChangeStatus::UNCHANGED;
2851 if (isKnownNotConvergent() &&
2852 A.hasAttr(getIRPosition(), Attribute::Convergent)) {
2853 A.removeAttrs(getIRPosition(), {Attribute::Convergent});
2854 return ChangeStatus::CHANGED;
2856 return ChangeStatus::UNCHANGED;
2866struct AAUndefinedBehaviorImpl :
public AAUndefinedBehavior {
2867 AAUndefinedBehaviorImpl(
const IRPosition &IRP, Attributor &
A)
2868 : AAUndefinedBehavior(IRP,
A) {}
2874 UndefBranchCondition,
2876 NullReturnViolatesNonNull,
2878 NullArgViolatesNonNull,
2882 std::optional<unsigned> ArgNo;
2884 UBInfo(Kind K) :
K(
K), ArgNo(std::nullopt) {}
2886 UBInfo(Kind K, std::optional<unsigned> ArgNo) :
K(
K), ArgNo(ArgNo) {}
2890 const size_t UBPrevSize = KnownUBInsts.size();
2891 const size_t NoUBPrevSize = AssumedNoUBInsts.size();
2899 if (AssumedNoUBInsts.count(&
I) || KnownUBInsts.count(&
I))
2908 "Expected pointer operand of memory accessing instruction");
2912 std::optional<Value *> SimplifiedPtrOp =
2913 stopOnUndefOrAssumed(
A, PtrOp, &
I, UBInfo::UndefPtrAccess);
2914 if (!SimplifiedPtrOp || !*SimplifiedPtrOp)
2916 const Value *PtrOpVal = *SimplifiedPtrOp;
2922 AssumedNoUBInsts.insert(&
I);
2934 AssumedNoUBInsts.insert(&
I);
2936 KnownUBInsts.try_emplace(&
I, UBInfo::NullPtrAccess);
2945 if (AssumedNoUBInsts.count(&
I) || KnownUBInsts.count(&
I))
2953 std::optional<Value *> SimplifiedCond = stopOnUndefOrAssumed(
2954 A, BrInst->getCondition(), BrInst, UBInfo::UndefBranchCondition);
2955 if (!SimplifiedCond || !*SimplifiedCond)
2957 AssumedNoUBInsts.insert(&
I);
2965 if (AssumedNoUBInsts.count(&
I) || KnownUBInsts.count(&
I))
2974 for (
unsigned idx = 0; idx < CB.
arg_size(); idx++) {
2980 if (idx >=
Callee->arg_size())
2992 bool IsKnownNoUndef;
2994 A,
this, CalleeArgumentIRP, DepClassTy::NONE, IsKnownNoUndef);
2995 if (!IsKnownNoUndef)
2997 bool UsedAssumedInformation =
false;
2998 std::optional<Value *> SimplifiedVal =
3001 if (UsedAssumedInformation)
3003 if (SimplifiedVal && !*SimplifiedVal)
3006 KnownUBInsts.try_emplace(&
I, UBInfo(UBInfo::UndefCallArgument, idx));
3012 bool IsKnownNonNull;
3014 A,
this, CalleeArgumentIRP, DepClassTy::NONE, IsKnownNonNull);
3016 KnownUBInsts.try_emplace(&
I,
3017 UBInfo(UBInfo::NullArgViolatesNonNull, idx));
3026 std::optional<Value *> SimplifiedRetValue = stopOnUndefOrAssumed(
3027 A, RI.getReturnValue(), &
I, UBInfo::UndefReturnValue);
3028 if (!SimplifiedRetValue || !*SimplifiedRetValue)
3046 bool IsKnownNonNull;
3051 KnownUBInsts.try_emplace(&
I, UBInfo::NullReturnViolatesNonNull);
3057 bool UsedAssumedInformation =
false;
3058 A.checkForAllInstructions(InspectMemAccessInstForUB, *
this,
3059 {Instruction::Load, Instruction::Store,
3060 Instruction::AtomicCmpXchg,
3061 Instruction::AtomicRMW},
3062 UsedAssumedInformation,
3064 A.checkForAllInstructions(InspectBrInstForUB, *
this, {Instruction::CondBr},
3065 UsedAssumedInformation,
3067 A.checkForAllCallLikeInstructions(InspectCallSiteForUB, *
this,
3068 UsedAssumedInformation);
3072 if (!getAnchorScope()->getReturnType()->isVoidTy()) {
3074 if (!
A.isAssumedDead(ReturnIRP,
this,
nullptr, UsedAssumedInformation)) {
3075 bool IsKnownNoUndef;
3077 A,
this, ReturnIRP, DepClassTy::NONE, IsKnownNoUndef);
3079 A.checkForAllInstructions(InspectReturnInstForUB, *
this,
3080 {Instruction::Ret}, UsedAssumedInformation,
3085 if (NoUBPrevSize != AssumedNoUBInsts.size() ||
3086 UBPrevSize != KnownUBInsts.size())
3087 return ChangeStatus::CHANGED;
3088 return ChangeStatus::UNCHANGED;
3091 bool isKnownToCauseUB(Instruction *
I)
const override {
3092 return KnownUBInsts.count(
I);
3095 bool isAssumedToCauseUB(Instruction *
I)
const override {
3102 switch (
I->getOpcode()) {
3103 case Instruction::Load:
3104 case Instruction::Store:
3105 case Instruction::AtomicCmpXchg:
3106 case Instruction::AtomicRMW:
3107 case Instruction::CondBr:
3108 return !AssumedNoUBInsts.count(
I);
3117 static void emitUBRemark(Attributor &
A, Instruction *
I,
const UBInfo &Info) {
3118 auto Remark = [&](OptimizationRemark
OR) {
3120 case UBInfo::NullPtrAccess:
3121 case UBInfo::UndefPtrAccess: {
3122 return OR <<
"Memory access through a pointer known to be "
3125 <<
" is undefined behavior; replacing with 'unreachable'.";
3127 case UBInfo::UndefBranchCondition:
3128 return OR <<
"Branch condition known to be "
3130 <<
" is undefined behavior; replacing with 'unreachable'.";
3131 case UBInfo::UndefReturnValue:
3132 case UBInfo::NullReturnViolatesNonNull:
3133 return OR <<
"Value returned known to be "
3136 <<
" is undefined behavior; replacing with 'unreachable'.";
3137 case UBInfo::UndefCallArgument:
3138 case UBInfo::NullArgViolatesNonNull: {
3139 bool IsUndef =
Info.K == UBInfo::UndefCallArgument;
3142 <<
" passed to parameter of ";
3147 return OR <<
" known to be "
3148 <<
ore::NV(
"Argument", IsUndef ?
"undef" :
"null")
3149 <<
" is undefined behavior; replacing with 'unreachable'.";
3154 A.emitRemark<OptimizationRemark>(
I,
"UndefinedBehavior",
Remark);
3158 if (KnownUBInsts.empty())
3159 return ChangeStatus::UNCHANGED;
3160 for (
const auto &[
I, Info] : KnownUBInsts) {
3161 emitUBRemark(
A,
I, Info);
3162 A.changeToUnreachableAfterManifest(
I);
3164 return ChangeStatus::CHANGED;
3167 const std::string getAsStr(Attributor *
A)
const override {
3168 return getAssumed() ?
"undefined-behavior" :
"no-ub";
3197 MapVector<Instruction *, UBInfo> KnownUBInsts;
3201 SmallPtrSet<Instruction *, 8> AssumedNoUBInsts;
3212 std::optional<Value *> stopOnUndefOrAssumed(Attributor &
A,
Value *
V,
3213 Instruction *
I, UBInfo::Kind K) {
3214 bool UsedAssumedInformation =
false;
3215 std::optional<Value *> SimplifiedV =
3218 if (!UsedAssumedInformation) {
3223 KnownUBInsts.try_emplace(
I, K);
3224 return std::nullopt;
3231 KnownUBInsts.try_emplace(
I, K);
3232 return std::nullopt;
3238struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl {
3239 AAUndefinedBehaviorFunction(
const IRPosition &IRP, Attributor &
A)
3240 : AAUndefinedBehaviorImpl(IRP,
A) {}
3242 void trackStatistics()
const override {
3243 STATS_DECL(UndefinedBehaviorInstruction, Instruction,
3244 "Number of instructions known to have UB");
3246 KnownUBInsts.size();
3257static bool mayContainUnboundedCycle(
Function &
F, Attributor &
A) {
3258 ScalarEvolution *SE =
3259 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
F);
3260 LoopInfo *LI =
A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
F);
3266 for (scc_iterator<Function *> SCCI =
scc_begin(&
F); !SCCI.isAtEnd(); ++SCCI)
3267 if (SCCI.hasCycle())
3277 for (
auto *L : LI->getLoopsInPreorder()) {
3284struct AAWillReturnImpl :
public AAWillReturn {
3285 AAWillReturnImpl(
const IRPosition &IRP, Attributor &
A)
3286 : AAWillReturn(IRP,
A) {}
3291 A,
nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
3296 bool isImpliedByMustprogressAndReadonly(Attributor &
A,
bool KnownOnly) {
3297 if (!
A.hasAttr(getIRPosition(), {Attribute::MustProgress}))
3302 return IsKnown || !KnownOnly;
3307 if (isImpliedByMustprogressAndReadonly(
A,
false))
3308 return ChangeStatus::UNCHANGED;
3314 A,
this, IPos, DepClassTy::REQUIRED, IsKnown)) {
3320 bool IsKnownNoRecurse;
3322 A,
this, IPos, DepClassTy::REQUIRED, IsKnownNoRecurse);
3325 bool UsedAssumedInformation =
false;
3326 if (!
A.checkForAllCallLikeInstructions(CheckForWillReturn, *
this,
3327 UsedAssumedInformation))
3328 return indicatePessimisticFixpoint();
3332 return !
I.isVolatile();
3334 if (!
A.checkForAllInstructions(CheckForVolatile, *
this,
3335 {Instruction::Load, Instruction::Store,
3336 Instruction::AtomicCmpXchg,
3337 Instruction::AtomicRMW},
3338 UsedAssumedInformation))
3339 return indicatePessimisticFixpoint();
3341 return ChangeStatus::UNCHANGED;
3344 const std::string getAsStr(Attributor *
A)
const override {
3345 return getAssumed() ?
"willreturn" :
"may-noreturn";
3349struct AAWillReturnFunction final : AAWillReturnImpl {
3350 AAWillReturnFunction(
const IRPosition &IRP, Attributor &
A)
3351 : AAWillReturnImpl(IRP,
A) {}
3354 AAWillReturnImpl::initialize(
A);
3357 assert(
F &&
"Did expect an anchor function");
3358 if (
F->isDeclaration() || mayContainUnboundedCycle(*
F,
A))
3359 indicatePessimisticFixpoint();
3366struct AAWillReturnCallSite final
3367 : AACalleeToCallSite<AAWillReturn, AAWillReturnImpl> {
3368 AAWillReturnCallSite(
const IRPosition &IRP, Attributor &
A)
3369 : AACalleeToCallSite<AAWillReturn, AAWillReturnImpl>(IRP,
A) {}
3372 if (isImpliedByMustprogressAndReadonly(
A,
false))
3373 return ChangeStatus::UNCHANGED;
3375 return AACalleeToCallSite::updateImpl(
A);
3396 const ToTy *
To =
nullptr;
3423 if (!ES || ES->
empty()) {
3424 ExclusionSet = nullptr;
3425 }
else if (MakeUnique) {
3426 ExclusionSet =
A.getInfoCache().getOrCreateUniqueBlockExecutionSet(ES);
3444 if (!PairDMI::isEqual({LHS->From, LHS->To}, {RHS->From, RHS->To}))
3446 return InstSetDMI::isEqual(LHS->ExclusionSet, RHS->ExclusionSet);
3454template <
typename BaseTy,
typename ToTy>
3455struct CachedReachabilityAA :
public BaseTy {
3456 using RQITy = ReachabilityQueryInfo<ToTy>;
3458 CachedReachabilityAA(
const IRPosition &IRP, Attributor &
A) : BaseTy(IRP,
A) {}
3460 bool isQueryAA()
const override {
return true; }
3464 for (
unsigned u = 0, e = QueryVector.size(); u < e; ++u) {
3465 RQITy *RQI = QueryVector[
u];
3466 if (RQI->Result == RQITy::Reachable::No &&
3468 Changed = ChangeStatus::CHANGED;
3474 bool IsTemporaryRQI) = 0;
3476 bool rememberResult(Attributor &
A,
typename RQITy::Reachable Result,
3477 RQITy &RQI,
bool UsedExclusionSet,
bool IsTemporaryRQI) {
3482 QueryCache.erase(&RQI);
3488 if (Result == RQITy::Reachable::Yes || !UsedExclusionSet) {
3489 RQITy PlainRQI(RQI.From, RQI.To);
3490 if (!QueryCache.count(&PlainRQI)) {
3491 RQITy *RQIPtr =
new (
A.Allocator) RQITy(RQI.From, RQI.To);
3493 QueryVector.push_back(RQIPtr);
3494 QueryCache.insert(RQIPtr);
3499 if (IsTemporaryRQI && Result != RQITy::Reachable::Yes && UsedExclusionSet) {
3500 assert((!RQI.ExclusionSet || !RQI.ExclusionSet->empty()) &&
3501 "Did not expect empty set!");
3502 RQITy *RQIPtr =
new (
A.Allocator)
3503 RQITy(
A, *RQI.From, *RQI.To, RQI.ExclusionSet,
true);
3504 assert(RQIPtr->Result == RQITy::Reachable::No &&
"Already reachable?");
3506 assert(!QueryCache.count(RQIPtr));
3507 QueryVector.push_back(RQIPtr);
3508 QueryCache.insert(RQIPtr);
3511 if (Result == RQITy::Reachable::No && IsTemporaryRQI)
3512 A.registerForUpdate(*
this);
3513 return Result == RQITy::Reachable::Yes;
3516 const std::string getAsStr(Attributor *
A)
const override {
3518 return "#queries(" + std::to_string(QueryVector.size()) +
")";
3521 bool checkQueryCache(Attributor &
A, RQITy &StackRQI,
3522 typename RQITy::Reachable &Result) {
3523 if (!this->getState().isValidState()) {
3524 Result = RQITy::Reachable::Yes;
3530 if (StackRQI.ExclusionSet) {
3531 RQITy PlainRQI(StackRQI.From, StackRQI.To);
3532 auto It = QueryCache.find(&PlainRQI);
3533 if (It != QueryCache.end() && (*It)->Result == RQITy::Reachable::No) {
3534 Result = RQITy::Reachable::No;
3539 auto It = QueryCache.find(&StackRQI);
3540 if (It != QueryCache.end()) {
3547 QueryCache.insert(&StackRQI);
3553 DenseSet<RQITy *> QueryCache;
3556struct AAIntraFnReachabilityFunction final
3557 :
public CachedReachabilityAA<AAIntraFnReachability, Instruction> {
3558 using Base = CachedReachabilityAA<AAIntraFnReachability, Instruction>;
3559 AAIntraFnReachabilityFunction(
const IRPosition &IRP, Attributor &
A)
3561 DT =
A.getInfoCache().getAnalysisResultForFunction<DominatorTreeAnalysis>(
3565 bool isAssumedReachable(
3566 Attributor &
A,
const Instruction &From,
const Instruction &To,
3568 auto *NonConstThis =
const_cast<AAIntraFnReachabilityFunction *
>(
this);
3572 RQITy StackRQI(
A, From, To, ExclusionSet,
false);
3574 if (!NonConstThis->checkQueryCache(
A, StackRQI, Result))
3575 return NonConstThis->isReachableImpl(
A, StackRQI,
3577 return Result == RQITy::Reachable::Yes;
3584 A.getAAFor<AAIsDead>(*
this, getIRPosition(), DepClassTy::OPTIONAL);
3587 [&](
const auto &DeadEdge) {
3588 return LivenessAA->isEdgeDead(DeadEdge.first,
3592 return LivenessAA->isAssumedDead(BB);
3594 return ChangeStatus::UNCHANGED;
3598 return Base::updateImpl(
A);
3602 bool IsTemporaryRQI)
override {
3604 bool UsedExclusionSet =
false;
3609 while (IP && IP != &To) {
3610 if (ExclusionSet && IP != Origin && ExclusionSet->
count(IP)) {
3611 UsedExclusionSet =
true;
3619 const BasicBlock *FromBB = RQI.From->getParent();
3620 const BasicBlock *ToBB = RQI.To->getParent();
3622 "Not an intra-procedural query!");
3626 if (FromBB == ToBB &&
3627 WillReachInBlock(*RQI.From, *RQI.To, RQI.ExclusionSet))
3628 return rememberResult(
A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3633 if (!WillReachInBlock(ToBB->
front(), *RQI.To, RQI.ExclusionSet))
3634 return rememberResult(
A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3638 SmallPtrSet<const BasicBlock *, 16> ExclusionBlocks;
3639 if (RQI.ExclusionSet)
3640 for (
auto *
I : *RQI.ExclusionSet)
3641 if (
I->getFunction() == Fn)
3642 ExclusionBlocks.
insert(
I->getParent());
3645 if (ExclusionBlocks.
count(FromBB) &&
3648 return rememberResult(
A, RQITy::Reachable::No, RQI,
true, IsTemporaryRQI);
3651 A.getAAFor<AAIsDead>(*
this, getIRPosition(), DepClassTy::OPTIONAL);
3652 if (LivenessAA && LivenessAA->isAssumedDead(ToBB)) {
3653 DeadBlocks.insert(ToBB);
3654 return rememberResult(
A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3658 SmallPtrSet<const BasicBlock *, 16> Visited;
3662 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> LocalDeadEdges;
3663 while (!Worklist.
empty()) {
3665 if (!Visited.
insert(BB).second)
3667 for (
const BasicBlock *SuccBB :
successors(BB)) {
3668 if (LivenessAA && LivenessAA->isEdgeDead(BB, SuccBB)) {
3669 LocalDeadEdges.
insert({BB, SuccBB});
3674 return rememberResult(
A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3677 return rememberResult(
A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
3680 if (ExclusionBlocks.
count(SuccBB)) {
3681 UsedExclusionSet =
true;
3688 DeadEdges.insert_range(LocalDeadEdges);
3689 return rememberResult(
A, RQITy::Reachable::No, RQI, UsedExclusionSet,
3693 void trackStatistics()
const override {}
3698 DenseSet<const BasicBlock *> DeadBlocks;
3702 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> DeadEdges;
3705 const DominatorTree *DT =
nullptr;
3713 bool IgnoreSubsumingPositions) {
3714 assert(ImpliedAttributeKind == Attribute::NoAlias &&
3715 "Unexpected attribute kind");
3721 IgnoreSubsumingPositions =
true;
3732 if (
A.hasAttr(IRP, {Attribute::ByVal, Attribute::NoAlias},
3733 IgnoreSubsumingPositions, Attribute::NoAlias))
3743 "Noalias is a pointer attribute");
3746 const std::string getAsStr(
Attributor *
A)
const override {
3747 return getAssumed() ?
"noalias" :
"may-alias";
3752struct AANoAliasFloating final : AANoAliasImpl {
3753 AANoAliasFloating(
const IRPosition &IRP, Attributor &
A)
3754 : AANoAliasImpl(IRP,
A) {}
3758 return indicatePessimisticFixpoint();
3761 void trackStatistics()
const override {
3767struct AANoAliasArgument final
3768 : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> {
3769 using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>;
3770 AANoAliasArgument(
const IRPosition &IRP, Attributor &
A) :
Base(IRP,
A) {}
3782 DepClassTy::OPTIONAL, IsKnownNoSycn))
3783 return Base::updateImpl(
A);
3788 return Base::updateImpl(
A);
3792 bool UsedAssumedInformation =
false;
3793 if (
A.checkForAllCallSites(
3794 [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *
this,
3795 true, UsedAssumedInformation))
3796 return Base::updateImpl(
A);
3804 return indicatePessimisticFixpoint();
3810struct AANoAliasCallSiteArgument final : AANoAliasImpl {
3811 AANoAliasCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
3812 : AANoAliasImpl(IRP,
A) {}
3816 bool mayAliasWithArgument(Attributor &
A, AAResults *&AAR,
3817 const AAMemoryBehavior &MemBehaviorAA,
3818 const CallBase &CB,
unsigned OtherArgNo) {
3820 if (this->getCallSiteArgNo() == (
int)OtherArgNo)
3828 auto *CBArgMemBehaviorAA =
A.getAAFor<AAMemoryBehavior>(
3832 if (CBArgMemBehaviorAA && CBArgMemBehaviorAA->isAssumedReadNone()) {
3833 A.recordDependence(*CBArgMemBehaviorAA, *
this, DepClassTy::OPTIONAL);
3840 if (CBArgMemBehaviorAA && CBArgMemBehaviorAA->isAssumedReadOnly() &&
3842 A.recordDependence(MemBehaviorAA, *
this, DepClassTy::OPTIONAL);
3843 A.recordDependence(*CBArgMemBehaviorAA, *
this, DepClassTy::OPTIONAL);
3849 AAR =
A.getInfoCache().getAnalysisResultForFunction<AAManager>(
3853 bool IsAliasing = !AAR || !AAR->
isNoAlias(&getAssociatedValue(), ArgOp);
3855 "callsite arguments: "
3856 << getAssociatedValue() <<
" " << *ArgOp <<
" => "
3857 << (IsAliasing ?
"" :
"no-") <<
"alias \n");
3862 bool isKnownNoAliasDueToNoAliasPreservation(
3863 Attributor &
A, AAResults *&AAR,
const AAMemoryBehavior &MemBehaviorAA) {
3876 auto UsePred = [&](
const Use &
U,
bool &Follow) ->
bool {
3892 bool IsKnownNoCapture;
3895 DepClassTy::OPTIONAL, IsKnownNoCapture))
3901 A, *UserI, *getCtxI(), *
this,
nullptr,
3902 [ScopeFn](
const Function &Fn) {
return &Fn != ScopeFn; }))
3917 LLVM_DEBUG(
dbgs() <<
"[AANoAliasCSArg] Unknown user: " << *UserI <<
"\n");
3921 bool IsKnownNoCapture;
3922 const AANoCapture *NoCaptureAA =
nullptr;
3924 A,
this, VIRP, DepClassTy::NONE, IsKnownNoCapture,
false, &NoCaptureAA);
3925 if (!IsAssumedNoCapture &&
3927 if (!
A.checkForAllUses(UsePred, *
this, getAssociatedValue())) {
3929 dbgs() <<
"[AANoAliasCSArg] " << getAssociatedValue()
3930 <<
" cannot be noalias as it is potentially captured\n");
3935 A.recordDependence(*NoCaptureAA, *
this, DepClassTy::OPTIONAL);
3941 for (
unsigned OtherArgNo = 0; OtherArgNo < CB.
arg_size(); OtherArgNo++)
3942 if (mayAliasWithArgument(
A, AAR, MemBehaviorAA, CB, OtherArgNo))
3951 auto *MemBehaviorAA =
3952 A.getAAFor<AAMemoryBehavior>(*
this, getIRPosition(), DepClassTy::NONE);
3954 A.recordDependence(*MemBehaviorAA, *
this, DepClassTy::OPTIONAL);
3955 return ChangeStatus::UNCHANGED;
3958 bool IsKnownNoAlias;
3961 A,
this, VIRP, DepClassTy::REQUIRED, IsKnownNoAlias)) {
3963 <<
" is not no-alias at the definition\n");
3964 return indicatePessimisticFixpoint();
3967 AAResults *AAR =
nullptr;
3968 if (MemBehaviorAA &&
3969 isKnownNoAliasDueToNoAliasPreservation(
A, AAR, *MemBehaviorAA)) {
3971 dbgs() <<
"[AANoAlias] No-Alias deduced via no-alias preservation\n");
3972 return ChangeStatus::UNCHANGED;
3975 return indicatePessimisticFixpoint();
3982struct AANoAliasReturned final : AANoAliasImpl {
3983 AANoAliasReturned(
const IRPosition &IRP, Attributor &
A)
3984 : AANoAliasImpl(IRP,
A) {}
3988 auto CheckReturnValue = [&](
Value &RV) ->
bool {
3999 bool IsKnownNoAlias;
4001 A,
this, RVPos, DepClassTy::REQUIRED, IsKnownNoAlias))
4004 bool IsKnownNoCapture;
4005 const AANoCapture *NoCaptureAA =
nullptr;
4007 A,
this, RVPos, DepClassTy::REQUIRED, IsKnownNoCapture,
false,
4009 return IsAssumedNoCapture ||
4013 if (!
A.checkForAllReturnedValues(CheckReturnValue, *
this))
4014 return indicatePessimisticFixpoint();
4016 return ChangeStatus::UNCHANGED;
4023struct AANoAliasCallSiteReturned final
4024 : AACalleeToCallSite<AANoAlias, AANoAliasImpl> {
4025 AANoAliasCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
4026 : AACalleeToCallSite<AANoAlias, AANoAliasImpl>(IRP,
A) {}
4035struct AAIsDeadValueImpl :
public AAIsDead {
4036 AAIsDeadValueImpl(
const IRPosition &IRP, Attributor &
A) : AAIsDead(IRP,
A) {}
4038 bool isAssumedDead()
const override {
return isAssumed(IS_DEAD); }
4040 bool isKnownDead()
const override {
return isKnown(IS_DEAD); }
4042 bool isAssumedDead(
const BasicBlock *BB)
const override {
return false; }
4044 bool isKnownDead(
const BasicBlock *BB)
const override {
return false; }
4046 bool isAssumedDead(
const Instruction *
I)
const override {
4047 return I == getCtxI() && isAssumedDead();
4050 bool isKnownDead(
const Instruction *
I)
const override {
4051 return isAssumedDead(
I) && isKnownDead();
4054 const std::string getAsStr(Attributor *
A)
const override {
4055 return isAssumedDead() ?
"assumed-dead" :
"assumed-live";
4059 bool areAllUsesAssumedDead(Attributor &
A,
Value &
V) {
4061 if (
V.getType()->isVoidTy() ||
V.use_empty())
4067 if (!
A.isRunOn(*
I->getFunction()))
4069 bool UsedAssumedInformation =
false;
4070 std::optional<Constant *>
C =
4071 A.getAssumedConstant(
V, *
this, UsedAssumedInformation);
4076 auto UsePred = [&](
const Use &
U,
bool &Follow) {
return false; };
4081 return A.checkForAllUses(UsePred, *
this,
V,
false,
4082 DepClassTy::REQUIRED,
4087 bool isAssumedSideEffectFree(Attributor &
A, Instruction *
I) {
4091 if (!
I->isTerminator() && !
I->mayHaveSideEffects())
4100 bool IsKnownNoUnwind;
4102 A,
this, CallIRP, DepClassTy::OPTIONAL, IsKnownNoUnwind))
4110struct AAIsDeadFloating :
public AAIsDeadValueImpl {
4111 AAIsDeadFloating(
const IRPosition &IRP, Attributor &
A)
4112 : AAIsDeadValueImpl(IRP,
A) {}
4115 AAIsDeadValueImpl::initialize(
A);
4118 indicatePessimisticFixpoint();
4123 if (!isAssumedSideEffectFree(
A,
I)) {
4125 indicatePessimisticFixpoint();
4127 removeAssumedBits(HAS_NO_EFFECT);
4131 bool isDeadFence(Attributor &
A, FenceInst &FI) {
4132 const auto *ExecDomainAA =
A.lookupAAFor<AAExecutionDomain>(
4134 if (!ExecDomainAA || !ExecDomainAA->isNoOpFence(FI))
4136 A.recordDependence(*ExecDomainAA, *
this, DepClassTy::OPTIONAL);
4140 bool isDeadStore(Attributor &
A, StoreInst &SI,
4141 SmallSetVector<Instruction *, 8> *AssumeOnlyInst =
nullptr) {
4143 if (
SI.isVolatile())
4149 bool UsedAssumedInformation =
false;
4150 if (!AssumeOnlyInst) {
4151 PotentialCopies.clear();
4153 UsedAssumedInformation)) {
4156 <<
"[AAIsDead] Could not determine potential copies of store!\n");
4160 LLVM_DEBUG(
dbgs() <<
"[AAIsDead] Store has " << PotentialCopies.size()
4161 <<
" potential copies.\n");
4163 InformationCache &InfoCache =
A.getInfoCache();
4166 UsedAssumedInformation))
4170 auto &UserI = cast<Instruction>(*U.getUser());
4171 if (InfoCache.isOnlyUsedByAssume(UserI)) {
4173 AssumeOnlyInst->insert(&UserI);
4176 return A.isAssumedDead(U,
this,
nullptr, UsedAssumedInformation);
4182 <<
" is assumed live!\n");
4187 const std::string getAsStr(Attributor *
A)
const override {
4191 return "assumed-dead-store";
4194 return "assumed-dead-fence";
4195 return AAIsDeadValueImpl::getAsStr(
A);
4201 if (!isDeadStore(
A, *SI))
4202 return indicatePessimisticFixpoint();
4204 if (!isDeadFence(
A, *FI))
4205 return indicatePessimisticFixpoint();
4207 if (!isAssumedSideEffectFree(
A,
I))
4208 return indicatePessimisticFixpoint();
4209 if (!areAllUsesAssumedDead(
A, getAssociatedValue()))
4210 return indicatePessimisticFixpoint();
4215 bool isRemovableStore()
const override {
4216 return isAssumed(IS_REMOVABLE) &&
isa<StoreInst>(&getAssociatedValue());
4220 Value &
V = getAssociatedValue();
4227 SmallSetVector<Instruction *, 8> AssumeOnlyInst;
4228 bool IsDead = isDeadStore(
A, *SI, &AssumeOnlyInst);
4231 A.deleteAfterManifest(*
I);
4232 for (
size_t i = 0; i < AssumeOnlyInst.
size(); ++i) {
4234 for (
auto *Usr : AOI->
users())
4236 A.deleteAfterManifest(*AOI);
4242 A.deleteAfterManifest(*FI);
4245 if (isAssumedSideEffectFree(
A,
I) && !
I->isTerminator()) {
4246 A.deleteAfterManifest(*
I);
4253 void trackStatistics()
const override {
4259 SmallSetVector<Value *, 4> PotentialCopies;
4262struct AAIsDeadArgument :
public AAIsDeadFloating {
4263 AAIsDeadArgument(
const IRPosition &IRP, Attributor &
A)
4264 : AAIsDeadFloating(IRP,
A) {}
4267 Argument &Arg = *getAssociatedArgument();
4268 if (
A.isValidFunctionSignatureRewrite(Arg, {}))
4269 if (
A.registerFunctionSignatureRewrite(
4273 return ChangeStatus::CHANGED;
4275 return ChangeStatus::UNCHANGED;
4281struct AAIsDeadCallSiteArgument :
public AAIsDeadValueImpl {
4282 AAIsDeadCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
4283 : AAIsDeadValueImpl(IRP,
A) {}
4286 AAIsDeadValueImpl::initialize(
A);
4288 indicatePessimisticFixpoint();
4296 Argument *Arg = getAssociatedArgument();
4298 return indicatePessimisticFixpoint();
4300 auto *ArgAA =
A.getAAFor<AAIsDead>(*
this, ArgPos, DepClassTy::REQUIRED);
4302 return indicatePessimisticFixpoint();
4310 "Expected undef values to be filtered out!");
4312 if (
A.changeUseAfterManifest(U, UV))
4313 return ChangeStatus::CHANGED;
4314 return ChangeStatus::UNCHANGED;
4320struct AAIsDeadCallSiteReturned :
public AAIsDeadFloating {
4321 AAIsDeadCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
4322 : AAIsDeadFloating(IRP,
A) {}
4324 bool isAssumedDead()
const override {
4325 return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree;
4329 AAIsDeadFloating::initialize(
A);
4331 indicatePessimisticFixpoint();
4336 IsAssumedSideEffectFree = isAssumedSideEffectFree(
A, getCtxI());
4341 if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(
A, getCtxI())) {
4342 IsAssumedSideEffectFree =
false;
4343 Changed = ChangeStatus::CHANGED;
4345 if (!areAllUsesAssumedDead(
A, getAssociatedValue()))
4346 return indicatePessimisticFixpoint();
4350 void trackStatistics()
const override {
4351 if (IsAssumedSideEffectFree)
4357 const std::string getAsStr(Attributor *
A)
const override {
4358 return isAssumedDead()
4360 : (getAssumed() ?
"assumed-dead-users" :
"assumed-live");
4364 bool IsAssumedSideEffectFree =
true;
4367struct AAIsDeadReturned :
public AAIsDeadValueImpl {
4368 AAIsDeadReturned(
const IRPosition &IRP, Attributor &
A)
4369 : AAIsDeadValueImpl(IRP,
A) {}
4373 bool UsedAssumedInformation =
false;
4374 A.checkForAllInstructions([](Instruction &) {
return true; }, *
this,
4375 {Instruction::Ret}, UsedAssumedInformation);
4377 auto PredForCallSite = [&](AbstractCallSite ACS) {
4378 if (ACS.isCallbackCall() || !ACS.getInstruction())
4380 return areAllUsesAssumedDead(
A, *ACS.getInstruction());
4383 if (!
A.checkForAllCallSites(PredForCallSite, *
this,
true,
4384 UsedAssumedInformation))
4385 return indicatePessimisticFixpoint();
4387 return ChangeStatus::UNCHANGED;
4392 bool AnyChange =
false;
4393 UndefValue &UV = *
UndefValue::get(getAssociatedFunction()->getReturnType());
4400 bool UsedAssumedInformation =
false;
4401 A.checkForAllInstructions(RetInstPred, *
this, {Instruction::Ret},
4402 UsedAssumedInformation);
4403 return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
4409struct AAIsDeadFunction :
public AAIsDead {
4410 AAIsDeadFunction(
const IRPosition &IRP, Attributor &
A) : AAIsDead(IRP,
A) {}
4414 assert(
F &&
"Did expect an anchor function");
4415 if (!isAssumedDeadInternalFunction(
A)) {
4416 ToBeExploredFrom.insert(&
F->getEntryBlock().front());
4417 assumeLive(
A,
F->getEntryBlock());
4421 bool isAssumedDeadInternalFunction(Attributor &
A) {
4422 if (!getAnchorScope()->hasLocalLinkage())
4428 if (!
A.shouldUpdateAA<AAIsDead>(getIRPosition()))
4430 bool UsedAssumedInformation =
false;
4431 return A.checkForAllCallSites([](AbstractCallSite) {
return false; }, *
this,
4432 true, UsedAssumedInformation);
4435 const std::string getAsStr(Attributor *
A)
const override {
4436 return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) +
"/" +
4437 std::to_string(getAnchorScope()->
size()) +
"][#TBEP " +
4438 std::to_string(ToBeExploredFrom.size()) +
"][#KDE " +
4439 std::to_string(KnownDeadEnds.size()) +
"]";
4443 assert(getState().isValidState() &&
4444 "Attempted to manifest an invalid state!");
4449 if (AssumedLiveBlocks.empty()) {
4450 A.deleteAfterManifest(
F);
4451 return ChangeStatus::CHANGED;
4457 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(
F);
4459 KnownDeadEnds.set_union(ToBeExploredFrom);
4460 for (
const Instruction *DeadEndI : KnownDeadEnds) {
4464 bool IsKnownNoReturn;
4472 A.registerInvokeWithDeadSuccessor(
const_cast<InvokeInst &
>(*
II));
4474 A.changeToUnreachableAfterManifest(
4475 const_cast<Instruction *
>(DeadEndI->getNextNode()));
4476 HasChanged = ChangeStatus::CHANGED;
4479 STATS_DECL(AAIsDead, BasicBlock,
"Number of dead basic blocks deleted.");
4480 for (BasicBlock &BB :
F)
4481 if (!AssumedLiveBlocks.count(&BB)) {
4482 A.deleteAfterManifest(BB);
4484 HasChanged = ChangeStatus::CHANGED;
4492 bool isEdgeDead(
const BasicBlock *From,
const BasicBlock *To)
const override {
4495 "Used AAIsDead of the wrong function");
4496 return isValidState() && !AssumedLiveEdges.count(std::make_pair(From, To));
4499 void trackStatistics()
const override {}
4502 bool isAssumedDead()
const override {
return false; }
4504 bool isKnownDead()
const override {
return false; }
4506 bool isAssumedDead(
const BasicBlock *BB)
const override {
4508 "BB must be in the same anchor scope function.");
4512 return !AssumedLiveBlocks.count(BB);
4515 bool isKnownDead(
const BasicBlock *BB)
const override {
4516 return getKnown() && isAssumedDead(BB);
4519 bool isAssumedDead(
const Instruction *
I)
const override {
4520 assert(
I->getParent()->getParent() == getAnchorScope() &&
4521 "Instruction must be in the same anchor scope function.");
4528 if (!AssumedLiveBlocks.count(
I->getParent()))
4534 if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI))
4541 bool isKnownDead(
const Instruction *
I)
const override {
4542 return getKnown() && isAssumedDead(
I);
4547 bool assumeLive(Attributor &
A,
const BasicBlock &BB) {
4548 if (!AssumedLiveBlocks.insert(&BB).second)
4551 if (!
A.isDuringDeduction())
4558 for (
const Instruction &
I : BB)
4561 if (
F->hasLocalLinkage()) {
4563 dbgs() <<
"[AAIsDead] Seeding live internal callee ";
4564 F->printAsOperand(
dbgs(),
false);
4566 BB.getParent()->printAsOperand(
dbgs(),
false);
4569 A.markLiveInternalFunction(*
F);
4576 SmallSetVector<const Instruction *, 8> ToBeExploredFrom;
4579 SmallSetVector<const Instruction *, 8> KnownDeadEnds;
4582 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> AssumedLiveEdges;
4585 DenseSet<const BasicBlock *> AssumedLiveBlocks;
4589identifyAliveSuccessors(Attributor &
A,
const CallBase &CB,
4590 AbstractAttribute &AA,
4591 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4594 bool IsKnownNoReturn;
4597 return !IsKnownNoReturn;
4606identifyAliveSuccessors(Attributor &
A,
const InvokeInst &
II,
4607 AbstractAttribute &AA,
4608 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4609 bool UsedAssumedInformation =
4615 if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*
II.getFunction())) {
4616 AliveSuccessors.
push_back(&
II.getUnwindDest()->front());
4620 bool IsKnownNoUnwind;
4623 UsedAssumedInformation |= !IsKnownNoUnwind;
4625 AliveSuccessors.
push_back(&
II.getUnwindDest()->front());
4628 return UsedAssumedInformation;
4632identifyAliveSuccessors(Attributor &,
const UncondBrInst &BI,
4633 AbstractAttribute &,
4634 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4640identifyAliveSuccessors(Attributor &
A,
const CondBrInst &BI,
4641 AbstractAttribute &AA,
4642 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4643 bool UsedAssumedInformation =
false;
4644 std::optional<Constant *>
C =
4645 A.getAssumedConstant(*BI.
getCondition(), AA, UsedAssumedInformation);
4655 UsedAssumedInformation =
false;
4657 return UsedAssumedInformation;
4661identifyAliveSuccessors(Attributor &
A,
const SwitchInst &SI,
4662 AbstractAttribute &AA,
4663 SmallVectorImpl<const Instruction *> &AliveSuccessors) {
4664 bool UsedAssumedInformation =
false;
4668 UsedAssumedInformation)) {
4670 for (
const BasicBlock *SuccBB :
successors(
SI.getParent()))
4679 return UsedAssumedInformation;
4682 Type &Ty = *
SI.getCondition()->getType();
4683 SmallPtrSet<ConstantInt *, 8>
Constants;
4684 auto CheckForConstantInt = [&](
Value *
V) {
4693 return CheckForConstantInt(VAC.
getValue());
4695 for (
const BasicBlock *SuccBB :
successors(
SI.getParent()))
4697 return UsedAssumedInformation;
4700 unsigned MatchedCases = 0;
4701 for (
const auto &CaseIt :
SI.cases()) {
4702 if (
Constants.count(CaseIt.getCaseValue())) {
4704 AliveSuccessors.
push_back(&CaseIt.getCaseSuccessor()->front());
4711 AliveSuccessors.
push_back(&
SI.getDefaultDest()->front());
4712 return UsedAssumedInformation;
4718 if (AssumedLiveBlocks.empty()) {
4719 if (isAssumedDeadInternalFunction(
A))
4723 ToBeExploredFrom.insert(&
F->getEntryBlock().front());
4724 assumeLive(
A,
F->getEntryBlock());
4728 LLVM_DEBUG(
dbgs() <<
"[AAIsDead] Live [" << AssumedLiveBlocks.size() <<
"/"
4729 << getAnchorScope()->
size() <<
"] BBs and "
4730 << ToBeExploredFrom.size() <<
" exploration points and "
4731 << KnownDeadEnds.size() <<
" known dead ends\n");
4736 ToBeExploredFrom.end());
4737 decltype(ToBeExploredFrom) NewToBeExploredFrom;
4740 while (!Worklist.
empty()) {
4747 I =
I->getNextNode();
4749 AliveSuccessors.
clear();
4751 bool UsedAssumedInformation =
false;
4752 switch (
I->getOpcode()) {
4756 "Expected non-terminators to be handled already!");
4757 for (
const BasicBlock *SuccBB :
successors(
I->getParent()))
4760 case Instruction::Call:
4762 *
this, AliveSuccessors);
4764 case Instruction::Invoke:
4766 *
this, AliveSuccessors);
4768 case Instruction::UncondBr:
4769 UsedAssumedInformation = identifyAliveSuccessors(
4772 case Instruction::CondBr:
4774 *
this, AliveSuccessors);
4776 case Instruction::Switch:
4778 *
this, AliveSuccessors);
4782 if (UsedAssumedInformation) {
4783 NewToBeExploredFrom.insert(
I);
4784 }
else if (AliveSuccessors.
empty() ||
4785 (
I->isTerminator() &&
4786 AliveSuccessors.
size() <
I->getNumSuccessors())) {
4787 if (KnownDeadEnds.insert(
I))
4792 << AliveSuccessors.
size() <<
" UsedAssumedInformation: "
4793 << UsedAssumedInformation <<
"\n");
4795 for (
const Instruction *AliveSuccessor : AliveSuccessors) {
4796 if (!
I->isTerminator()) {
4797 assert(AliveSuccessors.size() == 1 &&
4798 "Non-terminator expected to have a single successor!");
4802 auto Edge = std::make_pair(
I->getParent(), AliveSuccessor->getParent());
4803 if (AssumedLiveEdges.insert(
Edge).second)
4805 if (assumeLive(
A, *AliveSuccessor->getParent()))
4812 if (NewToBeExploredFrom.size() != ToBeExploredFrom.size() ||
4813 llvm::any_of(NewToBeExploredFrom, [&](
const Instruction *
I) {
4814 return !ToBeExploredFrom.count(I);
4817 ToBeExploredFrom = std::move(NewToBeExploredFrom);
4826 if (ToBeExploredFrom.empty() &&
4827 getAnchorScope()->
size() == AssumedLiveBlocks.size() &&
4828 llvm::all_of(KnownDeadEnds, [](
const Instruction *DeadEndI) {
4829 return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0;
4831 return indicatePessimisticFixpoint();
4836struct AAIsDeadCallSite final : AAIsDeadFunction {
4837 AAIsDeadCallSite(
const IRPosition &IRP, Attributor &
A)
4838 : AAIsDeadFunction(IRP,
A) {}
4846 "supported for call sites yet!");
4850 return indicatePessimisticFixpoint();
4853 void trackStatistics()
const override {}
4860struct AADereferenceableImpl : AADereferenceable {
4861 AADereferenceableImpl(
const IRPosition &IRP, Attributor &
A)
4862 : AADereferenceable(IRP,
A) {}
4863 using StateType = DerefState;
4866 Value &
V = *getAssociatedValue().stripPointerCasts();
4868 A.getAttrs(getIRPosition(),
4869 {Attribute::Dereferenceable, Attribute::DereferenceableOrNull},
4872 takeKnownDerefBytesMaximum(Attr.getValueAsInt());
4875 bool IsKnownNonNull;
4877 A,
this, getIRPosition(), DepClassTy::OPTIONAL, IsKnownNonNull);
4880 takeKnownDerefBytesMaximum(
V.getPointerDereferenceableBytes(
4881 A.getDataLayout(), CanBeNull,
nullptr));
4883 if (Instruction *CtxI = getCtxI())
4884 followUsesInMBEC(*
this,
A, getState(), *CtxI);
4887 StateType &getState()
override {
return *
this; }
4888 const StateType &getState()
const override {
return *
this; }
4891 void addAccessedBytesForUse(Attributor &
A,
const Use *U,
const Instruction *
I,
4892 DerefState &State) {
4893 const Value *UseV =
U->get();
4898 if (!Loc || Loc->Ptr != UseV || !Loc->Size.isPrecise() ||
I->isVolatile())
4903 Loc->Ptr,
Offset,
A.getDataLayout(),
true);
4904 if (
Base &&
Base == &getAssociatedValue())
4905 State.addAccessedBytes(
Offset, Loc->Size.getValue());
4909 bool followUseInMBEC(Attributor &
A,
const Use *U,
const Instruction *
I,
4910 AADereferenceable::StateType &State) {
4911 bool IsNonNull =
false;
4912 bool TrackUse =
false;
4913 int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse(
4914 A, *
this, getAssociatedValue(), U,
I, IsNonNull, TrackUse);
4915 LLVM_DEBUG(
dbgs() <<
"[AADereferenceable] Deref bytes: " << DerefBytes
4916 <<
" for instruction " << *
I <<
"\n");
4918 addAccessedBytesForUse(
A, U,
I, State);
4919 State.takeKnownDerefBytesMaximum(DerefBytes);
4925 bool IsKnownNonNull;
4927 A,
this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4928 if (IsAssumedNonNull &&
4929 A.hasAttr(getIRPosition(), Attribute::DereferenceableOrNull)) {
4930 A.removeAttrs(getIRPosition(), {Attribute::DereferenceableOrNull});
4931 return ChangeStatus::CHANGED;
4936 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
4937 SmallVectorImpl<Attribute> &Attrs)
const override {
4939 bool IsKnownNonNull;
4941 A,
this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4942 if (IsAssumedNonNull)
4943 Attrs.emplace_back(Attribute::getWithDereferenceableBytes(
4944 Ctx, getAssumedDereferenceableBytes()));
4946 Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes(
4947 Ctx, getAssumedDereferenceableBytes()));
4950 const std::string getAsStr(Attributor *
A)
const override {
4951 if (!getAssumedDereferenceableBytes())
4952 return "unknown-dereferenceable";
4953 bool IsKnownNonNull;
4954 bool IsAssumedNonNull =
false;
4957 *
A,
this, getIRPosition(), DepClassTy::NONE, IsKnownNonNull);
4958 return std::string(
"dereferenceable") +
4959 (IsAssumedNonNull ?
"" :
"_or_null") +
4960 (isAssumedGlobal() ?
"_globally" :
"") +
"<" +
4961 std::to_string(getKnownDereferenceableBytes()) +
"-" +
4962 std::to_string(getAssumedDereferenceableBytes()) +
">" +
4963 (!
A ?
" [non-null is unknown]" :
"");
4968struct AADereferenceableFloating : AADereferenceableImpl {
4969 AADereferenceableFloating(
const IRPosition &IRP, Attributor &
A)
4970 : AADereferenceableImpl(IRP,
A) {}
4974 bool UsedAssumedInformation =
false;
4976 if (!
A.getAssumedSimplifiedValues(getIRPosition(), *
this,
Values,
4978 Values.push_back({getAssociatedValue(), getCtxI()});
4981 Stripped =
Values.size() != 1 ||
4982 Values.front().getValue() != &getAssociatedValue();
4985 const DataLayout &
DL =
A.getDataLayout();
4988 auto VisitValueCB = [&](
const Value &
V) ->
bool {
4990 DL.getIndexSizeInBits(
V.getType()->getPointerAddressSpace());
4991 APInt
Offset(IdxWidth, 0);
4996 const auto *AA =
A.getAAFor<AADereferenceable>(
4998 int64_t DerefBytes = 0;
4999 if (!AA || (!Stripped &&
this == AA)) {
5003 DerefBytes =
Base->getPointerDereferenceableBytes(
5004 DL, CanBeNull,
nullptr);
5005 T.GlobalState.indicatePessimisticFixpoint();
5008 DerefBytes =
DS.DerefBytesState.getAssumed();
5009 T.GlobalState &=
DS.GlobalState;
5015 int64_t OffsetSExt =
Offset.getSExtValue();
5019 T.takeAssumedDerefBytesMinimum(
5020 std::max(int64_t(0), DerefBytes - OffsetSExt));
5025 T.takeKnownDerefBytesMaximum(
5026 std::max(int64_t(0), DerefBytes - OffsetSExt));
5027 T.indicatePessimisticFixpoint();
5028 }
else if (OffsetSExt > 0) {
5034 T.indicatePessimisticFixpoint();
5038 return T.isValidState();
5041 for (
const auto &VAC :
Values)
5042 if (!VisitValueCB(*VAC.
getValue()))
5043 return indicatePessimisticFixpoint();
5048 void trackStatistics()
const override {
5054struct AADereferenceableReturned final
5055 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> {
5057 AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>;
5058 AADereferenceableReturned(
const IRPosition &IRP, Attributor &
A)
5061 void trackStatistics()
const override {
5067struct AADereferenceableArgument final
5068 : AAArgumentFromCallSiteArguments<AADereferenceable,
5069 AADereferenceableImpl> {
5071 AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl>;
5072 AADereferenceableArgument(
const IRPosition &IRP, Attributor &
A)
5075 void trackStatistics()
const override {
5081struct AADereferenceableCallSiteArgument final : AADereferenceableFloating {
5082 AADereferenceableCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
5083 : AADereferenceableFloating(IRP,
A) {}
5085 void trackStatistics()
const override {
5091struct AADereferenceableCallSiteReturned final
5092 : AACalleeToCallSite<AADereferenceable, AADereferenceableImpl> {
5093 using Base = AACalleeToCallSite<AADereferenceable, AADereferenceableImpl>;
5094 AADereferenceableCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
5097 void trackStatistics()
const override {
5107static unsigned getKnownAlignForUse(Attributor &
A, AAAlign &QueryingAA,
5108 Value &AssociatedValue,
const Use *U,
5109 const Instruction *
I,
bool &TrackUse) {
5118 if (
GEP->hasAllConstantIndices())
5123 switch (
II->getIntrinsicID()) {
5124 case Intrinsic::ptrmask: {
5126 const auto *ConstVals =
A.getAAFor<AAPotentialConstantValues>(
5128 const auto *AlignAA =
A.getAAFor<AAAlign>(
5130 if (ConstVals && ConstVals->isValidState() && ConstVals->isAtFixpoint()) {
5131 unsigned ShiftValue = std::min(ConstVals->getAssumedMinTrailingZeros(),
5134 if (ConstAlign >= AlignAA->getKnownAlign())
5135 return Align(1).value();
5138 return AlignAA->getKnownAlign().
value();
5141 case Intrinsic::amdgcn_make_buffer_rsrc: {
5142 const auto *AlignAA =
A.getAAFor<AAAlign>(
5145 return AlignAA->getKnownAlign().
value();
5163 MA = MaybeAlign(AlignAA->getKnownAlign());
5166 const DataLayout &
DL =
A.getDataLayout();
5167 const Value *UseV =
U->get();
5169 if (
SI->getPointerOperand() == UseV)
5170 MA =
SI->getAlign();
5172 if (LI->getPointerOperand() == UseV)
5173 MA = LI->getAlign();
5175 if (AI->getPointerOperand() == UseV)
5176 MA = AI->getAlign();
5178 if (AI->getPointerOperand() == UseV)
5179 MA = AI->getAlign();
5189 if (
Base == &AssociatedValue) {
5194 uint32_t
gcd = std::gcd(uint32_t(
abs((int32_t)
Offset)), Alignment);
5202struct AAAlignImpl : AAAlign {
5203 AAAlignImpl(
const IRPosition &IRP, Attributor &
A) : AAAlign(IRP,
A) {}
5207 A.getAttrs(getIRPosition(), {Attribute::Alignment},
Attrs);
5209 takeKnownMaximum(Attr.getValueAsInt());
5211 Value &
V = *getAssociatedValue().stripPointerCasts();
5212 takeKnownMaximum(
V.getPointerAlignment(
A.getDataLayout()).value());
5214 if (Instruction *CtxI = getCtxI())
5215 followUsesInMBEC(*
this,
A, getState(), *CtxI);
5222 Value &AssociatedValue = getAssociatedValue();
5224 return ChangeStatus::UNCHANGED;
5226 for (
const Use &U : AssociatedValue.
uses()) {
5228 if (
SI->getPointerOperand() == &AssociatedValue)
5229 if (
SI->getAlign() < getAssumedAlign()) {
5231 "Number of times alignment added to a store");
5232 SI->setAlignment(getAssumedAlign());
5233 InstrChanged = ChangeStatus::CHANGED;
5236 if (LI->getPointerOperand() == &AssociatedValue)
5237 if (LI->getAlign() < getAssumedAlign()) {
5238 LI->setAlignment(getAssumedAlign());
5240 "Number of times alignment added to a load");
5241 InstrChanged = ChangeStatus::CHANGED;
5244 if (RMW->getPointerOperand() == &AssociatedValue) {
5245 if (RMW->getAlign() < getAssumedAlign()) {
5247 "Number of times alignment added to atomicrmw");
5249 RMW->setAlignment(getAssumedAlign());
5250 InstrChanged = ChangeStatus::CHANGED;
5254 if (CAS->getPointerOperand() == &AssociatedValue) {
5255 if (CAS->getAlign() < getAssumedAlign()) {
5257 "Number of times alignment added to cmpxchg");
5258 CAS->setAlignment(getAssumedAlign());
5259 InstrChanged = ChangeStatus::CHANGED;
5267 Align InheritAlign =
5268 getAssociatedValue().getPointerAlignment(
A.getDataLayout());
5269 if (InheritAlign >= getAssumedAlign())
5270 return InstrChanged;
5271 return Changed | InstrChanged;
5278 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
5279 SmallVectorImpl<Attribute> &Attrs)
const override {
5280 if (getAssumedAlign() > 1)
5282 Attribute::getWithAlignment(Ctx,
Align(getAssumedAlign())));
5286 bool followUseInMBEC(Attributor &
A,
const Use *U,
const Instruction *
I,
5287 AAAlign::StateType &State) {
5288 bool TrackUse =
false;
5290 unsigned int KnownAlign =
5291 getKnownAlignForUse(
A, *
this, getAssociatedValue(), U,
I, TrackUse);
5292 State.takeKnownMaximum(KnownAlign);
5297 const std::string getAsStr(Attributor *
A)
const override {
5298 return "align<" + std::to_string(getKnownAlign().value()) +
"-" +
5299 std::to_string(getAssumedAlign().value()) +
">";
5304struct AAAlignFloating : AAAlignImpl {
5305 AAAlignFloating(
const IRPosition &IRP, Attributor &
A) : AAAlignImpl(IRP,
A) {}
5308 const DataLayout &
DL =
A.getDataLayout();
5311 bool UsedAssumedInformation =
false;
5313 if (!
A.getAssumedSimplifiedValues(getIRPosition(), *
this,
Values,
5315 Values.push_back({getAssociatedValue(), getCtxI()});
5318 Stripped =
Values.size() != 1 ||
5319 Values.front().getValue() != &getAssociatedValue();
5323 auto VisitValueCB = [&](
Value &
V) ->
bool {
5327 DepClassTy::REQUIRED);
5328 if (!AA || (!Stripped &&
this == AA)) {
5346 T.takeKnownMaximum(Alignment);
5347 T.indicatePessimisticFixpoint();
5350 const AAAlign::StateType &
DS = AA->
getState();
5353 return T.isValidState();
5356 for (
const auto &VAC :
Values) {
5357 if (!VisitValueCB(*VAC.
getValue()))
5358 return indicatePessimisticFixpoint();
5370struct AAAlignReturned final
5371 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> {
5372 using Base = AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>;
5373 AAAlignReturned(
const IRPosition &IRP, Attributor &
A) :
Base(IRP,
A) {}
5379struct AAAlignArgument final
5380 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> {
5381 using Base = AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>;
5382 AAAlignArgument(
const IRPosition &IRP, Attributor &
A) :
Base(IRP,
A) {}
5388 if (
A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument()))
5389 return ChangeStatus::UNCHANGED;
5390 return Base::manifest(
A);
5396struct AAAlignCallSiteArgument final : AAAlignFloating {
5397 AAAlignCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
5398 : AAAlignFloating(IRP,
A) {}
5404 if (Argument *Arg = getAssociatedArgument())
5405 if (
A.getInfoCache().isInvolvedInMustTailCall(*Arg))
5406 return ChangeStatus::UNCHANGED;
5408 Align InheritAlign =
5409 getAssociatedValue().getPointerAlignment(
A.getDataLayout());
5410 if (InheritAlign >= getAssumedAlign())
5411 Changed = ChangeStatus::UNCHANGED;
5417 if (Argument *Arg = getAssociatedArgument()) {
5420 const auto *ArgAlignAA =
A.getAAFor<AAAlign>(
5423 takeKnownMaximum(ArgAlignAA->getKnownAlign().value());
5432struct AAAlignCallSiteReturned final
5433 : AACalleeToCallSite<AAAlign, AAAlignImpl> {
5434 using Base = AACalleeToCallSite<AAAlign, AAAlignImpl>;
5435 AAAlignCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
5441 switch (
II->getIntrinsicID()) {
5442 case Intrinsic::ptrmask: {
5446 const auto *ConstVals =
A.getAAFor<AAPotentialConstantValues>(
5448 if (ConstVals && ConstVals->isValidState()) {
5449 unsigned ShiftValue =
5450 std::min(ConstVals->getAssumedMinTrailingZeros(),
5451 Value::MaxAlignmentExponent);
5456 const auto *AlignAA =
5458 DepClassTy::REQUIRED);
5460 Alignment = std::max(AlignAA->getAssumedAlign(), Alignment);
5467 std::min(this->getAssumedAlign(), Alignment).value());
5473 case Intrinsic::amdgcn_make_buffer_rsrc: {
5474 const auto *AlignAA =
5476 DepClassTy::REQUIRED);
5479 this->getState(), AlignAA->getAssumedAlign().
value());
5486 return Base::updateImpl(
A);
5494struct AANoReturnImpl :
public AANoReturn {
5495 AANoReturnImpl(
const IRPosition &IRP, Attributor &
A) : AANoReturn(IRP,
A) {}
5500 A,
nullptr, getIRPosition(), DepClassTy::NONE, IsKnown));
5504 const std::string getAsStr(Attributor *
A)
const override {
5505 return getAssumed() ?
"noreturn" :
"may-return";
5509 auto CheckForNoReturn = [](
Instruction &) {
return false; };
5510 bool UsedAssumedInformation =
false;
5511 if (!
A.checkForAllInstructions(CheckForNoReturn, *
this,
5512 {(unsigned)Instruction::Ret},
5513 UsedAssumedInformation))
5514 return indicatePessimisticFixpoint();
5515 return ChangeStatus::UNCHANGED;
5519struct AANoReturnFunction final : AANoReturnImpl {
5520 AANoReturnFunction(
const IRPosition &IRP, Attributor &
A)
5521 : AANoReturnImpl(IRP,
A) {}
5527struct AANoReturnCallSite final
5528 : AACalleeToCallSite<AANoReturn, AANoReturnImpl> {
5529 AANoReturnCallSite(
const IRPosition &IRP, Attributor &
A)
5530 : AACalleeToCallSite<AANoReturn, AANoReturnImpl>(IRP,
A) {}
5540struct AAInstanceInfoImpl :
public AAInstanceInfo {
5541 AAInstanceInfoImpl(
const IRPosition &IRP, Attributor &
A)
5542 : AAInstanceInfo(IRP,
A) {}
5545 Value &
V = getAssociatedValue();
5547 if (
C->isThreadDependent())
5548 indicatePessimisticFixpoint();
5550 indicateOptimisticFixpoint();
5556 indicateOptimisticFixpoint();
5561 A.getInfoCache().getAnalysisResultForFunction<CycleAnalysis>(
5564 indicatePessimisticFixpoint();
5573 Value &
V = getAssociatedValue();
5576 Scope =
I->getFunction();
5579 if (!
Scope->hasLocalLinkage())
5583 return indicateOptimisticFixpoint();
5585 bool IsKnownNoRecurse;
5591 auto UsePred = [&](
const Use &
U,
bool &Follow) {
5606 if (!Callee || !
Callee->hasLocalLinkage())
5610 const auto *ArgInstanceInfoAA =
A.getAAFor<AAInstanceInfo>(
5612 DepClassTy::OPTIONAL);
5613 if (!ArgInstanceInfoAA ||
5614 !ArgInstanceInfoAA->isAssumedUniqueForAnalysis())
5619 A, *CB, *Scope, *
this,
nullptr,
5627 auto EquivalentUseCB = [&](
const Use &OldU,
const Use &NewU) {
5629 auto *Ptr =
SI->getPointerOperand()->stripPointerCasts();
5637 if (!
A.checkForAllUses(UsePred, *
this,
V,
true,
5638 DepClassTy::OPTIONAL,
5639 true, EquivalentUseCB))
5640 return indicatePessimisticFixpoint();
5645 const std::string getAsStr(Attributor *
A)
const override {
5646 return isAssumedUniqueForAnalysis() ?
"<unique [fAa]>" :
"<unknown>";
5649 void trackStatistics()
const override {}
5653struct AAInstanceInfoFloating : AAInstanceInfoImpl {
5654 AAInstanceInfoFloating(
const IRPosition &IRP, Attributor &
A)
5655 : AAInstanceInfoImpl(IRP,
A) {}
5659struct AAInstanceInfoArgument final : AAInstanceInfoFloating {
5660 AAInstanceInfoArgument(
const IRPosition &IRP, Attributor &
A)
5661 : AAInstanceInfoFloating(IRP,
A) {}
5665struct AAInstanceInfoCallSiteArgument final : AAInstanceInfoImpl {
5666 AAInstanceInfoCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
5667 : AAInstanceInfoImpl(IRP,
A) {}
5674 Argument *Arg = getAssociatedArgument();
5676 return indicatePessimisticFixpoint();
5679 A.getAAFor<AAInstanceInfo>(*
this, ArgPos, DepClassTy::REQUIRED);
5681 return indicatePessimisticFixpoint();
5687struct AAInstanceInfoReturned final : AAInstanceInfoImpl {
5688 AAInstanceInfoReturned(
const IRPosition &IRP, Attributor &
A)
5689 : AAInstanceInfoImpl(IRP,
A) {
5703struct AAInstanceInfoCallSiteReturned final : AAInstanceInfoFloating {
5704 AAInstanceInfoCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
5705 : AAInstanceInfoFloating(IRP,
A) {}
5712 bool IgnoreSubsumingPositions) {
5713 assert(ImpliedAttributeKind == Attribute::Captures &&
5714 "Unexpected attribute kind");
5728 A.getAttrs(IRP, {Attribute::Captures}, Attrs,
5738 {Attribute::Captures, Attribute::ByVal}, Attrs,
5777 bool NoThrow =
F.doesNotThrow();
5778 bool WillReturn =
F.willReturn();
5779 bool IsVoidReturn =
F.getReturnType()->isVoidTy();
5780 if (
ReadOnly && NoThrow && WillReturn && IsVoidReturn) {
5793 if (NoThrow && IsVoidReturn)
5798 if (!NoThrow || ArgNo < 0 ||
5799 !
F.getAttributes().hasAttrSomewhere(Attribute::Returned))
5802 for (
unsigned U = 0, E =
F.arg_size(); U < E; ++U)
5803 if (
F.hasParamAttribute(U, Attribute::Returned)) {
5804 if (U ==
unsigned(ArgNo))
5828 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
5829 SmallVectorImpl<Attribute> &Attrs)
const override {
5830 if (!isAssumedNoCaptureMaybeReturned())
5833 if (isArgumentPosition()) {
5834 if (isAssumedNoCapture())
5835 Attrs.emplace_back(Attribute::get(Ctx, Attribute::Captures));
5836 else if (
A.Opts.attributor_manifest_internal)
5837 Attrs.emplace_back(Attribute::get(Ctx,
"no-capture-maybe-returned"));
5841 const std::string getAsStr(Attributor *
A)
const override {
5842 if (isKnownNoCapture())
5843 return "known not-captured";
5844 if (isAssumedNoCapture())
5845 return "assumed not-captured";
5846 if (isKnownNoCaptureMaybeReturned())
5847 return "known not-captured-maybe-returned";
5848 if (isAssumedNoCaptureMaybeReturned())
5849 return "assumed not-captured-maybe-returned";
5850 return "assumed-captured";
5855 bool checkUse(Attributor &
A, AANoCapture::StateType &State,
const Use &U,
5858 LLVM_DEBUG(
dbgs() <<
"[AANoCapture] Check use: " << *
U.get() <<
" in "
5864 return isCapturedIn(State,
true,
true,
5871 return isCapturedIn(State,
true,
true,
5877 return isCapturedIn(State,
false,
false,
5879 return isCapturedIn(State,
true,
true,
5887 return isCapturedIn(State,
true,
true,
5894 bool IsKnownNoCapture;
5895 const AANoCapture *ArgNoCaptureAA =
nullptr;
5897 A,
this, CSArgPos, DepClassTy::REQUIRED, IsKnownNoCapture,
false,
5899 if (IsAssumedNoCapture)
5900 return isCapturedIn(State,
false,
false,
5904 return isCapturedIn(State,
false,
false,
5909 return isCapturedIn(State,
true,
true,
5916 static bool isCapturedIn(AANoCapture::StateType &State,
bool CapturedInMem,
5917 bool CapturedInInt,
bool CapturedInRet) {
5918 LLVM_DEBUG(
dbgs() <<
" - captures [Mem " << CapturedInMem <<
"|Int "
5919 << CapturedInInt <<
"|Ret " << CapturedInRet <<
"]\n");
5931 const IRPosition &IRP = getIRPosition();
5935 return indicatePessimisticFixpoint();
5942 return indicatePessimisticFixpoint();
5950 T.addKnownBits(NOT_CAPTURED_IN_MEM);
5952 addKnownBits(NOT_CAPTURED_IN_MEM);
5959 auto CheckReturnedArgs = [&](
bool &UsedAssumedInformation) {
5963 UsedAssumedInformation))
5965 bool SeenConstant =
false;
5966 for (
const AA::ValueAndContext &VAC :
Values) {
5970 SeenConstant =
true;
5972 VAC.
getValue() == getAssociatedArgument())
5978 bool IsKnownNoUnwind;
5981 bool IsVoidTy =
F->getReturnType()->isVoidTy();
5982 bool UsedAssumedInformation =
false;
5983 if (IsVoidTy || CheckReturnedArgs(UsedAssumedInformation)) {
5984 T.addKnownBits(NOT_CAPTURED_IN_RET);
5987 bool IsKnownWillReturn;
5990 if (IsAssumedWillReturn &&
T.isKnown(NOT_CAPTURED_IN_MEM))
5992 if (IsKnownNoUnwind && (IsVoidTy || !UsedAssumedInformation)) {
5993 addKnownBits(NOT_CAPTURED_IN_RET);
5994 if (IsKnownWillReturn && isKnown(NOT_CAPTURED_IN_MEM))
5995 return indicateOptimisticFixpoint();
6000 auto UseCheck = [&](
const Use &
U,
bool &Follow) ->
bool {
6009 return checkUse(
A,
T, U, Follow);
6012 if (!
A.checkForAllUses(UseCheck, *
this, *
V))
6013 return indicatePessimisticFixpoint();
6016 auto Assumed = S.getAssumed();
6017 S.intersectAssumedBits(
T.getAssumed());
6018 if (!isAssumedNoCaptureMaybeReturned())
6019 return indicatePessimisticFixpoint();
6025struct AANoCaptureArgument final : AANoCaptureImpl {
6026 AANoCaptureArgument(
const IRPosition &IRP, Attributor &
A)
6027 : AANoCaptureImpl(IRP,
A) {}
6033struct AANoCaptureCallSiteArgument final : AANoCaptureImpl {
6034 AANoCaptureCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
6035 : AANoCaptureImpl(IRP,
A) {}
6042 Argument *Arg = getAssociatedArgument();
6044 return indicatePessimisticFixpoint();
6046 bool IsKnownNoCapture;
6047 const AANoCapture *ArgAA =
nullptr;
6049 A,
this, ArgPos, DepClassTy::REQUIRED, IsKnownNoCapture,
false,
6051 return ChangeStatus::UNCHANGED;
6053 return indicatePessimisticFixpoint();
6057 void trackStatistics()
const override {
6063struct AANoCaptureFloating final : AANoCaptureImpl {
6064 AANoCaptureFloating(
const IRPosition &IRP, Attributor &
A)
6065 : AANoCaptureImpl(IRP,
A) {}
6067 void trackStatistics()
const override {
6073struct AANoCaptureReturned final : AANoCaptureImpl {
6074 AANoCaptureReturned(
const IRPosition &IRP, Attributor &
A)
6075 : AANoCaptureImpl(IRP,
A) {
6087 void trackStatistics()
const override {}
6091struct AANoCaptureCallSiteReturned final : AANoCaptureImpl {
6092 AANoCaptureCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
6093 : AANoCaptureImpl(IRP,
A) {}
6098 determineFunctionCaptureCapabilities(getIRPosition(), *
F, *
this);
6101 void trackStatistics()
const override {
6118 dbgs() <<
"[ValueSimplify] is assumed to be "
6121 dbgs() <<
"[ValueSimplify] is assumed to be <none>\n";
6132 if (getAssociatedValue().
getType()->isVoidTy())
6133 indicatePessimisticFixpoint();
6134 if (
A.hasSimplificationCallback(getIRPosition()))
6135 indicatePessimisticFixpoint();
6138 const std::string getAsStr(Attributor *
A)
const override {
6140 dbgs() <<
"SAV: " << (bool)SimplifiedAssociatedValue <<
" ";
6141 if (SimplifiedAssociatedValue && *SimplifiedAssociatedValue)
6142 dbgs() <<
"SAV: " << **SimplifiedAssociatedValue <<
" ";
6144 return isValidState() ? (isAtFixpoint() ?
"simplified" :
"maybe-simple")
6148 void trackStatistics()
const override {}
6150 std::optional<Value *>
6151 getAssumedSimplifiedValue(Attributor &
A)
const override {
6152 return SimplifiedAssociatedValue;
6159 static Value *ensureType(Attributor &
A,
Value &
V,
Type &Ty, Instruction *CtxI,
6163 if (CtxI &&
V.getType()->canLosslesslyBitCastTo(&Ty))
6165 : BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6174 static Value *reproduceInst(Attributor &
A,
6175 const AbstractAttribute &QueryingAA,
6176 Instruction &
I,
Type &Ty, Instruction *CtxI,
6178 assert(CtxI &&
"Cannot reproduce an instruction without context!");
6179 if (
Check && (
I.mayReadFromMemory() ||
6184 Value *NewOp = reproduceValue(
A, QueryingAA, *
Op, Ty, CtxI,
Check, VMap);
6186 assert(
Check &&
"Manifest of new value unexpectedly failed!");
6208 static Value *reproduceValue(Attributor &
A,
6209 const AbstractAttribute &QueryingAA,
Value &
V,
6210 Type &Ty, Instruction *CtxI,
bool Check,
6212 if (
const auto &NewV = VMap.
lookup(&
V))
6214 bool UsedAssumedInformation =
false;
6215 std::optional<Value *> SimpleV =
A.getAssumedSimplified(
6217 if (!SimpleV.has_value())
6221 EffectiveV = *SimpleV;
6226 return ensureType(
A, *EffectiveV, Ty, CtxI,
Check);
6228 if (
Value *NewV = reproduceInst(
A, QueryingAA, *
I, Ty, CtxI,
Check, VMap))
6229 return ensureType(
A, *NewV, Ty, CtxI,
Check);
6235 Value *manifestReplacementValue(Attributor &
A, Instruction *CtxI)
const {
6236 Value *NewV = SimplifiedAssociatedValue
6237 ? *SimplifiedAssociatedValue
6239 if (NewV && NewV != &getAssociatedValue()) {
6243 if (reproduceValue(
A, *
this, *NewV, *getAssociatedType(), CtxI,
6245 return reproduceValue(
A, *
this, *NewV, *getAssociatedType(), CtxI,
6253 bool checkAndUpdate(Attributor &
A,
const AbstractAttribute &QueryingAA,
6254 const IRPosition &IRP,
bool Simplify =
true) {
6255 bool UsedAssumedInformation =
false;
6258 QueryingValueSimplified =
A.getAssumedSimplified(
6260 return unionAssumed(QueryingValueSimplified);
6264 template <
typename AAType>
bool askSimplifiedValueFor(Attributor &
A) {
6265 if (!getAssociatedValue().
getType()->isIntegerTy())
6270 A.getAAFor<AAType>(*
this, getIRPosition(), DepClassTy::NONE);
6274 std::optional<Constant *> COpt = AA->getAssumedConstant(
A);
6277 SimplifiedAssociatedValue = std::nullopt;
6278 A.recordDependence(*AA, *
this, DepClassTy::OPTIONAL);
6281 if (
auto *
C = *COpt) {
6282 SimplifiedAssociatedValue =
C;
6283 A.recordDependence(*AA, *
this, DepClassTy::OPTIONAL);
6289 bool askSimplifiedValueForOtherAAs(Attributor &
A) {
6290 if (askSimplifiedValueFor<AAValueConstantRange>(
A))
6292 if (askSimplifiedValueFor<AAPotentialConstantValues>(
A))
6299 for (
auto &U : getAssociatedValue().uses()) {
6304 IP =
PHI->getIncomingBlock(U)->getTerminator();
6305 if (
auto *NewV = manifestReplacementValue(
A, IP)) {
6307 <<
" -> " << *NewV <<
" :: " << *
this <<
"\n");
6308 if (
A.changeUseAfterManifest(U, *NewV))
6309 Changed = ChangeStatus::CHANGED;
6313 return Changed | AAValueSimplify::manifest(
A);
6317 SimplifiedAssociatedValue = &getAssociatedValue();
6318 return AAValueSimplify::indicatePessimisticFixpoint();
6322struct AAValueSimplifyArgument final : AAValueSimplifyImpl {
6323 AAValueSimplifyArgument(
const IRPosition &IRP, Attributor &
A)
6324 : AAValueSimplifyImpl(IRP,
A) {}
6327 AAValueSimplifyImpl::initialize(
A);
6328 if (
A.hasAttr(getIRPosition(),
6329 {Attribute::InAlloca, Attribute::Preallocated,
6330 Attribute::StructRet, Attribute::Nest, Attribute::ByVal},
6332 indicatePessimisticFixpoint();
6338 Argument *Arg = getAssociatedArgument();
6344 return indicatePessimisticFixpoint();
6347 auto Before = SimplifiedAssociatedValue;
6349 auto PredForCallSite = [&](AbstractCallSite ACS) {
6350 const IRPosition &ACSArgPos =
6361 bool UsedAssumedInformation =
false;
6362 std::optional<Constant *> SimpleArgOp =
6363 A.getAssumedConstant(ACSArgPos, *
this, UsedAssumedInformation);
6370 return unionAssumed(*SimpleArgOp);
6375 bool UsedAssumedInformation =
false;
6376 if (hasCallBaseContext() &&
6377 getCallBaseContext()->getCalledOperand() == Arg->
getParent())
6379 AbstractCallSite(&getCallBaseContext()->getCalledOperandUse()));
6381 Success =
A.checkForAllCallSites(PredForCallSite, *
this,
true,
6382 UsedAssumedInformation);
6385 if (!askSimplifiedValueForOtherAAs(
A))
6386 return indicatePessimisticFixpoint();
6389 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6390 : ChangeStatus ::CHANGED;
6393 void trackStatistics()
const override {
6398struct AAValueSimplifyReturned : AAValueSimplifyImpl {
6399 AAValueSimplifyReturned(
const IRPosition &IRP, Attributor &
A)
6400 : AAValueSimplifyImpl(IRP,
A) {}
6402 std::optional<Value *>
6403 getAssumedSimplifiedValue(Attributor &
A)
const override {
6404 if (!isValidState())
6406 return SimplifiedAssociatedValue;
6410 auto Before = SimplifiedAssociatedValue;
6414 return checkAndUpdate(
6419 bool UsedAssumedInformation =
false;
6420 if (!
A.checkForAllInstructions(ReturnInstCB, *
this, {Instruction::Ret},
6421 UsedAssumedInformation))
6422 if (!askSimplifiedValueForOtherAAs(
A))
6423 return indicatePessimisticFixpoint();
6426 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6427 : ChangeStatus ::CHANGED;
6433 return ChangeStatus::UNCHANGED;
6436 void trackStatistics()
const override {
6441struct AAValueSimplifyFloating : AAValueSimplifyImpl {
6442 AAValueSimplifyFloating(
const IRPosition &IRP, Attributor &
A)
6443 : AAValueSimplifyImpl(IRP,
A) {}
6446 AAValueSimplifyImpl::initialize(
A);
6447 Value &
V = getAnchorValue();
6451 indicatePessimisticFixpoint();
6455 auto Before = SimplifiedAssociatedValue;
6456 if (!askSimplifiedValueForOtherAAs(
A))
6457 return indicatePessimisticFixpoint();
6460 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED
6461 : ChangeStatus ::CHANGED;
6464 void trackStatistics()
const override {
6469struct AAValueSimplifyFunction : AAValueSimplifyImpl {
6470 AAValueSimplifyFunction(
const IRPosition &IRP, Attributor &
A)
6471 : AAValueSimplifyImpl(IRP,
A) {}
6474 SimplifiedAssociatedValue =
nullptr;
6475 indicateOptimisticFixpoint();
6479 "AAValueSimplify(Function|CallSite)::updateImpl will not be called");
6481 void trackStatistics()
const override {
6486struct AAValueSimplifyCallSite : AAValueSimplifyFunction {
6487 AAValueSimplifyCallSite(
const IRPosition &IRP, Attributor &
A)
6488 : AAValueSimplifyFunction(IRP,
A) {}
6489 void trackStatistics()
const override {
6494struct AAValueSimplifyCallSiteReturned : AAValueSimplifyImpl {
6495 AAValueSimplifyCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
6496 : AAValueSimplifyImpl(IRP,
A) {}
6499 AAValueSimplifyImpl::initialize(
A);
6500 Function *Fn = getAssociatedFunction();
6501 assert(Fn &&
"Did expect an associted function");
6502 for (Argument &Arg : Fn->
args()) {
6507 checkAndUpdate(
A, *
this, IRP))
6508 indicateOptimisticFixpoint();
6510 indicatePessimisticFixpoint();
6517 return indicatePessimisticFixpoint();
6520 void trackStatistics()
const override {
6525struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating {
6526 AAValueSimplifyCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
6527 : AAValueSimplifyFloating(IRP,
A) {}
6532 auto *FloatAA =
A.lookupAAFor<AAValueSimplify>(
6534 if (FloatAA && FloatAA->getState().isValidState())
6537 if (
auto *NewV = manifestReplacementValue(
A, getCtxI())) {
6539 ->getArgOperandUse(getCallSiteArgNo());
6540 if (
A.changeUseAfterManifest(U, *NewV))
6541 Changed = ChangeStatus::CHANGED;
6544 return Changed | AAValueSimplify::manifest(
A);
6547 void trackStatistics()
const override {
6558 bool UsedAssumedInformation =
false;
6559 return A.checkForAllInstructions(
6562 if (CI.isTailCall() && !CI.isMustTailCall())
6566 QueryingAA, {Instruction::Call}, UsedAssumedInformation);
6571struct AAHeapToStackFunction final :
public AAHeapToStack {
6573 static bool isGlobalizedLocal(
const CallBase &CB) {
6575 return A.
isValid() &&
A.getValueAsString() ==
"__kmpc_alloc_shared";
6578 struct AllocationInfo {
6583 bool IsGlobalizedLocal =
false;
6590 } Status = STACK_DUE_TO_USE;
6594 bool HasPotentiallyFreeingUnknownUses =
false;
6598 bool MoveAllocaIntoEntry =
true;
6601 SmallSetVector<CallBase *, 1> PotentialFreeCalls{};
6604 struct DeallocationInfo {
6612 bool MightFreeUnknownObjects =
false;
6615 SmallSetVector<CallBase *, 1> PotentialAllocationCalls{};
6618 AAHeapToStackFunction(
const IRPosition &IRP, Attributor &
A)
6619 : AAHeapToStack(IRP,
A) {}
6621 ~AAHeapToStackFunction()
override {
6624 for (
auto &It : AllocationInfos)
6625 It.second->~AllocationInfo();
6626 for (
auto &It : DeallocationInfos)
6627 It.second->~DeallocationInfo();
6631 AAHeapToStack::initialize(
A);
6634 const auto *
TLI =
A.getInfoCache().getTargetLibraryInfoForFunction(*
F);
6641 DeallocationInfos[CB] =
new (
A.Allocator) DeallocationInfo{CB, FreedOp};
6648 auto *I8Ty = Type::getInt8Ty(CB->
getParent()->getContext());
6650 AllocationInfo *AI =
new (
A.Allocator) AllocationInfo{CB};
6651 AllocationInfos[CB] = AI;
6652 AI->IsGlobalizedLocal = isGlobalizedLocal(*CB);
6658 bool UsedAssumedInformation =
false;
6659 bool Success =
A.checkForAllCallLikeInstructions(
6660 AllocationIdentifierCB, *
this, UsedAssumedInformation,
6664 assert(
Success &&
"Did not expect the call base visit callback to fail!");
6667 [](
const IRPosition &,
const AbstractAttribute *,
6668 bool &) -> std::optional<Value *> {
return nullptr; };
6669 for (
const auto &It : AllocationInfos)
6672 for (
const auto &It : DeallocationInfos)
6677 const std::string getAsStr(Attributor *
A)
const override {
6678 unsigned NumH2SMallocs = 0, NumInvalidMallocs = 0;
6679 for (
const auto &It : AllocationInfos) {
6680 if (It.second->Status == AllocationInfo::INVALID)
6681 ++NumInvalidMallocs;
6685 return "[H2S] Mallocs Good/Bad: " + std::to_string(NumH2SMallocs) +
"/" +
6686 std::to_string(NumInvalidMallocs);
6689 void trackStatistics()
const override {
6692 "Number of malloc/calloc/aligned_alloc calls converted to allocas");
6693 for (
const auto &It : AllocationInfos)
6694 if (It.second->Status != AllocationInfo::INVALID)
6698 bool isAssumedHeapToStack(
const CallBase &CB)
const override {
6700 if (AllocationInfo *AI =
6701 AllocationInfos.lookup(
const_cast<CallBase *
>(&CB)))
6702 return AI->Status != AllocationInfo::INVALID;
6706 bool isAssumedHeapToStackRemovedFree(CallBase &CB)
const override {
6707 if (!isValidState())
6710 for (
const auto &It : AllocationInfos) {
6711 AllocationInfo &AI = *It.second;
6712 if (AI.Status == AllocationInfo::INVALID)
6715 if (AI.PotentialFreeCalls.count(&CB))
6723 assert(getState().isValidState() &&
6724 "Attempted to manifest an invalid state!");
6728 const auto *
TLI =
A.getInfoCache().getTargetLibraryInfoForFunction(*
F);
6732 if (
any_of(AllocationInfos,
6733 [](
const std::pair<CallBase *, AllocationInfo *> &It) {
6734 return It.second->Status != AllocationInfo::INVALID;
6737 return ChangeStatus::UNCHANGED;
6739 for (
auto &It : AllocationInfos) {
6740 AllocationInfo &AI = *It.second;
6741 if (AI.Status == AllocationInfo::INVALID)
6744 for (CallBase *FreeCall : AI.PotentialFreeCalls) {
6745 LLVM_DEBUG(
dbgs() <<
"H2S: Removing free call: " << *FreeCall <<
"\n");
6746 A.deleteAfterManifest(*FreeCall);
6747 HasChanged = ChangeStatus::CHANGED;
6750 LLVM_DEBUG(
dbgs() <<
"H2S: Removing malloc-like call: " << *AI.CB
6753 auto Remark = [&](OptimizationRemark
OR) {
6754 if (AI.IsGlobalizedLocal)
6755 return OR <<
"Moving globalized variable to the stack.";
6756 return OR <<
"Moving memory allocation from the heap to the stack.";
6758 if (AI.IsGlobalizedLocal)
6759 A.emitRemark<OptimizationRemark>(AI.CB,
"OMP110",
Remark);
6761 A.emitRemark<OptimizationRemark>(AI.CB,
"HeapToStack",
Remark);
6763 const DataLayout &
DL =
A.getInfoCache().getDL();
6765 std::optional<APInt> SizeAPI =
getSize(
A, *
this, AI);
6767 Size = ConstantInt::get(AI.CB->getContext(), *SizeAPI);
6769 ObjectSizeOpts Opts;
6770 ObjectSizeOffsetEvaluator Eval(*AI.CB->getModule(),
TLI, Opts);
6771 SizeOffsetValue SizeOffsetPair = Eval.compute(AI.CB);
6778 ?
F->getEntryBlock().begin()
6779 : AI.CB->getIterator();
6782 if (MaybeAlign RetAlign = AI.CB->getRetAlign())
6783 Alignment = std::max(Alignment, *RetAlign);
6785 std::optional<APInt> AlignmentAPI = getAPInt(
A, *
this, *Align);
6786 assert(AlignmentAPI && AlignmentAPI->getZExtValue() > 0 &&
6787 "Expected an alignment during manifest!");
6789 std::max(Alignment,
assumeAligned(AlignmentAPI->getZExtValue()));
6793 unsigned AS =
DL.getAllocaAddrSpace();
6795 new AllocaInst(Type::getInt8Ty(
F->getContext()), AS,
Size, Alignment,
6796 AI.CB->getName() +
".h2s", IP);
6798 if (Alloca->
getType() != AI.CB->getType())
6799 Alloca = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
6800 Alloca, AI.CB->getType(),
"malloc_cast", AI.CB->getIterator());
6802 auto *I8Ty = Type::getInt8Ty(
F->getContext());
6805 "Must be able to materialize initial memory state of allocation");
6810 auto *NBB =
II->getNormalDest();
6812 A.deleteAfterManifest(*AI.CB);
6814 A.deleteAfterManifest(*AI.CB);
6823 Builder.CreateMemSet(Alloca, InitVal,
Size, std::nullopt);
6825 HasChanged = ChangeStatus::CHANGED;
6828 for (CallInst *CI : TailCalls)
6829 CI->setTailCall(
false);
6834 std::optional<APInt> getAPInt(Attributor &
A,
const AbstractAttribute &AA,
6836 bool UsedAssumedInformation =
false;
6837 std::optional<Constant *> SimpleV =
6838 A.getAssumedConstant(
V, AA, UsedAssumedInformation);
6840 return APInt(64, 0);
6842 return CI->getValue();
6843 return std::nullopt;
6846 std::optional<APInt>
getSize(Attributor &
A,
const AbstractAttribute &AA,
6847 AllocationInfo &AI) {
6849 bool UsedAssumedInformation =
false;
6850 if (std::optional<Constant *> SimpleV =
6851 A.getAssumedConstant(*
V, AA, UsedAssumedInformation))
6858 const auto *
TLI =
A.getInfoCache().getTargetLibraryInfoForFunction(*
F);
6864 MapVector<CallBase *, AllocationInfo *> AllocationInfos;
6868 MapVector<CallBase *, DeallocationInfo *> DeallocationInfos;
6873ChangeStatus AAHeapToStackFunction::updateImpl(Attributor &
A) {
6876 const auto *
TLI =
A.getInfoCache().getTargetLibraryInfoForFunction(*
F);
6878 const auto *LivenessAA =
6881 MustBeExecutedContextExplorer *Explorer =
6882 A.getInfoCache().getMustBeExecutedContextExplorer();
6884 bool StackIsAccessibleByOtherThreads =
6885 A.getInfoCache().stackIsAccessibleByOtherThreads();
6888 A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(*F);
6889 std::optional<bool> MayContainIrreducibleControl;
6891 if (&
F->getEntryBlock() == &BB)
6893 if (!MayContainIrreducibleControl.has_value())
6895 if (*MayContainIrreducibleControl)
6904 bool HasUpdatedFrees =
false;
6906 auto UpdateFrees = [&]() {
6907 HasUpdatedFrees =
true;
6909 for (
auto &It : DeallocationInfos) {
6910 DeallocationInfo &DI = *It.second;
6913 if (DI.MightFreeUnknownObjects)
6917 bool UsedAssumedInformation =
false;
6918 if (
A.isAssumedDead(*DI.CB,
this, LivenessAA, UsedAssumedInformation,
6925 LLVM_DEBUG(
dbgs() <<
"[H2S] Unknown underlying object for free!\n");
6926 DI.MightFreeUnknownObjects =
true;
6939 DI.MightFreeUnknownObjects =
true;
6943 AllocationInfo *AI = AllocationInfos.lookup(ObjCB);
6945 LLVM_DEBUG(
dbgs() <<
"[H2S] Free of a non-allocation object: " << *Obj
6947 DI.MightFreeUnknownObjects =
true;
6951 DI.PotentialAllocationCalls.insert(ObjCB);
6955 auto FreeCheck = [&](AllocationInfo &AI) {
6959 if (!StackIsAccessibleByOtherThreads) {
6964 dbgs() <<
"[H2S] found an escaping use, stack is not accessible by "
6965 "other threads and function is not nosync:\n");
6969 if (!HasUpdatedFrees)
6973 if (AI.PotentialFreeCalls.size() != 1) {
6975 << AI.PotentialFreeCalls.size() <<
"\n");
6978 CallBase *UniqueFree = *AI.PotentialFreeCalls.begin();
6979 DeallocationInfo *DI = DeallocationInfos.lookup(UniqueFree);
6982 dbgs() <<
"[H2S] unique free call was not known as deallocation call "
6983 << *UniqueFree <<
"\n");
6986 if (DI->MightFreeUnknownObjects) {
6988 dbgs() <<
"[H2S] unique free call might free unknown allocations\n");
6991 if (DI->PotentialAllocationCalls.empty())
6993 if (DI->PotentialAllocationCalls.size() > 1) {
6995 << DI->PotentialAllocationCalls.size()
6996 <<
" different allocations\n");
6999 if (*DI->PotentialAllocationCalls.begin() != AI.CB) {
7002 <<
"[H2S] unique free call not known to free this allocation but "
7003 << **DI->PotentialAllocationCalls.begin() <<
"\n");
7008 if (!AI.IsGlobalizedLocal) {
7010 if (!Explorer || !Explorer->isInContextOf(UniqueFree, CtxI)) {
7011 LLVM_DEBUG(
dbgs() <<
"[H2S] unique free call might not be executed "
7012 "with the allocation "
7013 << *UniqueFree <<
"\n");
7020 auto UsesCheck = [&](AllocationInfo &AI) {
7021 bool ValidUsesOnly =
true;
7023 auto Pred = [&](
const Use &
U,
bool &Follow) ->
bool {
7028 if (
SI->getValueOperand() ==
U.get()) {
7030 <<
"[H2S] escaping store to memory: " << *UserI <<
"\n");
7031 ValidUsesOnly =
false;
7042 ValidUsesOnly =
false;
7048 if (DeallocationInfos.count(CB)) {
7049 AI.PotentialFreeCalls.insert(CB);
7056 bool IsKnownNoCapture;
7065 if (!IsAssumedNoCapture ||
7066 (!AI.IsGlobalizedLocal && !IsAssumedNoFree)) {
7067 AI.HasPotentiallyFreeingUnknownUses |= !IsAssumedNoFree;
7070 auto Remark = [&](OptimizationRemarkMissed ORM) {
7072 <<
"Could not move globalized variable to the stack. "
7073 "Variable is potentially captured in call. Mark "
7074 "parameter as `__attribute__((noescape))` to override.";
7077 if (ValidUsesOnly && AI.IsGlobalizedLocal)
7078 A.emitRemark<OptimizationRemarkMissed>(CB,
"OMP113",
Remark);
7081 ValidUsesOnly =
false;
7094 ValidUsesOnly =
false;
7097 if (!
A.checkForAllUses(
Pred, *
this, *AI.CB,
false,
7099 [&](
const Use &OldU,
const Use &NewU) {
7100 auto *SI = dyn_cast<StoreInst>(OldU.getUser());
7101 return !SI || StackIsAccessibleByOtherThreads ||
7102 AA::isAssumedThreadLocalObject(
7103 A, *SI->getPointerOperand(), *this);
7106 return ValidUsesOnly;
7111 for (
auto &It : AllocationInfos) {
7112 AllocationInfo &AI = *It.second;
7113 if (AI.Status == AllocationInfo::INVALID)
7117 std::optional<APInt> APAlign = getAPInt(
A, *
this, *Align);
7121 LLVM_DEBUG(
dbgs() <<
"[H2S] Unknown allocation alignment: " << *AI.CB
7123 AI.Status = AllocationInfo::INVALID;
7128 !APAlign->isPowerOf2()) {
7129 LLVM_DEBUG(
dbgs() <<
"[H2S] Invalid allocation alignment: " << APAlign
7131 AI.Status = AllocationInfo::INVALID;
7138 if (!AI.IsGlobalizedLocal &&
A.Opts.max_heap_to_stack_size != -1) {
7139 if (!
Size ||
Size->ugt(
A.Opts.max_heap_to_stack_size)) {
7142 dbgs() <<
"[H2S] Unknown allocation size: " << *AI.CB <<
"\n";
7144 dbgs() <<
"[H2S] Allocation size too large: " << *AI.CB <<
" vs. "
7145 <<
A.Opts.max_heap_to_stack_size <<
"\n";
7148 AI.Status = AllocationInfo::INVALID;
7154 switch (AI.Status) {
7155 case AllocationInfo::STACK_DUE_TO_USE:
7158 AI.Status = AllocationInfo::STACK_DUE_TO_FREE;
7160 case AllocationInfo::STACK_DUE_TO_FREE:
7163 AI.Status = AllocationInfo::INVALID;
7166 case AllocationInfo::INVALID:
7173 bool IsGlobalizedLocal = AI.IsGlobalizedLocal;
7174 if (AI.MoveAllocaIntoEntry &&
7175 (!
Size.has_value() ||
7176 (!IsGlobalizedLocal && IsInLoop(*AI.CB->getParent()))))
7177 AI.MoveAllocaIntoEntry =
false;
7186struct AAPrivatizablePtrImpl :
public AAPrivatizablePtr {
7187 AAPrivatizablePtrImpl(
const IRPosition &IRP, Attributor &
A)
7188 : AAPrivatizablePtr(IRP,
A), PrivatizableType(std::nullopt) {}
7191 AAPrivatizablePtr::indicatePessimisticFixpoint();
7192 PrivatizableType =
nullptr;
7193 return ChangeStatus::CHANGED;
7199 virtual std::optional<Type *> identifyPrivatizableType(Attributor &
A) = 0;
7203 std::optional<Type *> combineTypes(std::optional<Type *> T0,
7204 std::optional<Type *>
T1) {
7214 std::optional<Type *> getPrivatizableType()
const override {
7215 return PrivatizableType;
7218 const std::string getAsStr(Attributor *
A)
const override {
7219 return isAssumedPrivatizablePtr() ?
"[priv]" :
"[no-priv]";
7223 std::optional<Type *> PrivatizableType;
7228struct AAPrivatizablePtrArgument final :
public AAPrivatizablePtrImpl {
7229 AAPrivatizablePtrArgument(
const IRPosition &IRP, Attributor &
A)
7230 : AAPrivatizablePtrImpl(IRP,
A) {}
7232 std::optional<Type *> identifyPrivatizableType(Attributor &
A)
override {
7235 bool UsedAssumedInformation =
false;
7237 A.getAttrs(getIRPosition(), {Attribute::ByVal},
Attrs,
7239 if (!
Attrs.empty() &&
7240 A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *
this,
7241 true, UsedAssumedInformation))
7242 return Attrs[0].getValueAsType();
7244 std::optional<Type *> Ty;
7245 unsigned ArgNo = getIRPosition().getCallSiteArgNo();
7253 auto CallSiteCheck = [&](AbstractCallSite ACS) {
7262 A.getAAFor<AAPrivatizablePtr>(*
this, ACSArgPos, DepClassTy::REQUIRED);
7265 std::optional<Type *> CSTy = PrivCSArgAA->getPrivatizableType();
7268 dbgs() <<
"[AAPrivatizablePtr] ACSPos: " << ACSArgPos <<
", CSTy: ";
7272 dbgs() <<
"<nullptr>";
7277 Ty = combineTypes(Ty, CSTy);
7280 dbgs() <<
" : New Type: ";
7282 (*Ty)->print(
dbgs());
7284 dbgs() <<
"<nullptr>";
7293 if (!
A.checkForAllCallSites(CallSiteCheck, *
this,
true,
7294 UsedAssumedInformation))
7300 PrivatizableType = identifyPrivatizableType(
A);
7301 if (!PrivatizableType)
7302 return ChangeStatus::UNCHANGED;
7303 if (!*PrivatizableType)
7304 return indicatePessimisticFixpoint();
7309 DepClassTy::OPTIONAL);
7312 if (!
A.hasAttr(getIRPosition(), Attribute::ByVal) &&
7315 return indicatePessimisticFixpoint();
7321 identifyReplacementTypes(*PrivatizableType, ReplacementTypes);
7325 Function &Fn = *getIRPosition().getAnchorScope();
7327 A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn);
7329 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] Missing TTI for function "
7331 return indicatePessimisticFixpoint();
7334 auto CallSiteCheck = [&](AbstractCallSite ACS) {
7341 bool UsedAssumedInformation =
false;
7342 if (!
A.checkForAllCallSites(CallSiteCheck, *
this,
true,
7343 UsedAssumedInformation)) {
7345 dbgs() <<
"[AAPrivatizablePtr] ABI incompatibility detected for "
7347 return indicatePessimisticFixpoint();
7351 Argument *Arg = getAssociatedArgument();
7352 if (!
A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) {
7354 return indicatePessimisticFixpoint();
7361 auto IsCompatiblePrivArgOfCallback = [&](CallBase &CB) {
7364 for (
const Use *U : CallbackUses) {
7365 AbstractCallSite CBACS(U);
7366 assert(CBACS && CBACS.isCallbackCall());
7367 for (Argument &CBArg : CBACS.getCalledFunction()->args()) {
7368 int CBArgNo = CBACS.getCallArgOperandNo(CBArg);
7372 <<
"[AAPrivatizablePtr] Argument " << *Arg
7373 <<
"check if can be privatized in the context of its parent ("
7375 <<
")\n[AAPrivatizablePtr] because it is an argument in a "
7377 << CBArgNo <<
"@" << CBACS.getCalledFunction()->getName()
7378 <<
")\n[AAPrivatizablePtr] " << CBArg <<
" : "
7379 << CBACS.getCallArgOperand(CBArg) <<
" vs "
7381 <<
"[AAPrivatizablePtr] " << CBArg <<
" : "
7382 << CBACS.getCallArgOperandNo(CBArg) <<
" vs " << ArgNo <<
"\n";
7385 if (CBArgNo !=
int(ArgNo))
7387 const auto *CBArgPrivAA =
A.getAAFor<AAPrivatizablePtr>(
7389 if (CBArgPrivAA && CBArgPrivAA->isValidState()) {
7390 auto CBArgPrivTy = CBArgPrivAA->getPrivatizableType();
7393 if (*CBArgPrivTy == PrivatizableType)
7398 dbgs() <<
"[AAPrivatizablePtr] Argument " << *Arg
7399 <<
" cannot be privatized in the context of its parent ("
7401 <<
")\n[AAPrivatizablePtr] because it is an argument in a "
7403 << CBArgNo <<
"@" << CBACS.getCalledFunction()->getName()
7404 <<
").\n[AAPrivatizablePtr] for which the argument "
7405 "privatization is not compatible.\n";
7415 auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) {
7419 "Expected a direct call operand for callback call operand");
7424 dbgs() <<
"[AAPrivatizablePtr] Argument " << *Arg
7425 <<
" check if be privatized in the context of its parent ("
7427 <<
")\n[AAPrivatizablePtr] because it is an argument in a "
7429 << DCArgNo <<
"@" << DCCallee->
getName() <<
").\n";
7432 if (
unsigned(DCArgNo) < DCCallee->
arg_size()) {
7433 const auto *DCArgPrivAA =
A.getAAFor<AAPrivatizablePtr>(
7435 DepClassTy::REQUIRED);
7436 if (DCArgPrivAA && DCArgPrivAA->isValidState()) {
7437 auto DCArgPrivTy = DCArgPrivAA->getPrivatizableType();
7440 if (*DCArgPrivTy == PrivatizableType)
7446 dbgs() <<
"[AAPrivatizablePtr] Argument " << *Arg
7447 <<
" cannot be privatized in the context of its parent ("
7449 <<
")\n[AAPrivatizablePtr] because it is an argument in a "
7452 <<
").\n[AAPrivatizablePtr] for which the argument "
7453 "privatization is not compatible.\n";
7461 auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) {
7465 return IsCompatiblePrivArgOfDirectCS(ACS);
7469 if (!
A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *
this,
true,
7470 UsedAssumedInformation))
7471 return indicatePessimisticFixpoint();
7473 return ChangeStatus::UNCHANGED;
7479 identifyReplacementTypes(
Type *PrivType,
7480 SmallVectorImpl<Type *> &ReplacementTypes) {
7483 assert(PrivType &&
"Expected privatizable type!");
7487 for (
unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++)
7488 ReplacementTypes.
push_back(PrivStructType->getElementType(u));
7490 ReplacementTypes.
append(PrivArrayType->getNumElements(),
7491 PrivArrayType->getElementType());
7502 assert(PrivType &&
"Expected privatizable type!");
7505 const DataLayout &
DL =
F.getDataLayout();
7509 const StructLayout *PrivStructLayout =
DL.getStructLayout(PrivStructType);
7510 for (
unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
7513 new StoreInst(
F.getArg(ArgNo + u), Ptr, IP);
7516 Type *PointeeTy = PrivArrayType->getElementType();
7517 uint64_t PointeeTySize =
DL.getTypeStoreSize(PointeeTy);
7518 for (
unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
7520 new StoreInst(
F.getArg(ArgNo + u), Ptr, IP);
7523 new StoreInst(
F.getArg(ArgNo), &
Base, IP);
7529 void createReplacementValues(Align Alignment,
Type *PrivType,
7531 SmallVectorImpl<Value *> &ReplacementValues) {
7533 assert(PrivType &&
"Expected privatizable type!");
7541 const StructLayout *PrivStructLayout =
DL.getStructLayout(PrivStructType);
7542 for (
unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) {
7543 Type *PointeeTy = PrivStructType->getElementType(u);
7546 LoadInst *
L =
new LoadInst(PointeeTy, Ptr,
"", IP->
getIterator());
7547 L->setAlignment(Alignment);
7551 Type *PointeeTy = PrivArrayType->getElementType();
7552 uint64_t PointeeTySize =
DL.getTypeStoreSize(PointeeTy);
7553 for (
unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) {
7555 LoadInst *
L =
new LoadInst(PointeeTy, Ptr,
"", IP->
getIterator());
7556 L->setAlignment(Alignment);
7561 L->setAlignment(Alignment);
7567 if (!PrivatizableType)
7568 return ChangeStatus::UNCHANGED;
7569 assert(*PrivatizableType &&
"Expected privatizable type!");
7571 Argument *Arg = getAssociatedArgument();
7574 const auto *AlignAA =
7581 [=](
const Attributor::ArgumentReplacementInfo &ARI,
7583 BasicBlock &EntryBB = ReplacementFn.getEntryBlock();
7585 const DataLayout &
DL = IP->getDataLayout();
7586 unsigned AS =
DL.getAllocaAddrSpace();
7587 Instruction *AI =
new AllocaInst(*PrivatizableType, AS,
7588 Arg->
getName() +
".priv", IP);
7589 createInitialization(*PrivatizableType, *AI, ReplacementFn,
7590 ArgIt->getArgNo(), IP);
7593 AI = BitCastInst::CreatePointerBitCastOrAddrSpaceCast(
7601 if (CI && CI->isTailCall() && !CI->isMustTailCall())
7602 CI->setTailCall(
false);
7610 [=](
const Attributor::ArgumentReplacementInfo &ARI,
7611 AbstractCallSite ACS, SmallVectorImpl<Value *> &NewArgOperands) {
7614 createReplacementValues(
7615 AlignAA ? AlignAA->getAssumedAlign() :
Align(0),
7616 *PrivatizableType, ACS,
7624 identifyReplacementTypes(*PrivatizableType, ReplacementTypes);
7627 if (
A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes,
7628 std::move(FnRepairCB),
7629 std::move(ACSRepairCB)))
7630 return ChangeStatus::CHANGED;
7631 return ChangeStatus::UNCHANGED;
7634 void trackStatistics()
const override {
7639struct AAPrivatizablePtrFloating :
public AAPrivatizablePtrImpl {
7640 AAPrivatizablePtrFloating(
const IRPosition &IRP, Attributor &
A)
7641 : AAPrivatizablePtrImpl(IRP,
A) {}
7645 indicatePessimisticFixpoint();
7650 "updateImpl will not be called");
7653 std::optional<Type *> identifyPrivatizableType(Attributor &
A)
override {
7656 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] No underlying object found!\n");
7663 return AI->getAllocatedType();
7665 auto *PrivArgAA =
A.getAAFor<AAPrivatizablePtr>(
7667 if (PrivArgAA && PrivArgAA->isAssumedPrivatizablePtr())
7668 return PrivArgAA->getPrivatizableType();
7671 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] Underlying object neither valid "
7672 "alloca nor privatizable argument: "
7677 void trackStatistics()
const override {
7682struct AAPrivatizablePtrCallSiteArgument final
7683 :
public AAPrivatizablePtrFloating {
7684 AAPrivatizablePtrCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
7685 : AAPrivatizablePtrFloating(IRP,
A) {}
7688 if (
A.hasAttr(getIRPosition(), Attribute::ByVal))
7689 indicateOptimisticFixpoint();
7693 PrivatizableType = identifyPrivatizableType(
A);
7694 if (!PrivatizableType)
7695 return ChangeStatus::UNCHANGED;
7696 if (!*PrivatizableType)
7697 return indicatePessimisticFixpoint();
7699 const IRPosition &IRP = getIRPosition();
7700 bool IsKnownNoCapture;
7702 A,
this, IRP, DepClassTy::REQUIRED, IsKnownNoCapture);
7703 if (!IsAssumedNoCapture) {
7704 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] pointer might be captured!\n");
7705 return indicatePessimisticFixpoint();
7708 bool IsKnownNoAlias;
7710 A,
this, IRP, DepClassTy::REQUIRED, IsKnownNoAlias)) {
7711 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] pointer might alias!\n");
7712 return indicatePessimisticFixpoint();
7717 LLVM_DEBUG(
dbgs() <<
"[AAPrivatizablePtr] pointer is written!\n");
7718 return indicatePessimisticFixpoint();
7721 return ChangeStatus::UNCHANGED;
7724 void trackStatistics()
const override {
7729struct AAPrivatizablePtrCallSiteReturned final
7730 :
public AAPrivatizablePtrFloating {
7731 AAPrivatizablePtrCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
7732 : AAPrivatizablePtrFloating(IRP,
A) {}
7736 indicatePessimisticFixpoint();
7739 void trackStatistics()
const override {
7744struct AAPrivatizablePtrReturned final :
public AAPrivatizablePtrFloating {
7745 AAPrivatizablePtrReturned(
const IRPosition &IRP, Attributor &
A)
7746 : AAPrivatizablePtrFloating(IRP,
A) {}
7750 indicatePessimisticFixpoint();
7753 void trackStatistics()
const override {
7763struct AAMemoryBehaviorImpl :
public AAMemoryBehavior {
7764 AAMemoryBehaviorImpl(
const IRPosition &IRP, Attributor &
A)
7765 : AAMemoryBehavior(IRP,
A) {}
7768 intersectAssumedBits(BEST_STATE);
7769 getKnownStateFromValue(
A, getIRPosition(), getState());
7770 AAMemoryBehavior::initialize(
A);
7774 static void getKnownStateFromValue(Attributor &
A,
const IRPosition &IRP,
7775 BitIntegerState &State,
7776 bool IgnoreSubsumingPositions =
false) {
7778 A.getAttrs(IRP, AttrKinds, Attrs, IgnoreSubsumingPositions);
7780 switch (Attr.getKindAsEnum()) {
7781 case Attribute::ReadNone:
7784 case Attribute::ReadOnly:
7787 case Attribute::WriteOnly:
7811 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
7812 SmallVectorImpl<Attribute> &Attrs)
const override {
7815 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone));
7817 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly));
7818 else if (isAssumedWriteOnly())
7819 Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly));
7824 const IRPosition &IRP = getIRPosition();
7826 if (
A.hasAttr(IRP, Attribute::ReadNone,
7828 return ChangeStatus::UNCHANGED;
7837 return ChangeStatus::UNCHANGED;
7840 A.removeAttrs(IRP, AttrKinds);
7843 A.removeAttrs(IRP, Attribute::Writable);
7849 const std::string getAsStr(Attributor *
A)
const override {
7854 if (isAssumedWriteOnly())
7856 return "may-read/write";
7860 static const Attribute::AttrKind AttrKinds[3];
7864 Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly};
7867struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl {
7868 AAMemoryBehaviorFloating(
const IRPosition &IRP, Attributor &
A)
7869 : AAMemoryBehaviorImpl(IRP,
A) {}
7873 void trackStatistics()
const override {
7878 else if (isAssumedWriteOnly())
7885 bool followUsersOfUseIn(Attributor &
A,
const Use &U,
7886 const Instruction *UserI);
7889 void analyzeUseIn(Attributor &
A,
const Use &U,
const Instruction *UserI);
7893struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating {
7894 AAMemoryBehaviorArgument(
const IRPosition &IRP, Attributor &
A)
7895 : AAMemoryBehaviorFloating(IRP,
A) {}
7898 intersectAssumedBits(BEST_STATE);
7899 const IRPosition &IRP = getIRPosition();
7903 bool HasByVal =
A.hasAttr(IRP, {Attribute::ByVal},
7905 getKnownStateFromValue(
A, IRP, getState(),
7912 return ChangeStatus::UNCHANGED;
7916 if (
A.hasAttr(getIRPosition(),
7917 {Attribute::InAlloca, Attribute::Preallocated})) {
7918 removeKnownBits(NO_WRITES);
7919 removeAssumedBits(NO_WRITES);
7921 A.removeAttrs(getIRPosition(), AttrKinds);
7922 return AAMemoryBehaviorFloating::manifest(
A);
7925 void trackStatistics()
const override {
7930 else if (isAssumedWriteOnly())
7935struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument {
7936 AAMemoryBehaviorCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
7937 : AAMemoryBehaviorArgument(IRP,
A) {}
7942 Argument *Arg = getAssociatedArgument();
7944 indicatePessimisticFixpoint();
7948 addKnownBits(NO_WRITES);
7949 removeKnownBits(NO_READS);
7950 removeAssumedBits(NO_READS);
7952 AAMemoryBehaviorArgument::initialize(
A);
7953 if (getAssociatedFunction()->isDeclaration())
7954 indicatePessimisticFixpoint();
7962 Argument *Arg = getAssociatedArgument();
7965 A.getAAFor<AAMemoryBehavior>(*
this, ArgPos, DepClassTy::REQUIRED);
7967 return indicatePessimisticFixpoint();
7971 void trackStatistics()
const override {
7976 else if (isAssumedWriteOnly())
7982struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating {
7983 AAMemoryBehaviorCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
7984 : AAMemoryBehaviorFloating(IRP,
A) {}
7987 AAMemoryBehaviorImpl::initialize(
A);
7991 return ChangeStatus::UNCHANGED;
7994 void trackStatistics()
const override {}
7998struct AAMemoryBehaviorFunction final :
public AAMemoryBehaviorImpl {
7999 AAMemoryBehaviorFunction(
const IRPosition &IRP, Attributor &
A)
8000 : AAMemoryBehaviorImpl(IRP,
A) {}
8014 else if (isAssumedWriteOnly())
8017 A.removeAttrs(getIRPosition(), AttrKinds);
8020 for (Argument &Arg :
F.args())
8022 return A.manifestAttrs(getIRPosition(),
8023 Attribute::getWithMemoryEffects(
F.getContext(), ME));
8026 void trackStatistics()
const override {
8031 else if (isAssumedWriteOnly())
8037struct AAMemoryBehaviorCallSite final
8038 : AACalleeToCallSite<AAMemoryBehavior, AAMemoryBehaviorImpl> {
8039 AAMemoryBehaviorCallSite(
const IRPosition &IRP, Attributor &
A)
8040 : AACalleeToCallSite<AAMemoryBehavior, AAMemoryBehaviorImpl>(IRP,
A) {}
8050 else if (isAssumedWriteOnly())
8053 A.removeAttrs(getIRPosition(), AttrKinds);
8056 for (Use &U : CB.
args())
8058 Attribute::Writable);
8059 return A.manifestAttrs(
8060 getIRPosition(), Attribute::getWithMemoryEffects(CB.
getContext(), ME));
8063 void trackStatistics()
const override {
8068 else if (isAssumedWriteOnly())
8073ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &
A) {
8076 auto AssumedState = getAssumed();
8083 const auto *MemBehaviorAA =
A.getAAFor<AAMemoryBehavior>(
8085 if (MemBehaviorAA) {
8086 intersectAssumedBits(MemBehaviorAA->
getAssumed());
8087 return !isAtFixpoint();
8092 if (
I.mayReadFromMemory())
8093 removeAssumedBits(NO_READS);
8094 if (
I.mayWriteToMemory())
8095 removeAssumedBits(NO_WRITES);
8096 return !isAtFixpoint();
8099 bool UsedAssumedInformation =
false;
8100 if (!
A.checkForAllReadWriteInstructions(CheckRWInst, *
this,
8101 UsedAssumedInformation))
8102 return indicatePessimisticFixpoint();
8108ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &
A) {
8110 const IRPosition &IRP = getIRPosition();
8121 const auto *FnMemAA =
8124 FnMemAssumedState = FnMemAA->getAssumed();
8125 S.addKnownBits(FnMemAA->getKnown());
8126 if ((S.getAssumed() & FnMemAA->getAssumed()) == S.getAssumed())
8132 auto AssumedState = S.getAssumed();
8138 bool IsKnownNoCapture;
8139 const AANoCapture *ArgNoCaptureAA =
nullptr;
8144 if (!IsAssumedNoCapture &&
8146 S.intersectAssumedBits(FnMemAssumedState);
8152 auto UsePred = [&](
const Use &
U,
bool &Follow) ->
bool {
8154 LLVM_DEBUG(
dbgs() <<
"[AAMemoryBehavior] Use: " << *U <<
" in " << *UserI
8162 Follow = followUsersOfUseIn(
A, U, UserI);
8166 analyzeUseIn(
A, U, UserI);
8168 return !isAtFixpoint();
8171 if (!
A.checkForAllUses(UsePred, *
this, getAssociatedValue()))
8172 return indicatePessimisticFixpoint();
8178bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &
A,
const Use &U,
8179 const Instruction *UserI) {
8197 if (
U.get()->getType()->isPointerTy()) {
8199 bool IsKnownNoCapture;
8208void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &
A,
const Use &U,
8209 const Instruction *UserI) {
8216 case Instruction::Load:
8218 removeAssumedBits(NO_READS);
8221 case Instruction::Store:
8226 removeAssumedBits(NO_WRITES);
8228 indicatePessimisticFixpoint();
8231 case Instruction::Call:
8232 case Instruction::CallBr:
8233 case Instruction::Invoke: {
8240 indicatePessimisticFixpoint();
8247 removeAssumedBits(NO_READS);
8254 if (
U.get()->getType()->isPointerTy())
8258 const auto *MemBehaviorAA =
8264 intersectAssumedBits(MemBehaviorAA->
getAssumed());
8272 removeAssumedBits(NO_READS);
8274 removeAssumedBits(NO_WRITES);
8286 return "all memory";
8289 std::string S =
"memory:";
8295 S +=
"internal global,";
8297 S +=
"external global,";
8301 S +=
"inaccessible,";
8315 AccessKind2Accesses.fill(
nullptr);
8318 ~AAMemoryLocationImpl()
override {
8321 for (AccessSet *AS : AccessKind2Accesses)
8327 intersectAssumedBits(BEST_STATE);
8328 getKnownStateFromValue(
A, getIRPosition(), getState());
8329 AAMemoryLocation::initialize(
A);
8333 static void getKnownStateFromValue(Attributor &
A,
const IRPosition &IRP,
8334 BitIntegerState &State,
8335 bool IgnoreSubsumingPositions =
false) {
8344 bool UseArgMemOnly =
true;
8346 if (AnchorFn &&
A.isRunOn(*AnchorFn))
8350 A.getAttrs(IRP, {Attribute::Memory},
Attrs, IgnoreSubsumingPositions);
8359 State.
addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM,
true,
true));
8364 State.
addKnownBits(inverseLocation(NO_ARGUMENT_MEM,
true,
true));
8368 A.manifestAttrs(IRP,
8369 Attribute::getWithMemoryEffects(
8378 NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM,
true,
true));
8382 A.manifestAttrs(IRP,
8383 Attribute::getWithMemoryEffects(
8392 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
8393 SmallVectorImpl<Attribute> &Attrs)
const override {
8400 else if (isAssumedInaccessibleMemOnly())
8401 Attrs.push_back(Attribute::getWithMemoryEffects(
8403 else if (isAssumedArgMemOnly())
8406 else if (isAssumedInaccessibleOrArgMemOnly())
8407 Attrs.push_back(Attribute::getWithMemoryEffects(
8416 const IRPosition &IRP = getIRPosition();
8420 if (DeducedAttrs.
size() != 1)
8421 return ChangeStatus::UNCHANGED;
8431 return A.manifestAttrs(IRP, Attribute::getWithMemoryEffects(
8435 bool checkForAllAccessesToMemoryKind(
8437 MemoryLocationsKind)>
8439 MemoryLocationsKind RequestedMLK)
const override {
8440 if (!isValidState())
8443 MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation();
8444 if (AssumedMLK == NO_LOCATIONS)
8448 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS;
8449 CurMLK *= 2, ++
Idx) {
8450 if (CurMLK & RequestedMLK)
8453 if (
const AccessSet *
Accesses = AccessKind2Accesses[Idx])
8454 for (
const AccessInfo &AI : *
Accesses)
8455 if (!
Pred(AI.I, AI.Ptr, AI.Kind, CurMLK))
8468 MemoryLocationsKind KnownMLK = getKnown();
8470 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2)
8471 if (!(CurMLK & KnownMLK))
8472 updateStateAndAccessesMap(getState(), CurMLK,
I,
nullptr,
Changed,
8473 getAccessKindFromInst(
I));
8474 return AAMemoryLocation::indicatePessimisticFixpoint();
8494 bool operator()(
const AccessInfo &
LHS,
const AccessInfo &
RHS)
const {
8498 return LHS.Ptr <
RHS.Ptr;
8499 if (
LHS.Kind !=
RHS.Kind)
8500 return LHS.Kind <
RHS.Kind;
8507 using AccessSet = SmallSet<AccessInfo, 2, AccessInfo>;
8508 std::array<AccessSet *, llvm::ConstantLog2<VALID_STATE>()>
8509 AccessKind2Accesses;
8514 categorizeArgumentPointerLocations(Attributor &
A, CallBase &CB,
8515 AAMemoryLocation::StateType &AccessedLocs,
8520 categorizeAccessedLocations(Attributor &
A, Instruction &
I,
bool &
Changed);
8523 AccessKind getAccessKindFromInst(
const Instruction *
I) {
8526 AK =
I->mayReadFromMemory() ? READ :
NONE;
8535 void updateStateAndAccessesMap(AAMemoryLocation::StateType &State,
8536 MemoryLocationsKind MLK,
const Instruction *
I,
8545 if (MLK == NO_UNKOWN_MEM)
8547 State.removeAssumedBits(MLK);
8552 void categorizePtrValue(Attributor &
A,
const Instruction &
I,
const Value &Ptr,
8553 AAMemoryLocation::StateType &State,
bool &
Changed,
8554 unsigned AccessAS = 0);
8560void AAMemoryLocationImpl::categorizePtrValue(
8561 Attributor &
A,
const Instruction &
I,
const Value &Ptr,
8563 LLVM_DEBUG(
dbgs() <<
"[AAMemoryLocation] Categorize pointer locations for "
8568 unsigned ObjectAS =
Obj.getType()->getPointerAddressSpace();
8570 MemoryLocationsKind MLK = NO_LOCATIONS;
8590 MLK = NO_ARGUMENT_MEM;
8596 if (GVar->isConstant())
8599 if (GV->hasLocalLinkage())
8600 MLK = NO_GLOBAL_INTERNAL_MEM;
8602 MLK = NO_GLOBAL_EXTERNAL_MEM;
8611 bool IsKnownNoAlias;
8615 MLK = NO_MALLOCED_MEM;
8617 MLK = NO_UNKOWN_MEM;
8619 MLK = NO_UNKOWN_MEM;
8622 assert(MLK != NO_LOCATIONS &&
"No location specified!");
8623 LLVM_DEBUG(
dbgs() <<
"[AAMemoryLocation] Ptr value can be categorized: "
8624 << Obj <<
" -> " << getMemoryLocationsAsStr(MLK) <<
"\n");
8626 getAccessKindFromInst(&
I));
8631 const auto *AA =
A.getAAFor<AAUnderlyingObjects>(
8635 dbgs() <<
"[AAMemoryLocation] Pointer locations not categorized\n");
8636 updateStateAndAccessesMap(
State, NO_UNKOWN_MEM, &
I,
nullptr,
Changed,
8637 getAccessKindFromInst(&
I));
8642 dbgs() <<
"[AAMemoryLocation] Accessed locations with pointer locations: "
8646void AAMemoryLocationImpl::categorizeArgumentPointerLocations(
8649 for (
unsigned ArgNo = 0,
E = CB.
arg_size(); ArgNo <
E; ++ArgNo) {
8658 const auto *ArgOpMemLocationAA =
8661 if (ArgOpMemLocationAA && ArgOpMemLocationAA->isAssumedReadNone())
8666 categorizePtrValue(
A, CB, *ArgOp, AccessedLocs,
Changed);
8671AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &
A, Instruction &
I,
8673 LLVM_DEBUG(
dbgs() <<
"[AAMemoryLocation] Categorize accessed locations for "
8677 AccessedLocs.intersectAssumedBits(NO_LOCATIONS);
8682 const auto *CBMemLocationAA =
A.getAAFor<AAMemoryLocation>(
8685 <<
" [" << CBMemLocationAA <<
"]\n");
8686 if (!CBMemLocationAA) {
8687 updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &
I,
nullptr,
8688 Changed, getAccessKindFromInst(&
I));
8689 return NO_UNKOWN_MEM;
8692 if (CBMemLocationAA->isAssumedReadNone())
8693 return NO_LOCATIONS;
8695 if (CBMemLocationAA->isAssumedInaccessibleMemOnly()) {
8696 updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &
I,
nullptr,
8697 Changed, getAccessKindFromInst(&
I));
8698 return AccessedLocs.getAssumed();
8701 uint32_t CBAssumedNotAccessedLocs =
8702 CBMemLocationAA->getAssumedNotAccessedLocation();
8705 uint32_t CBAssumedNotAccessedLocsNoArgMem =
8706 CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM;
8708 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) {
8709 if (CBAssumedNotAccessedLocsNoArgMem & CurMLK)
8711 updateStateAndAccessesMap(AccessedLocs, CurMLK, &
I,
nullptr,
Changed,
8712 getAccessKindFromInst(&
I));
8717 bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM);
8718 if (HasGlobalAccesses) {
8721 updateStateAndAccessesMap(AccessedLocs, MLK, &
I, Ptr,
Changed,
8722 getAccessKindFromInst(&
I));
8725 if (!CBMemLocationAA->checkForAllAccessesToMemoryKind(
8726 AccessPred, inverseLocation(NO_GLOBAL_MEM,
false,
false)))
8727 return AccessedLocs.getWorstState();
8731 dbgs() <<
"[AAMemoryLocation] Accessed state before argument handling: "
8732 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) <<
"\n");
8735 bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM);
8737 categorizeArgumentPointerLocations(
A, *CB, AccessedLocs,
Changed);
8740 dbgs() <<
"[AAMemoryLocation] Accessed state after argument handling: "
8741 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) <<
"\n");
8743 return AccessedLocs.getAssumed();
8748 dbgs() <<
"[AAMemoryLocation] Categorize memory access with pointer: "
8749 <<
I <<
" [" << *Ptr <<
"]\n");
8750 categorizePtrValue(
A,
I, *Ptr, AccessedLocs,
Changed,
8751 Ptr->getType()->getPointerAddressSpace());
8752 return AccessedLocs.getAssumed();
8755 LLVM_DEBUG(
dbgs() <<
"[AAMemoryLocation] Failed to categorize instruction: "
8757 updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &
I,
nullptr,
Changed,
8758 getAccessKindFromInst(&
I));
8759 return AccessedLocs.getAssumed();
8763struct AAMemoryLocationFunction final :
public AAMemoryLocationImpl {
8764 AAMemoryLocationFunction(
const IRPosition &IRP, Attributor &
A)
8765 : AAMemoryLocationImpl(IRP,
A) {}
8769 const auto *MemBehaviorAA =
8770 A.getAAFor<AAMemoryBehavior>(*
this, getIRPosition(), DepClassTy::NONE);
8773 return indicateOptimisticFixpoint();
8775 "AAMemoryLocation was not read-none but AAMemoryBehavior was!");
8776 A.recordDependence(*MemBehaviorAA, *
this, DepClassTy::OPTIONAL);
8777 return ChangeStatus::UNCHANGED;
8781 auto AssumedState = getAssumed();
8785 MemoryLocationsKind MLK = categorizeAccessedLocations(
A,
I,
Changed);
8786 LLVM_DEBUG(
dbgs() <<
"[AAMemoryLocation] Accessed locations for " <<
I
8787 <<
": " << getMemoryLocationsAsStr(MLK) <<
"\n");
8788 removeAssumedBits(inverseLocation(MLK,
false,
false));
8791 return getAssumedNotAccessedLocation() != VALID_STATE;
8794 bool UsedAssumedInformation =
false;
8795 if (!
A.checkForAllReadWriteInstructions(CheckRWInst, *
this,
8796 UsedAssumedInformation))
8797 return indicatePessimisticFixpoint();
8799 Changed |= AssumedState != getAssumed();
8800 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
8803 void trackStatistics()
const override {
8806 else if (isAssumedArgMemOnly())
8808 else if (isAssumedInaccessibleMemOnly())
8810 else if (isAssumedInaccessibleOrArgMemOnly())
8816struct AAMemoryLocationCallSite final : AAMemoryLocationImpl {
8817 AAMemoryLocationCallSite(
const IRPosition &IRP, Attributor &
A)
8818 : AAMemoryLocationImpl(IRP,
A) {}
8821 AAMemoryLocationImpl::initialize(
A);
8828 removeKnownBits(NO_INACCESSIBLE_MEM);
8829 updateStateAndAccessesMap(getState(), NO_INACCESSIBLE_MEM, &CB,
nullptr,
8830 Changed, getAccessKindFromInst(&CB));
8842 A.getAAFor<AAMemoryLocation>(*
this, FnPos, DepClassTy::REQUIRED);
8844 return indicatePessimisticFixpoint();
8848 updateStateAndAccessesMap(getState(), MLK,
I, Ptr,
Changed,
8849 getAccessKindFromInst(
I));
8852 if (!FnAA->checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS))
8853 return indicatePessimisticFixpoint();
8854 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
8857 void trackStatistics()
const override {
8867struct AADenormalFPMathImpl :
public AADenormalFPMath {
8868 AADenormalFPMathImpl(
const IRPosition &IRP, Attributor &
A)
8869 : AADenormalFPMath(IRP,
A) {}
8871 const std::string getAsStr(Attributor *
A)
const override {
8872 std::string Str(
"AADenormalFPMath[");
8873 raw_string_ostream OS(Str);
8875 DenormalState
Known = getKnown();
8876 if (
Known.Mode.isValid())
8877 OS <<
"denormal-fp-math=" <<
Known.Mode;
8881 if (
Known.ModeF32.isValid())
8882 OS <<
" denormal-fp-math-f32=" <<
Known.ModeF32;
8888struct AADenormalFPMathFunction final : AADenormalFPMathImpl {
8889 AADenormalFPMathFunction(
const IRPosition &IRP, Attributor &
A)
8890 : AADenormalFPMathImpl(IRP,
A) {}
8894 DenormalFPEnv DenormEnv =
F->getDenormalFPEnv();
8904 auto CheckCallSite = [=, &Change, &
A](AbstractCallSite CS) {
8907 <<
"->" << getAssociatedFunction()->
getName() <<
'\n');
8909 const auto *CallerInfo =
A.getAAFor<AADenormalFPMath>(
8915 CallerInfo->getState());
8919 bool AllCallSitesKnown =
true;
8920 if (!
A.checkForAllCallSites(CheckCallSite, *
this,
true, AllCallSitesKnown))
8921 return indicatePessimisticFixpoint();
8923 if (Change == ChangeStatus::CHANGED && isModeFixed())
8929 LLVMContext &Ctx = getAssociatedFunction()->getContext();
8935 DenormalFPEnv KnownEnv(
Known.Mode,
Known.ModeF32);
8938 AttrToRemove.
push_back(Attribute::DenormalFPEnv);
8941 Ctx, Attribute::DenormalFPEnv,
8942 DenormalFPEnv(
Known.Mode,
Known.ModeF32).toIntValue()));
8945 auto &IRP = getIRPosition();
8948 return A.removeAttrs(IRP, AttrToRemove) |
8949 A.manifestAttrs(IRP, AttrToAdd,
true);
8952 void trackStatistics()
const override {
8961struct AAValueConstantRangeImpl : AAValueConstantRange {
8962 using StateType = IntegerRangeState;
8963 AAValueConstantRangeImpl(
const IRPosition &IRP, Attributor &
A)
8964 : AAValueConstantRange(IRP,
A) {}
8967 if (
A.hasSimplificationCallback(getIRPosition())) {
8968 indicatePessimisticFixpoint();
8973 intersectKnown(getConstantRangeFromSCEV(
A, getCtxI()));
8976 intersectKnown(getConstantRangeFromLVI(
A, getCtxI()));
8979 const std::string getAsStr(Attributor *
A)
const override {
8981 llvm::raw_string_ostream OS(Str);
8983 getKnown().print(OS);
8985 getAssumed().print(OS);
8992 const SCEV *getSCEV(Attributor &
A,
const Instruction *
I =
nullptr)
const {
8993 if (!getAnchorScope())
8996 ScalarEvolution *SE =
8997 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
9000 LoopInfo *LI =
A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(
9006 const SCEV *S = SE->
getSCEV(&getAssociatedValue());
9015 ConstantRange getConstantRangeFromSCEV(Attributor &
A,
9016 const Instruction *
I =
nullptr)
const {
9017 if (!getAnchorScope())
9020 ScalarEvolution *SE =
9021 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(
9024 const SCEV *S = getSCEV(
A,
I);
9034 getConstantRangeFromLVI(Attributor &
A,
9035 const Instruction *CtxI =
nullptr)
const {
9036 if (!getAnchorScope())
9039 LazyValueInfo *LVI =
9040 A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>(
9055 bool isValidCtxInstructionForOutsideAnalysis(Attributor &
A,
9056 const Instruction *CtxI,
9057 bool AllowAACtxI)
const {
9058 if (!CtxI || (!AllowAACtxI && CtxI == getCtxI()))
9070 InformationCache &InfoCache =
A.getInfoCache();
9071 const DominatorTree *DT =
9081 getAssumedConstantRange(Attributor &
A,
9082 const Instruction *CtxI =
nullptr)
const override {
9087 if (!isValidCtxInstructionForOutsideAnalysis(
A, CtxI,
9089 return getAssumed();
9091 ConstantRange LVIR = getConstantRangeFromLVI(
A, CtxI);
9092 ConstantRange SCEVR = getConstantRangeFromSCEV(
A, CtxI);
9093 return getAssumed().intersectWith(SCEVR).intersectWith(LVIR);
9098 getMDNodeForConstantRange(
Type *Ty, LLVMContext &Ctx,
9099 const ConstantRange &AssumedConstantRange) {
9101 Ty, AssumedConstantRange.
getLower())),
9103 Ty, AssumedConstantRange.
getUpper()))};
9108 static bool isBetterRange(
const ConstantRange &Assumed,
9109 const Instruction &
I) {
9113 std::optional<ConstantRange>
Known;
9117 }
else if (MDNode *KnownRanges =
I.getMetadata(LLVMContext::MD_range)) {
9123 if (KnownRanges->getNumOperands() > 2)
9126 ConstantInt *
Lower =
9128 ConstantInt *
Upper =
9138 setRangeMetadataIfisBetterRange(Instruction *
I,
9139 const ConstantRange &AssumedConstantRange) {
9140 if (isBetterRange(AssumedConstantRange, *
I)) {
9141 I->setMetadata(LLVMContext::MD_range,
9142 getMDNodeForConstantRange(
I->getType(),
I->getContext(),
9143 AssumedConstantRange));
9150 setRangeRetAttrIfisBetterRange(Attributor &
A,
const IRPosition &IRP,
9152 const ConstantRange &AssumedConstantRange) {
9153 if (isBetterRange(AssumedConstantRange, *
I)) {
9154 A.manifestAttrs(IRP,
9155 Attribute::get(
I->getContext(), Attribute::Range,
9156 AssumedConstantRange),
9165 ConstantRange AssumedConstantRange = getAssumedConstantRange(
A);
9168 auto &
V = getAssociatedValue();
9172 assert(
I == getCtxI() &&
"Should not annotate an instruction which is "
9173 "not the context instruction");
9175 if (setRangeMetadataIfisBetterRange(
I, AssumedConstantRange))
9176 Changed = ChangeStatus::CHANGED;
9178 if (setRangeRetAttrIfisBetterRange(
A, getIRPosition(),
I,
9179 AssumedConstantRange))
9180 Changed = ChangeStatus::CHANGED;
9188struct AAValueConstantRangeArgument final
9189 : AAArgumentFromCallSiteArguments<
9190 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
9192 using Base = AAArgumentFromCallSiteArguments<
9193 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState,
9195 AAValueConstantRangeArgument(
const IRPosition &IRP, Attributor &
A)
9198 void trackStatistics()
const override {
9203struct AAValueConstantRangeReturned
9204 : AAReturnedFromReturnedValues<AAValueConstantRange,
9205 AAValueConstantRangeImpl,
9206 AAValueConstantRangeImpl::StateType,
9209 AAReturnedFromReturnedValues<AAValueConstantRange,
9210 AAValueConstantRangeImpl,
9211 AAValueConstantRangeImpl::StateType,
9213 AAValueConstantRangeReturned(
const IRPosition &IRP, Attributor &
A)
9217 if (!
A.isFunctionIPOAmendable(*getAssociatedFunction()))
9218 indicatePessimisticFixpoint();
9221 void trackStatistics()
const override {
9226struct AAValueConstantRangeFloating : AAValueConstantRangeImpl {
9227 AAValueConstantRangeFloating(
const IRPosition &IRP, Attributor &
A)
9228 : AAValueConstantRangeImpl(IRP,
A) {}
9231 AAValueConstantRangeImpl::initialize(
A);
9235 Value &
V = getAssociatedValue();
9238 unionAssumed(ConstantRange(
C->getValue()));
9239 indicateOptimisticFixpoint();
9245 unionAssumed(ConstantRange(APInt(
getBitWidth(), 0)));
9246 indicateOptimisticFixpoint();
9258 if (
auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) {
9269 indicatePessimisticFixpoint();
9272 << getAssociatedValue() <<
"\n");
9275 bool calculateBinaryOperator(
9276 Attributor &
A, BinaryOperator *BinOp, IntegerRangeState &
T,
9277 const Instruction *CtxI,
9278 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9283 bool UsedAssumedInformation =
false;
9284 const auto &SimplifiedLHS =
A.getAssumedSimplified(
9287 if (!SimplifiedLHS.has_value())
9289 if (!*SimplifiedLHS)
9291 LHS = *SimplifiedLHS;
9293 const auto &SimplifiedRHS =
A.getAssumedSimplified(
9296 if (!SimplifiedRHS.has_value())
9298 if (!*SimplifiedRHS)
9300 RHS = *SimplifiedRHS;
9306 auto *LHSAA =
A.getAAFor<AAValueConstantRange>(
9308 DepClassTy::REQUIRED);
9312 auto LHSAARange = LHSAA->getAssumedConstantRange(
A, CtxI);
9314 auto *RHSAA =
A.getAAFor<AAValueConstantRange>(
9316 DepClassTy::REQUIRED);
9320 auto RHSAARange = RHSAA->getAssumedConstantRange(
A, CtxI);
9322 auto AssumedRange = LHSAARange.binaryOp(BinOp->
getOpcode(), RHSAARange);
9324 T.unionAssumed(AssumedRange);
9328 return T.isValidState();
9331 bool calculateCastInst(
9332 Attributor &
A, CastInst *CastI, IntegerRangeState &
T,
9333 const Instruction *CtxI,
9334 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9340 bool UsedAssumedInformation =
false;
9341 const auto &SimplifiedOpV =
A.getAssumedSimplified(
9344 if (!SimplifiedOpV.has_value())
9346 if (!*SimplifiedOpV)
9348 OpV = *SimplifiedOpV;
9353 auto *OpAA =
A.getAAFor<AAValueConstantRange>(
9355 DepClassTy::REQUIRED);
9359 T.unionAssumed(OpAA->getAssumed().castOp(CastI->
getOpcode(),
9361 return T.isValidState();
9365 calculateCmpInst(Attributor &
A, CmpInst *CmpI, IntegerRangeState &
T,
9366 const Instruction *CtxI,
9367 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) {
9372 bool UsedAssumedInformation =
false;
9373 const auto &SimplifiedLHS =
A.getAssumedSimplified(
9376 if (!SimplifiedLHS.has_value())
9378 if (!*SimplifiedLHS)
9380 LHS = *SimplifiedLHS;
9382 const auto &SimplifiedRHS =
A.getAssumedSimplified(
9385 if (!SimplifiedRHS.has_value())
9387 if (!*SimplifiedRHS)
9389 RHS = *SimplifiedRHS;
9395 auto *LHSAA =
A.getAAFor<AAValueConstantRange>(
9397 DepClassTy::REQUIRED);
9401 auto *RHSAA =
A.getAAFor<AAValueConstantRange>(
9403 DepClassTy::REQUIRED);
9407 auto LHSAARange = LHSAA->getAssumedConstantRange(
A, CtxI);
9408 auto RHSAARange = RHSAA->getAssumedConstantRange(
A, CtxI);
9411 if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet())
9414 bool MustTrue =
false, MustFalse =
false;
9416 auto AllowedRegion =
9419 if (AllowedRegion.intersectWith(LHSAARange).isEmptySet())
9425 assert((!MustTrue || !MustFalse) &&
9426 "Either MustTrue or MustFalse should be false!");
9429 T.unionAssumed(ConstantRange(APInt( 1, 1)));
9431 T.unionAssumed(ConstantRange(APInt( 1, 0)));
9433 T.unionAssumed(ConstantRange( 1,
true));
9435 LLVM_DEBUG(
dbgs() <<
"[AAValueConstantRange] " << *CmpI <<
" after "
9436 << (MustTrue ?
"true" : (MustFalse ?
"false" :
"unknown"))
9437 <<
": " <<
T <<
"\n\t" << *LHSAA <<
"\t<op>\n\t"
9441 return T.isValidState();
9452 bool UsedAssumedInformation =
false;
9453 const auto &SimplifiedOpV =
A.getAssumedSimplified(
9456 if (!SimplifiedOpV.has_value())
9458 if (!*SimplifiedOpV)
9460 Value *VPtr = *SimplifiedOpV;
9463 const auto *AA =
A.getAAFor<AAValueConstantRange>(
9465 DepClassTy::REQUIRED);
9469 T.unionAssumed(AA->getAssumedConstantRange(
A, CtxI));
9473 return T.isValidState();
9478 if (!calculateBinaryOperator(
A, BinOp,
T, CtxI, QuerriedAAs))
9481 if (!calculateCmpInst(
A, CmpI,
T, CtxI, QuerriedAAs))
9484 if (!calculateCastInst(
A, CastI,
T, CtxI, QuerriedAAs))
9490 T.indicatePessimisticFixpoint();
9497 for (
const AAValueConstantRange *QueriedAA : QuerriedAAs) {
9498 if (QueriedAA !=
this)
9501 if (
T.getAssumed() == getState().getAssumed())
9503 T.indicatePessimisticFixpoint();
9506 return T.isValidState();
9509 if (!VisitValueCB(getAssociatedValue(), getCtxI()))
9510 return indicatePessimisticFixpoint();
9515 return ChangeStatus::UNCHANGED;
9516 if (++NumChanges > MaxNumChanges) {
9517 LLVM_DEBUG(
dbgs() <<
"[AAValueConstantRange] performed " << NumChanges
9518 <<
" but only " << MaxNumChanges
9519 <<
" are allowed to avoid cyclic reasoning.");
9520 return indicatePessimisticFixpoint();
9522 return ChangeStatus::CHANGED;
9525 void trackStatistics()
const override {
9534 static constexpr int MaxNumChanges = 5;
9537struct AAValueConstantRangeFunction : AAValueConstantRangeImpl {
9538 AAValueConstantRangeFunction(
const IRPosition &IRP, Attributor &
A)
9539 : AAValueConstantRangeImpl(IRP,
A) {}
9542 llvm_unreachable(
"AAValueConstantRange(Function|CallSite)::updateImpl will "
9549struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction {
9550 AAValueConstantRangeCallSite(
const IRPosition &IRP, Attributor &
A)
9551 : AAValueConstantRangeFunction(IRP,
A) {}
9556struct AAValueConstantRangeCallSiteReturned
9557 : AACalleeToCallSite<AAValueConstantRange, AAValueConstantRangeImpl,
9558 AAValueConstantRangeImpl::StateType,
9560 AAValueConstantRangeCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
9561 : AACalleeToCallSite<AAValueConstantRange, AAValueConstantRangeImpl,
9562 AAValueConstantRangeImpl::StateType,
9568 if (std::optional<ConstantRange>
Range = CI->getRange())
9569 intersectKnown(*
Range);
9572 AAValueConstantRangeImpl::initialize(
A);
9575 void trackStatistics()
const override {
9579struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating {
9580 AAValueConstantRangeCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
9581 : AAValueConstantRangeFloating(IRP,
A) {}
9584 return ChangeStatus::UNCHANGED;
9587 void trackStatistics()
const override {
9597 :
Base(IRP,
true,
A.Opts.attributor_max_potential_values) {}
9607 if (
A.hasSimplificationCallback(getIRPosition()))
9608 indicatePessimisticFixpoint();
9613 bool fillSetWithConstantValues(Attributor &
A,
const IRPosition &IRP, SetTy &S,
9614 bool &ContainsUndef,
bool ForSelf) {
9616 bool UsedAssumedInformation =
false;
9618 UsedAssumedInformation)) {
9625 auto *PotentialValuesAA =
A.getAAFor<AAPotentialConstantValues>(
9626 *
this, IRP, DepClassTy::REQUIRED);
9627 if (!PotentialValuesAA || !PotentialValuesAA->getState().isValidState())
9629 ContainsUndef = PotentialValuesAA->getState().undefIsContained();
9630 S = PotentialValuesAA->getState().getAssumedSet();
9637 ContainsUndef =
false;
9638 for (
auto &It :
Values) {
9640 ContainsUndef =
true;
9646 S.insert(CI->getValue());
9648 ContainsUndef &= S.empty();
9653 const std::string getAsStr(Attributor *
A)
const override {
9655 llvm::raw_string_ostream OS(Str);
9661 return indicatePessimisticFixpoint();
9665struct AAPotentialConstantValuesArgument final
9666 : AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
9667 AAPotentialConstantValuesImpl,
9668 PotentialConstantIntValuesState> {
9669 using Base = AAArgumentFromCallSiteArguments<AAPotentialConstantValues,
9670 AAPotentialConstantValuesImpl,
9672 AAPotentialConstantValuesArgument(
const IRPosition &IRP, Attributor &
A)
9675 void trackStatistics()
const override {
9680struct AAPotentialConstantValuesReturned
9681 : AAReturnedFromReturnedValues<AAPotentialConstantValues,
9682 AAPotentialConstantValuesImpl> {
9683 using Base = AAReturnedFromReturnedValues<AAPotentialConstantValues,
9684 AAPotentialConstantValuesImpl>;
9685 AAPotentialConstantValuesReturned(
const IRPosition &IRP, Attributor &
A)
9689 if (!
A.isFunctionIPOAmendable(*getAssociatedFunction()))
9690 indicatePessimisticFixpoint();
9691 Base::initialize(
A);
9694 void trackStatistics()
const override {
9699struct AAPotentialConstantValuesFloating : AAPotentialConstantValuesImpl {
9700 AAPotentialConstantValuesFloating(
const IRPosition &IRP, Attributor &
A)
9701 : AAPotentialConstantValuesImpl(IRP,
A) {}
9704 AAPotentialConstantValuesImpl::initialize(
A);
9708 Value &
V = getAssociatedValue();
9711 unionAssumed(
C->getValue());
9712 indicateOptimisticFixpoint();
9717 unionAssumedWithUndef();
9718 indicateOptimisticFixpoint();
9728 indicatePessimisticFixpoint();
9731 << getAssociatedValue() <<
"\n");
9734 static bool calculateICmpInst(
const ICmpInst *ICI,
const APInt &
LHS,
9739 static APInt calculateCastInst(
const CastInst *CI,
const APInt &Src,
9740 uint32_t ResultBitWidth) {
9745 case Instruction::Trunc:
9746 return Src.trunc(ResultBitWidth);
9747 case Instruction::SExt:
9748 return Src.sext(ResultBitWidth);
9749 case Instruction::ZExt:
9750 return Src.zext(ResultBitWidth);
9751 case Instruction::BitCast:
9756 static APInt calculateBinaryOperator(
const BinaryOperator *BinOp,
9757 const APInt &
LHS,
const APInt &
RHS,
9758 bool &SkipOperation,
bool &Unsupported) {
9765 switch (BinOpcode) {
9769 case Instruction::Add:
9771 case Instruction::Sub:
9773 case Instruction::Mul:
9775 case Instruction::UDiv:
9777 SkipOperation =
true;
9781 case Instruction::SDiv:
9783 SkipOperation =
true;
9787 case Instruction::URem:
9789 SkipOperation =
true;
9793 case Instruction::SRem:
9795 SkipOperation =
true;
9799 case Instruction::Shl:
9801 case Instruction::LShr:
9803 case Instruction::AShr:
9805 case Instruction::And:
9807 case Instruction::Or:
9809 case Instruction::Xor:
9814 bool calculateBinaryOperatorAndTakeUnion(
const BinaryOperator *BinOp,
9815 const APInt &
LHS,
const APInt &
RHS) {
9816 bool SkipOperation =
false;
9819 calculateBinaryOperator(BinOp,
LHS,
RHS, SkipOperation, Unsupported);
9824 unionAssumed(Result);
9825 return isValidState();
9828 ChangeStatus updateWithICmpInst(Attributor &
A, ICmpInst *ICI) {
9829 auto AssumedBefore = getAssumed();
9833 bool LHSContainsUndef =
false, RHSContainsUndef =
false;
9834 SetTy LHSAAPVS, RHSAAPVS;
9836 LHSContainsUndef,
false) ||
9838 RHSContainsUndef,
false))
9839 return indicatePessimisticFixpoint();
9842 bool MaybeTrue =
false, MaybeFalse =
false;
9844 if (LHSContainsUndef && RHSContainsUndef) {
9847 unionAssumedWithUndef();
9848 }
else if (LHSContainsUndef) {
9849 for (
const APInt &R : RHSAAPVS) {
9850 bool CmpResult = calculateICmpInst(ICI,
Zero, R);
9851 MaybeTrue |= CmpResult;
9852 MaybeFalse |= !CmpResult;
9853 if (MaybeTrue & MaybeFalse)
9854 return indicatePessimisticFixpoint();
9856 }
else if (RHSContainsUndef) {
9857 for (
const APInt &L : LHSAAPVS) {
9858 bool CmpResult = calculateICmpInst(ICI, L,
Zero);
9859 MaybeTrue |= CmpResult;
9860 MaybeFalse |= !CmpResult;
9861 if (MaybeTrue & MaybeFalse)
9862 return indicatePessimisticFixpoint();
9865 for (
const APInt &L : LHSAAPVS) {
9866 for (
const APInt &R : RHSAAPVS) {
9867 bool CmpResult = calculateICmpInst(ICI, L, R);
9868 MaybeTrue |= CmpResult;
9869 MaybeFalse |= !CmpResult;
9870 if (MaybeTrue & MaybeFalse)
9871 return indicatePessimisticFixpoint();
9876 unionAssumed(APInt( 1, 1));
9878 unionAssumed(APInt( 1, 0));
9879 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9880 : ChangeStatus::CHANGED;
9883 ChangeStatus updateWithSelectInst(Attributor &
A, SelectInst *SI) {
9884 auto AssumedBefore = getAssumed();
9888 bool UsedAssumedInformation =
false;
9889 std::optional<Constant *>
C =
A.getAssumedConstant(
9890 *
SI->getCondition(), *
this, UsedAssumedInformation);
9893 bool OnlyLeft =
false, OnlyRight =
false;
9894 if (
C && *
C && (*C)->isOneValue())
9896 else if (
C && *
C && (*C)->isNullValue())
9899 bool LHSContainsUndef =
false, RHSContainsUndef =
false;
9900 SetTy LHSAAPVS, RHSAAPVS;
9903 LHSContainsUndef,
false))
9904 return indicatePessimisticFixpoint();
9908 RHSContainsUndef,
false))
9909 return indicatePessimisticFixpoint();
9911 if (OnlyLeft || OnlyRight) {
9913 auto *OpAA = OnlyLeft ? &LHSAAPVS : &RHSAAPVS;
9914 auto Undef = OnlyLeft ? LHSContainsUndef : RHSContainsUndef;
9917 unionAssumedWithUndef();
9919 for (
const auto &It : *OpAA)
9923 }
else if (LHSContainsUndef && RHSContainsUndef) {
9925 unionAssumedWithUndef();
9927 for (
const auto &It : LHSAAPVS)
9929 for (
const auto &It : RHSAAPVS)
9932 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9933 : ChangeStatus::CHANGED;
9936 ChangeStatus updateWithCastInst(Attributor &
A, CastInst *CI) {
9937 auto AssumedBefore = getAssumed();
9939 return indicatePessimisticFixpoint();
9944 bool SrcContainsUndef =
false;
9947 SrcContainsUndef,
false))
9948 return indicatePessimisticFixpoint();
9950 if (SrcContainsUndef)
9951 unionAssumedWithUndef();
9953 for (
const APInt &S : SrcPVS) {
9954 APInt
T = calculateCastInst(CI, S, ResultBitWidth);
9958 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
9959 : ChangeStatus::CHANGED;
9962 ChangeStatus updateWithBinaryOperator(Attributor &
A, BinaryOperator *BinOp) {
9963 auto AssumedBefore = getAssumed();
9967 bool LHSContainsUndef =
false, RHSContainsUndef =
false;
9968 SetTy LHSAAPVS, RHSAAPVS;
9970 LHSContainsUndef,
false) ||
9972 RHSContainsUndef,
false))
9973 return indicatePessimisticFixpoint();
9978 if (LHSContainsUndef && RHSContainsUndef) {
9979 if (!calculateBinaryOperatorAndTakeUnion(BinOp,
Zero,
Zero))
9980 return indicatePessimisticFixpoint();
9981 }
else if (LHSContainsUndef) {
9982 for (
const APInt &R : RHSAAPVS) {
9983 if (!calculateBinaryOperatorAndTakeUnion(BinOp,
Zero, R))
9984 return indicatePessimisticFixpoint();
9986 }
else if (RHSContainsUndef) {
9987 for (
const APInt &L : LHSAAPVS) {
9988 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L,
Zero))
9989 return indicatePessimisticFixpoint();
9992 for (
const APInt &L : LHSAAPVS) {
9993 for (
const APInt &R : RHSAAPVS) {
9994 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, R))
9995 return indicatePessimisticFixpoint();
9999 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
10000 : ChangeStatus::CHANGED;
10003 ChangeStatus updateWithInstruction(Attributor &
A, Instruction *Inst) {
10004 auto AssumedBefore = getAssumed();
10006 bool ContainsUndef;
10008 ContainsUndef,
true))
10009 return indicatePessimisticFixpoint();
10010 if (ContainsUndef) {
10011 unionAssumedWithUndef();
10013 for (
const auto &It : Incoming)
10016 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
10017 : ChangeStatus::CHANGED;
10021 Value &
V = getAssociatedValue();
10025 return updateWithICmpInst(
A, ICI);
10028 return updateWithSelectInst(
A, SI);
10031 return updateWithCastInst(
A, CI);
10034 return updateWithBinaryOperator(
A, BinOp);
10037 return updateWithInstruction(
A,
I);
10039 return indicatePessimisticFixpoint();
10042 void trackStatistics()
const override {
10047struct AAPotentialConstantValuesFunction : AAPotentialConstantValuesImpl {
10048 AAPotentialConstantValuesFunction(
const IRPosition &IRP, Attributor &
A)
10049 : AAPotentialConstantValuesImpl(IRP,
A) {}
10053 "AAPotentialConstantValues(Function|CallSite)::updateImpl will "
10057 void trackStatistics()
const override {
10062struct AAPotentialConstantValuesCallSite : AAPotentialConstantValuesFunction {
10063 AAPotentialConstantValuesCallSite(
const IRPosition &IRP, Attributor &
A)
10064 : AAPotentialConstantValuesFunction(IRP,
A) {}
10066 void trackStatistics()
const override {
10071struct AAPotentialConstantValuesCallSiteReturned
10072 : AACalleeToCallSite<AAPotentialConstantValues,
10073 AAPotentialConstantValuesImpl> {
10074 AAPotentialConstantValuesCallSiteReturned(
const IRPosition &IRP,
10076 : AACalleeToCallSite<AAPotentialConstantValues,
10077 AAPotentialConstantValuesImpl>(IRP,
A) {}
10079 void trackStatistics()
const override {
10084struct AAPotentialConstantValuesCallSiteArgument
10085 : AAPotentialConstantValuesFloating {
10086 AAPotentialConstantValuesCallSiteArgument(
const IRPosition &IRP,
10088 : AAPotentialConstantValuesFloating(IRP,
A) {}
10091 AAPotentialConstantValuesImpl::initialize(
A);
10092 if (isAtFixpoint())
10095 Value &
V = getAssociatedValue();
10098 unionAssumed(
C->getValue());
10099 indicateOptimisticFixpoint();
10104 unionAssumedWithUndef();
10105 indicateOptimisticFixpoint();
10111 Value &
V = getAssociatedValue();
10112 auto AssumedBefore = getAssumed();
10113 auto *AA =
A.getAAFor<AAPotentialConstantValues>(
10116 return indicatePessimisticFixpoint();
10117 const auto &S = AA->getAssumed();
10119 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED
10120 : ChangeStatus::CHANGED;
10123 void trackStatistics()
const override {
10132 bool IgnoreSubsumingPositions) {
10133 assert(ImpliedAttributeKind == Attribute::NoUndef &&
10134 "Unexpected attribute kind");
10135 if (
A.hasAttr(IRP, {Attribute::NoUndef}, IgnoreSubsumingPositions,
10136 Attribute::NoUndef))
10155 Value &
V = getAssociatedValue();
10157 indicatePessimisticFixpoint();
10158 assert(!isImpliedByIR(
A, getIRPosition(), Attribute::NoUndef));
10162 bool followUseInMBEC(Attributor &
A,
const Use *U,
const Instruction *
I,
10163 AANoUndef::StateType &State) {
10164 const Value *UseV =
U->get();
10165 const DominatorTree *DT =
nullptr;
10166 AssumptionCache *AC =
nullptr;
10167 InformationCache &InfoCache =
A.getInfoCache();
10173 bool TrackUse =
false;
10181 const std::string getAsStr(Attributor *
A)
const override {
10182 return getAssumed() ?
"noundef" :
"may-undef-or-poison";
10189 bool UsedAssumedInformation =
false;
10190 if (
A.isAssumedDead(getIRPosition(),
nullptr,
nullptr,
10191 UsedAssumedInformation))
10192 return ChangeStatus::UNCHANGED;
10196 if (!
A.getAssumedSimplified(getIRPosition(), *
this, UsedAssumedInformation,
10199 return ChangeStatus::UNCHANGED;
10200 return AANoUndef::manifest(
A);
10204struct AANoUndefFloating :
public AANoUndefImpl {
10205 AANoUndefFloating(
const IRPosition &IRP, Attributor &
A)
10206 : AANoUndefImpl(IRP,
A) {}
10209 AANoUndefImpl::initialize(
A);
10210 if (!getState().isAtFixpoint() && getAnchorScope() &&
10211 !getAnchorScope()->isDeclaration())
10212 if (Instruction *CtxI = getCtxI())
10213 followUsesInMBEC(*
this,
A, getState(), *CtxI);
10217 auto VisitValueCB = [&](
const IRPosition &IRP) ->
bool {
10218 bool IsKnownNoUndef;
10220 A,
this, IRP, DepClassTy::REQUIRED, IsKnownNoUndef);
10224 bool UsedAssumedInformation =
false;
10225 Value *AssociatedValue = &getAssociatedValue();
10227 if (!
A.getAssumedSimplifiedValues(getIRPosition(), *
this,
Values,
10232 Values.size() != 1 ||
Values.front().getValue() != AssociatedValue;
10240 if (AVIRP == getIRPosition() || !VisitValueCB(AVIRP))
10241 return indicatePessimisticFixpoint();
10242 return ChangeStatus::UNCHANGED;
10245 for (
const auto &VAC :
Values)
10247 return indicatePessimisticFixpoint();
10249 return ChangeStatus::UNCHANGED;
10257static bool checkPoisonGeneratingAttrsHold(
Attributor &
A,
10262 AttributeMask AM = AttributeFuncs::getPoisonGeneratingAttributes();
10268 case Attribute::NonNull: {
10275 case Attribute::Alignment: {
10276 const auto *AlignAA =
10278 if (!AlignAA || AlignAA->getAssumedAlign() < *Attr.
getAlignment())
10282 case Attribute::Range: {
10290 case Attribute::NoFPClass: {
10292 const auto *NoFPClassAA =
10294 if (!NoFPClassAA ||
10295 (NoFPClassAA->getAssumedNoFPClass() & NoFPClass) != NoFPClass)
10308struct AANoUndefReturned final
10309 : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl> {
10310 using Base = AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl>;
10311 AANoUndefReturned(
const IRPosition &IRP, Attributor &
A) :
Base(IRP,
A) {}
10314 Base::initialize(
A);
10315 RetAttrs = getAssociatedFunction()->getAttributes().getRetAttrs();
10321 if (RetAttrs.hasAttributes()) {
10324 return checkPoisonGeneratingAttrsHold(
A, *
this, RetAttrs,
10327 bool UsedAssumedInformation =
false;
10328 if (!
A.checkForAllInstructions(AttrsHold, *
this, {Instruction::Ret},
10329 UsedAssumedInformation))
10330 return indicatePessimisticFixpoint();
10333 return Base::updateImpl(
A);
10340 AttributeSet RetAttrs;
10343struct AANoUndefArgument final
10344 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl> {
10345 AANoUndefArgument(
const IRPosition &IRP, Attributor &
A)
10346 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl>(IRP,
A) {}
10351struct AANoUndefCallSiteArgument final : AANoUndefFloating {
10352 AANoUndefCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
10353 : AANoUndefFloating(IRP,
A) {}
10358struct AANoUndefCallSiteReturned final
10359 : AACalleeToCallSite<AANoUndef, AANoUndefImpl> {
10360 using Base = AACalleeToCallSite<AANoUndef, AANoUndefImpl>;
10361 AANoUndefCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
10365 Base::initialize(
A);
10373 if (RetAttrs.hasAttributes()) {
10376 return checkPoisonGeneratingAttrsHold(
10380 if (!
A.checkForAllCallees(AttrsHold, *
this,
10382 return indicatePessimisticFixpoint();
10385 return Base::updateImpl(
A);
10392 AttributeSet RetAttrs;
10398 AANoFPClassImpl(
const IRPosition &IRP, Attributor &
A) : AANoFPClass(IRP,
A) {}
10401 const IRPosition &IRP = getIRPosition();
10405 indicateOptimisticFixpoint();
10410 A.getAttrs(getIRPosition(), {Attribute::NoFPClass},
Attrs,
false);
10411 for (
const auto &Attr : Attrs) {
10418 const DataLayout &
DL =
A.getDataLayout();
10419 InformationCache &InfoCache =
A.getInfoCache();
10421 const DominatorTree *DT =
nullptr;
10422 AssumptionCache *AC =
nullptr;
10423 const TargetLibraryInfo *
TLI =
nullptr;
10427 if (!
F->isDeclaration()) {
10434 SimplifyQuery Q(
DL,
TLI, DT, AC, CtxI);
10441 followUsesInMBEC(*
this,
A, getState(), *CtxI);
10445 bool followUseInMBEC(Attributor &
A,
const Use *U,
const Instruction *
I,
10446 AANoFPClass::StateType &State) {
10457 if (
auto *NoFPAA =
A.getAAFor<AANoFPClass>(*
this, IRP, DepClassTy::NONE))
10458 State.addKnownBits(NoFPAA->getState().getKnown());
10462 const std::string getAsStr(Attributor *
A)
const override {
10463 std::string
Result =
"nofpclass";
10464 raw_string_ostream OS(Result);
10465 OS << getKnownNoFPClass() <<
'/' << getAssumedNoFPClass();
10469 void getDeducedAttributes(Attributor &
A, LLVMContext &Ctx,
10470 SmallVectorImpl<Attribute> &Attrs)
const override {
10471 Attrs.emplace_back(Attribute::getWithNoFPClass(Ctx, getAssumedNoFPClass()));
10475struct AANoFPClassFloating :
public AANoFPClassImpl {
10476 AANoFPClassFloating(
const IRPosition &IRP, Attributor &
A)
10477 : AANoFPClassImpl(IRP,
A) {}
10481 bool UsedAssumedInformation =
false;
10482 if (!
A.getAssumedSimplifiedValues(getIRPosition(), *
this,
Values,
10484 Values.push_back({getAssociatedValue(), getCtxI()});
10490 DepClassTy::REQUIRED);
10491 if (!AA ||
this == AA) {
10492 T.indicatePessimisticFixpoint();
10494 const AANoFPClass::StateType &S =
10495 static_cast<const AANoFPClass::StateType &
>(AA->
getState());
10498 return T.isValidState();
10501 for (
const auto &VAC :
Values)
10503 return indicatePessimisticFixpoint();
10508 void trackStatistics()
const override {
10513struct AANoFPClassReturned final
10514 : AAReturnedFromReturnedValues<AANoFPClass, AANoFPClassImpl,
10515 AANoFPClassImpl::StateType, false,
10516 Attribute::None, false> {
10517 AANoFPClassReturned(
const IRPosition &IRP, Attributor &
A)
10518 : AAReturnedFromReturnedValues<AANoFPClass, AANoFPClassImpl,
10519 AANoFPClassImpl::StateType,
false,
10522 void trackStatistics()
const override {
10527struct AANoFPClassArgument final
10528 : AAArgumentFromCallSiteArguments<AANoFPClass, AANoFPClassImpl> {
10529 AANoFPClassArgument(
const IRPosition &IRP, Attributor &
A)
10530 : AAArgumentFromCallSiteArguments<AANoFPClass, AANoFPClassImpl>(IRP,
A) {}
10535struct AANoFPClassCallSiteArgument final : AANoFPClassFloating {
10536 AANoFPClassCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
10537 : AANoFPClassFloating(IRP,
A) {}
10539 void trackStatistics()
const override {
10544struct AANoFPClassCallSiteReturned final
10545 : AACalleeToCallSite<AANoFPClass, AANoFPClassImpl> {
10546 AANoFPClassCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
10547 : AACalleeToCallSite<AANoFPClass, AANoFPClassImpl>(IRP,
A) {}
10549 void trackStatistics()
const override {
10555 AACallEdgesImpl(
const IRPosition &IRP, Attributor &
A) : AACallEdges(IRP,
A) {}
10557 const SetVector<Function *> &getOptimisticEdges()
const override {
10558 return CalledFunctions;
10561 bool hasUnknownCallee()
const override {
return HasUnknownCallee; }
10563 bool hasNonAsmUnknownCallee()
const override {
10564 return HasUnknownCalleeNonAsm;
10567 const std::string getAsStr(Attributor *
A)
const override {
10568 return "CallEdges[" + std::to_string(HasUnknownCallee) +
"," +
10569 std::to_string(CalledFunctions.size()) +
"]";
10572 void trackStatistics()
const override {}
10577 static Function *getOnlyCallee(
const CallBase &CB) {
10579 if (Callee && !
Callee->hasMetadata(LLVMContext::MD_callback))
10585 if (CalledFunctions.insert(Fn)) {
10586 Change = ChangeStatus::CHANGED;
10592 void setHasUnknownCallee(
bool NonAsm,
ChangeStatus &Change) {
10593 if (!HasUnknownCallee)
10594 Change = ChangeStatus::CHANGED;
10595 if (NonAsm && !HasUnknownCalleeNonAsm)
10596 Change = ChangeStatus::CHANGED;
10597 HasUnknownCalleeNonAsm |= NonAsm;
10598 HasUnknownCallee =
true;
10603 SetVector<Function *> CalledFunctions;
10606 bool HasUnknownCallee =
false;
10609 bool HasUnknownCalleeNonAsm =
false;
10612struct AACallEdgesCallSite :
public AACallEdgesImpl {
10613 AACallEdgesCallSite(
const IRPosition &IRP, Attributor &
A)
10614 : AACallEdgesImpl(IRP,
A) {}
10620 addCalledFunction(Callee, Change);
10621 indicateOptimisticFixpoint();
10630 addCalledFunction(Fn, Change);
10632 LLVM_DEBUG(
dbgs() <<
"[AACallEdges] Unrecognized value: " <<
V <<
"\n");
10633 setHasUnknownCallee(
true, Change);
10644 VisitValue(*
V, CtxI);
10648 bool UsedAssumedInformation =
false;
10652 Values.push_back({*
V, CtxI});
10654 for (
auto &VAC :
Values)
10661 if (
IA->hasSideEffects() &&
10664 setHasUnknownCallee(
false, Change);
10670 if (
auto *IndirectCallAA =
A.getAAFor<AAIndirectCallInfo>(
10671 *
this, getIRPosition(), DepClassTy::OPTIONAL))
10672 if (IndirectCallAA->foreachCallee(
10673 [&](
Function *Fn) { return VisitValue(*Fn, CB); }))
10682 for (
const Use *U : CallbackUses)
10683 ProcessCalledOperand(
U->get(), CB);
10689struct AACallEdgesFunction :
public AACallEdgesImpl {
10690 AACallEdgesFunction(
const IRPosition &IRP, Attributor &
A)
10691 : AACallEdgesImpl(IRP,
A) {}
10695 bool AllCallsDirect =
true;
10702 if (
Function *Callee = getOnlyCallee(CB)) {
10703 addCalledFunction(Callee, Change);
10707 AllCallsDirect =
false;
10708 auto *CBEdges =
A.getAAFor<AACallEdges>(
10712 if (CBEdges->hasNonAsmUnknownCallee())
10713 setHasUnknownCallee(
true, Change);
10714 if (CBEdges->hasUnknownCallee())
10715 setHasUnknownCallee(
false, Change);
10717 for (
Function *
F : CBEdges->getOptimisticEdges())
10718 addCalledFunction(
F, Change);
10724 bool UsedAssumedInformation =
false;
10725 if (!
A.checkForAllCallLikeInstructions(ProcessCallInst, *
this,
10726 UsedAssumedInformation,
10730 setHasUnknownCallee(
true, Change);
10734 if (AllCallsDirect && !UsedAssumedInformation)
10735 indicateOptimisticFixpoint();
10743struct AAInterFnReachabilityFunction
10744 :
public CachedReachabilityAA<AAInterFnReachability, Function> {
10745 using Base = CachedReachabilityAA<AAInterFnReachability, Function>;
10746 AAInterFnReachabilityFunction(
const IRPosition &IRP, Attributor &
A)
10749 bool instructionCanReach(
10750 Attributor &
A,
const Instruction &From,
const Function &To,
10753 auto *NonConstThis =
const_cast<AAInterFnReachabilityFunction *
>(
this);
10755 RQITy StackRQI(
A, From, To, ExclusionSet,
false);
10756 RQITy::Reachable
Result;
10757 if (!NonConstThis->checkQueryCache(
A, StackRQI, Result))
10758 return NonConstThis->isReachableImpl(
A, StackRQI,
10760 return Result == RQITy::Reachable::Yes;
10764 bool IsTemporaryRQI)
override {
10766 &RQI.From->getFunction()->getEntryBlock().front();
10767 if (EntryI != RQI.From &&
10768 !instructionCanReach(
A, *EntryI, *RQI.To,
nullptr))
10769 return rememberResult(
A, RQITy::Reachable::No, RQI,
false,
10772 auto CheckReachableCallBase = [&](CallBase *CB) {
10773 auto *CBEdges =
A.getAAFor<AACallEdges>(
10775 if (!CBEdges || !CBEdges->getState().isValidState())
10778 if (CBEdges->hasUnknownCallee())
10781 for (
Function *Fn : CBEdges->getOptimisticEdges()) {
10792 if (Fn == getAnchorScope()) {
10793 if (EntryI == RQI.From)
10798 const AAInterFnReachability *InterFnReachability =
10800 DepClassTy::OPTIONAL);
10803 if (!InterFnReachability ||
10811 const auto *IntraFnReachability =
A.getAAFor<AAIntraFnReachability>(
10813 DepClassTy::OPTIONAL);
10821 return IntraFnReachability && !IntraFnReachability->isAssumedReachable(
10822 A, *RQI.From, CBInst, RQI.ExclusionSet);
10825 bool UsedExclusionSet =
true;
10826 bool UsedAssumedInformation =
false;
10827 if (!
A.checkForAllCallLikeInstructions(CheckCallBase, *
this,
10828 UsedAssumedInformation,
10830 return rememberResult(
A, RQITy::Reachable::Yes, RQI, UsedExclusionSet,
10833 return rememberResult(
A, RQITy::Reachable::No, RQI, UsedExclusionSet,
10837 void trackStatistics()
const override {}
10841template <
typename AAType>
10842static std::optional<Constant *>
10845 if (!Ty.isIntegerTy())
10853 std::optional<Constant *> COpt =
AA->getAssumedConstant(
A);
10855 if (!COpt.has_value()) {
10857 return std::nullopt;
10859 if (
auto *
C = *COpt) {
10870 std::optional<Value *> V;
10871 for (
auto &It :
Values) {
10873 if (V.has_value() && !*V)
10876 if (!V.has_value())
10889 if (
A.hasSimplificationCallback(getIRPosition())) {
10890 indicatePessimisticFixpoint();
10893 Value *Stripped = getAssociatedValue().stripPointerCasts();
10895 addValue(
A, getState(), *Stripped, getCtxI(),
AA::AnyScope,
10897 indicateOptimisticFixpoint();
10900 AAPotentialValues::initialize(
A);
10903 const std::string getAsStr(Attributor *
A)
const override {
10905 llvm::raw_string_ostream OS(Str);
10910 template <
typename AAType>
10911 static std::optional<Value *> askOtherAA(Attributor &
A,
10912 const AbstractAttribute &AA,
10913 const IRPosition &IRP,
Type &Ty) {
10918 return std::nullopt;
10925 virtual void addValue(Attributor &
A, StateType &State,
Value &
V,
10931 for (
const auto &U : CB->
args()) {
10941 Type &Ty = *getAssociatedType();
10942 std::optional<Value *> SimpleV =
10943 askOtherAA<AAValueConstantRange>(
A, *
this, ValIRP, Ty);
10944 if (SimpleV.has_value() && !*SimpleV) {
10945 auto *PotentialConstantsAA =
A.getAAFor<AAPotentialConstantValues>(
10946 *
this, ValIRP, DepClassTy::OPTIONAL);
10947 if (PotentialConstantsAA && PotentialConstantsAA->isValidState()) {
10948 for (
const auto &It : PotentialConstantsAA->getAssumedSet())
10949 State.unionAssumed({{*ConstantInt::get(&Ty, It),
nullptr}, S});
10950 if (PotentialConstantsAA->undefIsContained())
10955 if (!SimpleV.has_value())
10967 State.unionAssumed({{*VPtr, CtxI}, S});
10973 AA::ValueAndContext
I;
10977 return II.I ==
I &&
II.S == S;
10980 return std::tie(
I, S) < std::tie(
II.I,
II.S);
10984 bool recurseForValue(Attributor &
A,
const IRPosition &IRP,
AA::ValueScope S) {
10985 SmallMapVector<AA::ValueAndContext, int, 8> ValueScopeMap;
10990 bool UsedAssumedInformation =
false;
10992 if (!
A.getAssumedSimplifiedValues(IRP,
this,
Values, CS,
10993 UsedAssumedInformation))
10997 ValueScopeMap[It] += CS;
10999 for (
auto &It : ValueScopeMap)
11000 addValue(
A, getState(), *It.first.getValue(), It.first.getCtxI(),
11006 void giveUpOnIntraprocedural(Attributor &
A) {
11007 auto NewS = StateType::getBestState(getState());
11008 for (
const auto &It : getAssumedSet()) {
11011 addValue(
A, NewS, *It.first.getValue(), It.first.getCtxI(),
11014 assert(!undefIsContained() &&
"Undef should be an explicit value!");
11021 getState() = StateType::getBestState(getState());
11022 getState().unionAssumed({{getAssociatedValue(), getCtxI()},
AA::AnyScope});
11023 AAPotentialValues::indicateOptimisticFixpoint();
11024 return ChangeStatus::CHANGED;
11028 return indicatePessimisticFixpoint();
11035 if (!getAssumedSimplifiedValues(
A,
Values, S))
11037 Value &OldV = getAssociatedValue();
11040 Value *NewV = getSingleValue(
A, *
this, getIRPosition(),
Values);
11041 if (!NewV || NewV == &OldV)
11046 if (
A.changeAfterManifest(getIRPosition(), *NewV))
11047 return ChangeStatus::CHANGED;
11049 return ChangeStatus::UNCHANGED;
11052 bool getAssumedSimplifiedValues(
11053 Attributor &
A, SmallVectorImpl<AA::ValueAndContext> &
Values,
11054 AA::ValueScope S,
bool RecurseForSelectAndPHI =
false)
const override {
11055 if (!isValidState())
11057 bool UsedAssumedInformation =
false;
11058 for (
const auto &It : getAssumedSet())
11059 if (It.second & S) {
11060 if (RecurseForSelectAndPHI && (
isa<PHINode>(It.first.getValue()) ||
11062 if (
A.getAssumedSimplifiedValues(
11064 this,
Values, S, UsedAssumedInformation))
11067 Values.push_back(It.first);
11069 assert(!undefIsContained() &&
"Undef should be an explicit value!");
11074struct AAPotentialValuesFloating : AAPotentialValuesImpl {
11075 AAPotentialValuesFloating(
const IRPosition &IRP, Attributor &
A)
11076 : AAPotentialValuesImpl(IRP,
A) {}
11079 auto AssumedBefore = getAssumed();
11081 genericValueTraversal(
A, &getAssociatedValue());
11083 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11084 : ChangeStatus::CHANGED;
11088 struct LivenessInfo {
11089 const AAIsDead *LivenessAA =
nullptr;
11090 bool AnyDead =
false;
11100 SmallVectorImpl<ItemInfo> &Worklist) {
11103 bool UsedAssumedInformation =
false;
11105 auto GetSimplifiedValues = [&](
Value &
V,
11107 if (!
A.getAssumedSimplifiedValues(
11111 Values.push_back(AA::ValueAndContext{
V,
II.I.getCtxI()});
11115 if (GetSimplifiedValues(*
LHS, LHSValues))
11117 if (GetSimplifiedValues(*
RHS, RHSValues))
11122 InformationCache &InfoCache =
A.getInfoCache();
11129 F ?
A.getInfoCache().getTargetLibraryInfoForFunction(*
F) :
nullptr;
11134 const DataLayout &
DL =
A.getDataLayout();
11135 SimplifyQuery Q(
DL,
TLI, DT, AC, CmpI);
11137 auto CheckPair = [&](
Value &LHSV,
Value &RHSV) {
11140 nullptr,
II.S, getAnchorScope());
11146 if (&LHSV == &RHSV &&
11148 Constant *NewV = ConstantInt::get(Type::getInt1Ty(Ctx),
11150 addValue(
A, getState(), *NewV,
nullptr,
II.S,
11157 if (TypedLHS && TypedRHS) {
11159 if (NewV && NewV != &Cmp) {
11160 addValue(
A, getState(), *NewV,
nullptr,
II.S,
11172 if (!LHSIsNull && !RHSIsNull)
11178 assert((LHSIsNull || RHSIsNull) &&
11179 "Expected nullptr versus non-nullptr comparison at this point");
11182 unsigned PtrIdx = LHSIsNull;
11183 bool IsKnownNonNull;
11186 DepClassTy::REQUIRED, IsKnownNonNull);
11187 if (!IsAssumedNonNull)
11193 addValue(
A, getState(), *NewV,
nullptr,
II.S,
11198 for (
auto &LHSValue : LHSValues)
11199 for (
auto &RHSValue : RHSValues)
11200 if (!CheckPair(*LHSValue.getValue(), *RHSValue.getValue()))
11205 bool handleSelectInst(Attributor &
A, SelectInst &SI, ItemInfo
II,
11206 SmallVectorImpl<ItemInfo> &Worklist) {
11208 bool UsedAssumedInformation =
false;
11210 std::optional<Constant *>
C =
11211 A.getAssumedConstant(*
SI.getCondition(), *
this, UsedAssumedInformation);
11212 bool NoValueYet = !
C.has_value();
11220 }
else if (&SI == &getAssociatedValue()) {
11225 std::optional<Value *> SimpleV =
A.getAssumedSimplified(
11227 if (!SimpleV.has_value())
11230 addValue(
A, getState(), **SimpleV, CtxI,
II.S, getAnchorScope());
11238 bool handleLoadInst(Attributor &
A, LoadInst &LI, ItemInfo
II,
11239 SmallVectorImpl<ItemInfo> &Worklist) {
11240 SmallSetVector<Value *, 4> PotentialCopies;
11241 SmallSetVector<Instruction *, 4> PotentialValueOrigins;
11242 bool UsedAssumedInformation =
false;
11244 PotentialValueOrigins, *
this,
11245 UsedAssumedInformation,
11247 LLVM_DEBUG(
dbgs() <<
"[AAPotentialValues] Failed to get potentially "
11248 "loaded values for load instruction "
11256 InformationCache &InfoCache =
A.getInfoCache();
11258 if (!
llvm::all_of(PotentialValueOrigins, [&](Instruction *
I) {
11262 return A.isAssumedDead(
SI->getOperandUse(0),
this,
11264 UsedAssumedInformation,
11266 return A.isAssumedDead(*
I,
this,
nullptr,
11267 UsedAssumedInformation,
11270 LLVM_DEBUG(
dbgs() <<
"[AAPotentialValues] Load is onl used by assumes "
11271 "and we cannot delete all the stores: "
11282 bool AllLocal = ScopeIsLocal;
11287 if (!DynamicallyUnique) {
11288 LLVM_DEBUG(
dbgs() <<
"[AAPotentialValues] Not all potentially loaded "
11289 "values are dynamically unique: "
11294 for (
auto *PotentialCopy : PotentialCopies) {
11296 Worklist.
push_back({{*PotentialCopy, CtxI},
II.S});
11301 if (!AllLocal && ScopeIsLocal)
11306 bool handlePHINode(
11307 Attributor &
A, PHINode &
PHI, ItemInfo
II,
11308 SmallVectorImpl<ItemInfo> &Worklist,
11309 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) {
11310 auto GetLivenessInfo = [&](
const Function &
F) -> LivenessInfo & {
11311 LivenessInfo &LI = LivenessAAs[&
F];
11312 if (!LI.LivenessAA)
11318 if (&
PHI == &getAssociatedValue()) {
11319 LivenessInfo &LI = GetLivenessInfo(*
PHI.getFunction());
11321 A.getInfoCache().getAnalysisResultForFunction<CycleAnalysis>(
11322 *
PHI.getFunction());
11326 for (
unsigned u = 0, e =
PHI.getNumIncomingValues(); u < e; u++) {
11328 if (LI.LivenessAA &&
11329 LI.LivenessAA->isEdgeDead(IncomingBB,
PHI.getParent())) {
11348 bool UsedAssumedInformation =
false;
11349 std::optional<Value *> SimpleV =
A.getAssumedSimplified(
11351 if (!SimpleV.has_value())
11355 addValue(
A, getState(), **SimpleV, &
PHI,
II.S, getAnchorScope());
11362 bool handleGenericInst(Attributor &
A, Instruction &
I, ItemInfo
II,
11363 SmallVectorImpl<ItemInfo> &Worklist) {
11364 bool SomeSimplified =
false;
11365 bool UsedAssumedInformation =
false;
11367 SmallVector<Value *, 8> NewOps(
I.getNumOperands());
11370 const auto &SimplifiedOp =
A.getAssumedSimplified(
11375 if (!SimplifiedOp.has_value())
11379 NewOps[
Idx] = *SimplifiedOp;
11383 SomeSimplified |= (NewOps[
Idx] !=
Op);
11389 if (!SomeSimplified)
11392 InformationCache &InfoCache =
A.getInfoCache();
11396 const auto *
TLI =
A.getInfoCache().getTargetLibraryInfoForFunction(*
F);
11399 const DataLayout &
DL =
I.getDataLayout();
11400 SimplifyQuery Q(
DL,
TLI, DT, AC, &
I);
11402 if (!NewV || NewV == &
I)
11405 LLVM_DEBUG(
dbgs() <<
"Generic inst " <<
I <<
" assumed simplified to "
11412 Attributor &
A, Instruction &
I, ItemInfo
II,
11413 SmallVectorImpl<ItemInfo> &Worklist,
11414 SmallMapVector<const Function *, LivenessInfo, 4> &LivenessAAs) {
11417 CI->getPredicate(),
II, Worklist);
11419 switch (
I.getOpcode()) {
11420 case Instruction::Select:
11422 case Instruction::PHI:
11424 case Instruction::Load:
11427 return handleGenericInst(
A,
I,
II, Worklist);
11432 void genericValueTraversal(Attributor &
A,
Value *InitialV) {
11433 SmallMapVector<const Function *, LivenessInfo, 4> LivenessAAs;
11435 SmallSet<ItemInfo, 16> Visited;
11453 if (Iteration++ >=
A.Opts.attributor_max_potential_values_iterations) {
11454 LLVM_DEBUG(
dbgs() <<
"Generic value traversal reached iteration limit: "
11455 << Iteration <<
"!\n");
11456 addValue(
A, getState(), *
V, CtxI, S, getAnchorScope());
11462 Value *NewV =
nullptr;
11463 if (
V->getType()->isPointerTy()) {
11469 for (Argument &Arg :
Callee->args())
11476 if (NewV && NewV !=
V) {
11477 Worklist.
push_back({{*NewV, CtxI}, S});
11491 if (
V == InitialV && CtxI == getCtxI()) {
11492 indicatePessimisticFixpoint();
11496 addValue(
A, getState(), *
V, CtxI, S, getAnchorScope());
11497 }
while (!Worklist.
empty());
11501 for (
auto &It : LivenessAAs)
11502 if (It.second.AnyDead)
11503 A.recordDependence(*It.second.LivenessAA, *
this, DepClassTy::OPTIONAL);
11506 void trackStatistics()
const override {
11511struct AAPotentialValuesArgument final : AAPotentialValuesImpl {
11512 using Base = AAPotentialValuesImpl;
11513 AAPotentialValuesArgument(
const IRPosition &IRP, Attributor &
A)
11519 indicatePessimisticFixpoint();
11523 auto AssumedBefore = getAssumed();
11525 unsigned ArgNo = getCalleeArgNo();
11527 bool UsedAssumedInformation =
false;
11529 auto CallSitePred = [&](AbstractCallSite ACS) {
11531 if (CSArgIRP.getPositionKind() == IRP_INVALID)
11534 if (!
A.getAssumedSimplifiedValues(CSArgIRP,
this,
Values,
11536 UsedAssumedInformation))
11539 return isValidState();
11542 if (!
A.checkForAllCallSites(CallSitePred, *
this,
11544 UsedAssumedInformation))
11545 return indicatePessimisticFixpoint();
11547 Function *Fn = getAssociatedFunction();
11548 bool AnyNonLocal =
false;
11549 for (
auto &It :
Values) {
11551 addValue(
A, getState(), *It.getValue(), It.getCtxI(),
AA::AnyScope,
11556 return indicatePessimisticFixpoint();
11560 addValue(
A, getState(), *It.getValue(), It.getCtxI(),
AA::AnyScope,
11566 AnyNonLocal =
true;
11568 assert(!undefIsContained() &&
"Undef should be an explicit value!");
11570 giveUpOnIntraprocedural(
A);
11572 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11573 : ChangeStatus::CHANGED;
11576 void trackStatistics()
const override {
11581struct AAPotentialValuesReturned :
public AAPotentialValuesFloating {
11582 using Base = AAPotentialValuesFloating;
11583 AAPotentialValuesReturned(
const IRPosition &IRP, Attributor &
A)
11588 if (!
F ||
F->isDeclaration() ||
F->getReturnType()->isVoidTy()) {
11589 indicatePessimisticFixpoint();
11593 for (Argument &Arg :
F->args())
11596 ReturnedArg = &Arg;
11599 if (!
A.isFunctionIPOAmendable(*
F) ||
11600 A.hasSimplificationCallback(getIRPosition())) {
11602 indicatePessimisticFixpoint();
11604 indicateOptimisticFixpoint();
11609 auto AssumedBefore = getAssumed();
11610 bool UsedAssumedInformation =
false;
11613 Function *AnchorScope = getAnchorScope();
11619 UsedAssumedInformation,
11625 bool AllInterAreIntra =
false;
11632 for (
const AA::ValueAndContext &VAC :
Values) {
11633 addValue(
A, getState(), *VAC.
getValue(),
11637 if (AllInterAreIntra)
11644 HandleReturnedValue(*ReturnedArg,
nullptr,
true);
11647 bool AddValues =
true;
11650 addValue(
A, getState(), *RetI.getOperand(0), &RetI,
AA::AnyScope,
11654 return HandleReturnedValue(*RetI.getOperand(0), &RetI, AddValues);
11657 if (!
A.checkForAllInstructions(RetInstPred, *
this, {Instruction::Ret},
11658 UsedAssumedInformation,
11660 return indicatePessimisticFixpoint();
11663 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11664 : ChangeStatus::CHANGED;
11669 return ChangeStatus::UNCHANGED;
11671 if (!getAssumedSimplifiedValues(
A,
Values, AA::ValueScope::Intraprocedural,
11673 return ChangeStatus::UNCHANGED;
11674 Value *NewVal = getSingleValue(
A, *
this, getIRPosition(),
Values);
11676 return ChangeStatus::UNCHANGED;
11681 "Number of function with unique return");
11684 {Attribute::get(Arg->
getContext(), Attribute::Returned)});
11689 Value *RetOp = RetI.getOperand(0);
11693 if (
A.changeUseAfterManifest(RetI.getOperandUse(0), *NewVal))
11694 Changed = ChangeStatus::CHANGED;
11697 bool UsedAssumedInformation =
false;
11698 (void)
A.checkForAllInstructions(RetInstPred, *
this, {Instruction::Ret},
11699 UsedAssumedInformation,
11705 return AAPotentialValues::indicatePessimisticFixpoint();
11708 void trackStatistics()
const override{
11715struct AAPotentialValuesFunction : AAPotentialValuesImpl {
11716 AAPotentialValuesFunction(
const IRPosition &IRP, Attributor &
A)
11717 : AAPotentialValuesImpl(IRP,
A) {}
11724 void trackStatistics()
const override {
11729struct AAPotentialValuesCallSite : AAPotentialValuesFunction {
11730 AAPotentialValuesCallSite(
const IRPosition &IRP, Attributor &
A)
11731 : AAPotentialValuesFunction(IRP,
A) {}
11733 void trackStatistics()
const override {
11738struct AAPotentialValuesCallSiteReturned : AAPotentialValuesImpl {
11739 AAPotentialValuesCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
11740 : AAPotentialValuesImpl(IRP,
A) {}
11743 auto AssumedBefore = getAssumed();
11747 return indicatePessimisticFixpoint();
11749 bool UsedAssumedInformation =
false;
11753 UsedAssumedInformation))
11754 return indicatePessimisticFixpoint();
11761 Values, S, UsedAssumedInformation))
11764 for (
auto &It :
Values) {
11765 Value *
V = It.getValue();
11766 std::optional<Value *> CallerV =
A.translateArgumentToCallSiteContent(
11767 V, *CB, *
this, UsedAssumedInformation);
11768 if (!CallerV.has_value()) {
11772 V = *CallerV ? *CallerV :
V;
11778 giveUpOnIntraprocedural(
A);
11781 addValue(
A, getState(), *
V, CB, S, getAnchorScope());
11786 return indicatePessimisticFixpoint();
11788 return indicatePessimisticFixpoint();
11789 return (AssumedBefore == getAssumed()) ? ChangeStatus::UNCHANGED
11790 : ChangeStatus::CHANGED;
11794 return AAPotentialValues::indicatePessimisticFixpoint();
11797 void trackStatistics()
const override {
11802struct AAPotentialValuesCallSiteArgument : AAPotentialValuesFloating {
11803 AAPotentialValuesCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
11804 : AAPotentialValuesFloating(IRP,
A) {}
11806 void trackStatistics()
const override {
11815 AAAssumptionInfoImpl(
const IRPosition &IRP, Attributor &
A,
11816 const DenseSet<StringRef> &
Known)
11817 : AAAssumptionInfo(IRP,
A,
Known) {}
11821 if (getKnown().isUniversal())
11822 return ChangeStatus::UNCHANGED;
11824 const IRPosition &IRP = getIRPosition();
11826 getAssumed().getSet().
end());
11828 return A.manifestAttrs(IRP,
11835 bool hasAssumption(
const StringRef Assumption)
const override {
11836 return isValidState() && setContains(Assumption);
11839 const std::string getAsStr(Attributor *
A)
const override {
11840 const SetContents &
Known = getKnown();
11841 const SetContents &Assumed = getAssumed();
11845 const std::string KnownStr =
llvm::join(Set,
",");
11847 std::string AssumedStr =
"Universal";
11848 if (!Assumed.isUniversal()) {
11849 Set.assign(Assumed.getSet().begin(), Assumed.getSet().end());
11852 return "Known [" + KnownStr +
"]," +
" Assumed [" + AssumedStr +
"]";
11867struct AAAssumptionInfoFunction final : AAAssumptionInfoImpl {
11868 AAAssumptionInfoFunction(
const IRPosition &IRP, Attributor &
A)
11869 : AAAssumptionInfoImpl(IRP,
A,
11875 auto CallSitePred = [&](AbstractCallSite ACS) {
11876 const auto *AssumptionAA =
A.getAAFor<AAAssumptionInfo>(
11878 DepClassTy::REQUIRED);
11882 Changed |= getIntersection(AssumptionAA->getAssumed());
11883 return !getAssumed().empty() || !getKnown().empty();
11886 bool UsedAssumedInformation =
false;
11891 if (!
A.checkForAllCallSites(CallSitePred, *
this,
true,
11892 UsedAssumedInformation))
11893 return indicatePessimisticFixpoint();
11895 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
11898 void trackStatistics()
const override {}
11902struct AAAssumptionInfoCallSite final : AAAssumptionInfoImpl {
11904 AAAssumptionInfoCallSite(
const IRPosition &IRP, Attributor &
A)
11905 : AAAssumptionInfoImpl(IRP,
A, getInitialAssumptions(IRP)) {}
11909 A.getAAFor<AAAssumptionInfo>(*
this, FnPos, DepClassTy::REQUIRED);
11914 auto *AssumptionAA =
11915 A.getAAFor<AAAssumptionInfo>(*
this, FnPos, DepClassTy::REQUIRED);
11917 return indicatePessimisticFixpoint();
11918 bool Changed = getIntersection(AssumptionAA->getAssumed());
11919 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
11922 void trackStatistics()
const override {}
11927 DenseSet<StringRef> getInitialAssumptions(
const IRPosition &IRP) {
11934 return Assumptions;
11949struct AAUnderlyingObjectsImpl
11954 const std::string getAsStr(
Attributor *
A)
const override {
11955 if (!isValidState())
11956 return "<invalid>";
11959 OS <<
"underlying objects: inter " << InterAssumedUnderlyingObjects.size()
11960 <<
" objects, intra " << IntraAssumedUnderlyingObjects.size()
11962 if (!InterAssumedUnderlyingObjects.empty()) {
11963 OS <<
"inter objects:\n";
11964 for (
auto *Obj : InterAssumedUnderlyingObjects)
11965 OS << *Obj <<
'\n';
11967 if (!IntraAssumedUnderlyingObjects.empty()) {
11968 OS <<
"intra objects:\n";
11969 for (
auto *Obj : IntraAssumedUnderlyingObjects)
11970 OS << *
Obj <<
'\n';
11975 void trackStatistics()
const override {}
11978 auto &Ptr = getAssociatedValue();
11980 bool UsedAssumedInformation =
false;
11981 auto DoUpdate = [&](SmallSetVector<Value *, 8> &UnderlyingObjects,
11983 SmallPtrSet<Value *, 8> SeenObjects;
11987 Scope, UsedAssumedInformation))
11988 return UnderlyingObjects.
insert(&Ptr);
11992 for (
unsigned I = 0;
I <
Values.size(); ++
I) {
11996 if (!SeenObjects.
insert(UO ? UO : Obj).second)
11998 if (UO && UO != Obj) {
12004 const auto *OtherAA =
A.getAAFor<AAUnderlyingObjects>(
12010 Values.emplace_back(
V,
nullptr);
12014 if (!OtherAA || !OtherAA->forallUnderlyingObjects(
Pred, Scope))
12016 "The forall call should not return false at this position");
12022 Changed |= handleIndirect(
A, *Obj, UnderlyingObjects, Scope,
12023 UsedAssumedInformation);
12029 for (
unsigned u = 0, e =
PHI->getNumIncomingValues(); u < e; u++) {
12031 handleIndirect(
A, *
PHI->getIncomingValue(u), UnderlyingObjects,
12032 Scope, UsedAssumedInformation);
12046 if (!UsedAssumedInformation)
12047 indicateOptimisticFixpoint();
12048 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
12051 bool forallUnderlyingObjects(
12054 if (!isValidState())
12055 return Pred(getAssociatedValue());
12058 ? IntraAssumedUnderlyingObjects
12059 : InterAssumedUnderlyingObjects;
12060 for (
Value *Obj : AssumedUnderlyingObjects)
12070 bool handleIndirect(Attributor &
A,
Value &
V,
12071 SmallSetVector<Value *, 8> &UnderlyingObjects,
12074 const auto *AA =
A.getAAFor<AAUnderlyingObjects>(
12080 if (!AA || !AA->forallUnderlyingObjects(
Pred, Scope))
12082 "The forall call should not return false at this position");
12088 SmallSetVector<Value *, 8> IntraAssumedUnderlyingObjects;
12090 SmallSetVector<Value *, 8> InterAssumedUnderlyingObjects;
12093struct AAUnderlyingObjectsFloating final : AAUnderlyingObjectsImpl {
12094 AAUnderlyingObjectsFloating(
const IRPosition &IRP, Attributor &
A)
12095 : AAUnderlyingObjectsImpl(IRP,
A) {}
12098struct AAUnderlyingObjectsArgument final : AAUnderlyingObjectsImpl {
12099 AAUnderlyingObjectsArgument(
const IRPosition &IRP, Attributor &
A)
12100 : AAUnderlyingObjectsImpl(IRP,
A) {}
12103struct AAUnderlyingObjectsCallSite final : AAUnderlyingObjectsImpl {
12104 AAUnderlyingObjectsCallSite(
const IRPosition &IRP, Attributor &
A)
12105 : AAUnderlyingObjectsImpl(IRP,
A) {}
12108struct AAUnderlyingObjectsCallSiteArgument final : AAUnderlyingObjectsImpl {
12109 AAUnderlyingObjectsCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
12110 : AAUnderlyingObjectsImpl(IRP,
A) {}
12113struct AAUnderlyingObjectsReturned final : AAUnderlyingObjectsImpl {
12114 AAUnderlyingObjectsReturned(
const IRPosition &IRP, Attributor &
A)
12115 : AAUnderlyingObjectsImpl(IRP,
A) {}
12118struct AAUnderlyingObjectsCallSiteReturned final : AAUnderlyingObjectsImpl {
12119 AAUnderlyingObjectsCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
12120 : AAUnderlyingObjectsImpl(IRP,
A) {}
12123struct AAUnderlyingObjectsFunction final : AAUnderlyingObjectsImpl {
12124 AAUnderlyingObjectsFunction(
const IRPosition &IRP, Attributor &
A)
12125 : AAUnderlyingObjectsImpl(IRP,
A) {}
12132 AAGlobalValueInfoFloating(
const IRPosition &IRP, Attributor &
A)
12133 : AAGlobalValueInfo(IRP,
A) {}
12137 bool checkUse(Attributor &
A,
const Use &U,
bool &Follow,
12138 SmallVectorImpl<const Value *> &Worklist) {
12144 if (!GV->hasLocalLinkage() && !
A.isClosedWorldModule())
12150 LLVM_DEBUG(
dbgs() <<
"[AAGlobalValueInfo] Check use: " << *
U.get() <<
" in "
12151 << *UInst <<
"\n");
12154 int Idx = &
Cmp->getOperandUse(0) == &
U;
12157 return U == &getAnchorValue();
12162 auto CallSitePred = [&](AbstractCallSite ACS) {
12163 Worklist.
push_back(ACS.getInstruction());
12166 bool UsedAssumedInformation =
false;
12168 if (!
A.checkForAllCallSites(CallSitePred, *UInst->
getFunction(),
12170 UsedAssumedInformation))
12188 if (!Fn || !
A.isFunctionIPOAmendable(*Fn))
12197 unsigned NumUsesBefore =
Uses.size();
12199 SmallPtrSet<const Value *, 8> Visited;
12203 auto UsePred = [&](
const Use &
U,
bool &Follow) ->
bool {
12211 return checkUse(
A, U, Follow, Worklist);
12213 auto EquivalentUseCB = [&](
const Use &OldU,
const Use &NewU) {
12214 Uses.insert(&OldU);
12218 while (!Worklist.
empty()) {
12220 if (!Visited.
insert(
V).second)
12222 if (!
A.checkForAllUses(UsePred, *
this, *
V,
12224 DepClassTy::OPTIONAL,
12225 true, EquivalentUseCB)) {
12226 return indicatePessimisticFixpoint();
12230 return Uses.size() == NumUsesBefore ? ChangeStatus::UNCHANGED
12231 : ChangeStatus::CHANGED;
12234 bool isPotentialUse(
const Use &U)
const override {
12235 return !isValidState() ||
Uses.contains(&U);
12239 return ChangeStatus::UNCHANGED;
12242 const std::string getAsStr(Attributor *
A)
const override {
12243 return "[" + std::to_string(
Uses.size()) +
" uses]";
12246 void trackStatistics()
const override {
12252 SmallPtrSet<const Use *, 8>
Uses;
12259 AAIndirectCallInfoCallSite(
const IRPosition &IRP, Attributor &
A)
12260 : AAIndirectCallInfo(IRP,
A) {}
12263 auto *MD = getCtxI()->getMetadata(LLVMContext::MD_callees);
12264 if (!MD && !
A.isClosedWorldModule())
12268 for (
const auto &
Op : MD->operands())
12270 PotentialCallees.insert(Callee);
12271 }
else if (
A.isClosedWorldModule()) {
12273 A.getInfoCache().getIndirectlyCallableFunctions(
A);
12274 PotentialCallees.insert_range(IndirectlyCallableFunctions);
12277 if (PotentialCallees.empty())
12278 indicateOptimisticFixpoint();
12286 SmallSetVector<Function *, 4> AssumedCalleesNow;
12287 bool AllCalleesKnownNow = AllCalleesKnown;
12289 auto CheckPotentialCalleeUse = [&](
Function &PotentialCallee,
12290 bool &UsedAssumedInformation) {
12291 const auto *GIAA =
A.getAAFor<AAGlobalValueInfo>(
12293 if (!GIAA || GIAA->isPotentialUse(CalleeUse))
12295 UsedAssumedInformation = !GIAA->isAtFixpoint();
12299 auto AddPotentialCallees = [&]() {
12300 for (
auto *PotentialCallee : PotentialCallees) {
12301 bool UsedAssumedInformation =
false;
12302 if (CheckPotentialCalleeUse(*PotentialCallee, UsedAssumedInformation))
12303 AssumedCalleesNow.
insert(PotentialCallee);
12309 bool UsedAssumedInformation =
false;
12312 AA::ValueScope::AnyScope,
12313 UsedAssumedInformation)) {
12314 if (PotentialCallees.empty())
12315 return indicatePessimisticFixpoint();
12316 AddPotentialCallees();
12321 auto CheckPotentialCallee = [&](
Function &Fn) {
12322 if (!PotentialCallees.empty() && !PotentialCallees.count(&Fn))
12325 auto &CachedResult = FilterResults[&Fn];
12326 if (CachedResult.has_value())
12327 return CachedResult.value();
12329 bool UsedAssumedInformation =
false;
12330 if (!CheckPotentialCalleeUse(Fn, UsedAssumedInformation)) {
12331 if (!UsedAssumedInformation)
12332 CachedResult =
false;
12341 for (
int I = NumCBArgs;
I < NumFnArgs; ++
I) {
12342 bool IsKnown =
false;
12345 DepClassTy::OPTIONAL, IsKnown)) {
12347 CachedResult =
false;
12352 CachedResult =
true;
12358 for (
auto &VAC :
Values) {
12366 if (CheckPotentialCallee(*VACFn))
12367 AssumedCalleesNow.
insert(VACFn);
12370 if (!PotentialCallees.empty()) {
12371 AddPotentialCallees();
12374 AllCalleesKnownNow =
false;
12377 if (AssumedCalleesNow == AssumedCallees &&
12378 AllCalleesKnown == AllCalleesKnownNow)
12379 return ChangeStatus::UNCHANGED;
12381 std::swap(AssumedCallees, AssumedCalleesNow);
12382 AllCalleesKnown = AllCalleesKnownNow;
12383 return ChangeStatus::CHANGED;
12388 if (!AllCalleesKnown && AssumedCallees.empty())
12389 return ChangeStatus::UNCHANGED;
12392 bool UsedAssumedInformation =
false;
12393 if (
A.isAssumedDead(*CB,
this,
nullptr,
12394 UsedAssumedInformation))
12395 return ChangeStatus::UNCHANGED;
12400 if (
FP->getType()->getPointerAddressSpace() != ProgramAS)
12401 FP =
new AddrSpaceCastInst(
12402 FP, PointerType::get(
FP->getContext(), ProgramAS),
12403 FP->getName() +
".as" + Twine(ProgramAS), CB->
getIterator());
12412 if (AssumedCallees.empty()) {
12413 assert(AllCalleesKnown &&
12414 "Expected all callees to be known if there are none.");
12415 A.changeToUnreachableAfterManifest(CB);
12416 return ChangeStatus::CHANGED;
12420 if (AllCalleesKnown && AssumedCallees.size() == 1) {
12421 auto *NewCallee = AssumedCallees.front();
12424 NumIndirectCallsPromoted++;
12425 return ChangeStatus::CHANGED;
12433 A.deleteAfterManifest(*CB);
12434 return ChangeStatus::CHANGED;
12444 bool SpecializedForAnyCallees =
false;
12445 bool SpecializedForAllCallees = AllCalleesKnown;
12446 ICmpInst *LastCmp =
nullptr;
12449 for (
Function *NewCallee : AssumedCallees) {
12450 if (!
A.shouldSpecializeCallSiteForCallee(*
this, *CB, *NewCallee,
12451 AssumedCallees.size())) {
12452 SkippedAssumedCallees.
push_back(NewCallee);
12453 SpecializedForAllCallees =
false;
12456 SpecializedForAnyCallees =
true;
12462 A.registerManifestAddedBasicBlock(*ThenTI->
getParent());
12463 A.registerManifestAddedBasicBlock(*IP->getParent());
12469 A.registerManifestAddedBasicBlock(*ElseBB);
12471 SplitTI->replaceUsesOfWith(CBBB, ElseBB);
12476 CastInst *RetBC =
nullptr;
12477 CallInst *NewCall =
nullptr;
12482 NumIndirectCallsPromoted++;
12491 auto AttachCalleeMetadata = [&](CallBase &IndirectCB) {
12492 if (!AllCalleesKnown)
12493 return ChangeStatus::UNCHANGED;
12494 MDBuilder MDB(IndirectCB.getContext());
12495 MDNode *Callees = MDB.createCallees(SkippedAssumedCallees);
12496 IndirectCB.setMetadata(LLVMContext::MD_callees, Callees);
12497 return ChangeStatus::CHANGED;
12500 if (!SpecializedForAnyCallees)
12501 return AttachCalleeMetadata(*CB);
12504 if (SpecializedForAllCallees) {
12507 new UnreachableInst(IP->getContext(), IP);
12508 IP->eraseFromParent();
12511 CBClone->setName(CB->
getName());
12512 CBClone->insertBefore(*IP->getParent(), IP);
12513 NewCalls.
push_back({CBClone,
nullptr});
12514 AttachCalleeMetadata(*CBClone);
12521 CB->
getParent()->getFirstInsertionPt());
12522 for (
auto &It : NewCalls) {
12523 CallBase *NewCall = It.first;
12524 Instruction *CallRet = It.second ? It.second : It.first;
12536 A.deleteAfterManifest(*CB);
12537 Changed = ChangeStatus::CHANGED;
12542 const std::string getAsStr(Attributor *
A)
const override {
12543 return std::string(AllCalleesKnown ?
"eliminate" :
"specialize") +
12544 " indirect call site with " + std::to_string(AssumedCallees.size()) +
12548 void trackStatistics()
const override {
12549 if (AllCalleesKnown) {
12551 Eliminated, CallSites,
12552 "Number of indirect call sites eliminated via specialization")
12555 "Number of indirect call sites specialized")
12559 bool foreachCallee(function_ref<
bool(
Function *)> CB)
const override {
12560 return isValidState() && AllCalleesKnown &&
all_of(AssumedCallees, CB);
12565 DenseMap<Function *, std::optional<bool>> FilterResults;
12569 SmallSetVector<Function *, 4> PotentialCallees;
12573 SmallSetVector<Function *, 4> AssumedCallees;
12577 bool AllCalleesKnown =
true;
12584struct AAInvariantLoadPointerImpl
12586 AAInvariantLoadPointer> {
12590 IS_NOALIAS = 1 << 0,
12593 IS_NOEFFECT = 1 << 1,
12595 IS_LOCALLY_INVARIANT = 1 << 2,
12597 IS_LOCALLY_CONSTRAINED = 1 << 3,
12599 IS_BEST_STATE = IS_NOALIAS | IS_NOEFFECT | IS_LOCALLY_INVARIANT |
12600 IS_LOCALLY_CONSTRAINED,
12602 static_assert(getBestState() == IS_BEST_STATE,
"Unexpected best state");
12605 StateWrapper<BitIntegerState<uint8_t, 15>, AAInvariantLoadPointer>;
12609 AAInvariantLoadPointerImpl(
const IRPosition &IRP, Attributor &
A)
12612 bool isKnownInvariant()
const final {
12613 return isKnownLocallyInvariant() && isKnown(IS_LOCALLY_CONSTRAINED);
12616 bool isKnownLocallyInvariant()
const final {
12617 if (isKnown(IS_LOCALLY_INVARIANT))
12619 return isKnown(IS_NOALIAS | IS_NOEFFECT);
12622 bool isAssumedInvariant()
const final {
12623 return isAssumedLocallyInvariant() && isAssumed(IS_LOCALLY_CONSTRAINED);
12626 bool isAssumedLocallyInvariant()
const final {
12627 if (isAssumed(IS_LOCALLY_INVARIANT))
12629 return isAssumed(IS_NOALIAS | IS_NOEFFECT);
12636 if (requiresNoAlias() && !isAssumed(IS_NOALIAS))
12637 return indicatePessimisticFixpoint();
12641 Changed |= updateLocalInvariance(
A);
12647 if (!isKnownInvariant())
12648 return ChangeStatus::UNCHANGED;
12651 const Value *Ptr = &getAssociatedValue();
12652 const auto TagInvariantLoads = [&](
const Use &
U,
bool &) {
12653 if (
U.get() != Ptr)
12661 if (!
A.isRunOn(
I->getFunction()))
12664 if (
I->hasMetadata(LLVMContext::MD_invariant_load))
12668 LI->setMetadata(LLVMContext::MD_invariant_load,
12670 Changed = ChangeStatus::CHANGED;
12675 (void)
A.checkForAllUses(TagInvariantLoads, *
this, *Ptr);
12679 const std::string getAsStr(Attributor *)
const override {
12680 if (isKnownInvariant())
12681 return "load-invariant pointer";
12682 return "non-invariant pointer";
12685 void trackStatistics()
const override {}
12689 bool requiresNoAlias()
const {
12690 switch (getPositionKind()) {
12696 case IRP_CALL_SITE:
12698 case IRP_CALL_SITE_RETURNED: {
12703 case IRP_ARGUMENT: {
12704 const Function *
F = getAssociatedFunction();
12705 assert(
F &&
"no associated function for argument");
12711 bool isExternal()
const {
12712 const Function *
F = getAssociatedFunction();
12716 getPositionKind() != IRP_CALL_SITE_RETURNED;
12720 if (isKnown(IS_NOALIAS) || !isAssumed(IS_NOALIAS))
12721 return ChangeStatus::UNCHANGED;
12724 if (
const auto *ANoAlias =
A.getOrCreateAAFor<AANoAlias>(
12725 getIRPosition(),
this, DepClassTy::REQUIRED)) {
12726 if (ANoAlias->isKnownNoAlias()) {
12727 addKnownBits(IS_NOALIAS);
12728 return ChangeStatus::CHANGED;
12731 if (!ANoAlias->isAssumedNoAlias()) {
12732 removeAssumedBits(IS_NOALIAS);
12733 return ChangeStatus::CHANGED;
12736 return ChangeStatus::UNCHANGED;
12741 if (
const Argument *Arg = getAssociatedArgument()) {
12743 addKnownBits(IS_NOALIAS);
12744 return ChangeStatus::UNCHANGED;
12749 removeAssumedBits(IS_NOALIAS);
12750 return ChangeStatus::CHANGED;
12753 return ChangeStatus::UNCHANGED;
12757 if (isKnown(IS_NOEFFECT) || !isAssumed(IS_NOEFFECT))
12758 return ChangeStatus::UNCHANGED;
12760 if (!getAssociatedFunction())
12761 return indicatePessimisticFixpoint();
12764 return indicatePessimisticFixpoint();
12766 const auto HasNoEffectLoads = [&](
const Use &
U,
bool &) {
12768 return !LI || !LI->mayHaveSideEffects();
12770 if (!
A.checkForAllUses(HasNoEffectLoads, *
this, getAssociatedValue()))
12771 return indicatePessimisticFixpoint();
12773 if (
const auto *AMemoryBehavior =
A.getOrCreateAAFor<AAMemoryBehavior>(
12774 getIRPosition(),
this, DepClassTy::REQUIRED)) {
12777 if (!AMemoryBehavior->isAssumedReadOnly())
12778 return indicatePessimisticFixpoint();
12780 if (AMemoryBehavior->isKnownReadOnly()) {
12781 addKnownBits(IS_NOEFFECT);
12782 return ChangeStatus::UNCHANGED;
12785 return ChangeStatus::UNCHANGED;
12788 if (
const Argument *Arg = getAssociatedArgument()) {
12790 addKnownBits(IS_NOEFFECT);
12791 return ChangeStatus::UNCHANGED;
12796 return indicatePessimisticFixpoint();
12799 return ChangeStatus::UNCHANGED;
12803 if (isKnown(IS_LOCALLY_INVARIANT) || !isAssumed(IS_LOCALLY_INVARIANT))
12804 return ChangeStatus::UNCHANGED;
12807 const auto *AUO =
A.getOrCreateAAFor<AAUnderlyingObjects>(
12808 getIRPosition(),
this, DepClassTy::REQUIRED);
12810 return ChangeStatus::UNCHANGED;
12812 bool UsedAssumedInformation =
false;
12813 const auto IsLocallyInvariantLoadIfPointer = [&](
const Value &
V) {
12814 if (!
V.getType()->isPointerTy())
12816 const auto *IsInvariantLoadPointer =
12818 DepClassTy::REQUIRED);
12820 if (!IsInvariantLoadPointer)
12823 if (IsInvariantLoadPointer->isKnownLocallyInvariant())
12825 if (!IsInvariantLoadPointer->isAssumedLocallyInvariant())
12828 UsedAssumedInformation =
true;
12831 if (!AUO->forallUnderlyingObjects(IsLocallyInvariantLoadIfPointer))
12832 return indicatePessimisticFixpoint();
12838 if (!IsLocallyInvariantLoadIfPointer(*Arg))
12839 return indicatePessimisticFixpoint();
12844 if (!UsedAssumedInformation) {
12846 addKnownBits(IS_LOCALLY_INVARIANT);
12847 return ChangeStatus::CHANGED;
12850 return ChangeStatus::UNCHANGED;
12854struct AAInvariantLoadPointerFloating final : AAInvariantLoadPointerImpl {
12855 AAInvariantLoadPointerFloating(
const IRPosition &IRP, Attributor &
A)
12856 : AAInvariantLoadPointerImpl(IRP,
A) {}
12859struct AAInvariantLoadPointerReturned final : AAInvariantLoadPointerImpl {
12860 AAInvariantLoadPointerReturned(
const IRPosition &IRP, Attributor &
A)
12861 : AAInvariantLoadPointerImpl(IRP,
A) {}
12864 removeAssumedBits(IS_LOCALLY_CONSTRAINED);
12868struct AAInvariantLoadPointerCallSiteReturned final
12869 : AAInvariantLoadPointerImpl {
12870 AAInvariantLoadPointerCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
12871 : AAInvariantLoadPointerImpl(IRP,
A) {}
12875 const Function *
F = getAssociatedFunction();
12877 indicatePessimisticFixpoint();
12881 if (!
F->isDeclaration() && !
F->isIntrinsic())
12882 return AAInvariantLoadPointerImpl::initialize(
A);
12887 return AAInvariantLoadPointerImpl::initialize(
A);
12889 if (
F->onlyReadsMemory() &&
F->hasNoSync())
12890 return AAInvariantLoadPointerImpl::initialize(
A);
12894 indicatePessimisticFixpoint();
12898struct AAInvariantLoadPointerArgument final : AAInvariantLoadPointerImpl {
12899 AAInvariantLoadPointerArgument(
const IRPosition &IRP, Attributor &
A)
12900 : AAInvariantLoadPointerImpl(IRP,
A) {}
12903 const Function *
F = getAssociatedFunction();
12904 assert(
F &&
"no associated function for argument");
12907 addKnownBits(IS_LOCALLY_CONSTRAINED);
12911 if (!
F->hasLocalLinkage())
12912 removeAssumedBits(IS_LOCALLY_CONSTRAINED);
12916struct AAInvariantLoadPointerCallSiteArgument final
12917 : AAInvariantLoadPointerImpl {
12918 AAInvariantLoadPointerCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
12919 : AAInvariantLoadPointerImpl(IRP,
A) {}
12926template <
typename InstType>
12927static bool makeChange(
Attributor &
A, InstType *MemInst,
const Use &U,
12929 bool UseOriginalValue) {
12930 if (
U.getOperandNo() != InstType::getPointerOperandIndex())
12933 if (MemInst->isVolatile()) {
12935 *MemInst->getFunction());
12936 unsigned NewAS = NewPtrTy->getPointerAddressSpace();
12937 if (!
TTI || !
TTI->hasVolatileVariant(MemInst, NewAS))
12941 if (UseOriginalValue) {
12942 A.changeUseAfterManifest(
const_cast<Use &
>(U), *OriginalValue);
12948 A.changeUseAfterManifest(
const_cast<Use &
>(U), *
CastInst);
12953 AAAddressSpaceImpl(
const IRPosition &IRP, Attributor &
A)
12954 : AAAddressSpace(IRP,
A) {}
12957 assert(isValidState() &&
"the AA is invalid");
12958 return AssumedAddressSpace;
12962 assert(getAssociatedType()->isPtrOrPtrVectorTy() &&
12963 "Associated value is not a pointer");
12965 if (!
A.getInfoCache().getFlatAddressSpace().has_value()) {
12966 indicatePessimisticFixpoint();
12970 unsigned FlatAS =
A.getInfoCache().getFlatAddressSpace().value();
12971 unsigned AS = getAssociatedType()->getPointerAddressSpace();
12972 if (AS != FlatAS) {
12973 [[maybe_unused]]
bool R = takeAddressSpace(AS);
12974 assert(R &&
"The take should happen");
12975 indicateOptimisticFixpoint();
12980 uint32_t OldAddressSpace = AssumedAddressSpace;
12981 unsigned FlatAS =
A.getInfoCache().getFlatAddressSpace().value();
12983 auto CheckAddressSpace = [&](
Value &
Obj) {
12989 unsigned ObjAS =
Obj.getType()->getPointerAddressSpace();
12990 if (ObjAS != FlatAS)
12991 return takeAddressSpace(ObjAS);
13005 A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(*F);
13007 if (AssumedAS != ~0U)
13008 return takeAddressSpace(AssumedAS);
13012 return takeAddressSpace(FlatAS);
13015 auto *AUO =
A.getOrCreateAAFor<AAUnderlyingObjects>(getIRPosition(),
this,
13016 DepClassTy::REQUIRED);
13017 if (!AUO->forallUnderlyingObjects(CheckAddressSpace))
13018 return indicatePessimisticFixpoint();
13020 return OldAddressSpace == AssumedAddressSpace ? ChangeStatus::UNCHANGED
13021 : ChangeStatus::CHANGED;
13027 if (NewAS == InvalidAddressSpace ||
13029 return ChangeStatus::UNCHANGED;
13031 unsigned FlatAS =
A.getInfoCache().getFlatAddressSpace().value();
13033 Value *AssociatedValue = &getAssociatedValue();
13034 Value *OriginalValue = peelAddrspacecast(AssociatedValue, FlatAS);
13037 PointerType::get(getAssociatedType()->
getContext(), NewAS);
13038 bool UseOriginalValue =
13043 auto Pred = [&](
const Use &
U,
bool &) {
13044 if (
U.get() != AssociatedValue)
13055 makeChange(
A, LI, U, OriginalValue, NewPtrTy, UseOriginalValue);
13058 makeChange(
A, SI, U, OriginalValue, NewPtrTy, UseOriginalValue);
13061 makeChange(
A, RMW, U, OriginalValue, NewPtrTy, UseOriginalValue);
13064 makeChange(
A, CmpX, U, OriginalValue, NewPtrTy, UseOriginalValue);
13071 (void)
A.checkForAllUses(
Pred, *
this, getAssociatedValue(),
13074 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
13077 const std::string getAsStr(Attributor *
A)
const override {
13078 if (!isValidState())
13079 return "addrspace(<invalid>)";
13080 return "addrspace(" +
13081 (AssumedAddressSpace == InvalidAddressSpace
13083 : std::to_string(AssumedAddressSpace)) +
13088 uint32_t AssumedAddressSpace = InvalidAddressSpace;
13090 bool takeAddressSpace(uint32_t AS) {
13091 if (AssumedAddressSpace == InvalidAddressSpace) {
13092 AssumedAddressSpace = AS;
13095 return AssumedAddressSpace == AS;
13098 static Value *peelAddrspacecast(
Value *
V,
unsigned FlatAS) {
13100 assert(
I->getSrcAddressSpace() != FlatAS &&
13101 "there should not be flat AS -> non-flat AS");
13102 return I->getPointerOperand();
13105 if (
C->getOpcode() == Instruction::AddrSpaceCast) {
13106 assert(
C->getOperand(0)->getType()->getPointerAddressSpace() !=
13108 "there should not be flat AS -> non-flat AS X");
13109 return C->getOperand(0);
13115struct AAAddressSpaceFloating final : AAAddressSpaceImpl {
13116 AAAddressSpaceFloating(
const IRPosition &IRP, Attributor &
A)
13117 : AAAddressSpaceImpl(IRP,
A) {}
13119 void trackStatistics()
const override {
13124struct AAAddressSpaceReturned final : AAAddressSpaceImpl {
13125 AAAddressSpaceReturned(
const IRPosition &IRP, Attributor &
A)
13126 : AAAddressSpaceImpl(IRP,
A) {}
13131 (void)indicatePessimisticFixpoint();
13134 void trackStatistics()
const override {
13139struct AAAddressSpaceCallSiteReturned final : AAAddressSpaceImpl {
13140 AAAddressSpaceCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
13141 : AAAddressSpaceImpl(IRP,
A) {}
13143 void trackStatistics()
const override {
13148struct AAAddressSpaceArgument final : AAAddressSpaceImpl {
13149 AAAddressSpaceArgument(
const IRPosition &IRP, Attributor &
A)
13150 : AAAddressSpaceImpl(IRP,
A) {}
13155struct AAAddressSpaceCallSiteArgument final : AAAddressSpaceImpl {
13156 AAAddressSpaceCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
13157 : AAAddressSpaceImpl(IRP,
A) {}
13162 (void)indicatePessimisticFixpoint();
13165 void trackStatistics()
const override {
13181 AANoAliasAddrSpaceImpl(
const IRPosition &IRP, Attributor &
A)
13182 : AANoAliasAddrSpace(IRP,
A) {}
13185 assert(getAssociatedType()->isPtrOrPtrVectorTy() &&
13186 "Associated value is not a pointer");
13190 std::optional<unsigned> FlatAS =
A.getInfoCache().getFlatAddressSpace();
13191 if (!FlatAS.has_value()) {
13192 indicatePessimisticFixpoint();
13198 unsigned AS = getAssociatedType()->getPointerAddressSpace();
13199 if (AS != *FlatAS) {
13201 indicateOptimisticFixpoint();
13206 unsigned FlatAS =
A.getInfoCache().getFlatAddressSpace().value();
13207 uint32_t OldAssumed = getAssumed();
13209 auto CheckAddressSpace = [&](
Value &
Obj) {
13213 unsigned AS =
Obj.getType()->getPointerAddressSpace();
13217 removeAS(
Obj.getType()->getPointerAddressSpace());
13221 const AAUnderlyingObjects *AUO =
A.getOrCreateAAFor<AAUnderlyingObjects>(
13222 getIRPosition(),
this, DepClassTy::REQUIRED);
13224 return indicatePessimisticFixpoint();
13226 return OldAssumed == getAssumed() ? ChangeStatus::UNCHANGED
13227 : ChangeStatus::CHANGED;
13231 unsigned FlatAS =
A.getInfoCache().getFlatAddressSpace().value();
13233 unsigned AS = getAssociatedType()->getPointerAddressSpace();
13234 if (AS != FlatAS ||
Map.empty())
13235 return ChangeStatus::UNCHANGED;
13237 LLVMContext &Ctx = getAssociatedValue().getContext();
13238 MDNode *NoAliasASNode =
nullptr;
13239 MDBuilder MDB(Ctx);
13241 for (RangeMap::const_iterator
I =
Map.begin();
I !=
Map.end();
I++) {
13244 unsigned Upper =
I.stop();
13245 unsigned Lower =
I.start();
13246 if (!NoAliasASNode) {
13247 NoAliasASNode = MDB.createRange(APInt(32,
Lower), APInt(32,
Upper + 1));
13250 MDNode *ASRange = MDB.createRange(APInt(32,
Lower), APInt(32,
Upper + 1));
13254 Value *AssociatedValue = &getAssociatedValue();
13257 auto AddNoAliasAttr = [&](
const Use &
U,
bool &) {
13258 if (
U.get() != AssociatedValue)
13261 if (!Inst || Inst->
hasMetadata(LLVMContext::MD_noalias_addrspace))
13268 Inst->
setMetadata(LLVMContext::MD_noalias_addrspace, NoAliasASNode);
13272 (void)
A.checkForAllUses(AddNoAliasAttr, *
this, *AssociatedValue,
13274 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED;
13277 const std::string getAsStr(Attributor *
A)
const override {
13278 if (!isValidState())
13279 return "<invalid>";
13281 raw_string_ostream OS(Str);
13282 OS <<
"CanNotBeAddrSpace(";
13283 for (RangeMap::const_iterator
I =
Map.begin();
I !=
Map.end();
I++) {
13284 unsigned Upper =
I.stop();
13285 unsigned Lower =
I.start();
13286 OS <<
' ' <<
'[' <<
Upper <<
',' <<
Lower + 1 <<
')';
13293 void removeAS(
unsigned AS) {
13294 RangeMap::iterator
I =
Map.find(AS);
13296 if (
I !=
Map.end()) {
13297 unsigned Upper =
I.stop();
13298 unsigned Lower =
I.start();
13302 if (AS != ~((
unsigned)0) && AS + 1 <=
Upper)
13304 if (AS != 0 &&
Lower <= AS - 1)
13309 void resetASRanges(Attributor &
A) {
13311 Map.insert(0,
A.getInfoCache().getMaxAddrSpace(),
true);
13315struct AANoAliasAddrSpaceFloating final : AANoAliasAddrSpaceImpl {
13316 AANoAliasAddrSpaceFloating(
const IRPosition &IRP, Attributor &
A)
13317 : AANoAliasAddrSpaceImpl(IRP,
A) {}
13319 void trackStatistics()
const override {
13324struct AANoAliasAddrSpaceReturned final : AANoAliasAddrSpaceImpl {
13325 AANoAliasAddrSpaceReturned(
const IRPosition &IRP, Attributor &
A)
13326 : AANoAliasAddrSpaceImpl(IRP,
A) {}
13328 void trackStatistics()
const override {
13333struct AANoAliasAddrSpaceCallSiteReturned final : AANoAliasAddrSpaceImpl {
13334 AANoAliasAddrSpaceCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
13335 : AANoAliasAddrSpaceImpl(IRP,
A) {}
13337 void trackStatistics()
const override {
13342struct AANoAliasAddrSpaceArgument final : AANoAliasAddrSpaceImpl {
13343 AANoAliasAddrSpaceArgument(
const IRPosition &IRP, Attributor &
A)
13344 : AANoAliasAddrSpaceImpl(IRP,
A) {}
13346 void trackStatistics()
const override {
13351struct AANoAliasAddrSpaceCallSiteArgument final : AANoAliasAddrSpaceImpl {
13352 AANoAliasAddrSpaceCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
13353 : AANoAliasAddrSpaceImpl(IRP,
A) {}
13355 void trackStatistics()
const override {
13363 AAAllocationInfoImpl(
const IRPosition &IRP, Attributor &
A)
13364 : AAAllocationInfo(IRP,
A) {}
13366 std::optional<TypeSize> getAllocatedSize()
const override {
13367 assert(isValidState() &&
"the AA is invalid");
13368 return AssumedAllocatedSize;
13371 std::optional<TypeSize> findInitialAllocationSize(Instruction *
I,
13372 const DataLayout &
DL) {
13375 switch (
I->getOpcode()) {
13376 case Instruction::Alloca: {
13381 return std::nullopt;
13387 const IRPosition &IRP = getIRPosition();
13392 return indicatePessimisticFixpoint();
13394 bool IsKnownNoCapture;
13396 A,
this, IRP, DepClassTy::OPTIONAL, IsKnownNoCapture))
13397 return indicatePessimisticFixpoint();
13399 const AAPointerInfo *PI =
13400 A.getOrCreateAAFor<AAPointerInfo>(IRP, *
this, DepClassTy::REQUIRED);
13403 return indicatePessimisticFixpoint();
13406 return indicatePessimisticFixpoint();
13408 const DataLayout &
DL =
A.getDataLayout();
13409 const auto AllocationSize = findInitialAllocationSize(
I,
DL);
13412 if (!AllocationSize)
13413 return indicatePessimisticFixpoint();
13417 if (*AllocationSize == 0)
13418 return indicatePessimisticFixpoint();
13424 return indicatePessimisticFixpoint();
13426 if (BinSize == 0) {
13427 auto NewAllocationSize = std::make_optional<TypeSize>(0,
false);
13428 if (!changeAllocationSize(NewAllocationSize))
13429 return ChangeStatus::UNCHANGED;
13430 return ChangeStatus::CHANGED;
13434 const auto &It = PI->
begin();
13437 if (It->first.Offset != 0)
13438 return indicatePessimisticFixpoint();
13440 uint64_t SizeOfBin = It->first.Offset + It->first.Size;
13442 if (SizeOfBin >= *AllocationSize)
13443 return indicatePessimisticFixpoint();
13445 auto NewAllocationSize = std::make_optional<TypeSize>(SizeOfBin * 8,
false);
13447 if (!changeAllocationSize(NewAllocationSize))
13448 return ChangeStatus::UNCHANGED;
13450 return ChangeStatus::CHANGED;
13455 assert(isValidState() &&
13456 "Manifest should only be called if the state is valid.");
13460 auto FixedAllocatedSizeInBits = getAllocatedSize()->getFixedValue();
13462 unsigned long NumBytesToAllocate = (FixedAllocatedSizeInBits + 7) / 8;
13464 switch (
I->getOpcode()) {
13466 case Instruction::Alloca: {
13470 Type *CharType = Type::getInt8Ty(
I->getContext());
13472 auto *NumBytesToValue =
13473 ConstantInt::get(
I->getContext(), APInt(32, NumBytesToAllocate));
13476 insertPt = std::next(insertPt);
13477 AllocaInst *NewAllocaInst =
13482 return ChangeStatus::CHANGED;
13490 return ChangeStatus::UNCHANGED;
13493 const std::string getAsStr(Attributor *
A)
const override {
13494 if (!isValidState())
13495 return "allocationinfo(<invalid>)";
13496 return "allocationinfo(" +
13497 (AssumedAllocatedSize == HasNoAllocationSize
13499 : std::to_string(AssumedAllocatedSize->getFixedValue())) +
13504 std::optional<TypeSize> AssumedAllocatedSize = HasNoAllocationSize;
13508 bool changeAllocationSize(std::optional<TypeSize>
Size) {
13509 if (AssumedAllocatedSize == HasNoAllocationSize ||
13510 AssumedAllocatedSize !=
Size) {
13511 AssumedAllocatedSize =
Size;
13518struct AAAllocationInfoFloating : AAAllocationInfoImpl {
13519 AAAllocationInfoFloating(
const IRPosition &IRP, Attributor &
A)
13520 : AAAllocationInfoImpl(IRP,
A) {}
13522 void trackStatistics()
const override {
13527struct AAAllocationInfoReturned : AAAllocationInfoImpl {
13528 AAAllocationInfoReturned(
const IRPosition &IRP, Attributor &
A)
13529 : AAAllocationInfoImpl(IRP,
A) {}
13534 (void)indicatePessimisticFixpoint();
13537 void trackStatistics()
const override {
13542struct AAAllocationInfoCallSiteReturned : AAAllocationInfoImpl {
13543 AAAllocationInfoCallSiteReturned(
const IRPosition &IRP, Attributor &
A)
13544 : AAAllocationInfoImpl(IRP,
A) {}
13546 void trackStatistics()
const override {
13551struct AAAllocationInfoArgument : AAAllocationInfoImpl {
13552 AAAllocationInfoArgument(
const IRPosition &IRP, Attributor &
A)
13553 : AAAllocationInfoImpl(IRP,
A) {}
13555 void trackStatistics()
const override {
13560struct AAAllocationInfoCallSiteArgument : AAAllocationInfoImpl {
13561 AAAllocationInfoCallSiteArgument(
const IRPosition &IRP, Attributor &
A)
13562 : AAAllocationInfoImpl(IRP,
A) {}
13566 (void)indicatePessimisticFixpoint();
13569 void trackStatistics()
const override {
13618#define SWITCH_PK_INV(CLASS, PK, POS_NAME) \
13619 case IRPosition::PK: \
13620 llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!");
13622#define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \
13623 case IRPosition::PK: \
13624 AA = new (A.Allocator) CLASS##SUFFIX(IRP, A); \
13628#define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13629 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13630 CLASS *AA = nullptr; \
13631 switch (IRP.getPositionKind()) { \
13632 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13633 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \
13634 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \
13635 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13636 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \
13637 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \
13638 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13639 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13644#define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13645 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13646 CLASS *AA = nullptr; \
13647 switch (IRP.getPositionKind()) { \
13648 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13649 SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \
13650 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \
13651 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13652 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13653 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \
13654 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13655 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13660#define CREATE_ABSTRACT_ATTRIBUTE_FOR_ONE_POSITION(POS, SUFFIX, CLASS) \
13661 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13662 CLASS *AA = nullptr; \
13663 switch (IRP.getPositionKind()) { \
13664 SWITCH_PK_CREATE(CLASS, IRP, POS, SUFFIX) \
13666 llvm_unreachable("Cannot create " #CLASS " for position otherthan " #POS \
13672#define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13673 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13674 CLASS *AA = nullptr; \
13675 switch (IRP.getPositionKind()) { \
13676 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13677 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13678 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13679 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13680 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13681 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \
13682 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13683 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13688#define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13689 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13690 CLASS *AA = nullptr; \
13691 switch (IRP.getPositionKind()) { \
13692 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13693 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \
13694 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \
13695 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13696 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \
13697 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \
13698 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \
13699 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13704#define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \
13705 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \
13706 CLASS *AA = nullptr; \
13707 switch (IRP.getPositionKind()) { \
13708 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \
13709 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \
13710 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \
13711 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \
13712 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \
13713 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \
13714 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \
13715 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \
13767#undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION
13768#undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION
13769#undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION
13770#undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION
13771#undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION
13772#undef CREATE_ABSTRACT_ATTRIBUTE_FOR_ONE_POSITION
13773#undef SWITCH_PK_CREATE
13774#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)
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.
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.
LLVM_ABI Constant * getInitialValueOfAllocation(const Value *V, const TargetLibraryInfo *TLI, Type *Ty)
If this is a call to an allocation function that initializes memory to a fixed value,...
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.
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)
LLVM_ABI bool isRemovableAlloc(const CallBase *V, const TargetLibraryInfo *TLI)
Return true if this is a call to an allocation function that does not have side effects that we are r...
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.
LLVM_ABI Value * getAllocAlignment(const CallBase *V, const TargetLibraryInfo *TLI)
Gets the alignment argument for an aligned_alloc-like function, using either built-in knowledge based...
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
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
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.
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 >
LLVM_ABI Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
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.
bool capturesNothing(CaptureComponents CC)
LLVM_ABI AssumeDereferenceableInfo getAssumeDereferenceableInfo(OperandBundleUse)
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)
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.