Commit graph

195 commits

Author SHA1 Message Date
Luuk de Gram
90f08a69aa wasm: Enable passing behavior tests
This also adds some float-related instructions to MIR/Emit
2022-03-09 13:53:20 -07:00
Andrew Kelley
38c161afab Sema: fix @hasDecl for simple enums 2022-03-07 13:54:25 -07:00
Andrew Kelley
c467f6693e stage2: fix union layout returning non-zero for zero-sized tag 2022-03-07 13:36:58 -07:00
Andrew Kelley
06b1a88a15 Sema: implement cast from anon struct ptr to union ptr 2022-03-02 20:18:22 -07:00
Andrew Kelley
f5e2e301e9 Sema: add coercion from anon structs to unions 2022-03-02 19:22:31 -07:00
Andrew Kelley
1c8a86f063 Sema: detect comptime-known union initializations
Follow a similar pattern as we already do for validate_array_init and
validate_struct_init.

I threw in a bit of behavior test cleanup on top of it.
2022-03-02 17:28:39 -07:00
Jakub Konka
ec54ceee6d
Merge pull request #11016 from ziglang/x64-more-codegen 2022-03-01 09:14:23 +01:00
Andrew Kelley
157f66ec07 Sema: fix pointer type hash and equality functions
Several issues with pointer types are fixed:

Prior to this commit, Zig would not canonicalize a pointer type with
an explicit alignment to alignment=0 if it matched the pointee ABI
alignment. In order to fix this, `Type.ptr` now takes a Target
parameter. I also moved the host_size canonicalization to `Type.ptr`
since target is now available. Similarly, is_allowzero in the case of
C pointers is now treated as a canonicalization done by the function
rather than a precondition.

in-memory coercion for pointers now properly checks ABI alignment
of pointee types instead of incorrectly treating the 0 value as an
alignment.

Type equality is completely reworked based on the tag() rather than the
zigTypeTag(). It's still semantically based on zigTypeTag() but that
knowledge is implied rather than dictating the control flow of the
logic. Importantly, this fixes cases for opaques, structs, tuples,
enums, and unions, where type equality was incorrectly returning based
on whether the tag() values were equal.

Additionally, pointer type equality now takes into account alignment.
Because we canonicalize non-zero alignment which equals pointee type ABI
alignment to alignment=0, this now can be a simple integer comparison.

Type hashing is implemented for pointers and floats. Array types now
additionally hash their sentinels.

This regressed some behavior tests that were passing but only because
of bugs regarding type equality.

The C backend has a noticeable problem with lowering differently-aligned
pointers (particularly slices) as the same type, causing C compilation
errors due to duplicate declarations.
2022-02-28 19:22:16 -07:00
Jakub Konka
66d28d0f20 x64: implement get_union_tag for register 2022-02-28 23:20:05 +01:00
Jakub Konka
decc90e0e7 x64: clean up loadMemPtrIntoRegister abstraction 2022-02-28 23:20:05 +01:00
Jakub Konka
331cc810de
Merge pull request #11012 from ziglang/x64-union-tag
stage2,x64: basic (un)tagged unions
2022-02-28 17:42:59 +01:00
Jakub Konka
16f9774d2d x64: fix switch condition mir; pass more union tests 2022-02-28 15:25:40 +01:00
Jakub Konka
a61ac9ecbf x64: fix store with ABI size > 8 on stack; pass union tests 2022-02-28 12:14:41 +01:00
joachimschmidt557
91fbcf7093
stage2 ARM: enable more behavior tests 2022-02-27 21:38:56 +01:00
Andrew Kelley
2687b8f7f4 stage2: implement @unionInit
The ZIR instruction `union_init_ptr` is renamed to `union_init`.
I made it always use by-value semantics for now, not taking the time to
invest in result location semantics, in case we decide to change the
rules for unions. This way is much simpler.

