zeynelsagcan - 9 hours ago

Hi Gabriele,

I've prepared a patch for SDCC bug #4276, which concerns incorrect initialization of anonymous unions in the PIC16 backend.

Root cause:

SDCC promotes members of anonymous unions into the containing structure's field list. The common initializer implementation handles the union as a single storage object and skips inactive alternatives.

However, the PIC16-specific implementation in pic16_printIvalStruct() processes those alternatives separately, incorrectly consuming additional initializer values. This can produce incorrect initialized data and, in some cases, emit more bytes than the actual structure size.

Changes:

  • Updated pic16_printIvalStruct() to follow the common initializer traversal logic.
  • Added support for selecting the appropriate union alternative when designated initializers are present.
  • Corrected skipping of inactive union alternatives and padding to subsequent field offsets.
  • Exported the existing designatedAlternative() and fieldHasIval() helpers for reuse by PIC16.
  • Kept the common initializer behavior unchanged.

Validation:

  • The original #4276 reproducer now generates the expected initialized bytes.
  • Additional cases involving designated initializers, larger union alternatives, and bit-fields were checked.
  • Five of seven existing anonymous-union regression cases previously generated incorrect PIC16 initialization data; the corrected output was inspected against the structure layouts.
  • Another 531 struct/union test cases produced unchanged output before and after the patch.
  • The patch applies cleanly to the r17307 source tree.

PIC16 validation was performed by compiling the test cases and comparing the generated initialization data against the expected structure layouts.

PIC16 runtime simulation was not performed because GPSIM was unavailable in the test environment.

Files modified:

  • src/SDCCglue.c
  • src/SDCCglue.h
  • src/SDCCval.c
  • src/pic16/glue.c

No PIC24-specific source files are modified. The changes to the common compiler sources are limited to exposing existing helper functions and related declarations or comments.

Attachment: bug4276-pic16-anon-union-init_v11.patch

Best regards

 

Last edit: zeynelsagcan 9 hours ago