Skip to content

Commit 261580c

Browse files
authored
[InstSimplify] Support non-inbounds GEP in ptrdiff fold (llvm#162676)
We can fold ptrdiff(ptradd(p, x), p) to x regardless of whether the ptradd is inbounds. Proof: https://alive2.llvm.org/ce/z/Xuvc7N
1 parent 31e85cc commit 261580c

File tree

2 files changed

+4
-8
lines changed

2 files changed

+4
-8
lines changed

llvm/lib/Analysis/InstructionSimplify.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -671,12 +671,12 @@ Value *llvm::simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
671671
/// This is very similar to stripAndAccumulateConstantOffsets(), except it
672672
/// normalizes the offset bitwidth to the stripped pointer type, not the
673673
/// original pointer type.
674-
static APInt stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
675-
bool AllowNonInbounds = false) {
674+
static APInt stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V) {
676675
assert(V->getType()->isPtrOrPtrVectorTy());
677676

678677
APInt Offset = APInt::getZero(DL.getIndexTypeSizeInBits(V->getType()));
679-
V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
678+
V = V->stripAndAccumulateConstantOffsets(DL, Offset,
679+
/*AllowNonInbounds=*/true);
680680
// As that strip may trace through `addrspacecast`, need to sext or trunc
681681
// the offset calculated.
682682
return Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(V->getType()));

llvm/test/Transforms/InstSimplify/ptr_diff.ll

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,7 @@ define i64 @ptrdiff(ptr %ptr) {
1414

1515
define i64 @ptrdiff_no_inbounds(ptr %ptr) {
1616
; CHECK-LABEL: @ptrdiff_no_inbounds(
17-
; CHECK-NEXT: [[LAST:%.*]] = getelementptr i8, ptr [[PTR:%.*]], i32 42
18-
; CHECK-NEXT: [[FIRST_INT:%.*]] = ptrtoint ptr [[PTR]] to i64
19-
; CHECK-NEXT: [[LAST_INT:%.*]] = ptrtoint ptr [[LAST]] to i64
20-
; CHECK-NEXT: [[DIFF:%.*]] = sub i64 [[LAST_INT]], [[FIRST_INT]]
21-
; CHECK-NEXT: ret i64 [[DIFF]]
17+
; CHECK-NEXT: ret i64 42
2218
;
2319
%last = getelementptr i8, ptr %ptr, i32 42
2420
%first.int = ptrtoint ptr %ptr to i64

0 commit comments

Comments
 (0)