Skip to content

[Loads] Fix incorrect replacement of pointers with different provenance - #224281

Merged
nikic merged 3 commits into
llvm:mainfrom
nikic:invariant-replacement
Sep 18, 2026
Merged

nikic merged 3 commits into
llvm:mainfrom
nikic:invariant-replacement

Conversation

@nikic

@nikic nikic commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

isPointerAlwaysReplaceable() uses getUnderlyingObject() to check whether the two pointers have the same provenance, because in that case the replacement is always legal. However, getUnderlyingObject() does not actually guarantee that the provenance is the same: In particular, it can look through some intrinsics like strip.invariant.group and launder.invariant.group, which do change the provenance of the pointer. And replacing the result of those intrinsics with their argument is indeed incorrect.

Fix this by adding a MustPreserveProvenance argument to the relevant APIs, and enable it in isPointerAlwaysReplaceable().

Noticed while working on #224222.

@llvmorg-github-actions llvmorg-github-actions Bot added llvm:analysis Includes value tracking, cost tables and constant folding llvm:transforms labels Sep 17, 2026
@llvmorg-github-actions

llvmorg-github-actions Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

@llvm/pr-subscribers-llvm-analysis

@llvm/pr-subscribers-llvm-transforms

Author: Nikita Popov (nikic)

Changes

isPointerAlwaysReplaceable() uses getUnderlyingObject() to check whether the two pointers have the same provenance, because in that case the replacement is always legal. However, getUnderlyingObject() does not actually guarantee that the provenance is the same: In particular, it can look through some intrinsics like strip.invariant.group and launder.invariant.group, which do change the provenance of the pointer. And replacing the result of those intrinsics with their argument is indeed incorrect.

Fix this by adding a MustPreserveProvenance argument to the relevant APIs, and enable it in isPointerAlwaysReplaceable().

Noticed while working on #224222.


Full diff: https://github.com/llvm/llvm-project/pull/224281.diff

4 Files Affected:

  • (modified) llvm/include/llvm/Analysis/ValueTracking.h (+20-10)
  • (modified) llvm/lib/Analysis/Loads.cpp (+2-2)
  • (modified) llvm/lib/Analysis/ValueTracking.cpp (+16-9)
  • (modified) llvm/test/Transforms/GVN/assume-equal.ll (+28)
diff --git a/llvm/include/llvm/Analysis/ValueTracking.h b/llvm/include/llvm/Analysis/ValueTracking.h
index 9a1fdd0ca05a9..42ee2b317be21 100644
--- a/llvm/include/llvm/Analysis/ValueTracking.h
+++ b/llvm/include/llvm/Analysis/ValueTracking.h
@@ -446,9 +446,12 @@ LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize = 8);
 /// the pointer within its underlying object. Offset preservation implies
 /// nullness preservation; pass true when callers reason about either offset or
 /// null equality (e.g. GEP decomposition, dereferenceability, isKnownNonZero).
+/// If \p MustPreserveProvenance is true, the call must preserve the provenance
+/// exactly, as opposed to being only based-on the argument.
 LLVM_ABI const Value *
 getArgumentAliasingToReturnedPointer(const CallBase *Call,
-                                     bool MustPreserveOffset);
+                                     bool MustPreserveOffset,
+                                     bool MustPreserveProvenance = false);
 inline Value *getArgumentAliasingToReturnedPointer(CallBase *Call,
                                                    bool MustPreserveOffset) {
   return const_cast<Value *>(getArgumentAliasingToReturnedPointer(
@@ -459,30 +462,37 @@ inline Value *getArgumentAliasingToReturnedPointer(CallBase *Call,
 /// and it only captures pointer by returning it.
 /// These intrinsics are not marked as nocapture, because returning is
 /// considered as capture. The arguments are not marked as returned neither,
-/// because it would make it useless. If \p MustPreserveOffset is true, the
-/// intrinsic must preserve the byte offset of the pointer within its
-/// underlying object (which excludes `llvm.ptrmask`, since masking off low
-/// bits changes the byte offset while still aliasing the same object).
+/// because it would make it useless. See getArgumentAliasingToReturnedPointer()
+/// for the meaning of \p MustPreserveOffset and \p MustPreserveProvenance.
 LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
-    const CallBase *Call, bool MustPreserveOffset);
+    const CallBase *Call, bool MustPreserveOffset,
+    bool MustPreserveProvenance = false);
 
 /// This method strips off any GEP address adjustments, pointer casts
 /// or `llvm.threadlocal.address` from the specified value \p V, returning the
 /// original object being addressed. Note that the returned value has pointer
 /// type if the specified value does. If the \p MaxLookup value is non-zero, it
 /// limits the number of instructions to be stripped off.
+/// If \p MustPreserveProvenance is true, return a pointer with the exactly
+/// same provenance as \p V, as opposed to \p V only being based-on the
+/// underlying object.
 LLVM_ABI const Value *
-getUnderlyingObject(const Value *V, unsigned MaxLookup = MaxLookupSearchDepth);
+getUnderlyingObject(const Value *V, unsigned MaxLookup = MaxLookupSearchDepth,
+                    bool MustPreserveProvenance = false);
 inline Value *getUnderlyingObject(Value *V,
-                                  unsigned MaxLookup = MaxLookupSearchDepth) {
+                                  unsigned MaxLookup = MaxLookupSearchDepth,
+                                  bool MustPreserveProvenance = false) {
   // Force const to avoid infinite recursion.
   const Value *VConst = V;
-  return const_cast<Value *>(getUnderlyingObject(VConst, MaxLookup));
+  return const_cast<Value *>(
+      getUnderlyingObject(VConst, MaxLookup, MustPreserveProvenance));
 }
 
 /// Like getUnderlyingObject(), but will try harder to find a single underlying
 /// object. In particular, this function also looks through selects and phis.
-LLVM_ABI const Value *getUnderlyingObjectAggressive(const Value *V);
+LLVM_ABI const Value *
+getUnderlyingObjectAggressive(const Value *V,
+                              bool MustPreserveProvenance = false);
 
 /// This method is similar to getUnderlyingObject except that it can
 /// look through phi and select instructions and return multiple objects.
diff --git a/llvm/lib/Analysis/Loads.cpp b/llvm/lib/Analysis/Loads.cpp
index de9022c540d42..394f7add60c02 100644
--- a/llvm/lib/Analysis/Loads.cpp
+++ b/llvm/lib/Analysis/Loads.cpp
@@ -860,8 +860,8 @@ static bool isPointerAlwaysReplaceable(const Value *From, const Value *To,
       isDereferenceablePointer(To, Type::getInt8Ty(To->getContext()), DL) &&
       IsBasedOnConstantGlobal(To))
     return true;
-  return getUnderlyingObjectAggressive(From) ==
-         getUnderlyingObjectAggressive(To);
+  return getUnderlyingObjectAggressive(From, /*MustPreserveProvenance=*/true) ==
+         getUnderlyingObjectAggressive(To, /*MustPreserveProvenance=*/true);
 }
 
 bool llvm::canReplacePointersInUseIfEqual(const Use &U, const Value *To,
diff --git a/llvm/lib/Analysis/ValueTracking.cpp b/llvm/lib/Analysis/ValueTracking.cpp
index dce213534d11f..a953b5b2386df 100644
--- a/llvm/lib/Analysis/ValueTracking.cpp
+++ b/llvm/lib/Analysis/ValueTracking.cpp
@@ -7195,20 +7195,22 @@ uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
 
 const Value *
 llvm::getArgumentAliasingToReturnedPointer(const CallBase *Call,
-                                           bool MustPreserveOffset) {
+                                           bool MustPreserveOffset,
+                                           bool MustPreserveProvenance) {
   assert(Call &&
          "getArgumentAliasingToReturnedPointer only works on nonnull calls");
   if (const Value *RV = Call->getReturnedArgOperand())
     return RV;
   // This can be used only as a aliasing property.
   if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
-          Call, MustPreserveOffset))
+          Call, MustPreserveOffset, MustPreserveProvenance))
     return Call->getArgOperand(0);
   return nullptr;
 }
 
 bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
