Skip to content

Add a 🛸 gc canonical ABI mode - #773

Open
fitzgen wants to merge 2 commits into
WebAssembly:mainfrom
fitzgen:gc
Open

fitzgen wants to merge 2 commits into
WebAssembly:mainfrom
fitzgen:gc

Conversation

@fitzgen

@fitzgen fitzgen commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator

Fixes #525

Depends on #772

`tagged_code_units` used the source memory's tag, but `store_string_into_range`
decoded it with the target memory's tag, so passing strings between 32- and
64-bit memories checked the wrong tag and this was guest-observable due to the
wrong `realloc` calls getting made.

This is fixed by having `load_string_from_range` eagerly decode and remember the
`String`'s encoding hint and `store_string_into_range` to just use that hint,
rather than try to read the hint itself.

Additionally, I made a `class StringHint(Enum)` so that it is more clear what
the hint cases are, and to differentiate dynamic hints from actual encodings and
the `string-encoding` canon option values.
@fitzgen

fitzgen commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

(Responding to this comment over here in the PR thread, where I think it makes sense to discuss specifics of the proposed ABI, now that it exists as a proper PR instead of an issue comment.)

@rossberg

The variant encoding is problematic, because it creates a fundamental discontinuity: by just adding or removing a case, the encoding can change unexpectedly and completely, for all other cases. That's not robust.

It is already the case today, with the linear memory ABI, that adding or removing a case can change the flattening from, e.g., [discriminant:i32 payload_union:i32] to [discriminant:i32 payload_union:i64] and similar for the in-memory representation. Do you see the GC ABI's equivalent changes when adding a case as any worse? In both the linear-memory ABI and GC ABI scenarios, adding a case is a breaking ABI change, which I would expect anyways since adding cases breaks existing exhaustive matches, so I think neither is any worse than the other.

The more canonical way to encode a variant while still preserving flattening typically is to use eqref, and all (small enough) nullary constructors become i31ref, while all others become (ref $variant). No special case needed then.

To make sure I understand, you're suggesting that

  • There is no special-casing of payload-free variants
  • The (ref $base) and the (rec (type $base (sub final (struct (field $discriminant <discriminant_type>))))) that represent all cases be replaced with (ref eq)
  • The payload-free cases be just their discriminant, encoded as (ref i31)s
  • The cases with payloads be something like (ref $case-i) where (rec (type $case-i (sub final (struct (field $discriminant <discriminant_type>) (field $payload <gc_storage_type(T)>)))))

Is that correct?

How does one do $O(1)$ exhaustive case matching with this approach?

I guess if there was a single common supertype for all the cases with payloads that introduced the $discriminant field, you could do an O(1) check for (ref i31) followed by either an $O(1)$ br_table on the i31 or an $O(1)$ br_table on the $discriminant field of the cases-with-payloads-supertype struct, maintaining $O(1)$ cost for the whole exhaustive case match, something like this:

block (result (ref i31))
  ...
  local.get $my-variant

  ;; Check for payload-free `case`s.
  br_on_cast (ref i31) 0

  ;; Handle `case`s with payloads.
  block
    block
      ...
        block
          local.get $my-variant
          ref.cast $my-variant-with-payload-supertype
          struct.get $my-variant-with-payload-supertype $discriminant
          br_table ...
        end
      ...
    end
    ...
  end
  ...

  unreachable
end

;; Handle payload-free cases
block
  block
    ...
      block
        local.get $my-variant
        ref.cast (ref i31)
        br_table ...
      end
    ...
  end
  ...
end
...

And while I admit that will give $O(1)$ exhaustive matching, it still feels somewhat displeasing because we've just moved the special-casing from choosing a static type at compile-time to performing an extra dynamic downcast at run-time. So I don't think that imposing run-time cost, even though it still maintains $O(1)$, is worth the proposed representation clean up.

Alternatively, if we wanted to statically choose a representation statically at compile-time between something like

  • (ref i31) -- for variants where no case has a payload

  • (ref $variant-base) -- for variants where at least one case has a payload

then we could achieve a variants-are-always-a-reference representation while also avoiding that extra dynamic downcast at run-time. (This is the same as the PR's current rules, but using (ref i31) instead of the smallest (potentially packed) integer that can hold the discriminant.) However, this alternative still has the downside, compared to the PR's current representation, where it wastes space: a payload-free variant (aka what enums desugar into) is always 4-bytes large, even when the discriminant could fit in a single byte, so e.g. (record "field" (enum A B C)) becomes (struct (field (ref i31))) instead of (struct (field i8)).

Yet another alternative is to remove the no-case-has-a-payload special case, and always use the (ref $variant-base) representation, including for variants where no case has a payload. But this imposes object allocation and GC pressure costs at run-time for values that are effectively just integers, which is quite suboptimal. Especially since enums desugar into variants without payloads -- this feels like too great a cost to pay. We really want enums to just be integers at the ABI level.

@sjrd

sjrd commented Nov 24, 2026

Copy link
Copy Markdown

We don't need to actually allocate anything for the cases without payload, even when they are represented as structs. They are statically known singletons; they can be allocated once and for all (well, once per component, since it doesn't know about the other ones).

For enums, I agree a simple integer is still better.

Either way to me using i31 brings only downsides in this situation.

@fitzgen

fitzgen commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

@sjrd

For enums, I agree a simple integer is still better.

Unfortunately, it isn't something orthogonal that we can discuss or special-case separately because the component model defines enums as syntax sugar for variants where each case has no payload.

We don't need to actually allocate anything for the cases without payload, even when they are represented as structs. They are statically known singletons; they can be allocated once and for all (well, once per component, since it doesn't know about the other ones).

That's a good point that the toolchain can pre-allocate or hashcons cases that they send across the ABI boundary, but the toolchain cannot do that for cases that they receive. Those values are created by the engine during lowering (imagine a linear-memory ABI component is returning the case value to a GC ABI component). Since whether the engine does hashconsing or pre-allocation is observable by guests via ref.eq and object identity, we would need to explicitly spec that behavior. But even better than having to spec pre-allocation or hashconsing is unasking the question by not using objects for these values, IMO.

But this actually raises an issue with the PR's current state: it specs allocating new objects during lowering (e.g. invoking struct.new) and ref.eq and object identity makes it observable whether e.g. a list<u8> -> list<u8> identity function across a component boundary returned its given array object or allocated a new copy. The goal has been, of course, that immutable GC objects don't need to be reallocated and copied. Since whether they are reallocated and copied is observable, we would need to spec that they must not be reallocated and copied, which will require some changes to the spec Python code, so that lifted CM values optionally hold onto the GC object that they were lifted from, and return that from lowering when it is present and compatible with the lowering. I don't love this...

@sjrd

sjrd commented Nov 24, 2026

Copy link
Copy Markdown

Can we spec it as intentionally unspecified whether we reallocate? Like we do for NaN's?

@lukewagner

Copy link
Copy Markdown
Member

Just on this point:

Unfortunately, it isn't something orthogonal that we can discuss or special-case separately because the component model defines enums as syntax sugar for variants where each case has no payload.

"Specializations" aren't quite syntactic sugar: they're treated as distinct type constructors (not type-equal to what they are a specialization of) and in some cases are given distinct ABIs (viz., string and flags). Thus "specialization" is mostly just a way to simplify/condense definitions.

@rossberg

Copy link
Copy Markdown
Member

@fitzgen:

Is that correct?

Yes, that's a typical representation that functional languages, which invented variants after all, have been using for decades.

It's true that this requires an extra cast for dispatching on a non-nullary constructor in Wasm, but many things do. Accessing such a constructor already requires a cast anyway.

The difficulty with avoiding allocations is that this effectively only works when you have a dedicated "owner" for a type definition who can provide the canonical constants, which is difficult to reconcile with structural and modular type definitions.

Following what @lukewagner says, that seems unrelated to unboxing types that are explicitly declared as enums.

@lukewagner lukewagner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great to see work on this! A few high-level questions/suggestions that affect the broader strokes:

Comment thread design/mvp/Text.md
| (canon thread.spawn-ref shared? core-prefix(<core:typeidx>) (core func <id>?)) 🧵②
| (canon thread.spawn-indirect shared? core-prefix(<core:typeidx>) core-prefix(<core:tableidx>) (core func <id>?)) 🧵②
| (canon thread.available-parallelism shared? (core func <id>?)) 🧵②
| (canon gc.resource.new <typeidx> (core func <id>?)) 🛸

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Understood that in the binary format, we need new opcodes b/c they don't already take opts. But in the AST and text format, I think we can backwards-compatibly add a gc? immediate to all the existing built-ins and then have the new opcodes decode to the existing built-ins with gc set. (We do this hack/trick in a number of other cases, like when we added async? to func type constructors.) Then, in CanonicalABI.md, we don't need a bunch of new built-in function definitions but, rather, you just in-place add a new gc boolean parameter (which is nice for code-sharing and seeing more-clearly how and where gc differs from linear memory).

Comment thread design/mvp/Binary.md
| 0x40 sh?:<sh?> ft:<core:typeidx> => (canon thread.spawn-ref sh? ft (core func)) 🧵②
| 0x41 sh?:<sh?> ft:<core:typeidx> t:<core:tableidx> => (canon thread.spawn-indirect sh? ft t (core func)) 🧵②
| 0x42 sh?:<sh?> => (canon thread.available-parallelism sh? (core func)) 🧵②
| 0x43 dst:<core:typeidx> src:<core:typeidx> => (canon array.new-array dst src (core func)) 🛸

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if, for simplicity of implementation, we can pick a single new opcode byte representing "the following built-in but with the gc option set", and then follow that with the existing binary encoding of an existing built-in. Taking a few liberties, I think we could write it like this:

| 0x50 b:<gcable-builtin> => add-gc(b) where add-gc((name rest)) = (name gc rest)

and then (in a refactoring PR/commit we could merge eagerly to minimize rebase pain) we could split out gcable-builtin from canon:

canon ::= 0x00 ... => (canon lift ...)
        | 0x01 ... => (canon lower ...)
        | b:<gcable-builtin> => b
        | ... everything else not covered by the above

and then when we add built-ins we can stick them in gcable-builtin as appropriate and hopefully both the spec and impl can have an easy time with it.

Comment thread design/mvp/Concurrency.md
```wat
(func (param $event-code i32)
(param $payload i32)
(param $waitable (ref null extern))

@lukewagner lukewagner Dec 3, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: do we need GC references for waitables? The big difference between waitables and owned handles is that they are implicitly kept alive while they are waiting for an event (whether you are explicitly waiting for them via waitable-set or not) and then once you receive that terminal event, you know you can drop them. Even with streams/futures, I think we don't want/need unreachability to implicitly cancel/drop (and, e.g., the WHATWG Streams API explicitly forbids this: a stream stays alive until the other end explicitly closes it or it is explicitly cancelled). Similarly, I think waitable-sets don't need to be GC'd (afaik, they are either global singletons or are scoped to a task which again has an explicit end-of-life that can be used to waitable-set.drop).

EDIT: in my initial version of this comment, I was asking about how you you correlate data with a waitable if it's an externref, but I see gc.handle-ref.get now is proposed to address that. However, if my suggestion in the previous paragraph works out and we can keep using i32 indicies for waitables, then I think it's quite possible we won't need handle-ref.{index,new,get} just for owned/borrowed handles either (they don't have the analogous challenge since there's no waitable-set.wait/callback where you're given an externref that you need to correlate with some previous usage of that same externref... you always get a fresh externref). This would be good b/c otherwise it seems like, if a host finalizer implicitly frees a handle-table element that has i32-index-correlated state, since guest code doesn't find out when this happens, the guest code can't reliably free/unregister the i32-indexed correlated state.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Pre-Proposal: Wasm GC Support in the Canonical ABI

4 participants