There is a new AIR instruction: union_init. This is for a comptime known
tag, runtime-known field value.
vector_init is renamed to aggregate_init, which solves a TODO comment.
2022-02-26 20:59:36 -07:00
Andrew Kelley
32e89a98d8 Sema: implement union value equality at comptime
Still TODO is extern unions.
2022-02-26 20:59:23 -07:00
Andrew Kelley
aefe4046de Sema: implement @enumToInt for unions 2022-02-26 16:53:23 -07:00
Andrew Kelley
d62229e3ad Sema: Module.Union.abiAlignment can return 0
When the union is a 0-bit type.
2022-02-26 16:53:23 -07:00
Jakub Konka
1b8ed7842c macho: redo selection of segment/section for decls and consts
* fix alignment issues for consts with natural ABI alignment not
  matching that of the `ldr` instruction in `aarch64` - solved by
  preceeding the `ldr` with an additional `add` instruction to form
  the full address before dereferencing the pointer.
* redo selection of segment/section for decls and consts based on
  combined type and value
2022-02-25 21:59:19 +01:00
Jakub Konka
d657ede324 x64: disable printing results on macos until I fix the linker
Hopefully, this will make the CI green, and in the meantime I can
fix the bugs in the MachO linker.
2022-02-22 21:57:44 +01:00
Jakub Konka
25e4b16e25 Port more behavior tests 2022-02-22 21:57:42 +01:00
Andrew Kelley
c2a9a591f6 Sema: fix union auto-enum numbering 2022-02-21 23:50:20 -07:00
Andrew Kelley
9dc98fbabb 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.
2022-02-21 23:49:38 -07:00
Andrew Kelley
0b7347fd18 move more behavior tests to the "passing" section 2022-02-12 21:35:29 -07:00
Andrew Kelley
c10fdde5a6 stage2: LLVM backend: make unnamed struct globals
LLVM union globals have to be lowered as unnamed structs if the
non-most-aligned field is the active tag. In this case it bubbles up so
that structs containing unions have the same restriction.

This fix needs to be applied to optionals and other callsites of
createNamedStruct.

The bug fixed in this commit was revealed in searching for
the cause of #10837.
2022-02-10 00:27:02 -07:00
Luuk de Gram
0682c9ac33
wasm: Implement genTypedValue for enums
This makes all union test cases succeed.
`rem` was also implemented as all we had to do is enable the instruction.
Loading and storing values based on ABI-size was simplified to a direct abiSize() call.

We also enabled all the newly passing test cases and disable them for all non-passing backends.
All of those test cases were verified to see if they perhaps already pass for the c-backend.
2022-01-25 19:29:40 +01:00
Andrew Kelley
b34f994c0b stage2: type system treats fn ptr and body separately
This commit updates stage2 to enforce the property that the syntax
`fn()void` is a function *body* not a *pointer*. To get a pointer, the
syntax `*const fn()void` is required.

ZIR puts function alignment into the func instruction rather than the
decl because this way it makes it into function types. LLVM backend
respects function alignments.

Struct and Union have methods `fieldSrcLoc` to help look up source
locations of their fields. These trigger full loading, tokenization, and
parsing of source files, so should only be called once it is confirmed
that an error message needs to be printed.

There are some nice new error hints for explaining why a type is
required to be comptime, particularly for structs that contain function
body types.

`Type.requiresComptime` is now moved into Sema because it can fail and
might need to trigger field type resolution. Comptime pointer loading
takes into account types that do not have a well-defined memory layout
and does not try to compute a byte offset for them.

`fn()void` syntax no longer secretly makes a pointer. You get a function
body type, which requires comptime. However a pointer to a function body
can be runtime known (obviously).

Compile errors that report "expected pointer, found ..." are factored
out into convenience functions `checkPtrOperand` and `checkPtrType` and
have a note about function pointers.

Implemented `Value.hash` for functions, enum literals, and undefined values.