-    const CallBase *Call, bool MustPreserveOffset) {
+    const CallBase *Call, bool MustPreserveOffset,
+    bool MustPreserveProvenance) {
   switch (Call->getIntrinsicID()) {
   case Intrinsic::launder_invariant_group:
   case Intrinsic::strip_invariant_group:
@@ -7224,7 +7226,7 @@ bool llvm::isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
   // writing, they are not), but we document this fact out of an abundance
   // of caution.
   case Intrinsic::amdgcn_make_buffer_rsrc:
-    return true;
+    return !MustPreserveProvenance;
   case Intrinsic::ptrmask:
     return !MustPreserveOffset;
   case Intrinsic::threadlocal_address:
@@ -7263,7 +7265,8 @@ static bool isSameUnderlyingObjectInLoop(const PHINode *PN,
   return true;
 }
 
-const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
+const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup,
+                                       bool MustPreserveProvenance) {
   for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
     if (auto *GEP = dyn_cast<GEPOperator>(V)) {
       const Value *PtrOp = GEP->getPointerOperand();
@@ -7298,7 +7301,7 @@ const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
         // cause weird miscompilations where 2 aliasing pointers are assumed to
         // noalias.
         if (auto *RP = getArgumentAliasingToReturnedPointer(
-                Call, /*MustPreserveOffset=*/false)) {
+                Call, /*MustPreserveOffset=*/false, MustPreserveProvenance)) {
           V = RP;
           continue;
         }
@@ -7353,7 +7356,8 @@ void llvm::getUnderlyingObjects(const Value *V,
   } while (!Worklist.empty());
 }
 
-const Value *llvm::getUnderlyingObjectAggressive(const Value *V) {
+const Value *llvm::getUnderlyingObjectAggressive(const Value *V,
+                                                 bool MustPreserveProvenance) {
   const unsigned MaxVisited = 8;
 
   SmallPtrSet<const Value *, 8> Visited;
@@ -7363,10 +7367,13 @@ const Value *llvm::getUnderlyingObjectAggressive(const Value *V) {
   // Used as fallback if we can't find a common underlying object through
   // recursion.
   bool First = true;
-  const Value *FirstObject = getUnderlyingObject(V);
+  const Value *FirstObject =
+      getUnderlyingObject(V, MaxLookupSearchDepth, MustPreserveProvenance);
   do {
     const Value *P = Worklist.pop_back_val();
-    P = First ? FirstObject : getUnderlyingObject(P);
+    P = First ? FirstObject
+              : getUnderlyingObject(P, MaxLookupSearchDepth,
+                                    MustPreserveProvenance);
     First = false;
 
     if (!Visited.insert(P).second)
diff --git a/llvm/test/Transforms/GVN/assume-equal.ll b/llvm/test/Transforms/GVN/assume-equal.ll
index d2a584e891703..f2ff8c8d411f5 100644
--- a/llvm/test/Transforms/GVN/assume-equal.ll
+++ b/llvm/test/Transforms/GVN/assume-equal.ll
@@ -464,6 +464,34 @@ define i8 @assume_ptr_eq_same_prov(ptr %p, i64 %x) {
   ret i8 %v
 }
 
+define ptr @test_strip_invariant(ptr %x) {
+; CHECK-LABEL: define ptr @test_strip_invariant(
+; CHECK-SAME: ptr [[X:%.*]]) {
+; CHECK-NEXT:    [[X_STRIP:%.*]] = call ptr @llvm.strip.invariant.group.p0(ptr [[X]])
+; CHECK-NEXT:    [[CMP:%.*]] = icmp eq ptr [[X]], [[X_STRIP]]
+; CHECK-NEXT:    call void @llvm.assume(i1 [[CMP]])
+; CHECK-NEXT:    ret ptr [[X_STRIP]]
+;
+  %x.strip = call ptr @llvm.strip.invariant.group(ptr %x)
+  %cmp = icmp eq ptr %x, %x.strip
+  call void @llvm.assume(i1 %cmp)
+  ret ptr %x.strip
+}
+
+define ptr @test_launder_invariant(ptr %x) {
+; CHECK-LABEL: define ptr @test_launder_invariant(
+; CHECK-SAME: ptr [[X:%.*]]) {
+; CHECK-NEXT:    [[X_LAUNDER:%.*]] = call ptr @llvm.launder.invariant.group.p0(ptr [[X]])
+; CHECK-NEXT:    [[CMP:%.*]] = icmp eq ptr [[X]], [[X_LAUNDER]]
+; CHECK-NEXT:    call void @llvm.assume(i1 [[CMP]])
+; CHECK-NEXT:    ret ptr [[X_LAUNDER]]
+;
+  %x.launder = call ptr @llvm.launder.invariant.group(ptr %x)
+  %cmp = icmp eq ptr %x, %x.launder
+  call void @llvm.assume(i1 %cmp)
+  ret ptr %x.launder
+}
+
 declare noalias ptr @_Znwm(i64)
 declare void @_ZN1AC1Ev(ptr)
 declare void @llvm.assume(i1)

@antoniofrighetto antoniofrighetto left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Comment on lines 455 to 456
inline Value *getArgumentAliasingToReturnedPointer(CallBase *Call,
bool MustPreserveOffset) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor nit: would update the non-const overload too, for consistency.

@fhahn fhahn left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks

@nikic
nikic merged commit 8fe013c into llvm:main Sep 18, 2026
12 checks passed
@nikic
nikic deleted the invariant-replacement branch September 18, 2026 14:21
@nikic

nikic commented Sep 18, 2026

Copy link
Copy Markdown
Contributor Author

@aeubanks Is it possible that this fix removes the need for the llvm.strip.invariant.group intrinsic entirely? The purpose of this intrinsic is really unclear from LangRef, but based on usage in clang and some old discussions, it seems like this intrinsic was inserted on comparisons (and casts to int and similar) to make sure that x == launder(x) does not result in launder(x) being replaced with x, by making it strip(x) == strip(launder(x)) instead (which is safe to replace because the !invariant.groups will be on x or launder(x) only, not strip(x).) With this change, the replacement would get prevented in the first place instead. Does that sound about right?

(I think you were involved with the invariant group stuff, sorry if I got the wrong person.)

@aeubanks

Copy link
Copy Markdown
Contributor

(yeah I was involved at some point trying to push things along but wasn't the initial designer)

yes I think that's right, we shouldn't need strip anymore with this

https://docs.google.com/document/d/16GVtCpzK8sIHNc2qZz6RN8amICNBtvjWUod2SujZVEo has the motivation for strip which is exactly what this PR solves

google-bazel-bot Bot pushed a commit to google-bazel-bot/llvm-project that referenced this pull request Sep 22, 2026
Clang currently emits calls to llvm.strip.invariant.group under
`-fstrict-vtable-pointers` whenever a pointer to a dynamic object is
used in a comparison or might be used in a comparison through operations
we cannot track.

The purpose of the llvm.strip.invariant.group intrinsic is to make sure
that if we have a dominating condition like `a ==
launder.invariant.group(a)`, we don't end up replacing the latter with
the former, as that would allow the optimizer to assume that the memory
stays invariant, despite going through a launder operation (e.g. on
placement new).

However, since this was introduced, we've come to the understanding that
replacing pointers based on equality comparison is generally only legal
if they have the same provenance, and stopped doing such replacements.
The specific strip.invariant.group/launder.invariant.group case was
still buggy due to an implementation bug, but this was fixed in
llvm#224281.

As such, I believe that we no longer need to emit
llvm.strip.invariant.group in Clang. I plan to also remove the LLVM
intrinsic in a followup.
llvm-upstreamsync Bot pushed a commit to qualcomm/cpullvm-toolchain that referenced this pull request Sep 22, 2026
Clang currently emits calls to llvm.strip.invariant.group under
`-fstrict-vtable-pointers` whenever a pointer to a dynamic object is
used in a comparison or might be used in a comparison through operations
we cannot track.

The purpose of the llvm.strip.invariant.group intrinsic is to make sure
that if we have a dominating condition like `a ==
launder.invariant.group(a)`, we don't end up replacing the latter with
the former, as that would allow the optimizer to assume that the memory
stays invariant, despite going through a launder operation (e.g. on
placement new).

However, since this was introduced, we've come to the understanding that
replacing pointers based on equality comparison is generally only legal
if they have the same provenance, and stopped doing such replacements.
The specific strip.invariant.group/launder.invariant.group case was
still buggy due to an implementation bug, but this was fixed in
llvm/llvm-project#224281.

As such, I believe that we no longer need to emit
llvm.strip.invariant.group in Clang. I plan to also remove the LLVM
intrinsic in a followup.
llvm-sync Bot pushed a commit to arm/arm-toolchain that referenced this pull request Sep 22, 2026
Clang currently emits calls to llvm.strip.invariant.group under
`-fstrict-vtable-pointers` whenever a pointer to a dynamic object is
used in a comparison or might be used in a comparison through operations
we cannot track.

The purpose of the llvm.strip.invariant.group intrinsic is to make sure
that if we have a dominating condition like `a ==
launder.invariant.group(a)`, we don't end up replacing the latter with
the former, as that would allow the optimizer to assume that the memory
stays invariant, despite going through a launder operation (e.g. on
placement new).

However, since this was introduced, we've come to the understanding that
replacing pointers based on equality comparison is generally only legal
if they have the same provenance, and stopped doing such replacements.
The specific strip.invariant.group/launder.invariant.group case was
still buggy due to an implementation bug, but this was fixed in
llvm/llvm-project#224281.

As such, I believe that we no longer need to emit
llvm.strip.invariant.group in Clang. I plan to also remove the LLVM
intrinsic in a followup.
nikic added a commit that referenced this pull request Sep 23, 2026
This intrinsic was originally introduced to make sure that if we have a
dominating condition like `a == launder.invariant.group(a)`, we don't
end up replacing the latter with the former, as that would allow the
optimizer to assume that the memory stays invariant, despite going
through a launder operation. Wrapping both comparison operands in
strip.invariant.group avoids the issue, because replacing one stripped
pointer with another is safe.

The underlying issue was fixed in
#224281 (and prior work), which
ensures that the problematic replacement cannot happen in the first
place.

#225072 stopped emitting
llvm.strip.invariant.group on the clang side.

This PR now removes the intrinsic entirely. To be on the safe side, it
is upgraded to llvm.launder.invariant.group. For Clang's specific usage,
just dropping it would be fine.
llvm-upstreamsync Bot pushed a commit to qualcomm/cpullvm-toolchain that referenced this pull request Sep 23, 2026
This intrinsic was originally introduced to make sure that if we have a
dominating condition like `a == launder.invariant.group(a)`, we don't
end up replacing the latter with the former, as that would allow the
optimizer to assume that the memory stays invariant, despite going
through a launder operation. Wrapping both comparison operands in
strip.invariant.group avoids the issue, because replacing one stripped
pointer with another is safe.

The underlying issue was fixed in
llvm/llvm-project#224281 (and prior work), which
ensures that the problematic replacement cannot happen in the first
place.

llvm/llvm-project#225072 stopped emitting
llvm.strip.invariant.group on the clang side.

This PR now removes the intrinsic entirely. To be on the safe side, it
is upgraded to llvm.launder.invariant.group. For Clang's specific usage,
just dropping it would be fine.
llvm-sync Bot pushed a commit to arm/arm-toolchain that referenced this pull request Sep 23, 2026
This intrinsic was originally introduced to make sure that if we have a
dominating condition like `a == launder.invariant.group(a)`, we don't
end up replacing the latter with the former, as that would allow the
optimizer to assume that the memory stays invariant, despite going
through a launder operation. Wrapping both comparison operands in
strip.invariant.group avoids the issue, because replacing one stripped
pointer with another is safe.

The underlying issue was fixed in
llvm/llvm-project#224281 (and prior work), which
ensures that the problematic replacement cannot happen in the first
place.

llvm/llvm-project#225072 stopped emitting
llvm.strip.invariant.group on the clang side.

This PR now removes the intrinsic entirely. To be on the safe side, it
is upgraded to llvm.launder.invariant.group. For Clang's specific usage,
just dropping it would be fine.
laoshd pushed a commit to laoshd/llvm-project that referenced this pull request Sep 30, 2026
This intrinsic was originally introduced to make sure that if we have a
dominating condition like `a == launder.invariant.group(a)`, we don't
end up replacing the latter with the former, as that would allow the
optimizer to assume that the memory stays invariant, despite going
through a launder operation. Wrapping both comparison operands in
strip.invariant.group avoids the issue, because replacing one stripped
pointer with another is safe.

The underlying issue was fixed in
llvm#224281 (and prior work), which
ensures that the problematic replacement cannot happen in the first
place.

llvm#225072 stopped emitting
llvm.strip.invariant.group on the clang side.

This PR now removes the intrinsic entirely. To be on the safe side, it
is upgraded to llvm.launder.invariant.group. For Clang's specific usage,
just dropping it would be fine.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

llvm:analysis Includes value tracking, cost tables and constant folding llvm:transforms

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants