diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp index 3d3a111f0514a..d32591ed896d0 100644 --- a/clang/lib/CodeGen/CGExpr.cpp +++ b/clang/lib/CodeGen/CGExpr.cpp @@ -4922,6 +4922,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()); } @@ -4979,9 +4982,13 @@ LValue CodeGenFunction::EmitLValueForField(LValue base, if (!UseVolatile) { if (!IsInPreservedAIRegion && (!getDebugInfo() || !rec->hasAttr())) { - 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()); diff --git a/clang/test/CodeGen/pointer-overflow.c b/clang/test/CodeGen/pointer-overflow.c index 9c7821b841980..70e3c855bff90 100644 --- a/clang/test/CodeGen/pointer-overflow.c +++ b/clang/test/CodeGen/pointer-overflow.c @@ -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 +}