Skip to content

BigInt addition: Moving analysis to toolchains #50

Closed

Description

@jakobkummerow

Background

BigInts are commonly represented as arrays of "digits" or "limbs", typically register-sized unsigned integers. So adding two BigInts means adding these digits and propagating carries; basically like elementary school math, just with bigger digits. In pseudo code, assuming identical length for simplicity, this is:

let carry = 0;
for (let i = 0; i < length; i++) {
  result[i], new_carry = add3(a[i], b[i], carry);
  carry = new_carry;
}

The code for the helper function add3 needs a way to express the carry it produces; languages like C++ or Rust typically accomplish that by using a type that's wider than the digit type:

u64 add3(u64 a, u64 b, u64 c_in, u64* c_out) {
  u128 result = u128{a} + u128{b} + u128{c};
  *c_out = result >> 64;
  return cast<u64>(result);
}

Of course, today's common 64-bit CPUs don't have 128-bit addition instructions, so compilers compile this code to a sequence of 64-bit operations. It's easy for a compiler to realize that the upper half of 64-to-128 bit widenings like u128{a} is zero, and to optimize out this constant. That leads to a machine code sequence like the following (x86_64; actual Clang output; all the names are denoting registers):

mov   result_low, carry_reg
xor   carry_reg, carry_reg
add   result_low, [src1 + 8*index]
setc  carry_reg
add   result_low, [src2 + 8*index]
adc   carry_reg, 0
mov   [dst + 8*index], result_low

Note that there are 3 additions in this sequence: one for adding c_in+a, one for adding b onto that, one for adding the two carry bits that the previous two additions might have produced. That's a correct translation for a context-free interpretation of the add3 function above: if all of a, b, c_in are sufficiently large values, then c_out could be 2, and all three additions perform nontrivial work.

Optimization opportunity

However, if we inline add3 into the for-loop above and take that context into account, we can generate a more optimal machine code sequence that needs only one or two additions. The reason is that carry starts out as 0, and in the loop's first iteration can at most become 1, and then in every following iteration is also guaranteed to remain in range 0..1: even if a and b are both maximal, at most one carry bit is produced by adding up all three values: 0xFFFF'FFFF'FFFF'FFFF + 0xFFFF'FFFF'FFFF'FFFF + 1 == 0x1'FFFF'FFFF'FFFF'FFFF. So there is no need for the third addition, and one of the other two can be replaced with a shift; we can get by with just this:

shr   carry_reg, 1  ;; Shifts carry_reg into the carry flag
mov   result_low, [src1 + 8*index]
adc   result_low, [src2 + 8*index]
setc  carry_reg  ;; register was zeroed by initial `shr`
mov   [dst + 8*index], result_low

Emitting this optimal machine code sequence hence requires analyzing the context and figuring out that one of the three inputs to add3 is guaranteed to remain in range 0..1. It is entirely possible to run this analysis in the optimizing JIT compiler of a Wasm engine. However, I argue that a design that allows moving this analysis work to AOT toolchains/optimizers would be a better fit for Wasm's philosophy: it would allow even simple engines to emit optimal machine code, without having to run fancy analysis passes first. This requires the Wasm wire bytes to carry more information than the add128 instruction in the current version of this proposal does.

Approach 1: Range annotation

One obvious approach would be to directly express the notion that c_in is in range 0..1. We could devise various range annotation schemes for this; one straightforward way to do it would be to introduce an i1 type. AOT toolchains (in particular: LLVM in Wasm mode) would detect the pattern discussed above, and would translate the entire add3 function to a single Wasm instruction add_with_carry with signature [i64, i64, i1] -> [i64, i1]. Engines could, with zero further analysis, translate that single Wasm instruction to the optimal machine code sequence; that's super simple to do even for a single-pass baseline compiler.

The i1 type would be a special tool for a special purpose; it would not be a general-purpose arithmetic type with a complete set of operations that process it. Like other scalar types, it would have no interaction with any other type (no subtyping/casting/…). It would not require any special hardware support, and would not be expected to be represented in the CPU's flags register. Recall its purpose, which is to annotate a register-sized integer with the fact that its value is guaranteed to be in range 0..1. So engines would be expected to represent it internally as exactly that: a conveniently-sized integer, with range information expressed by its type, which compilers can use to emit better code.

