# Sema: fix comptime union initialization · gitcafe/zig

[View on GitCafe](https://git.cafe/gitcafe/zig/commit/9dc98fbabbd5e91622d2459ec6265a8dae2405b8)

Repository: [gitcafe/zig](https://git.cafe/gitcafe/zig)

Visibility: public

Requested revision: 9dc98fbabbd5e91622d2459ec6265a8dae2405b8

Requested commit: 9dc98fbabbd5e91622d2459ec6265a8dae2405b8

Commit: 9dc98fbabbd5e91622d2459ec6265a8dae2405b8

Tree: e6198957420b30ae672a581d0e25e09771fbbcfc

Author: Andrew Kelley

Committer: Andrew Kelley

## Message

```
Sema: fix comptime union initialization

The mechanism behind initializing a union's tag is a bit complicated,
depending on whether the union is initialized at runtime,
forced comptime, or implicit comptime.

`coerce_result_ptr` now does not force a block to be a runtime context;
instead of adding runtime instructions directly, it forwards analysis to
the respective functions for initializing optionals and error unions.

`validateUnionInit` now has logic to still emit a runtime
`set_union_tag` instruction even if the union pointer is comptime-known,
for the case of a pointer that is not comptime mutable, such as a
variable or the result of `@intToPtr`.

`validateStructInit` looks for a completely different pattern now; it
now handles the possibility of the corresponding AIR instruction for
the `field_ptr` to be missing or the corresponding `store` to be missing.
See the new comment added to the function for more details. An
equivalent change should probably be made to `validateArrayInit`.

`analyzeOptionalPayloadPtr` and `analyzeErrUnionPayloadPtr` functions now
emit a `optional_payload_ptr_set` or `errunion_payload_ptr_set`
instruction respectively if `initializing` is true and the pointer value
is not comptime-mutable.

`storePtr2` now tries the comptime pointer store before checking if the
element type has one possible value because the comptime pointer store
can have side effects of setting a union tag, setting an optional payload
non-null, or setting an error union to be non-error.

The LLVM backend `lowerParentPtr` function is improved to take into
account the differences in how the LLVM values are lowered depending on
the Zig type. It now handles unions correctly as well as additionally
handling optionals and error unions.

In the LLVM backend, the instructions `optional_payload_ptr_set` and
`errunion_payload_ptr_set` check liveness analysis and only do the side
effects in the case the result of the instruction is unused.

A few wasm and C backend test cases regressed, but they are due to TODOs
in lowering of constants, so this is progress.

```

## Parents

- [7f48bc3493fbfb4487285c4e532acd6fad8cefa5](https://git.cafe/gitcafe/zig/commit/7f48bc3493fbfb4487285c4e532acd6fad8cefa5?format=markdown)

[Source at this commit](https://git.cafe/gitcafe/zig/tree/9dc98fbabbd5e91622d2459ec6265a8dae2405b8?format=markdown)
