Repository navigation
Description
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.constfor initializing the local. (Technically, implicit zero-initialization might be enough, but it's probably nice to have an instruction for this.)add_with_carryand its mirror imagesub_with_borrow- some way to inspect or convert the final carry after the end of the loop, perhaps
i64.extend_i1and/ori1.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
alexcrichton commentedon Jul 28, 2026
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
add3operations. In this situation the instruction lowering you're proposing is pretty far from optimal because being optimal requires keeping thei1in the flags register. This is similar to #33 where what LLVM sort of does isi(N*128)_add_with_carryrather than justi64. Currentlyi64.add128isn't great fori256arithmetic, 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.I wrote up some words for this in the explainer, but I can expand a bit more here. I believe that adding
i1is 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 supporti1are:i1working "everywhere", even in places that are unlikely to ever get used by toolchains. For examplestructfields,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.i1to WebAssembly for just this one operation feels like quite a wart. For example all comparison instructions (e.g.i32.le_u) morally produce ani1and would then have to be rationalized with why they producei32instead ofi1. There's also what I believe would be a nontrivial amount of work to formalize a specification fori1with formal semantics at all.i1only 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 fori1beyond what's there today. To me this means that adding a minimali1with the rationale of "not too much work" today is not taking into account all the future work that will be necessary to maintain and supporti1.jakobkummerow commentedon Jul 29, 2026
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
As you can see, this module uses a pair of
i64.add128instructions as currently proposed. Pattern matching, range analysis, and transformation toadd3happen on the fly; it's all implemented in the CL linked above.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.
Well, it's a clear improvement over the existing alternative of translating
add128to machine code directly. Please do feel encouraged to come up with even better approaches!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.
jakobkummerow commentedon Jul 29, 2026
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 msadd128add_with_carry, "treat as boolean" codegenSo 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:
(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...)
tlively commentedon Jul 30, 2026
This looks like Binaryen tripping over the multivalue results (cc @stevenfontanella)
jakobkummerow commentedon Jul 30, 2026
Indeed! Linking with
-O1(which AFAIK skips Binaryen) improves that locals sequence, but there's still a little dance that looks unnecessary: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_tdigits (instead ofuintptr_t), this brings performance of the Emscripten-generated module on par with the handwritten module. Yay!jakobkummerow commentedon Jul 31, 2026
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:
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 withadd3(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
add128instruction is preceded byi64.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 themul_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:tlively commentedon Jul 31, 2026
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?
alexcrichton commentedon Jul 31, 2026
I agree
i64.add_wide2 : [i64, i64] -> [i64, i64]would have a nice symmetry, and withi64.add_wide3that closely aligns with nativeaddandadcinstructions on x86_64 as well. My historical testing with a proposal of such a shape is effectively this section of the explainer. Foradd_wide2the second output is the overflow flag, and foradd_wide3the 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 foradd/adclookalikes on all platforms, but if the equivalent of a nativeaddoradcis 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 toi64.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 foradd_wide{2,3}I don't know how to think about the performance there. It sounds like you're taking wasm modules withi64.add128and translating them internally toadd_wide{2,3}as opposed to generating modules natively withadd_wide{2,3}. My hunch is that it's going to be significantly difficult to get LLVM to emit theadd_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'si64.add128lies, 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.
jakobkummerow commentedon Jul 31, 2026
No, there is a fundamental difference:
What that section explores is using two
add_wide/add_wide3for oneadd128, a transformation ("lowering") that increases the number of Wasm instructions.What I'm suggesting is the opposite: one
add_wide3instead of twoadd128, 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
add128approach, it just changes where the "replace two with one" transformation happens, and as a consequence makes the wire bytes more compact (where, including thei64.const 0instructions, it would replace five Wasm instructions with just one).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 singlei64.add_wide3would do the work of twoadd128, and the engine would translate that singleadd_wide3to a sequence consisting of severaladd/adcmachine instructions (e.g. the sequence in my previous message).alexcrichton commentedon Jul 31, 2026
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:
add_wide3is twoadd128s, then why isadd_wide2proposed above? Was this just a proposed addition for consistency/uniformity? If not, what is the intended use case? Given that we're agreed onadd_wide2means 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.i1is no longer needed andadd_wide3is all that's necessary? If yes, then I don't understand whyadd128is so controversial because matching twoadd128s into oneadd_wide3is 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 withadd_wide{2,3}wheni1isn't mentioned with them.My understanding is you're currently proposing
add_wide3 : [i64 i64 i64] -> [i64 i64]as a replacement foradd128with 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 equivalentadd128loop:and with a minor tweak I believe Wasmtime is generating basically the same code as GCC:
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]andi64.add_wide3 : [i64 i64 i64] -> [i64 i64]?tlively commentedon Jul 31, 2026
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-add3Here'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.
jakobkummerow commentedon Jul 31, 2026
Yes. I don't have a use case for it. I don't mind whether it's added or not.
Yes.
Yes; it's also the bread and butter of what Wasm module producers should be able to do.
What's "controversial" about
add128is that having one instruction in the wire bytes is better than having five. That's also the rationale for preferringadd_wide3.Yes.
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_wide3as a Wasm-level instruction, building on the existing backend support for internally-createdadd_wide3in 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 foradd_wide3. If the patch replacedadd128instead of adding another instruction, it would be line count negative by a wide margin.tlively commentedon Jul 31, 2026
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:
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!
alexcrichton commentedon Aug 1, 2026
Ok well if the question is
add128vsadd_wide3, that's quite different from the historical discussion up until this point to me at least. My thinking on this is:add_wide3is twoadd128s and oneadd128is twoadd_wide3sadd_wide3, my subjective reading is thatadd128is simpler to generate for guest toolchains because it matches guest idioms and doesn't require pattern-matching.add_wide3than withadd128(back to the carry-flag-in-a-register-when-it-shouldn't-be problem)add128andadd_wide3to perform the same with the same amount of engine complexity.So, overall in my opinion, the pros(+)/cons(-)/neutrals(0) of
add128are:Subjectively I don't feel like the final piece here, that two
add128s are a larger encoding of bigint addition thanadd_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. Alternativelyadd_wide3has 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 thatadd_wide3is not the best choice for this proposal andadd128is 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
add128than withadd_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 getadd128to 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 withadd128. 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.alexcrichton commentedon Aug 1, 2026
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)
tlively commentedon Aug 2, 2026
I think we're now all on the same page that
add128does 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).
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.)
alexcrichton commentedon Aug 2, 2026
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:
and these are the results of the "chained" benchmark:
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
add128being able to be on-par with Clang at least in Wasmtime foruint128_t. My suspicion is that Wasmtime with anadd_wide3would be significantly slower, but if you're able to provide the precompiled wasm binary I can confirm that as well.tlively commentedon Aug 2, 2026
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.
alexcrichton commentedon Aug 3, 2026
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 whereadd128is an improvement over today's baseline wasm, andadd_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).alexcrichton commentedon Aug 10, 2026
With last week's vote to move to phase 4, I'm going to close this. Thanks for the discussion regardless!