Skip to content

Compiler generates wrong code for assigning struct fields #16621

@thefallenidealist

Description

@thefallenidealist

Zig Version

0.11.0-dev.4000+3022c525e

Steps to Reproduce and Observed Behavior

Hi
Firstly, thanks for the interesting new language (and tutorials & videos)!
I am playing with Zig for the past few months with STM32 MCU board (armv7 thumb2)

Compiler started to generate wrong machine code for this part of my STM32 code:

Systick.CSR = .{
	.ENABLE = 1,
	.TICKINT = 1,
	.CLKSOURCE = 1,
};

I would expect that after it runs value in Systick.CSR register will be 0x7 but it is 0x6. GDB:

p/x *0xe000e010
0x6

watch *0xe000e010
CSR value: 0 -> 1 -> 3 -> 7 -> 6

I would also expect that example above will write 0x7 in the single pass but I'll leave that for the future investigation.

Systick is struct:

const struct_Systick = packed struct {
	CSR:     CSR,
	// ...
	const CSR = packed struct {
		ENABLE:    u1 = 0,
		TICKINT:   u1 = 0,
		CLKSOURCE: u1 = 0,
		_res1:    u13 = 0,
		COUNTFLAG: u1 = 0,
		_res2:    u15 = 0,
	};
};

Noticed on 2023.07.01. with (I think) zig version 0.11.0-dev.3892.
Before it was working but I am not sure with which version.
Tested today with 0.11.0-dev.4000+3022c525e and problem still persist.
Platform is FreeBSD 14.0-CURRENT with LLVM16 from ports.

One of the workaround is to try to write additional bit to the Systick.CSR (which will be ignored):

Systick.CSR = .{
	.ENABLE = 1,
	.TICKINT = 1,
	.CLKSOURCE = 1,
	.COUNTFLAG = 1,	// never written to CSR register, but it will help to write .ENABLE bit to CSR register
};

Now GDB will show values for Systick.CSR: 0 -> 1 -> 3 -> 7

I'll try to create minimal example of this later.
Possible related to bug report #16615

Expected Behavior

After this code runs

Systick.CSR = .{
	.ENABLE = 1,
	.TICKINT = 1,
	.CLKSOURCE = 1,
};

Systick.CSR value should be 7

Metadata

Metadata

Assignees

No one assigned

    Labels

    backend-llvmThe LLVM backend outputs an LLVM IR Module.bugObserved behavior contradicts documented or intended behaviormiscompilationThe compiler reports success but produces semantically incorrect code.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions