-
Notifications
You must be signed in to change notification settings - Fork 12.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Tracking Issue for bigint helper methods #85532
Comments
I'd like a mul_mod, as shown in #85017, because I think you can't implement it efficiently without asm and it's a basic block for power_mod and other things. |
Another set of methods that could be useful that I'll probably offer implementations for at some point: /// `(self << rhs) | carry`
fn carrying_shl(self, rhs: u32, carry: Self) -> (Self, Self);
/// `(self >> rhs) | carry`
fn borrowing_shr(self, rhs: u32, carry: Self) -> (Self, Self);
/// `self << rhs`
fn widening_shl(self, rhs: u32) -> (Self, Self);
/// `self >> rhs`
fn widening_shr(self, rhs: u32) -> (Self, Self); Essentially, return the two halves of a rotation, i.e. |
From @scottmcm in the original PR:
|
Why don't we add |
Mostly effort implementing them efficiently. In the meantime, you can do it with four calls to the |
I was very confused by this function name at first, since borrowing in Rust usually refers to references. I am not a native speaker, but I do formal mathematical work in English professionally, and yet I never before heard the term "borrowing" in the context of subtraction. So I think this, at least, needs some explanation in the docs. (I would have expected something like The current docs for some of the other methods could probably also be improved: they talk about not having the "ability to overflow", which makes it sound like not overflowing is a bad thing. |
The word borrow here comes from the terminology for a full subtractor. I am thinking that maybe the borrowing_sub function could be removed altogether. The same effect that borrowing_sub has can be obtained from carrying_add by making the first carrying_add in the chain have a set carry bit, and then bitnot every rhs. This fact could be put in the documentation of carrying_add. |
Considering how the primary goal of these methods is to be as efficient as possible, usually optimising down to a single instruction, I don't think it'd be reasonable to just get rid of subtraction in favour of telling everyone to use addition instead. Definitely open to changing the name, though. |
These helper methods will not be very useful to me unless they are implemented for every kind of integer. Here is an implementation for a widening multiplication-addition for u128:
I have tested this with my crate edit: There is a version of this that uses the Karatsuba trick to use 3 multiplications instead of 4, but it incurs extra summations, branches, and is not as parallel. For typical desktop processors the above should be the fastest. |
I would make a PR for that. |
Some alternative signatures include |
I would also change up the documentation headers for the
I specifically note |
|
But unsigned overflow and signed overflow are different. For example, on x86_64, while unsigned and signed integers share addition and subtraction instructions, unsigned overflow is detected using the carry flag while signed overflow is detected using the overflow flag. As a concrete example: Edit: I think I had misread your comment and thought the middle part of your comment was the current doc, not your suggestion, so it looks like I completely misinterpreted your final comment. |
Yes signed and unsigned overflow are different, but the |
I think all of these are good suggestions, and like mentioned earlier, these changes definitely should go in a PR if you have the time. I think one important thing to note is that so far the APIs here seem good, but the documentation definitely could use some work. Although if there's a bigger case for changing the subtraction behaviour to be more in line with what's expected (the existing behaviour is mostly modelled after the x86 instructions adc and sbb), then I'm for that. That said, the main goal is to make it relatively painless to write correct code that compiles down to the right instructions in release mode, so, I would say we should make sure that happens regardless of what's done. I would have added an explicit test for that but I honestly don't know how. |
…riplett Add more text and examples to `carrying_{add|mul}` `feature(bigint_helper_methods)` tracking issue rust-lang#85532 cc `@clarfonthey`
…riplett Add more text and examples to `carrying_{add|mul}` `feature(bigint_helper_methods)` tracking issue rust-lang#85532 cc ``@clarfonthey``
…riplett Add more text and examples to `carrying_{add|mul}` `feature(bigint_helper_methods)` tracking issue rust-lang#85532 cc ```@clarfonthey```
…riplett Add more text and examples to `carrying_{add|mul}` `feature(bigint_helper_methods)` tracking issue rust-lang#85532 cc ````@clarfonthey````
…riplett Add more text and examples to `carrying_{add|mul}` `feature(bigint_helper_methods)` tracking issue rust-lang#85532 cc `````@clarfonthey`````
Multiplication, and carry-less multiplication, are inherently a widening operation. Unfortunately, at the time of writing, the types in Rust don't capture this well, being built around fixed-width wrapping multiplication. Rust's stdlib can rely on compiler-level optimizations to clean up performance issues from unnecessarily-wide multiplications, but this becomes a bit of an issue for our library, especially for u64 types, since we rely on intrinsics, which may be hard for compilers to optimize around. This commit adds widening_mul, based on a proposal to add widening_mul to Rust's primitive types: rust-lang/rust#85532 As well as several other tweaks to how xmul is provided, moving more arch-level details into xmul, but still limiting when it is emitted.
I've seen before that you can fit a second carry, but usually in bigint libraries we just have a single carry to deal with in multiply-add chains. For long multiplication there are additions in two directions, but a loop can only handle one chain at at time and is usually adding to a temporary and handling that carry separately with |
@typetetris I don't know whether this will resonate, but I've been thinking of So the goal here to to provide that primitive as the obvious way to write it in math libraries, without needing to know about the best way to represent it in the backend in use. For example, LLVM represents wide multiplication by casting to a larger type and doing multiplication on that, but cranelift has So unless there's a particular use for the extra carry, I don't think it makes sense here, even though it's certainly a nice observation that another carry can fit. Like if the extra carry solved the slightly-wider intermediate result problem in Karatsuba then we should absolutely offer it (after all, it's easy to optimize out a |
Because it fits with |
The return type of This is entirely different for the The two multiplication functions should really return a named struct. |
@AaronKutch and @scottmcm Thanks for your explanations. I just had something like // result = result + lhs * rhs
pub fn classic_mul_add_in_place(result: &mut [u64], lhs: &[u64], rhs: &[u64]) {
debug_assert!(
result.len() > lhs.len() + rhs.len(),
"{} <= {} + {}",
result.len(),
lhs.len(),
rhs.len()
);
debug_assert!(result[lhs.len() + rhs.len()] < u64::MAX);
for (rhs_pos, rhs_leg) in rhs.iter().copied().enumerate() {
let mut carry = 0u64;
for (lhs_leg, result_place) in lhs
.iter()
.copied()
.chain(std::iter::repeat(0u64))
.zip(result[rhs_pos..].iter_mut())
{
let (new_digit, new_carry) = carrying_mul(rhs_leg, lhs_leg, *result_place, carry);
*result_place = new_digit;
carry = new_carry;
}
debug_assert_eq!(carry, 0u64);
}
} in a toy project of mine (certainly buggy, slow and not idiomatic or something!). The If you ever find a way to handle the slightly wider intermediate multiplication in Karatsuba, let me know, please. At the moment I just handle the carries from the additions of high and low part separately leading to some code bloat. Edit1: |
Thank you @typetetris! I found E.g., here is adapted @kennytm's function that uses pub fn u64_widening_mul2(x: u64, y: u64) -> u128 {
let a = (x >> u32::BITS) as u32;
let b = x as u32;
let c = (y >> u32::BITS) as u32;
let d = y as u32;
let (p1, p2) = widening_mul(b, d);
let (p2, p31) = carrying_mul(b, c, p2);
let (p2, p32) = carrying_mul(a, d, p2);
let (p3, p4) = carrying2_mul(a, c, p31, p32);
u128::from(p1) | u128::from(p2) << 32 | u128::from(p3) << 64 | u128::from(p4) << 96
} Ever assembly seems to be better than for initial version with explicit @scottmcm @AaronKutch I'm not sure if this affects the addition of this method to std. |
Btw I didn't find a way to generate optimal code for Tool: https://godbolt.org/ Rust code: #![feature(const_bigint_helper_methods)]
#![feature(bigint_helper_methods)]
#[no_mangle]
pub fn u128_widening_mul(x: u128, y: u128, result: &mut [u128; 2]) {
let a = (x >> 64) as u64;
let b = x as u64;
let c = (y >> 64) as u64;
let d = y as u64;
let (p1, p2) = b.widening_mul(d);
let (p2, p31) = b.carrying_mul(c, p2);
let (p2, p32) = a.carrying_mul(d, p2);
let (p3, p4o) = p31.overflowing_add(p32);
let (p3, p4) = a.carrying_mul(c, p3);
let p4 = p4.wrapping_add(p4o.into());
result[0] = u128::from(p1) | u128::from(p2) << 64;
result[1] = u128::from(p3) | u128::from(p4) << 64;
} output: u128_widening_mul:
umulh x8, x2, x0
mul x10, x3, x0
umulh x9, x3, x0
mul x12, x2, x1
adds x8, x8, x10
umulh x11, x2, x1
cinc x9, x9, hs
mul x14, x3, x1
adds x8, x8, x12
umulh x10, x3, x1
cinc x11, x11, hs
mul x13, x2, x0
adds x12, x9, x11
adds x12, x14, x12
cinc x10, x10, hs
cmn x9, x11
stp x13, x8, [x4]
cinc x8, x10, hs
stp x12, x8, [x4, #16]
ret But using Zig 0.12.0 it was able to generate optimal code: export fn u128_widening_mul(a: u128, b: u128, result: *[2]u128) void {
const value: u256 = @mulWithOverflow(@as(u256, a), @as(u256, b))[0];
result[0] = @intCast(value);
result[1] = @intCast(@shlWithOverflow(value, 128)[0]);
} output: u128_widening_mul:
umulh x8, x2, x0
stp xzr, xzr, [x4, #16]
mul x9, x2, x0
madd x8, x2, x1, x8
madd x8, x3, x0, x8
stp x9, x8, [x4]
ret |
This is kind of an aside to the discussion, but I greatly appreciate everyone discussing ways of optimising these functions for various targets, and ways of optimising using them for said targets. Very much reaffirms my assumption from the beginning that getting these right is very complicated and generally depends a lot on compiler internals, which is why they should exist in the standard library IMHO. |
@Lohann fyi you can share the link to your exact godbolt setup in the top right corner, here: https://godbolt.org/z/r19nKaGh5. But thanks for mentioning this. I think the above point still stands, that we would like to figure out the best API before adding methods that may require intrinsics (for i128/u128). |
@clarfonthey @tgross35 Makes sense. About the api, I also think that /// Calculates the complete product self * rhs without the possibility to overflow.
pub trait WideningMul<Rhs = Self> {
type Output;
#[must_use]
fn widening_mul(self, rhs: Rhs) -> (Self::Output, Self::Output);
} I implemented this trait for all primitives, except |
@Lohann are you sure the result of Zig make sense?u128_widening_mul:
; export fn u128_widening_mul(a: u128, b: u128, result: *[2]u128) void
;
; - x0 = lower 64-bit of `a`
; - x1 = upper 64-bit of `a`
; - x2 = lower 64-bit of `b`
; - x3 = upper 64-bit of `b`
; - x4 = pointer to `result`
umulh x8, x2, x0
; x8 := upper64(x2 * x0)
stp xzr, xzr, [x4, #16]
; x4[1] = 0
mul x9, x2, x0
; x9 := lower64(x2 * x0)
madd x8, x2, x1, x8
; x8 += lower64(x2 * x1)
madd x8, x3, x0, x8
; x8 += lower64(x3 * x0)
stp x9, x8, [x4]
; x4[0] = x8 << 64 | x9
ret it looks like it is simply computing result[0] = a * b
result[1] = 0 I think any compiler targeting aarch64 that generated code for u128*u128 significantly less than 18 instructions (which is the output of directly using LLVM-IR from #85532 (comment)) should be considered their bug. |
@kennytm good catch, you are right there was a bug in my zig code, I was doing shift left instead of shift right, fixed 🤦 . export fn u128_widening_mul(a: u128, b: u128, result: *[2]u128) void {
const x: u256 = @intCast(a);
const y: u256 = @intCast(b);
const value: u256 = @mulWithOverflow(x, y)[0];
result[0] = @truncate(value);
result[1] = @truncate(value >> 128);
} The rust code only generates one instruction more than the zig code, which is weird because zig also uses llvm, but that's not bad I can go forward with this implementation, thank you sir! |
One potential (weird) solution might be implementing an internal 256-bit integer which isn't exposed publicly and doesn't have all the operations implemented, but could be used oh LLVM's side to generate better code here. Or just going all out and doing generic integers like zig has, and keeping them internal until a public API is settled on. Both probably require an MCP. |
I think we don't need full-blown types -- an intrinsic can lower to LLVM |
@typetetris @nickkuk Your messages made me realize something: the way to justify If you want to send a PR adding it to nightly, I'm willing to approve it, though it'll need naming feedback from libs-api at some before before it would have a chance at stabilizing. (I could see @clarfonthey We have intrinsics with fallback bodies now, so we can add a poor version in rust in a way that it can be overridden by LLVM (to emit |
So, I was looking into this again and wanted to summarise some of the stuff folks have discussed so far, to see what common ground has been established. Addition methodsSo far, we're totally okay with the signatures of the two methods, where
The main issue is naming these methods, and there doesn't seem to be a consensus so far. A few of the options for addition:
And for subtraction:
One option I particularly like is using the
Although we definitely need to come up with a name consensus before stabilisation. The shed awaits… Multiplication methodsThese ones have undergone a lot of different discussion. A few notes that folks have added:
So, just to fully cover the signatures of these, using not-Rust syntax. Going to use a period for concatenation, and give a temporary name to them to hopefully make sense.
Not a whole lot has been done for names. Generally, people think of the two-word versions of multiplication as a "wide mul" or "widening mul" and that's okay. Probably the names Right now, it's unclear whether Finally, there's the subject of the return value. It seems reasonable to create a struct for this, since otherwise it won't be clear what word is which in most cases. Right now, only the Bit-shift methodsPeople seemed pretty amenable to adding these, although again, the carry/borrow name is a bit weird. Particularly, These aren't on nightly yet. ConclusionsIt seems definitely reasonable to add intrinsics for some of these methods as a good next step, since it's unlikely we'll get the right result without help. |
I don't think it's unlikely to get the right result for all of these without intrinsics. The intrinsics are needed to get them right and fast (easy to optimizable). |
So, I attempted to start writing some intrinsics for these, but I have not done this before and may have run into the most cursed compiler bug I've ever encountered, and I've also never done this before. But uh, we'll see what this ends up as later. Figured I'd mention in case anyone else was thinking of trying. In case you're wondering, it's me finding out that LLVM doesn't document any of its methods and secretly makes them all have unknown preconditions that can trigger UB if not properly met. I was getting illegal instructions just randomly in the middle of building my code. |
Is there a link pointing to some Internals-Forum or Zulip thread for bike-shedding the names? I'm aware that tracking-issues aren't meant for discussion, that's why I'm asking 😅 |
No, but you're more than welcome to make one and link it here! |
After looking at the assembly, I say that
|
It turns out that rustc was able to optimize the current implementation of |
Feature gate:
#![feature(bigint_helper_methods)]
This is a tracking issue for the following methods on integers:
carrying_add
borrowing_sub
carrying_mul
widening_mul
These methods are intended to help centralise the effort required for creating efficient big integer implementations, by offering a few methods which would otherwise require special compiler intrinsics or custom assembly code in order to do efficiently. They do not alone constitute big integer implementations themselves, but are necessary building blocks for a larger implementation.
Public API
Steps / History
widening_mul
RFC: widening_mul rfcs#2417carrying_add
,borrowing_sub
,carrying_mul
, andwidening_mul
Add carrying_add, borrowing_sub, widening_mul, carrying_mul methods to integers #85017carrying_add
andborrowing_sub
on signed types: Reimplementcarrying_add
andborrowing_sub
for signed integers. #93873("without the ability to overflow" can be confusing.)
Unresolved Questions
widening_mul
that simply returns the next-larger type? What would we do foru128
/i128
?The text was updated successfully, but these errors were encountered: