Index: llvm/lib/Analysis/ConstantFolding.cpp =================================================================== --- llvm/lib/Analysis/ConstantFolding.cpp +++ llvm/lib/Analysis/ConstantFolding.cpp @@ -866,21 +866,6 @@ Type *IntIdxTy = DL.getIndexType(Ptr->getType()); - // If this is "gep i8* Ptr, (sub 0, V)", fold this as: - // "inttoptr (sub (ptrtoint Ptr), V)" - if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) { - auto *CE = dyn_cast(Ops[1]); - assert((!CE || CE->getType() == IntIdxTy) && - "CastGEPIndices didn't canonicalize index types!"); - if (CE && CE->getOpcode() == Instruction::Sub && - CE->getOperand(0)->isNullValue()) { - Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType()); - Res = ConstantExpr::getSub(Res, CE->getOperand(1)); - Res = ConstantExpr::getIntToPtr(Res, ResTy); - return ConstantFoldConstant(Res, DL, TLI); - } - } - for (unsigned i = 1, e = Ops.size(); i != e; ++i) if (!isa(Ops[i])) return nullptr; @@ -1336,6 +1321,19 @@ DL, BaseOffset, /*AllowNonInbounds=*/true)); if (Base->isNullValue()) { FoldedValue = ConstantInt::get(CE->getContext(), BaseOffset); + } else { + // ptrtoint (gep i8, Ptr, (sub 0, V)) -> sub (ptrtoint Ptr), V + if (GEP->getNumIndices() == 1 && + GEP->getSourceElementType()->isIntegerTy(8)) { + auto *Ptr = cast(GEP->getPointerOperand()); + auto *Sub = dyn_cast(GEP->getOperand(1)); + Type *IntIdxTy = DL.getIndexType(Ptr->getType()); + if (Sub && Sub->getType() == IntIdxTy && + Sub->getOpcode() == Instruction::Sub && + Sub->getOperand(0)->isNullValue()) + FoldedValue = ConstantExpr::getSub( + ConstantExpr::getPtrToInt(Ptr, IntIdxTy), Sub->getOperand(1)); + } } } if (FoldedValue) { Index: llvm/test/Transforms/InstCombine/constant-fold-gep.ll =================================================================== --- llvm/test/Transforms/InstCombine/constant-fold-gep.ll +++ llvm/test/Transforms/InstCombine/constant-fold-gep.ll @@ -126,7 +126,7 @@ define i8* @gep_sub_self() { ; CHECK-LABEL: @gep_sub_self( -; CHECK-NEXT: ret i8* null +; CHECK-NEXT: ret i8* getelementptr (i8, i8* @g, i64 sub (i64 0, i64 ptrtoint (i8* @g to i64))) ; %p.int = ptrtoint i8* @g to i64 %p.int.neg = sub i64 0, %p.int @@ -136,7 +136,7 @@ define i8* @gep_sub_self_plus_addr(i64 %addr) { ; CHECK-LABEL: @gep_sub_self_plus_addr( -; CHECK-NEXT: [[P2:%.*]] = getelementptr i8, i8* null, i64 [[ADDR:%.*]] +; CHECK-NEXT: [[P2:%.*]] = getelementptr i8, i8* getelementptr (i8, i8* @g, i64 sub (i64 0, i64 ptrtoint (i8* @g to i64))), i64 [[ADDR:%.*]] ; CHECK-NEXT: ret i8* [[P2]] ; %p.int = ptrtoint i8* @g to i64 @@ -183,7 +183,7 @@ define i8* @gep_sub_other() { ; CHECK-LABEL: @gep_sub_other( -; CHECK-NEXT: ret i8* inttoptr (i64 sub (i64 ptrtoint (i8* @g to i64), i64 ptrtoint (i8* @g2 to i64)) to i8*) +; CHECK-NEXT: ret i8* getelementptr (i8, i8* @g, i64 sub (i64 0, i64 ptrtoint (i8* @g2 to i64))) ; %p.int = ptrtoint i8* @g2 to i64 %p.int.neg = sub i64 0, %p.int