Skip to content
This repository was archived by the owner on Apr 23, 2020. It is now read-only.

Commit 7428509

Browse files
committed
[InstSimplify] Fold gep (gep V, C), (sub 0, V) to C
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@277952 91177308-0d34-0410-b5e6-96231b3b80d8
1 parent 2a07d9f commit 7428509

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

lib/Analysis/InstructionSimplify.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3645,6 +3645,26 @@ static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
36453645
}
36463646
}
36473647

3648+
// gep (gep V, C), (sub 0, V) -> C
3649+
if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3650+
all_of(Ops.slice(1).drop_back(1),
3651+
[](Value *Idx) { return match(Idx, m_Zero()); })) {
3652+
unsigned PtrWidth =
3653+
Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3654+
if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3655+
APInt BasePtrOffset(PtrWidth, 0);
3656+
Value *StrippedBasePtr =
3657+
Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3658+
BasePtrOffset);
3659+
3660+
if (match(Ops.back(),
3661+
m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3662+
auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3663+
return ConstantExpr::getIntToPtr(CI, GEPTy);
3664+
}
3665+
}
3666+
}
3667+
36483668
// Check to see if this is constant foldable.
36493669
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
36503670
if (!isa<Constant>(Ops[i]))

test/Transforms/InstSimplify/compare.ll

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,19 @@ define i1 @gep17() {
219219
; CHECK-NEXT: ret i1 true
220220
}
221221

222+
define i32 @gep18() {
223+
; CHECK-LABEL: @gep18(
224+
%alloca = alloca i32, align 4 ; alloca + 0
225+
%gep = getelementptr inbounds i32, i32* %alloca, i32 1 ; alloca + 4
226+
%bc = bitcast i32* %gep to [4 x i8]* ; alloca + 4
227+
%pti = ptrtoint i32* %alloca to i32 ; alloca
228+
%sub = sub i32 0, %pti ; -alloca
229+
%add = getelementptr [4 x i8], [4 x i8]* %bc, i32 0, i32 %sub ; alloca + 4 - alloca == 4
230+
%add_to_int = ptrtoint i8* %add to i32 ; 4
231+
ret i32 %add_to_int ; 4
232+
; CHECK-NEXT: ret i32 4
233+
}
234+
222235
define i1 @zext(i32 %x) {
223236
; CHECK-LABEL: @zext(
224237
%e1 = zext i32 %x to i64

0 commit comments

Comments
 (0)