Skip to content

Commit 61907eb

Browse files
authored
[Clang][CodeGen] Do not use the GEP result to infer offset and result type (#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 #130734.
1 parent ecc3545 commit 61907eb

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

clang/lib/CodeGen/CGBuilder.h

+14-10
Original file line numberDiff line numberDiff line change
@@ -64,21 +64,25 @@ class CGBuilderTy : public CGBuilderBaseTy {
6464
Address createConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1,
6565
const llvm::Twine &Name) {
6666
const llvm::DataLayout &DL = BB->getDataLayout();
67-
llvm::GetElementPtrInst *GEP;
67+
llvm::Value *V;
6868
if (IsInBounds)
69-
GEP = cast<llvm::GetElementPtrInst>(CreateConstInBoundsGEP2_32(
70-
Addr.getElementType(), emitRawPointerFromAddress(Addr), Idx0, Idx1,
71-
Name));
69+
V = CreateConstInBoundsGEP2_32(Addr.getElementType(),
70+
emitRawPointerFromAddress(Addr), Idx0,
71+
Idx1, Name);
7272
else
73-
GEP = cast<llvm::GetElementPtrInst>(CreateConstGEP2_32(
74-
Addr.getElementType(), emitRawPointerFromAddress(Addr), Idx0, Idx1,
75-
Name));
73+
V = CreateConstGEP2_32(Addr.getElementType(),
74+
emitRawPointerFromAddress(Addr), Idx0, Idx1, Name);
7675
llvm::APInt Offset(
7776
DL.getIndexSizeInBits(Addr.getType()->getPointerAddressSpace()), 0,
7877
/*isSigned=*/true);
79-
if (!GEP->accumulateConstantOffset(DL, Offset))
80-
llvm_unreachable("offset of GEP with constants is always computable");
81-
return Address(GEP, GEP->getResultElementType(),
78+
if (!llvm::GEPOperator::accumulateConstantOffset(
79+
Addr.getElementType(), {getInt32(Idx0), getInt32(Idx1)}, DL,
80+
Offset))
81+
llvm_unreachable(
82+
"accumulateConstantOffset with constant indices should not fail.");
83+
llvm::Type *ElementTy = llvm::GetElementPtrInst::getIndexedType(
84+
Addr.getElementType(), {Idx0, Idx1});
85+
return Address(V, ElementTy,
8286
Addr.getAlignment().alignmentAtOffset(
8387
CharUnits::fromQuantity(Offset.getSExtValue())),
8488
IsInBounds ? Addr.isKnownNonNull() : NotKnownNonNull);

0 commit comments

Comments
 (0)