[Clang][CodeGen] Respect -fwrapv-pointer when emitting struct GEPs (#134269)

This patch turns off inbounds/nuw flags for member accesses when
`-fwrapv-pointer` is set.

Closes https://github.com/llvm/llvm-project/issues/132449.

It is required by https://github.com/llvm/llvm-project/pull/130734.
This commit is contained in:
Yingwei Zheng 2025-04-10 00:48:18 +08:00 committed by GitHub
parent 543e5f5842
commit c0480738cb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 30 additions and 2 deletions

View File

@ -4915,6 +4915,9 @@ static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
unsigned idx =
CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
if (CGF.getLangOpts().PointerOverflowDefined)
return CGF.Builder.CreateConstGEP2_32(base, 0, idx, field->getName());
return CGF.Builder.CreateStructGEP(base, idx, field->getName());
}
@ -4972,9 +4975,13 @@ LValue CodeGenFunction::EmitLValueForField(LValue base,
if (!UseVolatile) {
if (!IsInPreservedAIRegion &&
(!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
if (Idx != 0)
if (Idx != 0) {
// For structs, we GEP to the field that the record layout suggests.
Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
if (getLangOpts().PointerOverflowDefined)
Addr = Builder.CreateConstGEP2_32(Addr, 0, Idx, field->getName());
else
Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
}
} else {
llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
getContext().getRecordType(rec), rec->getLocation());

View File

@ -10,3 +10,24 @@ void test(void) {
// DEFAULT: getelementptr inbounds nuw i32, ptr
// FWRAPV-POINTER: getelementptr i32, ptr
}
struct S {
int a;
int b;
int c: 10;
int d: 10;
};
int test_struct(struct S* s) {
// -fwrapv-pointer should turn off inbounds nuw for struct GEP's
return s->b;
// DEFAULT: getelementptr inbounds nuw %struct.S, ptr
// FWRAPV-POINTER: getelementptr %struct.S, ptr
}
int test_struct_bitfield(struct S* s) {
// -fwrapv-pointer should turn off inbounds nuw for struct GEP's
return s->d;
// DEFAULT: getelementptr inbounds nuw %struct.S, ptr
// FWRAPV-POINTER: getelementptr %struct.S, ptr
}