stage1 is not updated to this (yet?), so some workarounds and disabled
tests are needed to keep everything working. Should we update stage1 to
these new type semantics? Yes probably because I don't want to add too
much conditional compilation logic in the std lib for the different
backends.
2022-01-24 21:47:53 -07:00
Andrew Kelley
be5130ec53 compiler_rt: move more functions to the stage2 section
also move more already-passing behavior tests to the passing section.
2021-12-29 00:39:25 -07:00
Andrew Kelley
efb7148a45 Sema: more union fixes
* `Module.Union.getLayout`: fixes to support components of the union
   being 0 bits.
 * Implement `@typeInfo` for unions.
 * Add missing calls to `resolveTypeFields`.
 * Fix explicitly-provided union tag types passing a `Zir.Inst.Ref`
   where an `Air.Inst.Ref` was expected. We don't have any type safety
   for this; these typess are aliases.
 * Fix explicitly-provided `union(enum)` tag Values allocated to the
   wrong arena.
2021-12-28 23:22:09 -07:00
Andrew Kelley
91619cdf57 Sema: implement calling a fn ptr via a union field
Also, ignore `packed` on unions because that will be removed from the
language.
2021-12-28 23:22:09 -07:00
Andrew Kelley
81a3910e44 Sema: improve union support
* reduce number of branches in zirCmpEq
 * implement equality comparison for enums and unions
 * fix coercion from union to its tag type resulting in the wrong type
 * fix method calls of unions
 * implement peer type resolution for unions, enums, and enum literals
 * fix union tag type memory in the wrong arena
2021-12-28 20:20:30 -07:00
Andrew Kelley
4b9b9e7257 stage2: LLVM backend: fix lowering of union constants
Comment from this commit reproduced here:

LLVM does not allow us to change the type of globals. So we must
create a new global with the correct type, copy all its attributes,
and then update all references to point to the new global,
delete the original, and rename the new one to the old one's name.
This is necessary because LLVM does not support const bitcasting
a struct with padding bytes, which is needed to lower a const union value
to LLVM, when a field other than the most-aligned is active. Instead,
we must lower to an unnamed struct, and pointer cast at usage sites
of the global. Such an unnamed struct is the cause of the global type
mismatch, because we don't have the LLVM type until the *value* is created,
whereas the global needs to be created based on the type alone, because
lowering the value may reference the global as a pointer.
2021-12-28 01:53:58 -07:00
Andrew Kelley
3af9731600 stage2: implement runtime pointer access to global constants
The main problem that motivated these changes is that global constants
which are referenced by pointer would not be emitted into the binary.
This happened because `semaDecl` did not add `codegen_decl` tasks for
global constants, instead relying on the constant values being copied as
necessary. However when the global constants are referenced by pointer,
they need to be sent to the linker to be emitted.

After making global const arrays, structs, and unions get emitted, this
uncovered a latent issue: the anonymous decls that they referenced would
get garbage collected (via `deleteUnusedDecl`) even though they would
later be referenced by the global const.

In order to solve this problem, I introduced `anon_work_queue` which is
the same as `work_queue` except a lower priority. The `codegen_decl`
task for anon decls goes into the `anon_work_queue` ensuring that the
owner decl gets a chance to mark its anon decls as alive before they are
possibly deleted.

This caused a few regressions, which I made the judgement call to add
workarounds for. Two steps forward, one step back, is still progress.

