Skip to content
This repository was archived by the owner on Feb 5, 2019. It is now read-only.

Commit bd3e05c

Browse files
majnemereddyb
authored andcommitted
[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 d31c987 commit bd3e05c

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
@@ -3597,6 +3597,26 @@ static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
35973597
}
35983598
}
35993599

3600+
// gep (gep V, C), (sub 0, V) -> C
3601+
if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3602+
all_of(Ops.slice(1).drop_back(1),
3603+
[](Value *Idx) { return match(Idx, m_Zero()); })) {
3604+
unsigned PtrWidth =
3605+
Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3606+
if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3607+
APInt BasePtrOffset(PtrWidth, 0);
3608+
Value *StrippedBasePtr =
3609+
Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3610+
BasePtrOffset);
3611+
3612+
if (match(Ops.back(),
3613+
m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3614+
auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3615+
return ConstantExpr::getIntToPtr(CI, GEPTy);
3616+
}
3617+
}
3618+
}
3619+
36003620
// Check to see if this is constant foldable.
36013621
for (unsigned i = 0, e = Ops.size(); i != e; ++i)
36023622
if (!isa<Constant>(Ops[i]))

test/Transforms/InstSimplify/compare.ll

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

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

0 commit comments

Comments
 (0)