[llvm] [ValueTracking] Prove constant-offset PtrAdd into known-size allocation is not poison. (PR #187825)
Nikita Popov via llvm-commits
llvm-commits at lists.llvm.org
Sun Mar 29 03:09:25 PDT 2026
================
@@ -7798,6 +7798,33 @@ static bool isGuaranteedNotToBeUndefOrPoison(
isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
return true;
+ // A GEP matching with PtrAdd into a known-size allocation cannot produce
+ // poison if the constant offset in bytes is non-negative, within the
+ // allocated range, and does not wrap at truncation to the pointer index type.
+ // Note that for PtrAdd, the offset in bytes is equal to the first & only
+ // index, and when the index is non-negative, no signed wrap (nusw) implies no
+ // unsigned wrap (nuw).
+ const Value *BasePtr;
+ const APInt *ConstIdx;
+ if (match(V, m_PtrAdd(m_Value(BasePtr), m_NonNegative(ConstIdx)))) {
+ BasePtr = BasePtr->stripPointerCastsSameRepresentation();
+ const DataLayout *DL = nullptr;
+ if (auto *AI = dyn_cast<AllocaInst>(BasePtr))
+ DL = &AI->getDataLayout();
+ else if (auto *GV = dyn_cast<GlobalVariable>(BasePtr))
+ DL = &GV->getDataLayout();
+ if (DL) {
+ unsigned IdxBitWidth = DL->getIndexTypeSizeInBits(V->getType());
+ if (ConstIdx->isSignedIntN(IdxBitWidth)) {
+ bool CanBeNull, CanBeFreed;
+ uint64_t DerefBytes =
+ BasePtr->getPointerDereferenceableBytes(*DL, CanBeNull, CanBeFreed);
+ if (DerefBytes != 0 && ConstIdx->ule(DerefBytes))
----------------
nikic wrote:
I checked and it won't assert. But I still think the condition here is incorrect as written. E.g. if the original index was i16 -1 and the index type size is 32, then this is going to treat the index as 65535. I believe an explicit check for a non-negative index is needed.
https://github.com/llvm/llvm-project/pull/187825
More information about the llvm-commits
mailing list