The regressions were:
 * Two behavior tests having to do with unions. These tests were
   intentionally exercising the LLVM constant value lowering, however,
   due to the bug with garbage collection that was fixed in this commit,
   the LLVM code was not getting exercised, and union types/values were
   not implemented correctly, due to me forgetting that LLVM does not
   allow bitcasting aggregate values.
   - This is worked around by allowing those 2 test cases to regress,
     moving them to the "passing for stage1 only" section.
 * The test-stage2 test cases (in test/cases/*) for non-LLVM backends
   previously did not have any calls to lower struct values, but now
   they do. The code that was there was just `@panic("TODO")`. I
   replaced that code with a stub that generates the wrong value. This
   is an intentional miscompilation that will obviously need to get
   fixed before any struct behavior tests pass. None of the current
   tests we have exercise loading any values from these global const
   structs, so there is not a problem until we try to improve these
   backends.
2021-10-26 22:41:19 -07:00
Andrew Kelley
dfb3231959 stage2: implement switching on unions
* AstGen: Move `refToIndex` and `indexToRef` to Zir
 * ZIR: the switch_block_*_* instruction tags are collapsed into one
   switch_block tag which uses 4 bits for flags, and reduces the
   scalar_cases_len field from 32 to 28 bits.
   This freed up more ZIR tags, 2 of which are now used for
   `switch_cond` and `switch_cond_ref` for producing the switch
   condition value. For example, for union values it returns the
   corresponding enum value.
 * switching with multiple cases and ranges is not yet supported because
   I want to change the ZIR encoding to store index pointers into the
   extra array rather than storing prong indexes. This will avoid O(N^2)
   iteration over prongs.
 * AstGen now adds a `switch_cond` on the operand and then passes the
   result of that to the `switch_block` instruction.
 * Sema: partially implement `switch_capture_*` instructions.
 * Sema: `unionToTag` notices if the enum type has only one possible value.
2021-10-19 20:22:47 -07:00
Andrew Kelley
8b88274781 stage2: improved union support
* `Module.Union.getFullyQualifiedName` returns a sentinel-terminated
   slice so that backends that need null-termination do not need an
   additional copy.
 * Module.Union: implement a `getLayout` function which returns
   information about ABI size and alignment so that the LLVM backend can
   properly lower union types into llvm types.
 * Sema: `resolveType` now returns `error.GenericPoison` rather than a
   Type with tag `generic_poison`. Callsites that want to allow that
   need to bypass this higher-level function.
 * Sema: implement coercion of enums and enum literals to unions.
 * Sema: fix comptime mutation of pointers to unions
 * LLVM backend: fully implement proper lowering of union types and
   values according to the union layout, and update the handling of AIR
   instructions that deal with unions to support union layouts.
 * LLVM backend: handle `decl_ref_mut`
   - Maybe this should be unreachable since comptime vars should be
     changed to be non-mutable when they go out of scope, but it's
     harmless for the LLVM backend to support lowering the value.
 * Type: fix `requiresComptime` for optionals, pointers, and some other
   types. This function is still wrong for structs, unions, and enums.
2021-10-14 17:44:46 -07:00
Andrew Kelley
09e1f37cb6 stage2: implement union coercion to its own tag
* AIR: add `get_union_tag` instruction
   - implement in LLVM backend
 * Sema: implement == and != for union and enum literal
   - Also implement coercion from union to its own tag type
 * Value: implement hashing for union values

The motivating example is this snippet:

    comptime assert(@typeInfo(T) == .Float);

This was the next blocker for stage2 building compiler-rt.
Now it is switch at compile-time on an integer.
2021-09-27 23:11:00 -07:00
Andrew Kelley
c0aa4a1a42 stage2: implement basic unions
* AIR instructions struct_field_ptr and related functions now are also
   emitted by the frontend for unions. Backends must inspect the type
   of the pointer operand to lower the instructions correctly.
   - These will be renamed to `agg_field_ptr` (short for "aggregate") in
     the future.
 * Introduce the new `set_union_tag` AIR instruction.
 * Introduce `Module.EnumNumbered` and associated `Type` methods. This
   is for enums which have no decls, but do have the possibility of
   overriding the integer tag type and tag values.
 * Sema: Implement support for union tag types in both the
   auto-generated and explicitly-provided cases, as well as explicitly
   provided enum tag values in union declarations.
 * LLVM backend: implement lowering union types, union field pointer
   instructions, and the new `set_union_tag` instruction.
2021-09-27 19:53:29 -07:00
Andrew Kelley
aecebf38ac stage2: progress towards ability to compile compiler-rt
* prepare compiler-rt to support being compiled by stage2
   - put in a few minor workarounds that will be removed later, such as
     using `builtin.stage2_arch` rather than `builtin.cpu.arch`.
   - only try to export a few symbols for now - we'll move more symbols
     over to the "working in stage2" section as they become functional
     and gain test coverage.
   - use `inline fn` at function declarations rather than `@call` with an
     always_inline modifier at the callsites, to avoid depending on the
     anonymous array literal syntax language feature (for now).
 * AIR: replace floatcast instruction with fptrunc and fpext for
   shortening and widening floating point values, respectively.
 * Introduce a new ZIR instruction, `export_value`, which implements
   `@export` for the case when the thing to be exported is a local
   comptime value that points to a function.
   - AstGen: fix `@export` not properly reporting ambiguous decl
     references.
 * Sema: handle ExportOptions linkage. The value is now available to all
   backends.
   - Implement setting global linkage as appropriate in the LLVM
     backend. I did not yet inspect the LLVM IR, so this still needs to
     be audited. There is already a pending task to make sure the alias
     stuff is working as intended, and this is related.
   - Sema almost handles section, just a tiny bit more code is needed in
     `resolveExportOptions`.
 * Sema: implement float widening and shortening for both `@floatCast`
   and float coercion.
   - Implement the LLVM backend code for this as well.
2021-09-21 23:21:07 -07:00
g-w1
ef56e42a2a
stage2: fix unreachable in union(enum) with anytype payload 2021-06-27 12:26:29 +03:00
Jacob G-W
9fffffb07b fix code broken from previous commit 2021-06-21 17:03:03 -07:00
Jacob G-W
641ecc260f std, src, doc, test: remove unused variables 2021-06-21 17:03:03 -07:00
Veikka Tuominen
e63ff4f1c1 add ast-check flag to zig fmt, fix found bugs 2021-06-14 00:16:40 +03:00
Martin Wickham
fc9430f567 Breaking hash map changes for 0.8.0
- hash/eql functions moved into a Context object
- *Context functions pass an explicit context
- *Adapted functions pass specialized keys and contexts
- new getPtr() function returns a pointer to value
- remove functions renamed to fetchRemove
- new remove functions return bool
- removeAssertDiscard deleted, use assert(remove(...)) instead
- Keys and values are stored in separate arrays
- Entry is now {*K, *V}, the new KV is {K, V}
- BufSet/BufMap functions renamed to match other set/map types
- fixed iterating-while-modifying bug in src/link/C.zig
2021-06-03 17:02:16 -05:00
Andrew Kelley
5619ce2406 Merge remote-tracking branch 'origin/master' into stage2-whole-file-astgen
Conflicts:
 * doc/langref.html.in
 * lib/std/enums.zig
 * lib/std/fmt.zig
 * lib/std/hash/auto_hash.zig
 * lib/std/math.zig
 * lib/std/mem.zig
 * lib/std/meta.zig
 * test/behavior/alignof.zig
 * test/behavior/bitcast.zig
 * test/behavior/bugs/1421.zig
 * test/behavior/cast.zig
 * test/behavior/ptrcast.zig
 * test/behavior/type_info.zig
 * test/behavior/vector.zig

Master branch added `try` to a bunch of testing function calls, and some
lines also had changed how to refer to the native architecture and other
`@import("builtin")` stuff.
2021-05-08 14:45:21 -07:00
Andrew Kelley
4307436b99 move behavior tests from test/stage1/ to test/
And fix test cases to make them pass. This is in preparation for
starting to pass behavior tests with self-hosted.
2021-04-29 15:54:04 -07:00
Renamed from test/stage1/behavior/union.zig (Browse further)