The only instructions required for an i1 type would be those that the loop above uses:

  • i1.const for initializing the local. (Technically, implicit zero-initialization might be enough, but it's probably nice to have an instruction for this.)
  • add_with_carry and its mirror image sub_with_borrow
  • some way to inspect or convert the final carry after the end of the loop, perhaps i64.extend_i1 and/or i1.eqz.

The only places where an i1 type must definitely be allowed to occur is in locals and on the value stack; however since it's just a "conveniently sized integer with attached range information", it is easy to allow it anywhere: function signatures, globals, structs, arrays.

Approach 2: "Special" instruction behavior

A possible alternative approach would be to only use existing types for add_with_carry's signature: [i64, i64, i64] -> [i64, i64], and add extra descriptions to the instruction's specified behavior.

Variant A: "the third input must be in range 0..1, and then the second output will also be in that range; otherwise the behavior is implementation-defined". That would allow engines to emit the optimal code sequence above, and simply not care about the weirdness that will happen if c_in > 1. (You may think "invalid inputs should trap", but as the assembly snippets in this post show, the whole endeavor is about shaving off every single machine instruction that we can get rid of, so adding a check for a trap would be way too costly to be worth it in comparison to the potential gains.)

Variant B: "the third input is treated like a boolean value: any value > 0 is treated as if it were 1. The second output is always in range 0..1". This idea of "treat it as a boolean" has precedent in the if instruction, which takes an i32 but only cares whether it is zero or non-zero. This variant would require a slightly different instruction sequence with distinct carry_in/carry_out registers, replacing the initial shr with an add to perform the "rounding" of any nonzero value to 1, and using an xor to clear carry_out:

xor   carry_out, carry_out
add   carry_in, -1  ;; sets carry flag iff carry_in != 0
mov   result_low, [src1 + 8*index]
adc   result_low, [src2 + 8*index]
setc  carry_out
mov   [dst + 8*index], result_low

While this seems at first like it would require an additional mov to move the value from carry_out to carry_in for the next iteration, this is often not the case in practice due to loop unrolling: for such a small loop, optimizing compilers will typically emit at least two copies of the loop body anyway, and can hence "ping-pong" the carry value between two registers without additional cost.

(You might consider replacing the xor before the setc with a zero-extending movzx after it, which would easily make it possible to use the same register for carry_in and carry_out, but that turns out to be slower due to CPU-internal data dependencies.)

It could make sense to use a different type for the third input just to make it clearer that the three are not interchangeable. The obvious choice for that would be i32, so we'd have [i64, i64, i32] -> [i64, i32] (with the same semantics as before).

Performance

It turns out that the two optimized machine code sequences above (the one with shr for "third input is in 0..1 range, either due to i1 type annotation or due to instruction semantics that ignore anything else", and the one with add -1 for "third input is treated as boolean") have practically the same performance.
In a loop that adds two BigInts (i.e. vectors of u64 digits stored in linear memory), the optimized sequences are consistently 9% faster than the original sequence on my machine (Zen 3). I think that speedup is worth having!
In Alex' i128 benchmarks, the largest impact is on "fib_10000" with around 3% improvement in my measurements. Considering that a Fibonacci benchmark should mostly be performing additions, I'm surprised that the impact is so much less there; I have not spent the time to figure out why that is.

Other thoughts

Adding an i1 type "just for this" might feel like a lot of effort, but considering that it would only need a very small instruction set, I argue that it would, in fact, not be a lot of effort. For engines it would be less implementation work than the add128 version of this proposal. And it could be a good investment in the sense that it could have other uses in the future.

In particular, it would be unfortunate if we accepted a slightly weird workaround now just to get by without an i1 type, only to introduce it next time it's useful. That said, aesthetics of the wire bytes don't really matter, and the approach of treating an i32 as a boolean works just as well to accomplish the performance goals here.

One conceivable future use for i1 is bit packing in struct fields, even denser than i8 fields. Of course the type would be just a hint and an engine's actual behavior unobservable, just like today it is up to engines to represent an i8 as an actual byte, rather than just treating it as an alias for "i32", and just like it is up to engines to reorder a field sequence like [i8, i32, i8] for better density.

Activity

  1. alexcrichton commented on Jul 28, 2026

    @alexcrichton
    Collaborator

    Would you be able to share guest source code and/or wasm binaries for the benchmark that you were running? I could try prototyping this in Wasmtime and see what the performance effect is there, for example.

    Additionally, do you know how difficult it would be to implement this sort of instruction in LLVM, and do you know if LLVM-emitted code matches the expected performance here? I originally started with this shape of instruction and found it very difficult to get LLVM to emit reasonable-looking wasm code. My attempts still required engines to jump through a lot of hoops to generate the machine code you describe here, it wasn't as simple as "just do this one translation for this wasm instruction and it all works".

    Finally, performance-wise, my other impression is that the loop you describe here is rarely what LLVM actually codegens. I would expect LLVM to unroll the loop to have a sequence of a fixed number of add3 operations. In this situation the instruction lowering you're proposing is pretty far from optimal because being optimal requires keeping the i1 in the flags register. This is similar to #33 where what LLVM sort of does is i(N*128)_add_with_carry rather than just i64. Currently i64.add128 isn't great for i256 arithmetic, but this is why I've tried to focus on end-to-end benchmarks where LLVM runs in full for both native and the guest to get a hopefully-complete picture of performance.

    Adding an i1 type "just for this" might feel like a lot of effort, but considering that it would only need a very small instruction set, I argue that it would, in fact, not be a lot of effort.

    I wrote up some words for this in the explainer, but I can expand a bit more here. I believe that adding i1 is large undertaking. From purely the perspective of a single engine I can see how it's probably not the most work, but broadening the scope the work items to support i1 are:

    • All wasm tooling needs to add a new value type. I maintain wasm-tools for example and this includes text-to-binary, binary-to-text, fuzz generation, shrinking, encoding etc. All of these locations need to add support for new instructions, new types, etc.
    • Engines are required to get i1 working "everywhere", even in places that are unlikely to ever get used by toolchains. For example struct fields, globals, function parameters/returns, etc. In my opinion, even for a single engine, this is a significant amount of work to take on. This touches a lot on core VM internals which means that any mistake anywhere is maybe-a-security-bug.
    • From a language perspective, retroactively adding i1 to WebAssembly for just this one operation feels like quite a wart. For example all comparison instructions (e.g. i32.le_u) morally produce an i1 and would then have to be rationalized with why they produce i32 instead of i1. There's also what I believe would be a nontrivial amount of work to formalize a specification for i1 with formal semantics at all.
    • In my opinion history has shown that intentional gaps in the instruction set, for example i1 only supporting a small handful of now-necessary operations, does not hold up against the test of time. In the limit of time there will be a desire to add a full suite of functionality for i1 beyond what's there today. To me this means that adding a minimal i1 with the rationale of "not too much work" today is not taking into account all the future work that will be necessary to maintain and support i1.
  2. jakobkummerow commented on Jul 29, 2026

    @jakobkummerow
    Author

    Would you be able to share guest source code and/or wasm binaries for the benchmark that you were running?

    Sure: https://chromium-review.googlesource.com/c/v8/v8/+/8138965/2/test/mjsunit/wasm/wide-add-benchmark.js

    Or if you prefer .wat syntax:

    Details
    (module
      (memory $memory (;0;) (export "memory") 40 40)
      (func $loop_v1 (;0;) (export "loop_v1") (param $var0 i32) (param $var1 i32) (param $var2 i32) (param $var3 i32) (result i64)
        (local $var4 i32)
        (local $var5 i32)
        (local $var6 i64)
        local.get $var3
        i32.const 3
        i32.shl
        local.set $var5
        i32.const 0
        local.set $var4
        i64.const 0
        local.set $var6
        block $label0
          loop $label1
            local.get $var4
            local.get $var5
            i32.ge_s
            br_if $label0
            local.get $var2
            local.get $var4
            i32.add
            local.get $var0
            local.get $var4
            i32.add
            i64.load
            i64.const 0
            local.get $var1
            local.get $var4
            i32.add
            i64.load
            i64.const 0
            i64.add128
            local.get $var6
            i64.const 0
            i64.add128
            local.set $var6
            i64.store
            local.get $var4
            i32.const 8
            i32.add
            local.set $var4
            br $label1
          end $label1
        end $label0
        local.get $var6
      )
    )

    As you can see, this module uses a pair of i64.add128 instructions as currently proposed. Pattern matching, range analysis, and transformation to add3 happen on the fly; it's all implemented in the CL linked above.

    do you know how difficult it would be to implement this sort of instruction in LLVM

    I've talked to the LLVM experts on our team and they said it looked quite feasible, and they'd be willing to implement it if that's where this proposal goes.

    the instruction lowering you're proposing is pretty far from optimal

    Well, it's a clear improvement over the existing alternative of translating add128 to machine code directly. Please do feel encouraged to come up with even better approaches!

    ...i1...

    I'm well aware that you're opposed to adding a type. I don't find the arguments you've listed convincing, but be that as it may: I've already described an alternative that gets by without adding a new type. I'm sure there are even more ways to enable wire bytes to make a binding statement about the range of the "carry in" value, if neither of the two I've described is satisfactory.

  3. jakobkummerow commented on Jul 29, 2026

    @jakobkummerow
    Author

    found it very difficult to get LLVM to emit reasonable-looking wasm code

    FWIW, there appears to be room for toolchain improvement even with the current status quo of add128. Implementing the exact same workload as above in C++ using V8's actual production code for BigInt addition and compiling it with Emscripten 6.0.4, I get:

    Baseline: x64 native, Clang 21.1.8 -O3: 377 ms

    keeping add128 on-the-fly conversion to add_with_carry, "treat as boolean" codegen
    Emscripten-compiled C++ 513 ms (+36%) 454 ms (+20%)
    handwritten Wasm 418 ms (+11%) 383 ms (+1.6% 🥳 )

    So the relative speedup that's unlocked by a restricted-range input is actually even greater there, but it's unfortunate that Emscripten-generated Wasm is so far behind handwritten Wasm in this case. The wire bytes do look a bit convoluted; not sure if locals handling is what's affecting performance or just looks weird:

            i64.const 0
            i64.add128
            local.set $var34
            local.tee $var33
            local.get $var34
            local.set $var25
            local.tee $var24
            local.get $var25
            local.set $var9
            local.tee $var8
            local.set $var17
            local.get $var9
            local.set $var3

    (Interestingly, a native binary compiled by GCC 15.2.0 achieves 267 ms (-29%). I haven't checked if that's due to legit optimizations, or if it found a way to cheat on my microbenchmark by shortcutting something...)

  4. tlively commented on Jul 30, 2026

    @tlively
    Member

    The wire bytes do look a bit convoluted; not sure if locals handling is what's affecting performance or just looks weird:

    This looks like Binaryen tripping over the multivalue results (cc @stevenfontanella)

  5. jakobkummerow commented on Jul 30, 2026

    @jakobkummerow
    Author

    This looks like Binaryen tripping over the multivalue results

    Indeed! Linking with -O1 (which AFAIK skips Binaryen) improves that locals sequence, but there's still a little dance that looks unnecessary:

                i64.const 0
                i64.add128
                local.set $var6
                local.set $var5
                local.get $var5
                local.get $var6
    

    Maybe that's WAI because LLVM chooses to rely on Binaryen to optimize that out?

    Also, if I additionally compile to wasm32 instead of wasm64 and hack the C++ BigInt code to nevertheless use uint64_t digits (instead of uintptr_t), this brings performance of the Emscripten-generated module on par with the handwritten module. Yay!

  6. jakobkummerow commented on Jul 31, 2026

    @jakobkummerow
    Author

    Plot twist: GCC emits an instruction sequence that intuitively looks slower but empirically runs faster than what LLVM emits, and doesn't rely on any range restrictions:

    mov  result_low, [src1 + 8*index]
    xor  carry_out, carry_out
    add  result_low, [src2 + 8*index]
    adc  carry_out, 0
    add  result_low, carry_in
    adc  carry_out, 0
    mov  [dst + 8*index], result_low
    

    Wasm can't compete with that performance-wise because operating in Wasm Linear Memory adds a level of indirection compared to native binaries' ability to operate on native memory directly, but for the addition itself this instruction sequence appears to be competitive with the range-restricted sequences discussed earlier. So using this approach, Wasm engines still need to pattern-match add128(add128(a, 0, b, 0), c, 0) and replace it with add3(a, b, c) on the fly (which a slight tweak to this proposal could avoid), but they don't need to worry about inferring the range of the third input via some fancy analysis. This should also alleviate any remaining concerns about the potential difficulty of performing the analysis in toolchains.

    In Emscripten-generated Wasm for BigInt addition, every single add128 instruction is preceded by i64.const 0, supporting the observation that it's only the wide output that matters, not the ability to provide a wide input. Wouldn't an addition instruction that takes i64 inputs and produces a [low, high] pair of results have a very pleasing symmetry with the mul_wide* instructions in this proposal? A version that takes three inputs would be most useful; it would also be easy to have a second version that only takes two inputs if anyone would like to have that:

    i64.add_wide2 : [i64, i64]   →    [i64, i64]  ;; [a_low, b_low]    →     [sum_low, sum_high]
    i64.add_wide3 : [i64, i64, i64] → [i64, i64]  ;; [a_low, b_low, c_low] → [sum_low, sum_high]
    
  7. tlively commented on Jul 31, 2026

    @tlively
    Member

    Looks like that alternative is already discussed in the overview: https://github.com/WebAssembly/wide-arithmetic/blob/main/proposals/wide-arithmetic/Overview.md#alternative-i64add_wide3. The conclusion there is that it's simple enough for the engine to pattern match add128(add128(a, 0, b, 0), c, 0), so we might as well go with a more general generalization (if I'm understanding the argument correctly).

    My personal take is that it would be nicer to avoid those extra constant 0s and the pattern matching, but I don't yet understand the benefit of having the more general generalization. @alexcrichton, can you explain the argument from the overview a little more?

  8. alexcrichton commented on Jul 31, 2026

    @alexcrichton
    Collaborator

    I agree i64.add_wide2 : [i64, i64] -> [i64, i64] would have a nice symmetry, and with i64.add_wide3 that closely aligns with native add and adc instructions on x86_64 as well. My historical testing with a proposal of such a shape is effectively this section of the explainer. For add_wide2 the second output is the overflow flag, and for add_wide3 the third input/second output is more-or-less the overflow value. At the time with end-to-end testing I could not get LLVM to produce code that was then reasonable to codegen in Wasmtime. LLVM has abstractions internally for add/adc lookalikes on all platforms, but if the equivalent of a native add or adc is emitted then it's not required for good performance to avoid materializing the overflow flag in a register. That property is what ended up being extremely difficult to optimize, leading me to i64.add128.

    I realize that everything I just said here is already in the explainer, and also nothing new over what I've mentioned in presentations past. I found the best input for informing this proposal, and the final state with i64.add128, was end-to-end testing from source code to LLVM to an engine and measuring performance of various shapes of the proposal. In the absence of this for add_wide{2,3} I don't know how to think about the performance there. It sounds like you're taking wasm modules with i64.add128 and translating them internally to add_wide{2,3} as opposed to generating modules natively with add_wide{2,3}. My hunch is that it's going to be significantly difficult to get LLVM to emit the add_wide{2,3} module natively in such a way that the engine does not have to "fuse" sibling instructions together to avoid materializing the carry flag. This hunch is sort of exactly where the rationale for this proposal's i64.add128 lies, and in the absence of a working thing to poke at I find it difficult to discuss concrete specifics here.

    Basically I've no doubt we're all familiar with the explainer I've written at this point, but to me it still feels like there's a misunderstanding/disagreement with the conclusions reached. What I would personally find the easiest to reason about would be to have both proposals working end-to-end. For example source code compiled with two sets of flags and then running in the same engine which supports both shapes of the proposal. At that point I would find it much easier to reason about exact tradeoffs made, complexity, performance, etc. I realize that this is a lot of work, but this is also a reflection of all the work I've historically put into this proposal for its current shape.

  9. jakobkummerow commented on Jul 31, 2026

    @jakobkummerow
    Author

    My historical testing with a proposal of such a shape is effectively this section of the explainer

    No, there is a fundamental difference:
    What that section explores is using two add_wide/add_wide3 for one add128, a transformation ("lowering") that increases the number of Wasm instructions.
    What I'm suggesting is the opposite: one add_wide3 instead of two add128, a transformation ("pattern matching") that decreases the number of Wasm instructions.

    I wouldn't know how to make the former approach work well either; we've agreed on that before. Whereas the latter approach leads to identical machine code as the add128 approach, it just changes where the "replace two with one" transformation happens, and as a consequence makes the wire bytes more compact (where, including the i64.const 0 instructions, it would replace five Wasm instructions with just one).

    My hunch is that it's going to be significantly difficult to get LLVM to emit the add_wide{2,3} module natively in such a way that the engine does not have to "fuse" sibling instructions together to avoid materializing the carry flag.

    LLVM would do the fusing (add128(add128(a, 0, b, 0), c, 0) -> add_wide3(a, b, c)), so there's nothing left to fuse for the engine. A single i64.add_wide3 would do the work of two add128, and the engine would translate that single add_wide3 to a sequence consisting of several add/adc machine instructions (e.g. the sequence in my previous message).

  10. alexcrichton commented on Jul 31, 2026

    @alexcrichton
    Collaborator

    I'm doing my best to keep up here, but I'm unfortunately left pretty confused now at this point. I'm sorry if some of these questions sound like repeats, but what I'm thinking now is:

    • If add_wide3 is two add128s, then why is add_wide2 proposed above? Was this just a proposed addition for consistency/uniformity? If not, what is the intended use case? Given that we're agreed on add_wide2 means the overflow flag is materialized, I don't know of a situation where that would actually be used since AFAIK it almost always performs worse than what you can do today.
    • Are you proposing that i1 is no longer needed and add_wide3 is all that's necessary? If yes, then I don't understand why add128 is so controversial because matching two add128s into one add_wide3 is the bread-and-butter of what optimizing compilers already do all the time for wasm today (weaving a tree of wasm instructions into a single or small set of machine instructions). If not, then I'm not sure what this tangent is about with add_wide{2,3} when i1 isn't mentioned with them.

    My understanding is you're currently proposing add_wide3 : [i64 i64 i64] -> [i64 i64] as a replacement for add128 with the rationale that's basically what gcc does which appears to be the fastest in the benchmark you're running. I poked around Wasmtime's codegen for what I believe is the equivalent add128 loop:

    (module
      (memory 1)
      (func $add_leaf (param i32 i32 i32 i64) (result i64)
        (local $t i64)
        local.get 2
        (i64.load (local.get 0))
        i64.const 0
        (i64.load (local.get 1))
        i64.const 0
        i64.add128
        local.get 3
        i64.const 0
        i64.add128
        local.set $t
        i64.store
        local.get $t
      )
    )

    and with a minor tweak I believe Wasmtime is generating basically the same code as GCC:

    wasm[0]::function[0]::add_leaf:
                pushq   %rbp
                movq    %rsp, %rbp
                movq    0x38(%rdi), %rsi
                movl    %edx, %eax
                movq    (%rsi, %rax), %r10
                ╰─╼ trap: Normal(MemoryOutOfBounds)
                movl    %ecx, %edx
                xorq    %rax, %rax
                addq    (%rsi, %rdx), %r10
                ╰─╼ trap: Normal(MemoryOutOfBounds)
                adcq    $0, %rax
                addq    %r9, %r10
                adcq    $0, %rax
                movl    %r8d, %ecx
                movq    %r10, (%rsi, %rcx)
                ╰─╼ trap: Normal(MemoryOutOfBounds)
                movq    %rbp, %rsp
                popq    %rbp
                retq
    

    Sure enough the fib_* benchmark goes from being 24% slower-than-native to 8% slower-than-native.


    So, to clarify, @jakobkummerow are you now thinking this all boils down to a decision between i64.add128 : [i64 i64 i64 i64] -> [i64 i64] and i64.add_wide3 : [i64 i64 i64] -> [i64 i64]?

  11. tlively commented on Jul 31, 2026

    @tlively
    Member

    So, to clarify, @jakobkummerow are you now thinking this all boils down to a decision between i64.add128 : [i64 i64 i64 i64] -> [i64 i64] and i64.add_wide3 : [i64 i64 i64] -> [i64 i64]?

    That's my understanding of the situation.


    Since prototyping is free these days, here's an LLVM patch adding support for i64.add_wide2 and i64.add_wide3 as well as the add128(add128(a, 0, b, 0), c, 0) -> add_wide3(a, b, c) fusing: llvm/llvm-project@main...tlively:llvm-project:wasm-wide-arithmetic-add2-add3

    Here's the corresponding Binaryen patch: WebAssembly/binaryen@main...tlively:binaryen:wide-arithmetic-add3-add2

    Jakob has a prototype V8 patch that adds support for i64.add_wide3 only, so here's an additional LLVM patch that emits i64.add_wide3 with a constant zero instead of i64.add_wide2: tlively/llvm-project@wasm-wide-arithmetic-add2-add3...tlively:llvm-project:wasm-wide-arithmetic-add3-only

    Here are the resulting .wasms and .wats. Note that the .wats are going to have extra scratch locals not present in the binaries due to the way Binaryen's parser works with multivalue.

    add-shell.zip

    The add-shell.new.{wasm,wat} files are with both i64.add_wide2 and i64.add_wide3, the add-shell.wide3.{wasm,wat} files have only i64.add_wide3, and the add-shell.add128.{wasm,wat} files use i64.add128.

    Most of the differences between the add128 and add_wide modules are incidental changes in code structure and locals, but the salient change is that the 9 i64.add128 instructions are replaced with 3 i64.add_wide2 and 3 i64.add_wide3 (or just 6 i64.add_wide3) instructions.

  12. jakobkummerow commented on Jul 31, 2026

    @jakobkummerow
    Author

    why is add_wide2 proposed above? Was this just a proposed addition for consistency/uniformity?

    Yes. I don't have a use case for it. I don't mind whether it's added or not.

    Are you proposing that i1 is no longer needed and add_wide3 is all that's necessary?

    Yes.

    matching two add128s into one add_wide3 is the bread-and-butter of what optimizing compilers already do all the time for wasm today

    Yes; it's also the bread and butter of what Wasm module producers should be able to do.
    What's "controversial" about add128 is that having one instruction in the wire bytes is better than having five. That's also the rationale for preferring add_wide3.

    So, to clarify, @jakobkummerow are you now thinking this all boils down to a decision between i64.add128 : [i64 i64 i64 i64] -> [i64 i64] and i64.add_wide3 : [i64 i64 i64] -> [i64 i64]?

    Yes.

    prototype V8 patch that adds support for i64.add_wide3

    Here it is: https://chromium-review.googlesource.com/c/v8/v8/+/8138965/3..4
    That link shows the diff between patch sets 3 and 4, which is adding support for add_wide3 as a Wasm-level instruction, building on the existing backend support for internally-created add_wide3 in the optimizing compiler. (The rest of that CL is rather experimental and won't land in this state.) I hope this demonstrates convincingly that no fusing (or other fancy magic) is required for add_wide3. If the patch replaced add128 instead of adding another instruction, it would be line count negative by a wide margin.

  13. tlively commented on Jul 31, 2026

    @tlively
    Member

    Here's the JS file used to run the .wasms I shared above in patched d8: add-shell.js

    Just rename the .wasm you are interested in running (add-shell.add128.wasm or add-shell.wide3.wasm) to "add-shell.wasm" and run with d8 --wasm-wide_arithmetic --wasm-wide-add=[0-4] add-shell.js. The value passed to --wasm-wide-add determines the codegen strategy used.

    Here are the results from native builds with clang and gcc and Wasm builds with i64.add128 and i64.add_wide3, each with all 5 codegen strategies: https://docs.google.com/spreadsheets/d/1PcUw140KovRGoRsL_mp82AldlWCQV-rSfOz9MY1gMrQ/edit?usp=sharing

    And a chart of results:

    Image

    The codegen strategies, as Jakob described them to me:

    0: What Jakob used to think was optimal (e.g. in the opening post). Requires i1 range analysis.

    1: "treat as boolean" (e.g. option 2B from the opening post)

    2: No range analysis or assumptions. Uses setc.

    3: No optimization of i64.add128, not even pattern matching zeroes.

    4: No range analysis or assumptions. The GCC style sequence, replacing setc with another adc.

    (Unfortunately we will have to wait for Jakob to wake up to get any more detail on these)

    So i64.add_wide3 can match the highest possible performance of i64.add128 (at least for this bigint use case) while pushing all optimization and pattern matching to the toolchain and requiring fewer Wasm instructions. This seems like a win all around to me!

  14. alexcrichton commented on Aug 1, 2026

    @alexcrichton
    Collaborator

    Ok well if the question is add128 vs add_wide3, that's quite different from the historical discussion up until this point to me at least. My thinking on this is:

    • Expressivity: Both are co-expressive. add_wide3 is two add128s and one add128 is two add_wide3s
    • Engine impact: Both are, IMO, the same order of magnitude of difficulty to implement in an engine. Both require special-casing constant inputs, etc.
    • Toolchain impact: From @tlively's LLVM patch to generate add_wide3, my subjective reading is that add128 is simpler to generate for guest toolchains because it matches guest idioms and doesn't require pattern-matching.
    • Use case: bigints: both perform the same with the same magintude of complexity needed in the engine to get good performance.
    • Use case: 128-bit addition: I would expect the matching performance in this use case to require significantly more engine work with add_wide3 than with add128 (back to the carry-flag-in-a-register-when-it-shouldn't-be problem)
    • Use case: add-with-overflow: I would expect both add128 and add_wide3 to perform the same with the same amount of engine complexity.

    So, overall in my opinion, the pros(+)/cons(-)/neutrals(0) of add128 are:

    • (+) Better performance for less complexity for 128-bit addition
    • (+) Simpler guest toolchain
    • (0) Optimal performance of bigint addition
    • (0) Not increasing complexity in engines massively
    • (0) Reasonable performance for add-with-overflow
    • (-) larger bytecode encoding for bigint's use case

    Subjectively I don't feel like the final piece here, that two add128s are a larger encoding of bigint addition than add_wide3, is something that should be really weighted all that much. We're talking a handful of bytes that might happen a handful of times in an entire program. Alternatively add_wide3 has the opposite of what I'm laying out here, meaning 128-bit addition will suffer in performance and the guest toolchain is more complex. For the primary reason of losing performance on 128-bit addition I would personally still say that add_wide3 is not the best choice for this proposal and add128 is still the best choice.


    @tlively w.r.t. the graph you have here, thanks for collecting the data for that! For 0/1 it looks like both proposals perform the same, but I understand the goal is to avoid the need for this level of engine analysis. I don't think it's worth looking at the "3" codegen pattern myself because I don't think it makes sense to compare alternatives when one is specifically de-optimized. For 2/4, I'm not familiar enough with V8 myself to know where the difference is coming from, but the purpose of my post above was to show that as a data point Wasmtime is able to generate optimal codegen (or, what is as-of-yesterday now considered optimal codegen) with add128. For Wasmtime the only optimization required to achieve this codegen was pattern-matching 0s in high bits.

    Would you, or @jakobkummerow, be willing to dig in and better explain why 2/4 perform worse in v8 with add128 than with add_wide3? If it's anything like Wasmtime's backend I've found that small tweaks to rules/patterns can have an outside impact on performance, like in the PR that I linked above. Basically, I continue to be surprised by the assertion that a large level of engine complexity is necessary to get add128 to perform well. I can speak for Wasmtime and say that it did not require new complexity to perform well, and while I can't speak for the complexity in SpiderMonkey and JSC I've benchmarked them historically and they also perform quite well with add128. For JSC the performance on aarch64 of bigint addition actually matches native, although I collected that data after that comment so I don't have a chart to link to just yet.

  15. alexcrichton commented on Aug 1, 2026

    @alexcrichton
    Collaborator

    Er, apologies, I hit a button a bit too soon and additionally hit the wrong button. I've edited my comment above a bit (sorry it won't send out email notifications for the edits)

  16. tlively commented on Aug 2, 2026

    @tlively
    Member

    Basically, I continue to be surprised by the assertion that a large level of engine complexity is necessary to get add128 to perform well.

    I think we're now all on the same page that add128 does not require significant complexity in the engine, and now we're pretty much bikeshedding whether it's better to do the trivial pattern matching in the tools or engines.

    If we were exclusively focused on the bigint use case, I think it would be slightly better to have the toolchain do the pattern matching than the engine (but again, I agree it's trivial either way). But you raise a good point that we should consider the plain 128-bit addition use case, too. Even if you assume the bigint use case is more important, the stakes are so low there that considering other use cases to break the tie is a good idea.

    I asked Gemini to write a 128-bit addition benchmark, and it independently decided to test several ways to express the addition in the source code and to test both streaming (i.e. independent) and chained adds. Good idea! Wish I had thought of it. Here's the benchmark: https://gist.github.com/tlively/e677ed95d7a7799657f0705a350b9973

    The raw results are here: https://docs.google.com/spreadsheets/d/1PcUw140KovRGoRsL_mp82AldlWCQV-rSfOz9MY1gMrQ/edit?gid=1596736251#gid=1596736251 (a second tab of the same spreadsheet from before).

    Image

    In both the streaming and chained cases, the fastest WebAssembly implementation is when the source code uses __uint128_t and LLVM emits only i64.add128 instructions. I'm sure there's more work that could be done in the tools or engine to make the i64.add_wide3 cases faster, but the whole point is that we don't really want to do that work.

    With that result, I'm convinced that keeping the proposal as-is with i64.add128 is the best move.

    (But also it would be good to figure out why we're so far off native performance for 128-bit adds. I would have thought that having a dedicated instruction for it would have gotten us closer.)

  17. alexcrichton commented on Aug 2, 2026

    @alexcrichton
    Collaborator

    I wanted to test out that benchmark in Wasmtime as well and see how it shapes up and at least provide another data point. I graphed here the "ns/op" column which means lower-is-better, and these are all absolute values (not percentage differences). I left out the "ADC intrinsic" because like your graphs I found GCC was a huge outlier (much slower than Clang) and made it harder to see smaller differences in the results. I've also not included the add_wide3 version here mostly because rebuilding/patching LLVM is a bit intimidating for me -- @tlively could you share the binary wasm of this benchmark compiled with baseline wasm, add128, and add_wide3? I should be able to whip up an implementation of add_wide3 in Wasmtime pretty quickly to test that out.

    These are the results of the "streaming" benchmark:

    Image

    and these are the results of the "chained" benchmark:

    Image

    The most interesting part here to me is that for "streaming" wasm is basically already on-par with native even without wide arithmetic. Otherwise this shows a data point of add128 being able to be on-par with Clang at least in Wasmtime for uint128_t. My suspicion is that Wasmtime with an add_wide3 would be significantly slower, but if you're able to provide the precompiled wasm binary I can confirm that as well.

  18. tlively commented on Aug 2, 2026

    @tlively
    Member

    Here are all three .wasm builds I was testing:

    add128-benchmark-wasms.zip

    Your results showing Wasm and native being so similar made me realize that the benchmark wasn't tiering up in V8 when I ran it. I've run it again with --no-liftoff, but I don't think the conclusions are materially different.

    Image
  19. alexcrichton commented on Aug 3, 2026

    @alexcrichton
    Collaborator

    Thanks! It took a bit of reverse engineering/hacks to get that working Wasmtime (WASI host, not an Emscripten host), but I think I was able to get it running with some LLM assistance. I benchmarked those modules you've provided, lightly edited to work in Wasmtime, with gcc/clang/wasi-sdk on the original source you linked above as well. For the most interesting chart, using uint128_t, this shows what I'd expect where add128 is an improvement over today's baseline wasm, and add_carry3, for 128-bit integer arithmetic, is a regression over today's basline wasm without putting too much extra effort into Wasmtime (other than handling constant 0s in the various places).

    Image
  20. alexcrichton commented on Aug 10, 2026

    @alexcrichton
    Collaborator

    With last week's vote to move to phase 4, I'm going to close this. Thanks for the discussion regardless!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions