https://github.com/dtcxzyw created https://github.com/llvm/llvm-project/pull/134221
If `CreateConstInBoundsGEP2_32` returns a constant null/gep, the cast to GetElementPtrInst will fail. This patch uses two static helpers `GEPOperator::accumulateConstantOffset/GetElementPtrInst::getIndexedType` to infer offset and result type instead of depending on the GEP result. This patch is extracted from https://github.com/llvm/llvm-project/pull/130734. It may be useful to fix https://github.com/llvm/llvm-project/issues/132449. >From e07237777e3a2215f69ced633fd281ac026eda61 Mon Sep 17 00:00:00 2001 From: Yingwei Zheng <dtcxzyw2...@gmail.com> Date: Thu, 3 Apr 2025 16:32:56 +0800 Subject: [PATCH] [Clang][CodeGen] Do not use the GEP result to infer offset --- clang/lib/CodeGen/CGBuilder.h | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/clang/lib/CodeGen/CGBuilder.h b/clang/lib/CodeGen/CGBuilder.h index b8036cf6e6a30..090f75d3b5d3c 100644 --- a/clang/lib/CodeGen/CGBuilder.h +++ b/clang/lib/CodeGen/CGBuilder.h @@ -64,21 +64,25 @@ class CGBuilderTy : public CGBuilderBaseTy { Address createConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name) { const llvm::DataLayout &DL = BB->getDataLayout(); - llvm::GetElementPtrInst *GEP; + llvm::Value *V; if (IsInBounds) - GEP = cast<llvm::GetElementPtrInst>(CreateConstInBoundsGEP2_32( - Addr.getElementType(), emitRawPointerFromAddress(Addr), Idx0, Idx1, - Name)); + V = CreateConstInBoundsGEP2_32(Addr.getElementType(), + emitRawPointerFromAddress(Addr), Idx0, + Idx1, Name); else - GEP = cast<llvm::GetElementPtrInst>(CreateConstGEP2_32( - Addr.getElementType(), emitRawPointerFromAddress(Addr), Idx0, Idx1, - Name)); + V = CreateConstGEP2_32(Addr.getElementType(), + emitRawPointerFromAddress(Addr), Idx0, Idx1, Name); llvm::APInt Offset( DL.getIndexSizeInBits(Addr.getType()->getPointerAddressSpace()), 0, /*isSigned=*/true); - if (!GEP->accumulateConstantOffset(DL, Offset)) - llvm_unreachable("offset of GEP with constants is always computable"); - return Address(GEP, GEP->getResultElementType(), + if (!llvm::GEPOperator::accumulateConstantOffset( + Addr.getElementType(), {getInt32(Idx0), getInt32(Idx1)}, DL, + Offset)) + llvm_unreachable( + "accumulateConstantOffset with constant indices should not fail."); + llvm::Type *ElementTy = llvm::GetElementPtrInst::getIndexedType( + Addr.getElementType(), {Idx0, Idx1}); + return Address(V, ElementTy, Addr.getAlignment().alignmentAtOffset( CharUnits::fromQuantity(Offset.getSExtValue())), IsInBounds ? Addr.isKnownNonNull() : NotKnownNonNull); _______________________________________________ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits