Skip to content

Commit

Permalink
[InstSimplify] Remove zero-index opaque pointer GEP
Browse files Browse the repository at this point in the history
With opaque pointers, a zero-index GEP is a no-op. It does not
need to be retained for the pointer element type change it may
perform.
  • Loading branch information
nikic committed Feb 10, 2022
1 parent 9d90531 commit 87a0b1b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
6 changes: 6 additions & 0 deletions llvm/lib/Analysis/InstructionSimplify.cpp
Expand Up @@ -4473,6 +4473,12 @@ static Value *SimplifyGEPInst(Type *SrcTy, Value *Ptr,
}
}

// For opaque pointers an all-zero GEP is a no-op. For typed pointers,
// it may be equivalent to a bitcast.
if (Ptr->getType()->isOpaquePointerTy() &&
all_of(Indices, [](const auto *V) { return match(V, m_Zero()); }))
return Ptr;

// getelementptr poison, idx -> poison
// getelementptr baseptr, poison -> poison
if (isa<PoisonValue>(Ptr) ||
Expand Down
28 changes: 28 additions & 0 deletions llvm/test/Transforms/InstSimplify/opaque-ptr.ll
@@ -0,0 +1,28 @@
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
; RUN: opt -S -instsimplify -opaque-pointers < %s | FileCheck %s

define ptr @gep_zero_indices(ptr %p) {
; CHECK-LABEL: @gep_zero_indices(
; CHECK-NEXT: ret ptr [[P:%.*]]
;
%p2 = getelementptr { i64, i64 }, ptr %p, i64 0, i32 0
ret ptr %p2
}

define ptr @gep_non_zero_indices1(ptr %p) {
; CHECK-LABEL: @gep_non_zero_indices1(
; CHECK-NEXT: [[P2:%.*]] = getelementptr { i64, i64 }, ptr [[P:%.*]], i64 0, i32 1
; CHECK-NEXT: ret ptr [[P2]]
;
%p2 = getelementptr { i64, i64 }, ptr %p, i64 0, i32 1
ret ptr %p2
}

define ptr @gep_non_zero_indices2(ptr %p) {
; CHECK-LABEL: @gep_non_zero_indices2(
; CHECK-NEXT: [[P2:%.*]] = getelementptr { i64, i64 }, ptr [[P:%.*]], i64 1, i32 0
; CHECK-NEXT: ret ptr [[P2]]
;
%p2 = getelementptr { i64, i64 }, ptr %p, i64 1, i32 0
ret ptr %p2
}

0 comments on commit 87a0b1b

Please sign in to comment.