You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Alternative or addition: instructions with overflow/carry flags #6
Perhaps the primary alternative to this proposal that would try to solve the same original problem would be to add instructions that manipulate/expose the overflow flag directly from native hardware. This is lower level than 128-bit operations themselves and the theory is that 128-bit operations could be built from these lower level instructions. The original proposal explicitly did not propose this due to complexity of optimizing these instructions and the ease of achieving performance on desired benchmarks with 128-bit operations. In the CG meeting however it was brought up that these lower-level primitives might be a better choice.
This issue is intended to be a discussion location for continuing to flesh out the flags-vs-128-bit-ops story. More thorough rationale will be needed in later phases to either explicitly use flag-based ops or not. This will likely be informed through experience in implementations in other engines in addition to performance numbers of relevant benchmarks.
I've opened #10 with some more discussion behind the background of this proposal. It notably outlines the possible shape of these instructions plus why they had bad performance in Wasmtime with the initial implementation.
One concern I might have with going exclusively with overflow/carry flags is that platforms like RISC-V don't have the same instructions as x86/aarch64 and they might be slower. For example implementing i64.add_with_carry_u on RISC-V to achieve 128-bit addition might end up being slower than what RISC-V already generates today. I'm not aware of other platforms missing these instructions, though, so RISC-V may be the only one affected and I additionally do not have a machine to benchmark on to confirm this hypothesis one way or another.
One concern I might have with going exclusively with overflow/carry flags is that platforms like RISC-V don't have the same instructions as x86/aarch64 and they might be slower. For example implementing i64.add_with_carry_u on RISC-V to achieve 128-bit addition might end up being slower than what RISC-V already generates today. I'm not aware of other platforms missing these instructions, though, so RISC-V may be the only one affected and I additionally do not have a machine to benchmark on to confirm this hypothesis one way or another.
It is more likely to be a problem with the design of RISC-V ISA itself, as suggested by this discussion. It could be a big sacrifice for WASM if we give up such common operations on other hardware platforms, just because RISC-V people currently don't care about this.
That's a good point! I should clarify that it's something I think is worth measuring, but I don't think it's a showstopper preventing such an alternative such as this.
Orthogonally I wanted to flesh out some more numbers on this of what I'm measuring locally. Using the benchmarks in https://github.com/alexcrichton/wasm-benchmark-i128 I measured the slowdown relative-to-native of wasm today, with this proposal as-is with 128-bit ops, and then with this alternative instead of overflow/carry flags (plus i64.mul_wide_*). Each column in the table is a different wasm binary benchmarked and each row is a benchmark. Lower is better as it means it's closer to native. This was collected with Wasmtime 25ish and on Linux x86_64.
Benchmark
Wasm Today
Wasm + 128-bit-arithmetic
Wasm + overflow/carry/mul_wide
blind-sig
617%
74%
79%
lehmer
362%
12%
-7%
mul-bignum
391%
30%
111%
fib_10000
122%
15%
100%
shl
93%
92%
93%
shr
98%
98%
95%
div-bignum
345%
160%
234%
sort signed
63%
64%
64%
sort unsigned
72%
72%
69%
Summary,:
blind-sig - both approaches are roughly equivalent as this is a multiplication-heavy benchmark
mul-bignum / div-bignum - these benchmarks have more addition than previous ones and show that the overflow/carry approach is significantly slower than add128
fib_10000 - this shows add128 performing much better than overflow/carry
others - not affected
The most notable result is that add128 is performing much better in addition operations than overflow/carry operations. This may be counterintuitive to expectation. I've outlined the reason as to why in the explainer a bit but to summarize that here the most general lowerings of overflow/carry ops require moving the carry flag out of the EFLAGS register and back into it. That in turn causes significant slowdown if it's not optimized away, and Wasmtime/Cranelift do not have a means of optimizing it away. In the 128-bit op case that more closely matches the original program semantics
Basically, I agree with your opinion. The correct modeling of how the carry flag works in the compiler is rare. There is a trade-off between less effort and optimal performance. The instructions to be added can not be perfect semantically, especially considering there aren't many people dedicated to the work. The current speedup is already considerable, so please go ahead and push this proposal upstream!
most general lowerings of overflow/carry ops require moving the carry flag out of the EFLAGS register and back into it
I'm not an x86 person, so could you clarify how your are lowering these operations? Can't a 'wide' add be lowered to add and adc, without having to explicitly move data from flags? Or do you just mean this is happening an a micro-arch level?
I mainly ask because the mul_wide operations sound good, but I expected to see add/sub with the same signature.
You're correct that i64.add128 gets lowered to add + adc (and add + adds on aarch64). The problem that I was describing there was i64.add_overflow_s, a separate instruction, which produces two values: the addition result + overflow bit. That overflow bit, in the most general case, needs to be put in a general purpose register which is the "move out of EFLAGS". Later if that's then combined with i64.add_with_carry_s which takes three inputs (e.g. lhs/rhs/overflow bit) then to use adc (or adds) then the overflow bit needs to be "put back in EFLAGS" somehow since adc and adds don't actually take three register input operands, only 2 and one is implicitly in the flags register.
While I'm strongly in favor of making wide arithmetic faster in Wasm, I continue to be unconvinced by the claim that "add128 is faster than add_with_overflow", and I believe that the experimental numbers that "prove" it only reflect prototype implementation deficiencies that could be ironed out (and wouldn't even be hard to iron out). Let me explain:
The "bignum" use case is, in general and regardless of specific library or language, an addition loop: given two vectors A, B of integers, add them element-by-element, propagating the carry, storing each result element in a result vector S (much like we all did by hand in elementary school). The integers will typically have register width, i.e. be uint64 on 64-bit hardware, because that's most efficient. The heavy lifting will be done by some loop, in pseudocode roughly:
carry = 0;
for each pair of items a=A[i], b=B[i] {
[sum, next_carry] = add_snowman(a, b, carry)
S[i] = sum
carry = next_carry
}
S[A.length] = carry
So, how can we represent add_snowman in Wasm? It must take three inputs (at a minimum: two in 64-bit range, one in 1-bit range), and produce two outputs: the low 64 bits of the addition, and the overflow (=carry) bit (which is guaranteed to be either 0 or 1, and could have any type large enough to represent these). Let's consider a few hypothetical possibilities:
A. add128 as currently proposed. We actually need two of them:
[temp_low, temp_high] = add128(a, 0, b, 0) // The two '0' are the "high parts" of a and b.
[sum, next_carry] = add128(temp_low, temp_high, carry, 0)
For easier comparison with the following options, let's write this in one line and with abbreviated names:
[s, nc] = add128(add128(a, 0, b, 0), c, 0)
That works fine, but the nesting is unsightly, leading to an idea to streamline that:
B. add128_three taking three (lo, hi) pairs of i64 inputs and producing a (lo, hi) pair of i64 outputs:
[s, nc] = add128_three(a, 0, b, 0, c, 0)
That's more elegant, but why should we have to emit so many zero-constants? Let's streamline those too, leading to the next idea:
C. add64_three taking three i64 "low halves" and returning a (lo, hi) pair:
[s, nc] = add64_three(a, b, c)
D. add_with_carry: That's actually the same as (C), just with a different name, and a degree of freedom whether the type of the third summand should be i64 like the others, or something smaller -- doesn't really matter.
Notably, all four options should get compiled to the same machine instruction sequence. In fact, engines have the hardest job for (A): they need to special-case the fact that two add128 instructions are immediately following each other, and they need to special-case the fact that half of the inputs are constant zeros; only then can they emit the most efficient machine code sequence. In the fully generic case of arbitrary inputs, they'll have to emit a lot more code. Engines have it easiest with (C)/(D), where no pattern recognition is necessary and even simple baseline/single-pass compilers can do a good job (i.e. emit an add/adc pair internally).
Also notably, an engine that has implemented (A) can trivially map (C) onto that implementation by filling in the 0 constants for the high parts. That's why the claim that (D) is necessarily slower than (A) is absolutely unconvincing.
I think all options are implementable. I do think that (A) is significantly more complex, because it has to be prepared to handle the case where none of the inputs are constant 0, while also needing a bunch of pattern-matching to make the common case as fast as possible (i.e. as fast as (C)). And I also think that for the bignum use case, there is no way (A) would have a fundamental performance benefit over either (B) or (C).
Of course, if you pick addition of two 128-bit integers with ignored/truncated overflow into the 129th bit as the example you study, then (A) will be the best fit, because it does exactly that. But for the "bignum" use case (as exemplified in the "fib_10000" benchmark quoted above), there should be no performance difference between all four options -- if there is one, then something's wrong with the implementation(s) of toolchains or engines or both.
In summary, I see a pleasing symmetry here:
For multiplication, it's uncontentious that we want an instruction that does [a:i64, b:i64] -> [low:i64, high:i64]. And for addition, the simplest equivalent would be an instruction with the same signature. A more efficient (for the primary use case) alternative would be a 3-summand addition with wide output [a:i64, b:i64, c:i64] -> [low:i64, high:i64] because grouping two 2-summand additions like that makes it easier for simple engines to use the most-efficient machine instruction (adc) more often.
My pseudocode example above assumed for simplicity that both inputs have the same vector length. If they have unequal lengths, then a two-operand addition with wide output is useful too. So, my suggestion for maximum performance and simplicity would be to add the following six instructions:
i64.add_wide: [i64, i64] -> [i64, i64] ;; a + b -> (low, high=carry)
i64.add3_wide: [i64, i64, i64] -> [i64, i64] ;; a + b + c -> (low, high=carry)
i64.sub_wide: [i64, i64] -> [i64, i64] ;; a - b -> (difference, borrow)
i64.sub2_wide: [i64, i64, i64] -> [i64, i64] ;; a - b - c -> (difference, borrow)
i64.mul_wide_u: [i64, i64] -> [i64, i64] ;; a * b -> (low, high)
i64.mul_wide_s: [i64, i64] -> [i64, i64] ;; a * b -> (low, high)
(I didn't see any detailed discussion of sub128 in this repo. Having "wide input" semantics there is probably workable but weird, because you'd normally have to pass constant 1 as the high part, and then the result's high part is the inverse of the "borrow bit", i.e. it's 0 if the borrow is 1 and vice versa, and you'd have to flip it before being able to use it in the vector processing loop's next iteration. I think it's easier for everyone to just return the borrow bit as the second result.)
To clarify I'm not claiming that this proposal as-is is the fastest of all possible designs/use-cases. I've primarily been comparing against the idea of representing the overflow flag as a value and that's what's been causing such a slowdown. Your proposed instructions don't do that, however, so I think it's very much worth considering!
For reference the code that I've been benchmarking (with i64.add128) looks like this:
You're correct that the inner loop here is add128(add128(a, 0, b, 0), c, 0) and this is reflected in the instructions too. The loop here is also unrolled once by LLVM but overall the main structure is the same between native and wasm-compiled-to-native. The main difference is that native has a setb r8b for one of the combos where Wasmtime uses xor %r14,%r14 ... adc $0x0, %r14 for the same thing.
Basically I wanted to point out that at least from a purely technical point of view add128 as-is suffices for generating mostly optimal instructions here. There's still cleanups that can be done in Wasmtime naturally, and you're right that Wasmtime has special handling of the case where one side is zero-extended (e.g. upper bits are i64.const 0). For Wasmtime/Cranelift though this sort of instruction matching is the bread-and-butter of backends and isn't something I considered costly for Cranelift's implementation. I've been (perhaps naively) assuming other compilers also have well-established means of combining data-dependent instructions together.
For what you're proposing I want to confirm, are you thinking that the translation for i64.add3_wide would look something like this?
If so that seems reasonable to me and it avoids the problem of dealing with flags-as-a-value where other drafts of this proposal have tried to interpret the c operand here as "one more if nonzero" or "zero if zero". Treating it as a full 64-bit value definitely simplifies the codegen and lowering. The problem with it though is that I don't know how to integrate this into language toolchains (aka LLVM).
One problem is that the i64.add3_wide operation, as far as I know, has no equivalent in any source language. This means that compilers would have to pattern-match some sequence of operations to generate such an instruction. LLVM may have the tools to do this where it'd probably use llvm.uadd.with.overflow.* intrinsics and such to model this in IR. Later when LLVM lowers to target-independent IR opcodes there's still no match to what this instruction has, so there'd then have to be wasm-specific logic to pattern-match such an instruction and generate it. For me, personally, this is enough leaps-of-faith that I'm not necessarily confident this would be generated. For example the Rust source code linked above is only using u128, it's not actually using any intrinsics, and I'd want that to still optimize to using i64.add3_wide for example.
In contrast with i64.add128 this was surprisingly easy, even for me who's unfamiliar with LLVM, to integrate. Languages naturally all represent addition already and while not everyone has 128-bit integers those that do support native addition on them typically. That means it's quite easy to plumb intent all the way through from the language frontend to the emitted wasm. It's true that compilers will need to pattern-match common cases where the upper bits are zero but I'd argue that's already the case for many other instructions. For example if a wasm compiler doesn't pattern-match constants in instructions at all it's probably going to perform a good amount worse than compilers today.
So overall, again assuming I've understood the lowering of i64.add3_wide correctly, I'd personally at least still need convincing on the lower-this-to-wasm side of things. I won't claim that i64.add128 is the end-all-be-all by any means but from what I've seen it represents a nice balance between high performance and ease of implementation of producers/consumers alike.
As a final note, I also ideally don't want to over-rotate on bignum arithmetic as well. Lowering an optimal sequence of basic 128-bit addition is naturally easy with i64.add128 but doing so with i64.add_wide and i64.add3_wide is not obvious to me. I'm not sure how using those two opcodes (or a combination) it could compile to a literal add/adc combo.
As a side note:
I didn't see any detailed discussion of sub128 in this repo
I've kept around sub as "it's probably best to keep sub on-par with addition so whatever's there for addition might as well add it for subtraction too. Beyond that I have not thought too deeply about subtraction specifically.
from a purely technical point of view add128 as-is suffices for generating mostly optimal instructions
Yes, with enough effort all four options I described lead to the same generated code.
are you thinking that the translation for i64.add3_wide would look something like this?
Yes, modulo perhaps replacing xor %ret_hi,ret_hi; adc $0,%ret_hi with setb %ret_hi, as you point out yourself.
And the 2-operand i64.add_wide would basically just skip the adc %c,%ret_lo part.
compilers would have to pattern-match some sequence of operations to generate such an instruction. LLVM may have the tools to do this
Yes. The pattern they'd match is add128(add128(a, 0, b, 0), c, 0), or phrased differently "a + b + c where a, b, c are all u128s created by zero-extending u64s". I'm not an LLVM engineer and don't know how to express it there (or at which point in the pipeline to apply the matching), but since we know that LLVM can go from that u128+u128+u128 addition to the final machine code we want, it must already have this matching implemented somewhere.
In other words, the adcfunction in the "Native x64 compilation" godbolt link in your last message is almost exactly the i64.add3_wide instruction, except it overloads its acc parameters for 3 (!) purposes: u64 input, u64 output, and u128 temp value. If you rephrased it as:
#[inline]fnadc(a:BigDigit,b:BigDigit,c:BigDigit,acc:&mutBigDigit) -> BigDigit{letmut tmp = c asDoubleBigDigit;
tmp += a asDoubleBigDigit;
tmp += b asDoubleBigDigit;let lo = tmp asBigDigit;*acc = tmp >> BITS;
lo
}
then it would more obviously equal the i64.add3_wide instruction. (Please forgive any syntactic mistakes, I don't speak Rust.)
This also illustrates why i64.add3_wide is useful: when you don't have it (e.g. in Rust), you're going to implement a helper function that does what it does! (We have an equivalent helper function in V8, using Clang's nonstandard-C++ __uint128_t instead of Rust's u128.)
a nice balance between high performance and ease of implementation of producers/consumers alike.
Generally, Wasm tries to do as much work as possible as early as possible, i.e. it prefers doing things in toolchains rather than in engines (when possible). There's an explicit goal that it should be possible to implement simple engines that still perform well. As an alternative phrasing, it should be possible to implement engines with high peak performance and low latency -- because most optimizations are done ahead of time.
I also ideally don't want to over-rotate on bignum arithmetic
I do think that bignum is the primary use case. In fact, while I'm sure it exists somewhere, I don't recall ever encountering an "actual i128" use case myself. But that said:
Lowering an optimal sequence of basic 128-bit addition [...] with i64.add_wide and i64.add3_wide
(func add128 (parami64i64i64i64) (resulti64i64)
local.get0local.get2
i64.add_wide ;; value stack: res_lo, tmp_hilocal.get1local.get3;; value stack: res_lo, tmp_hi, a_hi, b_hi
i64.add3_wide ;; value stack: res_lo, res_hi, discarddrop
)
A baseline/single-pass compiler clearly won't emit the best possible machine code for this, but that's okay (firstly because baseline compilers are almost never optimal, and secondly because this use case is likely rare).
Teaching an optimizing compiler to emit only an add/adc pair requires a rule "if one of the inputs to an add3_wide IR node is the "high" output of an add_wide IR node, and the latter is scheduled right before the former, then the former can emit an adc instruction and nothing else". I haven't tried to implement that yet, but it sounds feasible.
Come to think of it, this could even be done peephole-style very early on, possibly even in the decoder or its interface to the baseline compiler (in V8 we already do similar tricks there to optimize compare+if sequences): when encountering an i64.add_wide, don't "commit" it right away, but stash it away in a 1-element cache of "tentative instructions", and when then seeing an i64.add3_wide as the next instruction (after the local.gets, which don't really count because they only affect compiler state, not actual emitted code), replace both of them with an internal add128 (with custom-tailored codegen).
That said, I also wouldn't mind having both (add_wide and add128) as explicit instructions in Wasm, if full-width i128 computations are assumed to be sufficiently common to motivate this.
Do you have a source link on-hand for that? I'd like to add that to the reperotoire of "things to study". Or do you mean V8 has the equivalent of fn adc(a: BigDigit, b: BigDigit, c: BigDigit, acc: &mut BigDigit) -> BigDigit? (in which case no link necessary)
a nice balance between high performance and ease of implementation of producers/consumers alike.
Generally, Wasm tries to do as much work as possible as early as possible
Oh I'm no stranger to this. I'm talking from a practical "this is all working today" point of view. The work required on behalf of Cranelift is objectively very small to pattern match. I am (again, possibly naively) assuming that the work required to have a few extra patterns in other compilers is also going to be quite small. I'm not proposing we require LICM to have fast wasm compilers, instead just a pattern match or two.
Teaching an optimizing compiler to emit only an add/adc pair requires a rule "if one of the inputs to an add3_wide IR node is the "high" output of an add_wide IR node, and the latter is scheduled right before the former, then the former can emit an adc instruction and nothing else".
...
Come to think of it, this could even be done peephole-style very early on ...
This section of the overview, the slides from the February CG meeting, and these slides from the CG meeting last October outline the case for why I think that the optimization you describe here I believe is infeasible. Empirically in Cranelift this optimization is not possible without significant refactoring/restructuring. Such refactoring is not worth the value of optimizing 128-bit addition we've concluded.
You're definitely correct though in that other compilers might find such a transformation easy to implement. I mostly think that if performance relied on such an optimization happening we would find such a proposal not-useful in Wasmtime/Cranelift.
That said, I also wouldn't mind having both (add_wide and add128) as explicit instructions in Wasm, if full-width i128 computations are assumed to be sufficiently common to motivate this.
Personally I would also have no issue with this. It's something I've wondered as well where if we admit that the lowest-level primitive of adc is too difficult to implement in wasm then i64.add128 is not sufficient for capturing all possible use cases of adc easily, so other instructions might be necessary. In that sense i64.add_wide{,_3}, while definitely related to i64.add128, I think could still help serve other use cases as you've shown where 128-bit arithmetic is not necessarily the best primitive.
To save you the trouble of looking up the typedefs: digit_t is what's BigDigit in Rust, twodigit_t is DoubleBigDigit, Digits is "read-only vector of digit_t", RWDigits is when it may be written into.
Yes, that all matches my thoughts, with very few clarifying footnotes:
Whether "native code is optimal" or not depends on which specific Rust snippet you compile with rustc/LLVM. Some of them are more optimal than others.
As potential Wasm instructions, add_wide3 and add_with_carry_u have the same signature and the same behavior. (And the same equality holds for add_wide vs add_overflow_u.) So between the instructions themselves, there is no difference; the difference that matters is how they're used: the key point is that Wasm module producers don't attempt to model machine instructions, instead they should consider the instruction a high-level primitive that will be lowered to a handful of immediately-consecutive machine instructions by the engine.
For the usefulness of add_wide3 in addition to add128, I don't disagree about the facts; it just so happens that my conclusion is a weak leaning towards having it for the minor benefit it brings. But I can also live with having only add128 for now. I do think that add_wide3 with i64 inputs is better than not having it; however the idea of leaving it out for now and then adding it later with an i1 input, which would make it even better, is appealing.
Oh for add_with_carry and add_overflow they were subtly different, the overflow flag was modeled as i32. Both were guaranteed to produce 0: i32 or 1: i32, but the input to add_with_carry_u was interpreted as "zero or nonzero". In essence it was a poor-man's i1 without actually adding i1, and it made using them quite awkward. Notably though I never prototyped something like add_wide3 where the semantics were "add all 3 full-width numbers and return a full-width carry".
Overall though would you feel ok deferring add_wide3 and add_wide to a future where i1 were added? That would basically mean reviving the original instructions I worked with but with i1 in the signatures instead of i32 or i64.
Realistically there's a good chance that that future will never happen, and then it'll be sad to not have add_wide3 at all; but my prototype has shown that V8 can get the performance it wants via engine smarts, and I should now stop spending my time arguing for things that would help other implementations.
Ok I've opened up #36 to capture the discussion here and I've annotated that to close this issue as well. I'll leave that open for a week or so to let folks comment on it.
Activity
alexcrichton commentedon Aug 20, 2024
I've opened #10 with some more discussion behind the background of this proposal. It notably outlines the possible shape of these instructions plus why they had bad performance in Wasmtime with the initial implementation.
alexcrichton commentedon Aug 26, 2024
One concern I might have with going exclusively with overflow/carry flags is that platforms like RISC-V don't have the same instructions as x86/aarch64 and they might be slower. For example implementing
i64.add_with_carry_uon RISC-V to achieve 128-bit addition might end up being slower than what RISC-V already generates today. I'm not aware of other platforms missing these instructions, though, so RISC-V may be the only one affected and I additionally do not have a machine to benchmark on to confirm this hypothesis one way or another.waterlens commentedon Sep 3, 2024
It is more likely to be a problem with the design of RISC-V ISA itself, as suggested by this discussion. It could be a big sacrifice for WASM if we give up such common operations on other hardware platforms, just because RISC-V people currently don't care about this.
alexcrichton commentedon Sep 4, 2024
That's a good point! I should clarify that it's something I think is worth measuring, but I don't think it's a showstopper preventing such an alternative such as this.
Orthogonally I wanted to flesh out some more numbers on this of what I'm measuring locally. Using the benchmarks in https://github.com/alexcrichton/wasm-benchmark-i128 I measured the slowdown relative-to-native of wasm today, with this proposal as-is with 128-bit ops, and then with this alternative instead of overflow/carry flags (plus
i64.mul_wide_*). Each column in the table is a different wasm binary benchmarked and each row is a benchmark. Lower is better as it means it's closer to native. This was collected with Wasmtime 25ish and on Linux x86_64.Summary,:
blind-sig- both approaches are roughly equivalent as this is a multiplication-heavy benchmarklehmer- this shows mostly that mul_wide can sometimes optimize better than mul128. I'll note this in Ismul128going to be as fast as widening multiplication? #11.mul-bignum/div-bignum- these benchmarks have more addition than previous ones and show that the overflow/carry approach is significantly slower than add128fib_10000- this shows add128 performing much better than overflow/carryThe most notable result is that add128 is performing much better in addition operations than overflow/carry operations. This may be counterintuitive to expectation. I've outlined the reason as to why in the explainer a bit but to summarize that here the most general lowerings of overflow/carry ops require moving the carry flag out of the EFLAGS register and back into it. That in turn causes significant slowdown if it's not optimized away, and Wasmtime/Cranelift do not have a means of optimizing it away. In the 128-bit op case that more closely matches the original program semantics
Remove `i64.mul128`, add `i64.mul_wide_{s,u}`
alexcrichton commentedon Sep 20, 2024
I've posted some more thoughts to record in the overview in #18
waterlens commentedon Sep 22, 2024
Basically, I agree with your opinion. The correct modeling of how the carry flag works in the compiler is rare. There is a trade-off between less effort and optimal performance. The instructions to be added can not be perfect semantically, especially considering there aren't many people dedicated to the work. The current speedup is already considerable, so please go ahead and push this proposal upstream!
sparker-arm commentedon Dec 11, 2024
Hi @alexcrichton
I'm not an x86 person, so could you clarify how your are lowering these operations? Can't a 'wide' add be lowered to
addandadc, without having to explicitly move data from flags? Or do you just mean this is happening an a micro-arch level?I mainly ask because the
mul_wideoperations sound good, but I expected to see add/sub with the same signature.alexcrichton commentedon Dec 11, 2024
Hello! And sure! I might also point towards the overview docs which is a summary of the phase 2 presentation I last gave to the CG.
You're correct that
i64.add128gets lowered toadd+adc(andadd+addson aarch64). The problem that I was describing there wasi64.add_overflow_s, a separate instruction, which produces two values: the addition result + overflow bit. That overflow bit, in the most general case, needs to be put in a general purpose register which is the "move out of EFLAGS". Later if that's then combined withi64.add_with_carry_swhich takes three inputs (e.g. lhs/rhs/overflow bit) then to useadc(oradds) then the overflow bit needs to be "put back in EFLAGS" somehow sinceadcandaddsdon't actually take three register input operands, only 2 and one is implicitly in the flags register.sparker-arm commentedon Dec 11, 2024
Ah yes, I understand now. Flags are a pain... :)
Thanks.
jakobkummerow commentedon Feb 27, 2025
While I'm strongly in favor of making wide arithmetic faster in Wasm, I continue to be unconvinced by the claim that "
add128is faster thanadd_with_overflow", and I believe that the experimental numbers that "prove" it only reflect prototype implementation deficiencies that could be ironed out (and wouldn't even be hard to iron out). Let me explain:The "bignum" use case is, in general and regardless of specific library or language, an addition loop: given two vectors A, B of integers, add them element-by-element, propagating the carry, storing each result element in a result vector S (much like we all did by hand in elementary school). The integers will typically have register width, i.e. be
uint64on 64-bit hardware, because that's most efficient. The heavy lifting will be done by some loop, in pseudocode roughly:So, how can we represent
add_snowmanin Wasm? It must take three inputs (at a minimum: two in 64-bit range, one in 1-bit range), and produce two outputs: the low 64 bits of the addition, and the overflow (=carry) bit (which is guaranteed to be either 0 or 1, and could have any type large enough to represent these). Let's consider a few hypothetical possibilities:A.
add128as currently proposed. We actually need two of them:For easier comparison with the following options, let's write this in one line and with abbreviated names:
That works fine, but the nesting is unsightly, leading to an idea to streamline that:
B.
add128_threetaking three (lo, hi) pairs ofi64inputs and producing a (lo, hi) pair ofi64outputs:That's more elegant, but why should we have to emit so many zero-constants? Let's streamline those too, leading to the next idea:
C.
add64_threetaking threei64"low halves" and returning a (lo, hi) pair:D.
add_with_carry: That's actually the same as (C), just with a different name, and a degree of freedom whether the type of the third summand should bei64like the others, or something smaller -- doesn't really matter.Notably, all four options should get compiled to the same machine instruction sequence. In fact, engines have the hardest job for (A): they need to special-case the fact that two
add128instructions are immediately following each other, and they need to special-case the fact that half of the inputs are constant zeros; only then can they emit the most efficient machine code sequence. In the fully generic case of arbitrary inputs, they'll have to emit a lot more code. Engines have it easiest with (C)/(D), where no pattern recognition is necessary and even simple baseline/single-pass compilers can do a good job (i.e. emit anadd/adcpair internally).Also notably, an engine that has implemented (A) can trivially map (C) onto that implementation by filling in the
0constants for the high parts. That's why the claim that (D) is necessarily slower than (A) is absolutely unconvincing.I think all options are implementable. I do think that (A) is significantly more complex, because it has to be prepared to handle the case where none of the inputs are constant
0, while also needing a bunch of pattern-matching to make the common case as fast as possible (i.e. as fast as (C)). And I also think that for the bignum use case, there is no way (A) would have a fundamental performance benefit over either (B) or (C).Of course, if you pick addition of two 128-bit integers with ignored/truncated overflow into the 129th bit as the example you study, then (A) will be the best fit, because it does exactly that. But for the "bignum" use case (as exemplified in the "fib_10000" benchmark quoted above), there should be no performance difference between all four options -- if there is one, then something's wrong with the implementation(s) of toolchains or engines or both.
In summary, I see a pleasing symmetry here:
For multiplication, it's uncontentious that we want an instruction that does
[a:i64, b:i64] -> [low:i64, high:i64]. And for addition, the simplest equivalent would be an instruction with the same signature. A more efficient (for the primary use case) alternative would be a 3-summand addition with wide output[a:i64, b:i64, c:i64] -> [low:i64, high:i64]because grouping two 2-summand additions like that makes it easier for simple engines to use the most-efficient machine instruction (adc) more often.My pseudocode example above assumed for simplicity that both inputs have the same vector length. If they have unequal lengths, then a two-operand addition with wide output is useful too. So, my suggestion for maximum performance and simplicity would be to add the following six instructions:
(I didn't see any detailed discussion of
sub128in this repo. Having "wide input" semantics there is probably workable but weird, because you'd normally have to pass constant1as the high part, and then the result's high part is the inverse of the "borrow bit", i.e. it's 0 if the borrow is 1 and vice versa, and you'd have to flip it before being able to use it in the vector processing loop's next iteration. I think it's easier for everyone to just return the borrow bit as the second result.)alexcrichton commentedon Feb 27, 2025
To clarify I'm not claiming that this proposal as-is is the fastest of all possible designs/use-cases. I've primarily been comparing against the idea of representing the overflow flag as a value and that's what's been causing such a slowdown. Your proposed instructions don't do that, however, so I think it's very much worth considering!
For reference the code that I've been benchmarking (with
i64.add128) looks like this:Native x64 compilation
full output on godbolt but the main loop is:
Wasm code generation
full output online but the main loop is:
Compiled code on x64 with Wasmtime
Here I've just snipped the main loop, not the whole binary.
You're correct that the inner loop here is
add128(add128(a, 0, b, 0), c, 0)and this is reflected in the instructions too. The loop here is also unrolled once by LLVM but overall the main structure is the same between native and wasm-compiled-to-native. The main difference is that native has asetb r8bfor one of the combos where Wasmtime usesxor %r14,%r14 ... adc $0x0, %r14for the same thing.Basically I wanted to point out that at least from a purely technical point of view
add128as-is suffices for generating mostly optimal instructions here. There's still cleanups that can be done in Wasmtime naturally, and you're right that Wasmtime has special handling of the case where one side is zero-extended (e.g. upper bits arei64.const 0). For Wasmtime/Cranelift though this sort of instruction matching is the bread-and-butter of backends and isn't something I considered costly for Cranelift's implementation. I've been (perhaps naively) assuming other compilers also have well-established means of combining data-dependent instructions together.For what you're proposing I want to confirm, are you thinking that the translation for
i64.add3_widewould look something like this?If so that seems reasonable to me and it avoids the problem of dealing with flags-as-a-value where other drafts of this proposal have tried to interpret the
coperand here as "one more if nonzero" or "zero if zero". Treating it as a full 64-bit value definitely simplifies the codegen and lowering. The problem with it though is that I don't know how to integrate this into language toolchains (aka LLVM).One problem is that the
i64.add3_wideoperation, as far as I know, has no equivalent in any source language. This means that compilers would have to pattern-match some sequence of operations to generate such an instruction. LLVM may have the tools to do this where it'd probably usellvm.uadd.with.overflow.*intrinsics and such to model this in IR. Later when LLVM lowers to target-independent IR opcodes there's still no match to what this instruction has, so there'd then have to be wasm-specific logic to pattern-match such an instruction and generate it. For me, personally, this is enough leaps-of-faith that I'm not necessarily confident this would be generated. For example the Rust source code linked above is only usingu128, it's not actually using any intrinsics, and I'd want that to still optimize to usingi64.add3_widefor example.In contrast with
i64.add128this was surprisingly easy, even for me who's unfamiliar with LLVM, to integrate. Languages naturally all represent addition already and while not everyone has 128-bit integers those that do support native addition on them typically. That means it's quite easy to plumb intent all the way through from the language frontend to the emitted wasm. It's true that compilers will need to pattern-match common cases where the upper bits are zero but I'd argue that's already the case for many other instructions. For example if a wasm compiler doesn't pattern-match constants in instructions at all it's probably going to perform a good amount worse than compilers today.So overall, again assuming I've understood the lowering of
i64.add3_widecorrectly, I'd personally at least still need convincing on the lower-this-to-wasm side of things. I won't claim thati64.add128is the end-all-be-all by any means but from what I've seen it represents a nice balance between high performance and ease of implementation of producers/consumers alike.As a final note, I also ideally don't want to over-rotate on bignum arithmetic as well. Lowering an optimal sequence of basic 128-bit addition is naturally easy with
i64.add128but doing so withi64.add_wideandi64.add3_wideis not obvious to me. I'm not sure how using those two opcodes (or a combination) it could compile to a literaladd/adccombo.As a side note:
I've kept around
subas "it's probably best to keepsubon-par with addition so whatever's there for addition might as well add it for subtraction too. Beyond that I have not thought too deeply about subtraction specifically.jakobkummerow commentedon Feb 28, 2025
Yes, with enough effort all four options I described lead to the same generated code.
Yes, modulo perhaps replacing
xor %ret_hi,ret_hi; adc $0,%ret_hiwithsetb %ret_hi, as you point out yourself.And the 2-operand
i64.add_widewould basically just skip theadc %c,%ret_lopart.Yes. The pattern they'd match is
add128(add128(a, 0, b, 0), c, 0), or phrased differently "a + b + cwherea,b,care allu128s created by zero-extendingu64s". I'm not an LLVM engineer and don't know how to express it there (or at which point in the pipeline to apply the matching), but since we know that LLVM can go from thatu128+u128+u128addition to the final machine code we want, it must already have this matching implemented somewhere.In other words, the
adcfunction in the "Native x64 compilation" godbolt link in your last message is almost exactly thei64.add3_wideinstruction, except it overloads itsaccparameters for 3 (!) purposes: u64 input, u64 output, and u128 temp value. If you rephrased it as:then it would more obviously equal the
i64.add3_wideinstruction. (Please forgive any syntactic mistakes, I don't speak Rust.)This also illustrates why
i64.add3_wideis useful: when you don't have it (e.g. in Rust), you're going to implement a helper function that does what it does! (We have an equivalent helper function in V8, using Clang's nonstandard-C++__uint128_tinstead of Rust'su128.)Generally, Wasm tries to do as much work as possible as early as possible, i.e. it prefers doing things in toolchains rather than in engines (when possible). There's an explicit goal that it should be possible to implement simple engines that still perform well. As an alternative phrasing, it should be possible to implement engines with high peak performance and low latency -- because most optimizations are done ahead of time.
I do think that bignum is the primary use case. In fact, while I'm sure it exists somewhere, I don't recall ever encountering an "actual i128" use case myself. But that said:
is very straightforward on the producer side:
That's even pretty concise in actual wat syntax:
A baseline/single-pass compiler clearly won't emit the best possible machine code for this, but that's okay (firstly because baseline compilers are almost never optimal, and secondly because this use case is likely rare).
Teaching an optimizing compiler to emit only an
add/adcpair requires a rule "if one of the inputs to anadd3_wideIR node is the "high" output of anadd_wideIR node, and the latter is scheduled right before the former, then the former can emit anadcinstruction and nothing else". I haven't tried to implement that yet, but it sounds feasible.Come to think of it, this could even be done peephole-style very early on, possibly even in the decoder or its interface to the baseline compiler (in V8 we already do similar tricks there to optimize
compare+ifsequences): when encountering ani64.add_wide, don't "commit" it right away, but stash it away in a 1-element cache of "tentative instructions", and when then seeing ani64.add3_wideas the next instruction (after thelocal.gets, which don't really count because they only affect compiler state, not actual emitted code), replace both of them with an internaladd128(with custom-tailored codegen).That said, I also wouldn't mind having both (
add_wideandadd128) as explicit instructions in Wasm, if full-widthi128computations are assumed to be sufficiently common to motivate this.alexcrichton commentedon Feb 28, 2025
Do you have a source link on-hand for that? I'd like to add that to the reperotoire of "things to study". Or do you mean V8 has the equivalent of
fn adc(a: BigDigit, b: BigDigit, c: BigDigit, acc: &mut BigDigit) -> BigDigit? (in which case no link necessary)Oh I'm no stranger to this. I'm talking from a practical "this is all working today" point of view. The work required on behalf of Cranelift is objectively very small to pattern match. I am (again, possibly naively) assuming that the work required to have a few extra patterns in other compilers is also going to be quite small. I'm not proposing we require LICM to have fast wasm compilers, instead just a pattern match or two.
This section of the overview, the slides from the February CG meeting, and these slides from the CG meeting last October outline the case for why I think that the optimization you describe here I believe is infeasible. Empirically in Cranelift this optimization is not possible without significant refactoring/restructuring. Such refactoring is not worth the value of optimizing 128-bit addition we've concluded.
You're definitely correct though in that other compilers might find such a transformation easy to implement. I mostly think that if performance relied on such an optimization happening we would find such a proposal not-useful in Wasmtime/Cranelift.
Personally I would also have no issue with this. It's something I've wondered as well where if we admit that the lowest-level primitive of
adcis too difficult to implement in wasm theni64.add128is not sufficient for capturing all possible use cases ofadceasily, so other instructions might be necessary. In that sensei64.add_wide{,_3}, while definitely related toi64.add128, I think could still help serve other use cases as you've shown where 128-bit arithmetic is not necessarily the best primitive.jakobkummerow commentedon Mar 2, 2025
I'd call it an exact equivalent of that
fn adc, yes: https://source.chromium.org/chromium/chromium/src/+/main:v8/src/bigint/digit-arithmetic.h;l=37?q=digit_add3And it's used in a vector-iterating loop like so: https://source.chromium.org/chromium/chromium/src/+/main:v8/src/bigint/vector-arithmetic.cc;l=48?q=digit_add3 (that example also shows how the 2-operand version is useful once the iteration proceeds beyond the length of the shorter summand, propagating the carry through the longer summand)
I haven't checked just now, but Clang should compile it to pretty much exactly the same machine code as your Rust example. So it probably isn't interesting as an additional thing to study, rather as a datapoint confirming relevance of the Rust example.
To save you the trouble of looking up the typedefs:
digit_tis what'sBigDigitin Rust,twodigit_tisDoubleBigDigit,Digitsis "read-only vector ofdigit_t",RWDigitsis when it may be written into.24 remaining items
jakobkummerow commentedon Mar 20, 2025
Yes, that all matches my thoughts, with very few clarifying footnotes:
Whether "native code is optimal" or not depends on which specific Rust snippet you compile with rustc/LLVM. Some of them are more optimal than others.
As potential Wasm instructions,
add_wide3andadd_with_carry_uhave the same signature and the same behavior. (And the same equality holds foradd_widevsadd_overflow_u.) So between the instructions themselves, there is no difference; the difference that matters is how they're used: the key point is that Wasm module producers don't attempt to model machine instructions, instead they should consider the instruction a high-level primitive that will be lowered to a handful of immediately-consecutive machine instructions by the engine.For the usefulness of
add_wide3in addition toadd128, I don't disagree about the facts; it just so happens that my conclusion is a weak leaning towards having it for the minor benefit it brings. But I can also live with having onlyadd128for now. I do think thatadd_wide3withi64inputs is better than not having it; however the idea of leaving it out for now and then adding it later with ani1input, which would make it even better, is appealing.alexcrichton commentedon Mar 20, 2025
Oh for add_with_carry and add_overflow they were subtly different, the overflow flag was modeled as
i32. Both were guaranteed to produce0: i32or1: i32, but the input toadd_with_carry_uwas interpreted as "zero or nonzero". In essence it was a poor-man'si1without actually addingi1, and it made using them quite awkward. Notably though I never prototyped something likeadd_wide3where the semantics were "add all 3 full-width numbers and return a full-width carry".Overall though would you feel ok deferring
add_wide3andadd_wideto a future wherei1were added? That would basically mean reviving the original instructions I worked with but withi1in the signatures instead ofi32ori64.jakobkummerow commentedon Mar 21, 2025
Yeah, sure.
Realistically there's a good chance that that future will never happen, and then it'll be sad to not have
add_wide3at all; but my prototype has shown that V8 can get the performance it wants via engine smarts, and I should now stop spending my time arguing for things that would help other implementations.Summarize the conclusion of `i64.add_wide3`
alexcrichton commentedon Mar 21, 2025
Ok I've opened up #36 to capture the discussion here and I've annotated that to close this issue as well. I'll leave that open for a week or so to let folks comment on it.
[WebAssembly] Add more lowerings for wide-arithmetic
[WebAssembly] Add more lowerings for wide-arithmetic (#132430)
Automerge: [WebAssembly] Add more lowerings for wide-arithmetic (#132…
[WebAssembly] Add more lowerings for wide-arithmetic (#132430)
fix: make WideArithmetic proposal opt-in with --enable-wide-arithmetic
fix: make WideArithmetic proposal opt-in with --enable-wide-arithmetic