← Back to Pull requests

Add hwy/contrib/multiprec: fixed-width unsigned multiply (MulAdd52) #3372

Open
tvost2 opened this pull request with 1183 lines diff across 5 files
View on GitHub
tvost2 tvost2 commented on Sep 11, 2026 06:40 UTC
Author

Adds hwy/contrib/multiprec: a fixed-width unsigned multiply layer built on the MulAdd52 ops from #3365.

Design

  • Digits are 52 bits ("nails"), the largest width for which MulAdd52Lo/Hi are exact: for inputs < 2^52 the two together return the full 104-bit product. They exist on every target (native HWY_NATIVE_MULADD52, generic fallback otherwise), so there is no separate code path.

  • Layout is SoA: digit i of each operand is passed in its own vector, and the lanes of those vectors hold independent multiplications — the crypto use case (several RSA/ECC instances in parallel).

  • Schoolbook accumulation of the low/high parts of each product with per-digit carries.
  • API

  • WideMul<kDigits>::Mul(d, a, b, out) — SoA vector form; out has 2*kDigits digits.

  • WideMulBits<kBits> — bit-width form (kDigits = ceil(kBits/52)).

  • WideMulLimbs<kBits>(a, b, out) — scalar convenience over little-endian 64-bit limbs (e.g. u128/u192/u256).
  • Tests

  • WideMul<kDigits> for kDigits = 1..4, checked against a scalar reference on all targets.

  • WideMulLimbs<128/192/256> checked against an independent ripple-carry reference, plus maximum inputs.
  • Dependency

    Depends on #3365 (MulAdd52); this branch is stacked on feat/muladd52, so the diff includes it until #3365 merges. Part of #3352.

    Diff: 1183 lines (+1183 / -0) across 5 files Reviewer: jan-wassenberg Review duration: 41714m
    All Vouch review confidence checks passed
    Residual risk 0.05 = Change Risk (0.49) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.49 · 1183 lines diff across 5 files
    0.49
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    38 items
    jan-wassenberg jan-wassenberg commented on Sep 11, 2026 18:03 UTC
    Contributor

    Nice, this sounds sensible but I'm not experienced in this field. Can we first write a short 'market research' of existing approaches and both their APIs and their implementations, to help make sure our interface meets user needs?

    On naming: do we intend to provide more such operations, or will it stay mul-only? If the latter, we should probably rename the directory.

    Also, the test has arrays of vectors which does not compile on RVV/SVE. Let's replace with dynamically allocated arrays of T.

    tvost2 tvost2 commented on Sep 16, 2026 13:27 UTC
    Author

    Here is the market research you asked for (§1-3 are the survey, §4-5 the
    conclusions). Short version:

  • Our API already matches what every serious fixed-width library does: width in

  • the type, 2n digits out-of-place, caller-owned memory, no allocation. The
    outliers are the allocating high-level bignums (GMP mpz, OpenSSL BN,
    mbedtls_mpi), which are not a fit for this use case anyway.
  • The two things users will ask for next are Montgomery reduction and carry

  • helpers (add/sub with carry, add-multiply-accumulate). That is also the
    argument in §5 for keeping a directory name that covers multi-precision
    arithmetic rather than multiply only.
  • WideMul<kDigits> sits where crypto-bigint::Uint<LIMBS> and

  • ruint::Uint<BITS, LIMBS> sit, and the lane-parallel layout matches Intel's
    multibuffer model, which is the same RSA/ECC use case that motivated this.

    Naming: I would keep multiprec, and give the reduction its own name when it
    lands rather than growing WideMul.

    The RVV/SVE test fix (arrays of vectors replaced by dynamically allocated arrays
    of T) is next - it is what the four failing AArch64/RISC-V jobs in the current
    run are hitting.

    ---

    Market research: fixed-width multi-precision multiply

    What existing approaches do, what their APIs and implementations look like, and
    what that implies for hwy/contrib/multiprec.

    1. The question

    The interface has to serve a specific user: RSA/ECC-style code that multiplies
    kDigits-digit operands, in parallel across SIMD lanes, with no allocation and
    no data-dependent branches. So the useful comparison axes are:

  • how the width is expressed (type, template argument, runtime size argument),

  • where the result lives (2n digits out-of-place, in-place, returned),

  • who owns the memory (caller-supplied pointers vs. heap),

  • whether aliasing/overlap is allowed,

  • the digit/limb width, and whether digits are saturated or have spare bits

  • ("nails"),
  • whether the library also provides the reduction step (Montgomery), which is

  • what any real user does next with the product,
  • and whether it is lane-parallel (many independent instances) or single-instance.
  • 2. Prior art

    2.1 High-level, allocating bignums

    mpz_ (GMP), BN_ (OpenSSL), mbedtls_mpi_, num-bigint (Rust),
    BigInteger (Java), int (Python). The API is result = a
    b with heap
    allocation, dynamic length, and often data-dependent behaviour (early exits,
    variable limb counts). Convenient, but the wrong shape here: allocation is not
    acceptable in crypto callers, and the length is not known at compile time.
    mbedTLS' newer "core" API partially moves away from this with fixed-size
    limb-array functions (mbedtls_mpi_core_mul and friends) — the same direction we
    are taking.

    2.2 Low-level limb arrays, caller-managed memory

    This is the classic shape, and the closest relative of what we are adding.

  • *GMP mpn_*: mpn_mul_n (rp, s1p, s2p, n) and

  • mpn_mul (rp, s1p, s1n, s2p, s2n). A source is
    (pointer to least significant
    limb, count), a destination is just a pointer, and the caller guarantees the
    space. The per-limb helpers are mpn_addmul_1 (rp, s1p, n, s2limb),
    mpn_mul_1, mpn_submul_1, each returning the carry rather than storing
    it. In-place is allowed only where documented, and
    partial overlap is not.
    There is also a "secure" family (mpn_sec_mul) with explicit scratch space and
    constant-time guarantees.
  • Nails. GMP's nail feature reserves a few top bits of every limb

  • (GMP_NAIL_BITS, GMP_NUMB_BITS, GMP_LIMB_BITS). The manual makes two
    points that are directly relevant here: nails "can significantly improve carry
    handling on some processors", and a future non-zero nail "would help vector
    processors since carries would only ever need to propagate one or two limbs".
    Our 52-bit digits are that idea, with the spare 12 bits used to make
    MulAdd52Lo/Hi exact.
  • BearSSL ships the idea as the representation: i32 (32-bit limbs),

  • i31 (31-bit limbs stored in uint32_t, chosen for portability and speed),
    i15 (for cores without a 64-bit multiply) and i62 (a 64x64->128 path for
    modular exponentiation). Multiplication is br_i31_mulacc / br_i32_mulacc
    with a documented working area, constant-time, and deliberately frugal in ROM
    and RAM.
  • OpenSSL / BoringSSL: BN_mul/BN_sqr at the high level, BN_MONT_CTX +

  • BN_mod_mul_montgomery/BN_mod_exp_mont for the field, with a
    per-architecture bn_mul_mont assembly kernel underneath. The lesson is that
    Montgomery is the first thing layered on top, and that the low-level kernel
    is written for one fixed limb size per architecture.

    2.3 Fixed-size, formally verified kernels

    The modern high-assurance school converges on a very specific API shape: one
    function per (operation, size), fixed width, out-of-place, no allocation,
    constant-time, no partial overlap.

  • s2n-bignum (AWS): pure machine code for x86_64 and aarch64, one routine per

  • size and operation (bignum_mul_4_8-style names), constant-time by
    construction, and every function carries a machine-checked HOL-Light proof of
    its mathematical result. Used by aws-lc.
  • HACL: verified bignum arithmetic (fixed-size entry points plus a generic

  • implementation), extracted from F, used in Firefox and Linux.
  • fiat-crypto: generates field arithmetic per modulus from a Coq model

  • (e.g. fiat_25519_carry_mul), saturated limb arithmetic with explicit carry
    chains, verified correct; deployed in BoringSSL (see its boringssl_notes.md).

    2.4 Const-generic fixed-width types

  • crypto-bigint (RustCrypto): Uint<LIMBS>, U256, U1024, ... stack

  • allocated, constant-time by default, and
    explicitly variable-time functions
    suffixed _vartime. The widening operations are the ones we care about:
    mul_wide, square_wide, plus mul_mod and Montgomery helpers.
  • ruint: Uint<BITS, LIMBS> with 64-bit limbs and aliases (U256),

  • widening multiplication, and optional Karatsuba / Montgomery (REDC).

    The takeaway: the width belongs in the type (or a compile-time constant), and
    the widening multiply is the primitive everything else is built on.

    2.5 Field-specialized, hand-written with nails

  • libsecp256k1: field_5x52_int128_impl.h stores a field element as five

  • 52-bit limbs, multiplies with 64x64->128 products and a hand-written carry
    chain, and asserts VERIFY_BITS on every intermediate to show nothing
    overflows. There is a 10x26 variant as well. Fixed width, no allocation, no
    branches. Same family as the Curve25519 "5x51" representations.
  • This is the strongest evidence for our digit choice: 52 bits is the largest

  • width for which a product stays exact in the available 52-bit multiply
    primitives — the same reason we use MulAdd52.

    2.6 SIMD / multibuffer libraries

  • Intel Cryptography Primitives (formerly ipp-crypto) and its Crypto

  • Multi-buffer Library: RSA/ECDSA/ECDH/x25519/SM2 primitives that process
    many
    independent instances in parallel on AVX-512, which is precisely the use case
    in the PR description. Their memory model is arrays of instances — SoA across
    lanes, digits in separate registers — and the selling point is throughput on
    servers doing many handshakes.

    Our WideMul<kDigits>::Mul(d, a, b, out), with one digit vector per operand and
    independent multiplications in the lanes, is the same model, except that the lane
    count comes from HWY_LANES rather than being fixed to 512 bits.

    3. Comparison

    | Approach | Width expressed as | Result | Memory | Aliasing | Digits | Reduction provided | Lane-parallel |
    |---|---|---|---|---|---|---|---|
    | GMP mpz / OpenSSL BN / mbedTLS mpi | runtime length | new object | heap | n/a | 32/64 | Montgomery (BN/mbedTLS) | no |
    | GMP mpn | runtime n | caller buffer, 2n limbs | caller | in-place if documented, no partial overlap | 32/64 + nails | separate mpn_
    | no |
    | BearSSL i31/i32/i15/i62 | runtime n per impl. | caller buffer | caller | in-place | 15/31/32 | br_i31_montymul etc. | no |
    | s2n-bignum | in the name (_4_8) | caller buffer | caller | none | 64 | separate routines | no |
    | HACL | in the name / generic | caller buffer | caller | none | 32/64 | separate | partly (HACLxN) |
    | fiat-crypto | in the
    name, per modulus | caller buffer | caller | none | saturated | in the "carry" functions | no |
    | crypto-bigint | in the type (Uint<LIMBS>) | returned tuple | stack | n/a | 32/64 | mul_mod, Montgomery | no |
    | ruint | in the type (Uint<BITS, LIMBS>) | returned tuple | stack | n/a | 64 | REDC | no |
    | libsecp256k1 | in the type (fe = 5x52) | in-place fe | stack | n/a | 52 (nails) | fe_mul includes it | no |
    | Intel multibuffer | in the call (ifma_
    ) | caller arrays | caller | none | 52 (IFMA) | separate | yes |
    | this PR | in the type (WideMul<kDigits>) | caller buffer, 2kDigits digits | caller | none (documented) | 52 (nails) | not yet | yes |

    4. What this means for our interface

    Points of agreement with the field (keep them):

    1. Width in the type (WideMul<kDigits>, WideMulBits<kBits>) matches
    crypto-bigint, ruint and the field types; nobody in this space uses a
    runtime length for a fixed-width use case.
    2. Caller-supplied output and no allocation matches mpn, BearSSL,
    s2n-bignum, HACL
    , fiat-crypto and the multibuffer libraries.
    3. *2kDigits digits out-of-place is the universal convention
    (mpn_mul_n writes 2n limbs, bignum_mul_4_8 writes 8).
    4.
    Unsaturated digits with documented spare bits is GMP's nails and the
    52-bit representations of secp256k1 and IFMA. We should state the invariant
    as explicitly as GMP does (nails zero on entry and exit) — i.e. whether digits
    are normalized on input and on output.
    5.
    Lane-parallel equals multibuffer matches Intel's model, which is exactly
    the RSA/ECC-in-parallel use case.

    Gaps worth closing before users arrive:

    1. Reduction. Every RSA/ECC user multiplies and then reduces (Montgomery).
    Without it they will reimplement the loop over our output. A MontMul/Redc
    helper (or at least a documented pattern) is the single most valuable
    addition.
    2.
    Carry helpers. Schoolbook accumulation needs add/sub with carry and
    add-multiply-accumulate (mpn_addmul_1-style). Cheap to provide, awkward to
    hand-roll on top of a Mul that only returns full products.
    3.
    Aliasing contract. Be explicit, as mpn is: may out alias a or b?
    Today the answer is no, and the doc should say so, since mpn users expect
    in-place to work "where documented".
    4.
    Squaring. Mul with a == b should be documented as the supported way to
    square (or specialized, since it is about 2x cheaper).
    5.
    Digit-count arithmetic.* Spell out the mapping in the docs, since that is
    how users will pick kBits: 2048, 3072, 4096 and 8192 bits are 40, 60, 79 and
    158 digits of 52 bits.

    5. On naming

    The question was whether we intend to provide more such operations or stay
    multiply-only, because that decides the directory name. The prior art says the
    directory
    will grow: every serious library pairs the widening multiply with
    Montgomery reduction and carry helpers, because that is what the caller needs
    next. So:

  • keep a name that covers "multi-precision arithmetic" and state the roadmap in

  • the header: multiprec does that. Alternatives: bignum collides with the
    high-level meaning above; intwide is narrower than where we will end up.
  • keep the type names specific: WideMul, WideMulBits, WideMulLimbs are

  • honest as long as they only multiply. The reduction should get its own name
    (MontMul or similar) rather than growing into WideMul.

    6. Sources

  • GMP low-level functions and nails:

  • <https://gmplib.org/manual/Low_002dlevel-Functions>
  • BearSSL big integer design (i15/i31/i32/i62):

  • <https://bearssl.org/bigint.html>
  • s2n-bignum (verified, constant-time bignum routines):

  • <https://github.com/awslabs/s2n-bignum>
  • HACL: <https://github.com/hacl-star/hacl-star>

  • fiat-crypto: <https://github.com/mit-plv/fiat-crypto>

  • libsecp256k1 5x52 multiply:

  • <https://github.com/bitcoin-core/secp256k1/blob/master/src/field_5x52_int128_impl.h>
  • crypto-bigint: <https://github.com/RustCrypto/crypto-bigint>

  • ruint: <https://github.com/recmo/uint>

  • Intel Cryptography Primitives (multi-buffer RSA/ECC):

  • <https://github.com/intel/ipp-crypto>
  • OpenSSL BIGNUM (BN_mul, BN_mod_mul_montgomery, BN_MONT_CTX):

  • <https://docs.openssl.org/master/man3/BN_mul/>

    tvost2 tvost2 commented on Sep 16, 2026 13:29 UTC
    Author

    One more finding while preparing the test fix, because I do not think the test
    alone is what the RVV/SVE jobs are hitting.

    multiprec-inl.h also keeps vectors in arrays, which is equally ill-formed where
    Vec<D> is a sizeless type (vfloat64m1_t/svfloat64_t):

    // multiprec-inl.h, SchoolbookMul
    Vec<D> low[2 * kDigits - 1];
    Vec<D> high[2 * kDigits - 1];
    

    and the public entry point takes them by array:

    // multiprec-inl.h
    template <size_t kDigits, class D>
    HWY_INLINE void SchoolbookMul(D d, const Vec<D>* HWY_RESTRICT a, ...)
    

    So replacing the test's arrays with arrays of T (as you suggested) is necessary
    but not sufficient: the test would then just fail to compile inside the kernel
    instead of at its own call site. Vec<D> pointers are fine, but the local
    low[]/high[] arrays are not, and neither is an array-typed parameter for the
    digits.

    Two ways out, and I would like your preference:

    1. Guard it now: keep the vector kernel for targets that can hold vectors in
    arrays (#if !HWY_HAVE_SCALABLE), and on scalable targets either omit the
    contrib or provide a T-based fallback. Cheap and unblocks the AArch64/RISC-V
    jobs immediately, at the cost of the contrib being unavailable where Highway
    is most portable.
    2. Make the interface T-based: Mul(d, const T
    a, const T b, T out)
    with digits at a + i N, Load/Store inside, and either a caller-provided
    scratch buffer for the 2
    kDigits-1 partial products or a scalar loop on
    scalable targets. This matches the "arrays of T" direction and works
    everywhere, but the partial products must then live in memory rather than in
    registers, which is exactly where the IFMA win comes from.

    My preference is (1) for this PR (so the target-restriction is explicit and
    documented, like TestWideMul already is with #if HWY_TARGET != HWY_SCALAR),
    and (2) as a follow-up if we want the contrib to be usable on SVE/RVV. Either
    way I will do the test fix in the same commit as whichever we pick.

    jan-wassenberg jan-wassenberg commented on code on Sep 16, 2026 14:26 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,318 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Digits are 52 bits ("nails"), the largest width for which the IFMA
    +// MulAdd52Lo/Hi ops are exact: for inputs < 2^52 the two together return the
    +// full 104-bit product exactly. Those ops exist on every target (native
    +// HWY_NATIVE_MULADD52 where available, the generic fallback otherwise), so
    +// this works everywhere without a separate fallback.
    +//
    +// Layout is SoA: digit i (little-endian) of each operand is passed in its own
    +// vector, `a[i]` / `b[i]`. The lanes of those vectors hold independent
    +// multiplications, which is how crypto (several RSA/ECC instances) uses it.
    +
    +constexpr size_t kWideMulDigitBits = 52;
    +constexpr uint64_t kWideMulDigitMask = (uint64_t{1} << kWideMulDigitBits) - 1;
    +
    +// The schoolbook kernel costs O(kDigits^2). Karatsuba's 3-way split lowers
    +// that to ~O(kDigits^1.585) but adds additions, subtractions and copies, so
    +// it only pays off above this many digits.
    +constexpr size_t kWideMulKaratsubaMinDigits = 8;
    +
    +#if HWY_TARGET != HWY_SCALAR
    +
    +namespace detail {
    +
    +// out[0..2*kDigits) = a * b, schoolbook. Both operands have kDigits digits,
    +// each < 2^52.
    +template <size_t kDigits, class D>
    +HWY_INLINE void SchoolbookMul(D d, const Vec<D>* HWY_RESTRICT a,
    +                              const Vec<D>* HWY_RESTRICT b,
    +                              Vec<D>* HWY_RESTRICT out) {
    +  // low[k] is the sum of the low 52 bits of a[i]*b[j] over all i+j == k;
    +  // high[k] is the sum of bits 52..103 of the same products. Both fit in 64
    +  // bits because there are at most kDigits terms, each < 2^52.
    +  Vec<D> low[2 * kDigits - 1];

    In addition to the SVE issue (no arrays of vectors), this may spill even for non-scalable targets for large kDigits. Comba's method loops over k and sums i+j = k and would only use 3 vectors.

    jan-wassenberg jan-wassenberg commented on code on Sep 16, 2026 14:26 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,318 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Digits are 52 bits ("nails"), the largest width for which the IFMA
    +// MulAdd52Lo/Hi ops are exact: for inputs < 2^52 the two together return the
    +// full 104-bit product exactly. Those ops exist on every target (native
    +// HWY_NATIVE_MULADD52 where available, the generic fallback otherwise), so
    +// this works everywhere without a separate fallback.
    +//
    +// Layout is SoA: digit i (little-endian) of each operand is passed in its own
    +// vector, `a[i]` / `b[i]`. The lanes of those vectors hold independent
    +// multiplications, which is how crypto (several RSA/ECC instances) uses it.
    +
    +constexpr size_t kWideMulDigitBits = 52;
    +constexpr uint64_t kWideMulDigitMask = (uint64_t{1} << kWideMulDigitBits) - 1;
    +
    +// The schoolbook kernel costs O(kDigits^2). Karatsuba's 3-way split lowers
    +// that to ~O(kDigits^1.585) but adds additions, subtractions and copies, so
    +// it only pays off above this many digits.
    +constexpr size_t kWideMulKaratsubaMinDigits = 8;
    +
    +#if HWY_TARGET != HWY_SCALAR
    +
    +namespace detail {
    +
    +// out[0..2*kDigits) = a * b, schoolbook. Both operands have kDigits digits,
    +// each < 2^52.
    +template <size_t kDigits, class D>
    +HWY_INLINE void SchoolbookMul(D d, const Vec<D>* HWY_RESTRICT a,
    +                              const Vec<D>* HWY_RESTRICT b,
    +                              Vec<D>* HWY_RESTRICT out) {
    +  // low[k] is the sum of the low 52 bits of a[i]*b[j] over all i+j == k;
    +  // high[k] is the sum of bits 52..103 of the same products. Both fit in 64
    +  // bits because there are at most kDigits terms, each < 2^52.
    +  Vec<D> low[2 * kDigits - 1];
    +  Vec<D> high[2 * kDigits - 1];
    +  for (size_t k = 0; k < 2 * kDigits - 1; ++k) {
    +    low[k] = Zero(d);
    +    high[k] = Zero(d);
    +  }
    +  for (size_t i = 0; i < kDigits; ++i) {
    +    for (size_t j = 0; j < kDigits; ++j) {
    +      low[i + j] = MulAdd52Lo(a[i], b[j], low[i + j]);
    +      high[i + j] = MulAdd52Hi(a[i], b[j], high[i + j]);
    +    }
    +  }
    +
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k + 1 < 2 * kDigits; ++k) {
    +    const Vec<D> sum = Add(low[k], carry);
    +    out[k] = And(sum, mask);
    +    carry = Add(ShiftRight<kWideMulDigitBits>(sum), high[k]);
    +  }
    +  out[2 * kDigits - 1] = And(carry, mask);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out digit.
    +template <class D>
    +HWY_INLINE Vec<D> AddDigitsCarry(D d, const Vec<D>* HWY_RESTRICT a,
    +                                 const Vec<D>* HWY_RESTRICT b, size_t kCount,
    +                                 Vec<D>* HWY_RESTRICT out) {
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum = Add(Add(a[i], b[i]), carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// out[kOffset..kTotal) += src[0..kCount), with carry ripple. kCount is
    +// clamped so that nothing is written at or past kTotal.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, Vec<D>* HWY_RESTRICT out,
    +                        const Vec<D>* HWY_RESTRICT src) {
    +  constexpr size_t kUsed = kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(Add(out[kOffset + i], src[i]), carry);
    +    out[kOffset + i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(out[i], carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +}
    +
    +// dst[0..kTotal) -= src[kOffset..kOffset + kCount), zero-extending src, with
    +// borrow ripple. The result must be non-negative.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, Vec<D>* HWY_RESTRICT dst,
    +                        const Vec<D>* HWY_RESTRICT src) {
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> one = Set(d, 1);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? src[kOffset + i] : zero;
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Mask<D> underflow = Lt(dst[i], sub);
    +    dst[i] = And(Sub(dst[i], sub), mask);
    +    borrow = IfThenElse(underflow, one, zero);
    +  }
    +}
    +
    +// out[0..2*kDigits) = a * b. Karatsuba's 3-way split above the threshold;
    +// schoolbook for small or odd sizes (whose split would be unbalanced).
    +template <size_t kDigits, class D>
    +HWY_INLINE void MulRec(D d, const Vec<D>* HWY_RESTRICT a,
    +                       const Vec<D>* HWY_RESTRICT b, Vec<D>* HWY_RESTRICT out) {
    +  if constexpr (kDigits < kWideMulKaratsubaMinDigits || (kDigits & 1) != 0) {
    +    SchoolbookMul<kDigits>(d, a, b, out);
    +  } else {
    +    constexpr size_t kHalf = kDigits / 2;
    +    constexpr size_t kTotal = 2 * kDigits;
    +    constexpr size_t kSumDigits = 2 * (kHalf + 1);
    +
    +    for (size_t k = 0; k < kTotal; ++k) out[k] = Zero(d);
    +
    +    {  // z0 = a_lo * b_lo, at digit 0.
    +      Vec<D> z0[2 * kHalf];
    +      MulRec<kHalf>(d, a, b, z0);
    +      AddInto<0, 2 * kHalf, kTotal>(d, out, z0);
    +    }
    +    {  // z2 = a_hi * b_hi, at digit 2*kHalf.
    +      Vec<D> z2[2 * kHalf];
    +      MulRec<kHalf>(d, a + kHalf, b + kHalf, z2);
    +      AddInto<2 * kHalf, 2 * kHalf, kTotal>(d, out, z2);
    +    }
    +
    +    // s = a_lo + a_hi and t = b_lo + b_hi, each kHalf + 1 digits.
    +    Vec<D> s[kHalf + 1];

    Also array of T with MaxLanes * kNumVectors.

    jan-wassenberg jan-wassenberg commented on code on Sep 16, 2026 14:27 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,318 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Digits are 52 bits ("nails"), the largest width for which the IFMA

    Nails are the unused bits in the word/limb. Digits seems like confusing terminology, I'd suggest just using limbs and saying whether they are 52 or 64-bit.

    jan-wassenberg jan-wassenberg commented on code on Sep 16, 2026 14:30 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,318 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Digits are 52 bits ("nails"), the largest width for which the IFMA
    +// MulAdd52Lo/Hi ops are exact: for inputs < 2^52 the two together return the
    +// full 104-bit product exactly. Those ops exist on every target (native
    +// HWY_NATIVE_MULADD52 where available, the generic fallback otherwise), so
    +// this works everywhere without a separate fallback.
    +//
    +// Layout is SoA: digit i (little-endian) of each operand is passed in its own
    +// vector, `a[i]` / `b[i]`. The lanes of those vectors hold independent
    +// multiplications, which is how crypto (several RSA/ECC instances) uses it.
    +
    +constexpr size_t kWideMulDigitBits = 52;
    +constexpr uint64_t kWideMulDigitMask = (uint64_t{1} << kWideMulDigitBits) - 1;
    +
    +// The schoolbook kernel costs O(kDigits^2). Karatsuba's 3-way split lowers
    +// that to ~O(kDigits^1.585) but adds additions, subtractions and copies, so
    +// it only pays off above this many digits.
    +constexpr size_t kWideMulKaratsubaMinDigits = 8;
    +
    +#if HWY_TARGET != HWY_SCALAR
    +
    +namespace detail {
    +
    +// out[0..2*kDigits) = a * b, schoolbook. Both operands have kDigits digits,
    +// each < 2^52.
    +template <size_t kDigits, class D>
    +HWY_INLINE void SchoolbookMul(D d, const Vec<D>* HWY_RESTRICT a,
    +                              const Vec<D>* HWY_RESTRICT b,
    +                              Vec<D>* HWY_RESTRICT out) {
    +  // low[k] is the sum of the low 52 bits of a[i]*b[j] over all i+j == k;
    +  // high[k] is the sum of bits 52..103 of the same products. Both fit in 64
    +  // bits because there are at most kDigits terms, each < 2^52.
    +  Vec<D> low[2 * kDigits - 1];
    +  Vec<D> high[2 * kDigits - 1];
    +  for (size_t k = 0; k < 2 * kDigits - 1; ++k) {
    +    low[k] = Zero(d);
    +    high[k] = Zero(d);
    +  }
    +  for (size_t i = 0; i < kDigits; ++i) {
    +    for (size_t j = 0; j < kDigits; ++j) {
    +      low[i + j] = MulAdd52Lo(a[i], b[j], low[i + j]);
    +      high[i + j] = MulAdd52Hi(a[i], b[j], high[i + j]);
    +    }
    +  }
    +
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k + 1 < 2 * kDigits; ++k) {
    +    const Vec<D> sum = Add(low[k], carry);
    +    out[k] = And(sum, mask);
    +    carry = Add(ShiftRight<kWideMulDigitBits>(sum), high[k]);
    +  }
    +  out[2 * kDigits - 1] = And(carry, mask);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out digit.
    +template <class D>
    +HWY_INLINE Vec<D> AddDigitsCarry(D d, const Vec<D>* HWY_RESTRICT a,
    +                                 const Vec<D>* HWY_RESTRICT b, size_t kCount,
    +                                 Vec<D>* HWY_RESTRICT out) {
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum = Add(Add(a[i], b[i]), carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// out[kOffset..kTotal) += src[0..kCount), with carry ripple. kCount is
    +// clamped so that nothing is written at or past kTotal.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, Vec<D>* HWY_RESTRICT out,
    +                        const Vec<D>* HWY_RESTRICT src) {
    +  constexpr size_t kUsed = kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(Add(out[kOffset + i], src[i]), carry);
    +    out[kOffset + i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(out[i], carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +}
    +
    +// dst[0..kTotal) -= src[kOffset..kOffset + kCount), zero-extending src, with
    +// borrow ripple. The result must be non-negative.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, Vec<D>* HWY_RESTRICT dst,
    +                        const Vec<D>* HWY_RESTRICT src) {
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> one = Set(d, 1);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? src[kOffset + i] : zero;
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Mask<D> underflow = Lt(dst[i], sub);
    +    dst[i] = And(Sub(dst[i], sub), mask);
    +    borrow = IfThenElse(underflow, one, zero);
    +  }
    +}
    +
    +// out[0..2*kDigits) = a * b. Karatsuba's 3-way split above the threshold;
    +// schoolbook for small or odd sizes (whose split would be unbalanced).
    +template <size_t kDigits, class D>
    +HWY_INLINE void MulRec(D d, const Vec<D>* HWY_RESTRICT a,
    +                       const Vec<D>* HWY_RESTRICT b, Vec<D>* HWY_RESTRICT out) {
    +  if constexpr (kDigits < kWideMulKaratsubaMinDigits || (kDigits & 1) != 0) {
    +    SchoolbookMul<kDigits>(d, a, b, out);
    +  } else {
    +    constexpr size_t kHalf = kDigits / 2;
    +    constexpr size_t kTotal = 2 * kDigits;
    +    constexpr size_t kSumDigits = 2 * (kHalf + 1);
    +
    +    for (size_t k = 0; k < kTotal; ++k) out[k] = Zero(d);
    +
    +    {  // z0 = a_lo * b_lo, at digit 0.
    +      Vec<D> z0[2 * kHalf];
    +      MulRec<kHalf>(d, a, b, z0);
    +      AddInto<0, 2 * kHalf, kTotal>(d, out, z0);
    +    }
    +    {  // z2 = a_hi * b_hi, at digit 2*kHalf.
    +      Vec<D> z2[2 * kHalf];
    +      MulRec<kHalf>(d, a + kHalf, b + kHalf, z2);
    +      AddInto<2 * kHalf, 2 * kHalf, kTotal>(d, out, z2);
    +    }
    +
    +    // s = a_lo + a_hi and t = b_lo + b_hi, each kHalf + 1 digits.
    +    Vec<D> s[kHalf + 1];
    +    Vec<D> t[kHalf + 1];
    +    s[kHalf] = AddDigitsCarry(d, a, a + kHalf, kHalf, s);
    +    t[kHalf] = AddDigitsCarry(d, b, b + kHalf, kHalf, t);
    +
    +    // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo. z0 and z2 are already in
    +    // `out` at digits 0 and 2*kHalf and nothing else has been added yet, so
    +    // subtract them from there.
    +    Vec<D> st[kSumDigits];
    +    MulRec<kHalf + 1>(d, s, t, st);

    Do we care about power of two kDigits? If so, that's often going to hit the schoolbook codepath because this is always odd.
    I think we can either handle odd cases inside Karatsuba, or keep the recursion at kHalf by handling carries separately.

    jan-wassenberg jan-wassenberg commented on code on Sep 16, 2026 14:30 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,318 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Digits are 52 bits ("nails"), the largest width for which the IFMA
    +// MulAdd52Lo/Hi ops are exact: for inputs < 2^52 the two together return the
    +// full 104-bit product exactly. Those ops exist on every target (native
    +// HWY_NATIVE_MULADD52 where available, the generic fallback otherwise), so
    +// this works everywhere without a separate fallback.
    +//
    +// Layout is SoA: digit i (little-endian) of each operand is passed in its own
    +// vector, `a[i]` / `b[i]`. The lanes of those vectors hold independent
    +// multiplications, which is how crypto (several RSA/ECC instances) uses it.
    +
    +constexpr size_t kWideMulDigitBits = 52;
    +constexpr uint64_t kWideMulDigitMask = (uint64_t{1} << kWideMulDigitBits) - 1;
    +
    +// The schoolbook kernel costs O(kDigits^2). Karatsuba's 3-way split lowers
    +// that to ~O(kDigits^1.585) but adds additions, subtractions and copies, so
    +// it only pays off above this many digits.
    +constexpr size_t kWideMulKaratsubaMinDigits = 8;
    +
    +#if HWY_TARGET != HWY_SCALAR
    +
    +namespace detail {
    +
    +// out[0..2*kDigits) = a * b, schoolbook. Both operands have kDigits digits,
    +// each < 2^52.
    +template <size_t kDigits, class D>
    +HWY_INLINE void SchoolbookMul(D d, const Vec<D>* HWY_RESTRICT a,
    +                              const Vec<D>* HWY_RESTRICT b,
    +                              Vec<D>* HWY_RESTRICT out) {
    +  // low[k] is the sum of the low 52 bits of a[i]*b[j] over all i+j == k;
    +  // high[k] is the sum of bits 52..103 of the same products. Both fit in 64
    +  // bits because there are at most kDigits terms, each < 2^52.
    +  Vec<D> low[2 * kDigits - 1];
    +  Vec<D> high[2 * kDigits - 1];
    +  for (size_t k = 0; k < 2 * kDigits - 1; ++k) {
    +    low[k] = Zero(d);
    +    high[k] = Zero(d);
    +  }
    +  for (size_t i = 0; i < kDigits; ++i) {
    +    for (size_t j = 0; j < kDigits; ++j) {
    +      low[i + j] = MulAdd52Lo(a[i], b[j], low[i + j]);
    +      high[i + j] = MulAdd52Hi(a[i], b[j], high[i + j]);
    +    }
    +  }
    +
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k + 1 < 2 * kDigits; ++k) {
    +    const Vec<D> sum = Add(low[k], carry);
    +    out[k] = And(sum, mask);
    +    carry = Add(ShiftRight<kWideMulDigitBits>(sum), high[k]);
    +  }
    +  out[2 * kDigits - 1] = And(carry, mask);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out digit.
    +template <class D>
    +HWY_INLINE Vec<D> AddDigitsCarry(D d, const Vec<D>* HWY_RESTRICT a,
    +                                 const Vec<D>* HWY_RESTRICT b, size_t kCount,
    +                                 Vec<D>* HWY_RESTRICT out) {
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum = Add(Add(a[i], b[i]), carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// out[kOffset..kTotal) += src[0..kCount), with carry ripple. kCount is
    +// clamped so that nothing is written at or past kTotal.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, Vec<D>* HWY_RESTRICT out,
    +                        const Vec<D>* HWY_RESTRICT src) {
    +  constexpr size_t kUsed = kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(Add(out[kOffset + i], src[i]), carry);
    +    out[kOffset + i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(out[i], carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +}
    +
    +// dst[0..kTotal) -= src[kOffset..kOffset + kCount), zero-extending src, with
    +// borrow ripple. The result must be non-negative.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, Vec<D>* HWY_RESTRICT dst,
    +                        const Vec<D>* HWY_RESTRICT src) {
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> one = Set(d, 1);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? src[kOffset + i] : zero;
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Mask<D> underflow = Lt(dst[i], sub);
    +    dst[i] = And(Sub(dst[i], sub), mask);
    +    borrow = IfThenElse(underflow, one, zero);
    +  }
    +}
    +
    +// out[0..2*kDigits) = a * b. Karatsuba's 3-way split above the threshold;
    +// schoolbook for small or odd sizes (whose split would be unbalanced).
    +template <size_t kDigits, class D>
    +HWY_INLINE void MulRec(D d, const Vec<D>* HWY_RESTRICT a,
    +                       const Vec<D>* HWY_RESTRICT b, Vec<D>* HWY_RESTRICT out) {
    +  if constexpr (kDigits < kWideMulKaratsubaMinDigits || (kDigits & 1) != 0) {
    +    SchoolbookMul<kDigits>(d, a, b, out);
    +  } else {
    +    constexpr size_t kHalf = kDigits / 2;
    +    constexpr size_t kTotal = 2 * kDigits;
    +    constexpr size_t kSumDigits = 2 * (kHalf + 1);
    +
    +    for (size_t k = 0; k < kTotal; ++k) out[k] = Zero(d);
    +
    +    {  // z0 = a_lo * b_lo, at digit 0.
    +      Vec<D> z0[2 * kHalf];
    +      MulRec<kHalf>(d, a, b, z0);
    +      AddInto<0, 2 * kHalf, kTotal>(d, out, z0);
    +    }
    +    {  // z2 = a_hi * b_hi, at digit 2*kHalf.
    +      Vec<D> z2[2 * kHalf];
    +      MulRec<kHalf>(d, a + kHalf, b + kHalf, z2);
    +      AddInto<2 * kHalf, 2 * kHalf, kTotal>(d, out, z2);
    +    }
    +
    +    // s = a_lo + a_hi and t = b_lo + b_hi, each kHalf + 1 digits.
    +    Vec<D> s[kHalf + 1];
    +    Vec<D> t[kHalf + 1];
    +    s[kHalf] = AddDigitsCarry(d, a, a + kHalf, kHalf, s);
    +    t[kHalf] = AddDigitsCarry(d, b, b + kHalf, kHalf, t);
    +
    +    // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo. z0 and z2 are already in
    +    // `out` at digits 0 and 2*kHalf and nothing else has been added yet, so
    +    // subtract them from there.
    +    Vec<D> st[kSumDigits];
    +    MulRec<kHalf + 1>(d, s, t, st);
    +    SubInto<0, 2 * kHalf, kSumDigits>(d, st, out);
    +    SubInto<2 * kHalf, 2 * kHalf, kSumDigits>(d, st, out);
    +    AddInto<kHalf, kSumDigits, kTotal>(d, out, st);
    +  }
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kDigits-digit unsigned integers, each digit < 2^52, into
    +// 2*kDigits digits. `d` must be a u64 vector descriptor; `out` must have room
    +// for 2*kDigits digits. Input digits at or above 2^52 are ignored (as in

    Actually these inputs are no longer ignored, they must be < 2^52.

    jan-wassenberg jan-wassenberg commented on code on Sep 16, 2026 14:33 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,318 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Digits are 52 bits ("nails"), the largest width for which the IFMA
    +// MulAdd52Lo/Hi ops are exact: for inputs < 2^52 the two together return the
    +// full 104-bit product exactly. Those ops exist on every target (native
    +// HWY_NATIVE_MULADD52 where available, the generic fallback otherwise), so
    +// this works everywhere without a separate fallback.
    +//
    +// Layout is SoA: digit i (little-endian) of each operand is passed in its own
    +// vector, `a[i]` / `b[i]`. The lanes of those vectors hold independent
    +// multiplications, which is how crypto (several RSA/ECC instances) uses it.
    +
    +constexpr size_t kWideMulDigitBits = 52;
    +constexpr uint64_t kWideMulDigitMask = (uint64_t{1} << kWideMulDigitBits) - 1;
    +
    +// The schoolbook kernel costs O(kDigits^2). Karatsuba's 3-way split lowers
    +// that to ~O(kDigits^1.585) but adds additions, subtractions and copies, so
    +// it only pays off above this many digits.
    +constexpr size_t kWideMulKaratsubaMinDigits = 8;
    +
    +#if HWY_TARGET != HWY_SCALAR
    +
    +namespace detail {
    +
    +// out[0..2*kDigits) = a * b, schoolbook. Both operands have kDigits digits,
    +// each < 2^52.
    +template <size_t kDigits, class D>
    +HWY_INLINE void SchoolbookMul(D d, const Vec<D>* HWY_RESTRICT a,
    +                              const Vec<D>* HWY_RESTRICT b,
    +                              Vec<D>* HWY_RESTRICT out) {
    +  // low[k] is the sum of the low 52 bits of a[i]*b[j] over all i+j == k;
    +  // high[k] is the sum of bits 52..103 of the same products. Both fit in 64
    +  // bits because there are at most kDigits terms, each < 2^52.
    +  Vec<D> low[2 * kDigits - 1];
    +  Vec<D> high[2 * kDigits - 1];
    +  for (size_t k = 0; k < 2 * kDigits - 1; ++k) {
    +    low[k] = Zero(d);
    +    high[k] = Zero(d);
    +  }
    +  for (size_t i = 0; i < kDigits; ++i) {
    +    for (size_t j = 0; j < kDigits; ++j) {
    +      low[i + j] = MulAdd52Lo(a[i], b[j], low[i + j]);
    +      high[i + j] = MulAdd52Hi(a[i], b[j], high[i + j]);
    +    }
    +  }
    +
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k + 1 < 2 * kDigits; ++k) {
    +    const Vec<D> sum = Add(low[k], carry);
    +    out[k] = And(sum, mask);
    +    carry = Add(ShiftRight<kWideMulDigitBits>(sum), high[k]);
    +  }
    +  out[2 * kDigits - 1] = And(carry, mask);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out digit.
    +template <class D>
    +HWY_INLINE Vec<D> AddDigitsCarry(D d, const Vec<D>* HWY_RESTRICT a,
    +                                 const Vec<D>* HWY_RESTRICT b, size_t kCount,
    +                                 Vec<D>* HWY_RESTRICT out) {
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum = Add(Add(a[i], b[i]), carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// out[kOffset..kTotal) += src[0..kCount), with carry ripple. kCount is
    +// clamped so that nothing is written at or past kTotal.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, Vec<D>* HWY_RESTRICT out,
    +                        const Vec<D>* HWY_RESTRICT src) {
    +  constexpr size_t kUsed = kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(Add(out[kOffset + i], src[i]), carry);
    +    out[kOffset + i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(out[i], carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +}
    +
    +// dst[0..kTotal) -= src[kOffset..kOffset + kCount), zero-extending src, with

    Behavior of kOffset differs between Add and Sub - out vs src. Should we be consistent in one or the other?

    jan-wassenberg jan-wassenberg commented on code on Sep 16, 2026 14:35 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,318 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Digits are 52 bits ("nails"), the largest width for which the IFMA
    +// MulAdd52Lo/Hi ops are exact: for inputs < 2^52 the two together return the
    +// full 104-bit product exactly. Those ops exist on every target (native
    +// HWY_NATIVE_MULADD52 where available, the generic fallback otherwise), so
    +// this works everywhere without a separate fallback.
    +//
    +// Layout is SoA: digit i (little-endian) of each operand is passed in its own
    +// vector, `a[i]` / `b[i]`. The lanes of those vectors hold independent
    +// multiplications, which is how crypto (several RSA/ECC instances) uses it.
    +
    +constexpr size_t kWideMulDigitBits = 52;
    +constexpr uint64_t kWideMulDigitMask = (uint64_t{1} << kWideMulDigitBits) - 1;
    +
    +// The schoolbook kernel costs O(kDigits^2). Karatsuba's 3-way split lowers
    +// that to ~O(kDigits^1.585) but adds additions, subtractions and copies, so
    +// it only pays off above this many digits.
    +constexpr size_t kWideMulKaratsubaMinDigits = 8;
    +
    +#if HWY_TARGET != HWY_SCALAR
    +
    +namespace detail {
    +
    +// out[0..2*kDigits) = a * b, schoolbook. Both operands have kDigits digits,
    +// each < 2^52.
    +template <size_t kDigits, class D>
    +HWY_INLINE void SchoolbookMul(D d, const Vec<D>* HWY_RESTRICT a,
    +                              const Vec<D>* HWY_RESTRICT b,
    +                              Vec<D>* HWY_RESTRICT out) {
    +  // low[k] is the sum of the low 52 bits of a[i]*b[j] over all i+j == k;
    +  // high[k] is the sum of bits 52..103 of the same products. Both fit in 64
    +  // bits because there are at most kDigits terms, each < 2^52.
    +  Vec<D> low[2 * kDigits - 1];
    +  Vec<D> high[2 * kDigits - 1];
    +  for (size_t k = 0; k < 2 * kDigits - 1; ++k) {
    +    low[k] = Zero(d);
    +    high[k] = Zero(d);
    +  }
    +  for (size_t i = 0; i < kDigits; ++i) {
    +    for (size_t j = 0; j < kDigits; ++j) {
    +      low[i + j] = MulAdd52Lo(a[i], b[j], low[i + j]);
    +      high[i + j] = MulAdd52Hi(a[i], b[j], high[i + j]);
    +    }
    +  }
    +
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k + 1 < 2 * kDigits; ++k) {
    +    const Vec<D> sum = Add(low[k], carry);
    +    out[k] = And(sum, mask);
    +    carry = Add(ShiftRight<kWideMulDigitBits>(sum), high[k]);
    +  }
    +  out[2 * kDigits - 1] = And(carry, mask);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out digit.
    +template <class D>
    +HWY_INLINE Vec<D> AddDigitsCarry(D d, const Vec<D>* HWY_RESTRICT a,
    +                                 const Vec<D>* HWY_RESTRICT b, size_t kCount,
    +                                 Vec<D>* HWY_RESTRICT out) {
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum = Add(Add(a[i], b[i]), carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// out[kOffset..kTotal) += src[0..kCount), with carry ripple. kCount is
    +// clamped so that nothing is written at or past kTotal.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, Vec<D>* HWY_RESTRICT out,
    +                        const Vec<D>* HWY_RESTRICT src) {
    +  constexpr size_t kUsed = kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(Add(out[kOffset + i], src[i]), carry);
    +    out[kOffset + i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(out[i], carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +}
    +
    +// dst[0..kTotal) -= src[kOffset..kOffset + kCount), zero-extending src, with
    +// borrow ripple. The result must be non-negative.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, Vec<D>* HWY_RESTRICT dst,
    +                        const Vec<D>* HWY_RESTRICT src) {
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> one = Set(d, 1);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? src[kOffset + i] : zero;
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Mask<D> underflow = Lt(dst[i], sub);
    +    dst[i] = And(Sub(dst[i], sub), mask);
    +    borrow = IfThenElse(underflow, one, zero);

    Can't we compute borrow as the upper bit shifted right 63?

    jan-wassenberg jan-wassenberg commented on code on Sep 16, 2026 14:35 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,318 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Digits are 52 bits ("nails"), the largest width for which the IFMA
    +// MulAdd52Lo/Hi ops are exact: for inputs < 2^52 the two together return the
    +// full 104-bit product exactly. Those ops exist on every target (native
    +// HWY_NATIVE_MULADD52 where available, the generic fallback otherwise), so
    +// this works everywhere without a separate fallback.
    +//
    +// Layout is SoA: digit i (little-endian) of each operand is passed in its own
    +// vector, `a[i]` / `b[i]`. The lanes of those vectors hold independent
    +// multiplications, which is how crypto (several RSA/ECC instances) uses it.
    +
    +constexpr size_t kWideMulDigitBits = 52;
    +constexpr uint64_t kWideMulDigitMask = (uint64_t{1} << kWideMulDigitBits) - 1;
    +
    +// The schoolbook kernel costs O(kDigits^2). Karatsuba's 3-way split lowers
    +// that to ~O(kDigits^1.585) but adds additions, subtractions and copies, so
    +// it only pays off above this many digits.
    +constexpr size_t kWideMulKaratsubaMinDigits = 8;
    +
    +#if HWY_TARGET != HWY_SCALAR
    +
    +namespace detail {
    +
    +// out[0..2*kDigits) = a * b, schoolbook. Both operands have kDigits digits,
    +// each < 2^52.
    +template <size_t kDigits, class D>
    +HWY_INLINE void SchoolbookMul(D d, const Vec<D>* HWY_RESTRICT a,
    +                              const Vec<D>* HWY_RESTRICT b,
    +                              Vec<D>* HWY_RESTRICT out) {
    +  // low[k] is the sum of the low 52 bits of a[i]*b[j] over all i+j == k;
    +  // high[k] is the sum of bits 52..103 of the same products. Both fit in 64
    +  // bits because there are at most kDigits terms, each < 2^52.
    +  Vec<D> low[2 * kDigits - 1];
    +  Vec<D> high[2 * kDigits - 1];
    +  for (size_t k = 0; k < 2 * kDigits - 1; ++k) {
    +    low[k] = Zero(d);
    +    high[k] = Zero(d);
    +  }
    +  for (size_t i = 0; i < kDigits; ++i) {
    +    for (size_t j = 0; j < kDigits; ++j) {
    +      low[i + j] = MulAdd52Lo(a[i], b[j], low[i + j]);
    +      high[i + j] = MulAdd52Hi(a[i], b[j], high[i + j]);
    +    }
    +  }
    +
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k + 1 < 2 * kDigits; ++k) {
    +    const Vec<D> sum = Add(low[k], carry);
    +    out[k] = And(sum, mask);
    +    carry = Add(ShiftRight<kWideMulDigitBits>(sum), high[k]);
    +  }
    +  out[2 * kDigits - 1] = And(carry, mask);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out digit.
    +template <class D>
    +HWY_INLINE Vec<D> AddDigitsCarry(D d, const Vec<D>* HWY_RESTRICT a,
    +                                 const Vec<D>* HWY_RESTRICT b, size_t kCount,
    +                                 Vec<D>* HWY_RESTRICT out) {
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum = Add(Add(a[i], b[i]), carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// out[kOffset..kTotal) += src[0..kCount), with carry ripple. kCount is
    +// clamped so that nothing is written at or past kTotal.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, Vec<D>* HWY_RESTRICT out,
    +                        const Vec<D>* HWY_RESTRICT src) {
    +  constexpr size_t kUsed = kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(Add(out[kOffset + i], src[i]), carry);
    +    out[kOffset + i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(out[i], carry);
    +    out[i] = And(sum, mask);
    +    carry = ShiftRight<kWideMulDigitBits>(sum);
    +  }
    +}
    +
    +// dst[0..kTotal) -= src[kOffset..kOffset + kCount), zero-extending src, with
    +// borrow ripple. The result must be non-negative.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, Vec<D>* HWY_RESTRICT dst,
    +                        const Vec<D>* HWY_RESTRICT src) {
    +  const Vec<D> mask = Set(d, kWideMulDigitMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> one = Set(d, 1);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? src[kOffset + i] : zero;
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Mask<D> underflow = Lt(dst[i], sub);
    +    dst[i] = And(Sub(dst[i], sub), mask);
    +    borrow = IfThenElse(underflow, one, zero);
    +  }
    +}
    +
    +// out[0..2*kDigits) = a * b. Karatsuba's 3-way split above the threshold;
    +// schoolbook for small or odd sizes (whose split would be unbalanced).
    +template <size_t kDigits, class D>
    +HWY_INLINE void MulRec(D d, const Vec<D>* HWY_RESTRICT a,
    +                       const Vec<D>* HWY_RESTRICT b, Vec<D>* HWY_RESTRICT out) {
    +  if constexpr (kDigits < kWideMulKaratsubaMinDigits || (kDigits & 1) != 0) {
    +    SchoolbookMul<kDigits>(d, a, b, out);
    +  } else {
    +    constexpr size_t kHalf = kDigits / 2;
    +    constexpr size_t kTotal = 2 * kDigits;
    +    constexpr size_t kSumDigits = 2 * (kHalf + 1);
    +
    +    for (size_t k = 0; k < kTotal; ++k) out[k] = Zero(d);
    +
    +    {  // z0 = a_lo * b_lo, at digit 0.
    +      Vec<D> z0[2 * kHalf];
    +      MulRec<kHalf>(d, a, b, z0);
    +      AddInto<0, 2 * kHalf, kTotal>(d, out, z0);
    +    }
    +    {  // z2 = a_hi * b_hi, at digit 2*kHalf.
    +      Vec<D> z2[2 * kHalf];
    +      MulRec<kHalf>(d, a + kHalf, b + kHalf, z2);
    +      AddInto<2 * kHalf, 2 * kHalf, kTotal>(d, out, z2);
    +    }
    +
    +    // s = a_lo + a_hi and t = b_lo + b_hi, each kHalf + 1 digits.
    +    Vec<D> s[kHalf + 1];
    +    Vec<D> t[kHalf + 1];
    +    s[kHalf] = AddDigitsCarry(d, a, a + kHalf, kHalf, s);
    +    t[kHalf] = AddDigitsCarry(d, b, b + kHalf, kHalf, t);
    +
    +    // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo. z0 and z2 are already in
    +    // `out` at digits 0 and 2*kHalf and nothing else has been added yet, so
    +    // subtract them from there.
    +    Vec<D> st[kSumDigits];
    +    MulRec<kHalf + 1>(d, s, t, st);
    +    SubInto<0, 2 * kHalf, kSumDigits>(d, st, out);
    +    SubInto<2 * kHalf, 2 * kHalf, kSumDigits>(d, st, out);
    +    AddInto<kHalf, kSumDigits, kTotal>(d, out, st);
    +  }
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kDigits-digit unsigned integers, each digit < 2^52, into
    +// 2*kDigits digits. `d` must be a u64 vector descriptor; `out` must have room
    +// for 2*kDigits digits. Input digits at or above 2^52 are ignored (as in
    +// MulAdd52*).
    +//
    +// kDigits is limited so that the per-digit accumulators cannot overflow 64
    +// bits: each accumulator holds at most kDigits products < 2^52.
    +template <size_t kDigits>
    +struct WideMul {
    +  static_assert(kDigits >= 1, "need at least one digit");
    +  static_assert(kDigits <= 2048, "accumulators may overflow");
    +  static constexpr size_t kNumResultDigits = 2 * kDigits;
    +
    +  template <class D>

    Probably want HWY_IF_U64_D(D) here.

    jan-wassenberg jan-wassenberg requested changes on Sep 16, 2026 14:36 UTC
    Changes Requested Reviewer

    Thanks for the survey. I have heard of Montgomery reduction being central in this space, and agree the multiprec name makes sense.

    tvost2 tvost2 commented on Sep 16, 2026 15:22 UTC
    Author

    Round 2 in 732c73c0, one commit.

    SchoolbookMul -> Comba. You are right on both counts: the 2kNumLimbs-1
    column arrays are arrays of vectors, and they spill. The kernel is now Comba's
    method, which keeps only the carry plus a low/high accumulator pair live. While
    doing it I re-derived the accumulator bound: with the carry from the previous
    limb folded in, kNumLimbs <= 2048 can overflow by one step, so it is 1024 now,
    with the arithmetic written out next to the assertion.

    Arrays of T, in the API and the test. Mul now takes
    const TFromD<D>
    a, const TFromD<D> b, TFromD<D> out, with limb i of an
    operand at a + i * N, and Loads/Stores inside the kernel. That is what makes
    SVE/RVV work, and it removes the arrays of vectors from the test as you asked.

    Karatsuba removed. Two reasons, both from your comments: its temporaries were
    arrays of vectors, and its split is unbalanced for power-of-two limb counts, since
    the a_lo + a_hi sums need kHalf + 1 limbs (an even size would fall back to
    schoolbook anyway). Removing it also removes AddDigitsCarry/AddInto/SubInto,
    so the inconsistent kOffset between Add and Sub, and the comparison-based borrow
    in Sub, are gone with them rather than left as dead code. I would like to bring
    Karatsuba back as a follow-up with T scratch and a split that handles the extra
    limb, once we agree on the recursion — happy to do that now if you prefer.

    digits -> limbs, with the 12 unused bits of each 64-bit word called nails, as
    GMP does. Docs corrected on the two points you flagged: inputs must be below
    2^52 (no longer "ignored above"), and out must not overlap a or b. Also
    documented that the top result limb of WideMulLimbs may be partial.

    HWY_IF_U64_D(D) added to Mul.

    Build. BUILD and meson.build did not register the new contrib at all, which
    would have failed the bazel and meson jobs as soon as anything compiled it; both
    now have the header library, plus a test target in bazel. CMakeLists.txt already
    listed the two files.

    Extra coverage while in there: the vector test runs an all-ones round as well
    (largest representable inputs, every carry), and static_asserts pin the bit-width
    alias (WideMulBits<128> == WideMul<3>, <256> == WideMul<5>, <2048> has
    80 result limbs).

    Local: clean under -Wall -Wextra -Wconversion -Wsign-conversion, and the test
    passes 10/10 (TestAllWideMul, TestAllWideMulLimbs) on SSE2, SSSE3, SSE4, AVX2
    and EMU128. No arrays of vectors remain anywhere in the contrib, which is what the
    AArch64/RISC-V jobs were failing on.

    tvost2 tvost2 commented on Sep 16, 2026 16:39 UTC
    Author

    Correction to my previous comment: I did not end up removing Karatsuba. It is back
    in 98504f6c (still a single commit), done the way you suggested in the comment
    about power-of-two sizes, and with the two helper fixes you asked for.

  • It recurses only at kHalf, never at kHalf + 1. The carries of

  • a_lo + a_hi and b_lo + b_hi are tracked as separate 0/1 vectors and folded
    back in with branch-free masked adds, so the recursion stays on the same size
    and the base case is Comba. A power-of-two limb count no longer drops to
    schoolbook at every other level.
  • All of its temporaries are arrays of T (z0, z2, s, t, st, plus one limb

  • holding the constant 1) in caller-provided scratch: no arrays of vectors and no
    allocation. The requirement is exposed as WideMul<>::kScratchLimbs, and the
    scratch-free Mul remains Comba.
  • One kOffset convention for AddInto, AddIntoIf and SubInto: it

  • indexes the destination. SubInto now takes the borrow from bit 63 of the
    wrapped difference instead of comparing, which is exact because both operands
    are below 2^52 — your suggestion, and it removes the mask from the inner loop.

    The test now exercises both paths for every size where kScratchLimbs is
    nonzero (8 and 16 here) against the same independent reference, in addition to the
    all-ones round. Local: -Wall -Wextra -Wconversion -Wsign-conversion clean,
    10/10 passing on SSE2, SSSE3, SSE4, AVX2 and EMU128.

    For the record, the review points that were about code that no longer exists
    (whether kOffset should mean the same thing in Add and Sub, and the borrow) are
    now answered by fixing that code rather than by deleting it.

    tvost2 tvost2 commented on Sep 16, 2026 17:26 UTC
    Author

    Montgomery is in (same single commit, 6fe22ac6). Design notes, since you know this space better than I do:

  • MontgomeryN0(d, low limb of N) returns -N[0]^{-1} mod 2^52 per lane, by Newton iteration starting from the 3 correct bits an odd input gives; six steps cover 3/6/12/24/48/96 bits. It is taken on the low limb of the modulus, so callers compute it once per modulus and reuse it.

  • Montgomery<kNumLimbs>::Mul is CIOS (Koc): one row of the product alternating with one reduction step, so the working array is kNumLimbs + 2 limbs and no separate 2kNumLimbs product is needed. Scratch is kScratchLimbs Lanes(d) limbs.

  • It is branch-free, and moduli differ per lane, which is the point (several RSA/ECC instances in parallel): both the extra carry handling and the final conditional subtraction are per-lane selects. The subtraction runs twice so that N above R/2 is covered as well, and the borrow is bit 63 of the wrapped difference, as in SubInto.

  • The reduction row needs one care point worth spelling out: the low limb of t cancels exactly by construction of n0, but its sum can still carry into the next limb, so the carry has to come from the full sum (t[0] included) rather than from the high half of m*N[0] alone. That was the first bug my test caught.

  • The tests use an independent reference: modular multiplication by binary double-and-add over the same 52-bit limbs, with no Montgomery and no R. Cases: random operands, 0, 1 and n-1, a modulus above R/2, and a modulus whose low limb is 1 (so n0 is -1), across all lanes. The second bug it caught was subtraction limbs leaking bits above 2^52 when a borrow is repaid by a higher limb, so everything is masked now.
  • Local: 15/15 (TestAllWideMul, TestAllWideMulLimbs, TestAllMontgomery) on SSE2, SSSE3, SSE4, AVX2 and EMU128, clean under -Wall -Wextra -Wconversion -Wsign-conversion.

    Still open, and I would rather ask than guess: conversion helpers. Multiplying in Montgomery form needs R^2 mod N to get in and out, and computing that needs modular arithmetic we do not have yet. Do you want that in this PR (a generic ModMul/reduction would be the building block), or is supplying R^2 mod N the caller a reasonable contract for now? I have documented it as the latter.

    tvost2 tvost2 commented on Sep 16, 2026 18:46 UTC
    Author

    R^2 is in (same single commit, 2f44c3f5), so callers no longer have to supply it:

  • MontgomeryR2(d, n, out, scratch) returns R^2 mod n as 104kNumLimbs modular doublings from 1, branch-free in the same style as the reduction: the carry out of the top limb and the borrow of the conditional subtraction become one per-lane select. Scratch is MontgomeryR2ScratchLimbs<kNumLimbs>() Lanes(d) limbs.

  • With that, both conversions are Montgomery products:
  • ToMontgomery(x) = Montgomery<>::Mul(x, r2, ...)
    FromMontgomery(y) = Montgomery<>::Mul(y, one, ...) // one = {1, 0, ...}

    which answers the question I had left open: neither direction needs a generic modular multiplication, so the "caller supplies R^2" contract is gone. I have documented both conversions next to the helper.

  • Tests: R^2 against the independent double-and-add reference, and the round trip x -> Mul(x, R2) -> Mul(., one) == x, for every size the helper applies to.
  • Worth recording, because it cost me a detour: the first version of these tests failed, and the failures were in the test rather than in the kernel. It was reducing operands with a single conditional subtraction, which is only valid when n exceeds half the limb range, and my first replacement reference was circular - it assumed a < n while being used to establish a < n. I ended up checking the kernels separately with a standalone sweep over 1, 2, 4 and 8-limb moduli, 300 random cases each, which passed and pointed back at the test. Operand reduction is proper now, and the suite is 20/20 (it was 15/15).

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 11:25 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next

    Can update, we do have reduction now.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:10 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {
    +    if (scratch != nullptr) {
    +      KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +      return;
    +    }
    +  }
    +  CombaMul<kNumLimbs>(d, a, b, out);
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kNumLimbs-limb unsigned integers into 2*kNumLimbs limbs. `d`
    +// must be a u64 vector descriptor; `a`, `b` and `out` point to arrays of at
    +// least kNumLimbs*N, kNumLimbs*N and 2*kNumLimbs*N elements respectively, N
    +// being Lanes(d). All input limbs must be < 2^52, as MulAdd52* requires; only
    +// the low 52 bits of each are used. `out` must not overlap `a` or `b`.
    +//
    +// kNumLimbs is limited so that the per-limb accumulators cannot overflow 64
    +// bits: each holds at most kNumLimbs products < 2^52, plus the carry from the
    +// previous limb, which is itself below kNumLimbs * (2^52 + 1). 1024 therefore
    +// leaves ample headroom below 2^64.
    +template <size_t kNumLimbs>
    +struct WideMul {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = 2 * kNumLimbs;
    +  // Limbs of T per lane required by the Karatsuba overload below; zero when
    +  // this size does not use Karatsuba.
    +  static constexpr size_t kScratchLimbs = detail::MulScratchLimbs<kNumLimbs>();
    +
    +  // Comba: no scratch, always available. This is also what the recursive calls
    +  // fall back to for small or odd sizes.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out) {
    +    detail::CombaMul<kNumLimbs>(d, a, b, out);
    +  }
    +
    +  // Karatsuba: fewer multiplies above kWideMulKaratsubaMinLimbs limbs, but the
    +  // caller must supply scratch of kScratchLimbs * Lanes(d) elements. Nothing is
    +  // allocated here, and `scratch` must not overlap `a`, `b` or `out`.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    static_assert(kScratchLimbs != 0,
    +                  "this size does not use Karatsuba; call Mul without scratch");
    +    detail::KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52), so e.g.
    +// `WideMulBits<256>` multiplies 256-bit values held as 5 limbs each.
    +template <size_t kBits>
    +using WideMulBits = WideMul<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +namespace detail {}  // namespace detail
    +
    +// ------------------------------ Montgomery
    +
    +// Returns -x^{-1} mod 2^52 for every lane, given the low limb of the modulus,
    +// which must be odd. This is the constant that makes the low limb of T + m*N
    +// vanish, so callers compute it once per modulus and reuse it for every
    +// multiplication.
    +template <class D, HWY_IF_U64_D(D)>
    +HWY_INLINE Vec<D> MontgomeryN0(D d, Vec<D> n0) {
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> two = Set(d, 2);
    +  // Newton iteration for the inverse modulo 2^52. Each step doubles the number
    +  // of correct bits, starting from 3 (x*x = 1 mod 8 for odd x), so six steps
    +  // cover 3, 6, 12, 24, 48 and 96 bits. MulAdd52Lo is the low 52 bits of a
    +  // product, which is exact here because every value is below 2^52.
    +  Vec<D> x = n0;
    +  for (int i = 0; i < 6; ++i) {
    +    const Vec<D> t = MulAdd52Lo(n0, x, zero);  // n0 * x mod 2^52
    +    // 2 - t mod 2^52: negate modulo 2^64, add, then mask.
    +    const Vec<D> complement = And(Add(Sub(zero, t), two), mask);
    +    x = MulAdd52Lo(x, complement, zero);
    +  }
    +  return And(Sub(zero, x), mask);  // -x mod 2^52
    +}
    +
    +namespace detail {
    +
    +// out = a * b * R^{-1} mod n by CIOS (Koc): alternate one row of the product
    +// with one step of the reduction, so the working array is only kNumLimbs + 2
    +// limbs and no full 2*kNumLimbs product is needed. Scratch is kTotal limbs for
    +// the accumulator plus kNumLimbs for the tentative difference.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CiosMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                        const TFromD<D>* HWY_RESTRICT b,
    +                        const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                        TFromD<D>* HWY_RESTRICT out,
    +                        TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kTotal = kNumLimbs + 2;
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const t = scratch;
    +  TFromD<D>* const diff = t + kTotal * N;
    +  for (size_t j = 0; j < kTotal; ++j) {
    +    StoreU(zero, d, t + j * N);
    +  }
    +
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const Vec<D> bv = LoadU(d, b + i * N);
    +    // t += a * b[i], with the low and high halves of each product separate.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> av = LoadU(d, a + j * N);
    +      const Vec<D> lo = MulAdd52Lo(av, bv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + j * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(av, bv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + kNumLimbs * N);
    +      StoreU(ShiftRight<kWideMulLimbBits>(sum), d, t + (kNumLimbs + 1) * N);
    +    }
    +
    +    // m = t[0] * n0 mod 2^52, then t += m * n and shift down by one limb. The
    +    // low limb of t cancels exactly by construction of n0, so it is dropped,
    +    // but its sum can still carry into the next limb; that is why `lo` below
    +    // adds t[0] rather than starting from zero.
    +    const Vec<D> m = MulAdd52Lo(LoadU(d, t), n0, zero);
    +    const Vec<D> n0v = LoadU(d, n);
    +    {
    +      const Vec<D> lo = MulAdd52Lo(m, n0v, LoadU(d, t));
    +      carry = Add(ShiftRight<kWideMulLimbBits>(lo), MulAdd52Hi(m, n0v, zero));
    +    }
    +    for (size_t j = 1; j < kNumLimbs; ++j) {
    +      const Vec<D> nv = LoadU(d, n + j * N);
    +      const Vec<D> lo = MulAdd52Lo(m, nv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + (j - 1) * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(m, nv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + (kNumLimbs - 1) * N);
    +      StoreU(Add(LoadU(d, t + (kNumLimbs + 1) * N),
    +                 ShiftRight<kWideMulLimbBits>(sum)),
    +             d, t + kNumLimbs * N);
    +    }
    +  }
    +
    +  // r = t[0..kNumLimbs) with an extra top limb is below 2n, so one conditional
    +  // subtraction suffices when n < R/2; a second pass makes it correct for any
    +  // odd n below R, where the value is then below 3n. Both take the borrow from
    +  // bit 63 of the wrapped difference, as SubInto does.
    +  for (int pass = 0; pass < 2; ++pass) {
    +    Vec<D> borrow = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> sub = Add(LoadU(d, n + j * N), borrow);
    +      const Vec<D> d_j = Sub(LoadU(d, t + j * N), sub);
    +      borrow = ShiftRight<63>(d_j);
    +      StoreU(And(d_j, mask), d, diff + j * N);
    +    }
    +    const Vec<D> top = Sub(LoadU(d, t + kNumLimbs * N), borrow);
    +    // The top limb is zero or one, but keep the invariant of limbs < 2^52.
    +    const Vec<D> top_masked = And(top, mask);
    +    const Mask<D> keep_diff = Eq(ShiftRight<63>(top), zero);
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      StoreU(IfThenElse(keep_diff, LoadU(d, diff + j * N), LoadU(d, t + j * N)),

    IfThenElse+LoadU can be fused into MaskedLoadOr.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:11 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {
    +    if (scratch != nullptr) {
    +      KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +      return;
    +    }
    +  }
    +  CombaMul<kNumLimbs>(d, a, b, out);
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kNumLimbs-limb unsigned integers into 2*kNumLimbs limbs. `d`
    +// must be a u64 vector descriptor; `a`, `b` and `out` point to arrays of at
    +// least kNumLimbs*N, kNumLimbs*N and 2*kNumLimbs*N elements respectively, N
    +// being Lanes(d). All input limbs must be < 2^52, as MulAdd52* requires; only
    +// the low 52 bits of each are used. `out` must not overlap `a` or `b`.
    +//
    +// kNumLimbs is limited so that the per-limb accumulators cannot overflow 64
    +// bits: each holds at most kNumLimbs products < 2^52, plus the carry from the
    +// previous limb, which is itself below kNumLimbs * (2^52 + 1). 1024 therefore
    +// leaves ample headroom below 2^64.
    +template <size_t kNumLimbs>
    +struct WideMul {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = 2 * kNumLimbs;
    +  // Limbs of T per lane required by the Karatsuba overload below; zero when
    +  // this size does not use Karatsuba.
    +  static constexpr size_t kScratchLimbs = detail::MulScratchLimbs<kNumLimbs>();
    +
    +  // Comba: no scratch, always available. This is also what the recursive calls
    +  // fall back to for small or odd sizes.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out) {
    +    detail::CombaMul<kNumLimbs>(d, a, b, out);
    +  }
    +
    +  // Karatsuba: fewer multiplies above kWideMulKaratsubaMinLimbs limbs, but the
    +  // caller must supply scratch of kScratchLimbs * Lanes(d) elements. Nothing is
    +  // allocated here, and `scratch` must not overlap `a`, `b` or `out`.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    static_assert(kScratchLimbs != 0,
    +                  "this size does not use Karatsuba; call Mul without scratch");
    +    detail::KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52), so e.g.
    +// `WideMulBits<256>` multiplies 256-bit values held as 5 limbs each.
    +template <size_t kBits>
    +using WideMulBits = WideMul<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +namespace detail {}  // namespace detail
    +
    +// ------------------------------ Montgomery
    +
    +// Returns -x^{-1} mod 2^52 for every lane, given the low limb of the modulus,
    +// which must be odd. This is the constant that makes the low limb of T + m*N
    +// vanish, so callers compute it once per modulus and reuse it for every
    +// multiplication.
    +template <class D, HWY_IF_U64_D(D)>
    +HWY_INLINE Vec<D> MontgomeryN0(D d, Vec<D> n0) {
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> two = Set(d, 2);
    +  // Newton iteration for the inverse modulo 2^52. Each step doubles the number
    +  // of correct bits, starting from 3 (x*x = 1 mod 8 for odd x), so six steps
    +  // cover 3, 6, 12, 24, 48 and 96 bits. MulAdd52Lo is the low 52 bits of a
    +  // product, which is exact here because every value is below 2^52.
    +  Vec<D> x = n0;
    +  for (int i = 0; i < 6; ++i) {
    +    const Vec<D> t = MulAdd52Lo(n0, x, zero);  // n0 * x mod 2^52
    +    // 2 - t mod 2^52: negate modulo 2^64, add, then mask.
    +    const Vec<D> complement = And(Add(Sub(zero, t), two), mask);
    +    x = MulAdd52Lo(x, complement, zero);
    +  }
    +  return And(Sub(zero, x), mask);  // -x mod 2^52
    +}
    +
    +namespace detail {
    +
    +// out = a * b * R^{-1} mod n by CIOS (Koc): alternate one row of the product
    +// with one step of the reduction, so the working array is only kNumLimbs + 2
    +// limbs and no full 2*kNumLimbs product is needed. Scratch is kTotal limbs for
    +// the accumulator plus kNumLimbs for the tentative difference.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CiosMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                        const TFromD<D>* HWY_RESTRICT b,
    +                        const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                        TFromD<D>* HWY_RESTRICT out,
    +                        TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kTotal = kNumLimbs + 2;
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const t = scratch;
    +  TFromD<D>* const diff = t + kTotal * N;
    +  for (size_t j = 0; j < kTotal; ++j) {
    +    StoreU(zero, d, t + j * N);
    +  }
    +
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const Vec<D> bv = LoadU(d, b + i * N);
    +    // t += a * b[i], with the low and high halves of each product separate.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> av = LoadU(d, a + j * N);
    +      const Vec<D> lo = MulAdd52Lo(av, bv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + j * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(av, bv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + kNumLimbs * N);
    +      StoreU(ShiftRight<kWideMulLimbBits>(sum), d, t + (kNumLimbs + 1) * N);
    +    }
    +
    +    // m = t[0] * n0 mod 2^52, then t += m * n and shift down by one limb. The
    +    // low limb of t cancels exactly by construction of n0, so it is dropped,
    +    // but its sum can still carry into the next limb; that is why `lo` below
    +    // adds t[0] rather than starting from zero.
    +    const Vec<D> m = MulAdd52Lo(LoadU(d, t), n0, zero);
    +    const Vec<D> n0v = LoadU(d, n);
    +    {
    +      const Vec<D> lo = MulAdd52Lo(m, n0v, LoadU(d, t));
    +      carry = Add(ShiftRight<kWideMulLimbBits>(lo), MulAdd52Hi(m, n0v, zero));
    +    }
    +    for (size_t j = 1; j < kNumLimbs; ++j) {
    +      const Vec<D> nv = LoadU(d, n + j * N);
    +      const Vec<D> lo = MulAdd52Lo(m, nv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + (j - 1) * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(m, nv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + (kNumLimbs - 1) * N);
    +      StoreU(Add(LoadU(d, t + (kNumLimbs + 1) * N),
    +                 ShiftRight<kWideMulLimbBits>(sum)),
    +             d, t + kNumLimbs * N);
    +    }
    +  }
    +
    +  // r = t[0..kNumLimbs) with an extra top limb is below 2n, so one conditional
    +  // subtraction suffices when n < R/2; a second pass makes it correct for any
    +  // odd n below R, where the value is then below 3n. Both take the borrow from
    +  // bit 63 of the wrapped difference, as SubInto does.
    +  for (int pass = 0; pass < 2; ++pass) {
    +    Vec<D> borrow = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> sub = Add(LoadU(d, n + j * N), borrow);
    +      const Vec<D> d_j = Sub(LoadU(d, t + j * N), sub);
    +      borrow = ShiftRight<63>(d_j);
    +      StoreU(And(d_j, mask), d, diff + j * N);
    +    }
    +    const Vec<D> top = Sub(LoadU(d, t + kNumLimbs * N), borrow);
    +    // The top limb is zero or one, but keep the invariant of limbs < 2^52.
    +    const Vec<D> top_masked = And(top, mask);
    +    const Mask<D> keep_diff = Eq(ShiftRight<63>(top), zero);
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      StoreU(IfThenElse(keep_diff, LoadU(d, diff + j * N), LoadU(d, t + j * N)),
    +             d, t + j * N);
    +    }
    +    StoreU(IfThenElse(keep_diff, top_masked, LoadU(d, t + kNumLimbs * N)), d,
    +           t + kNumLimbs * N);
    +  }
    +
    +  for (size_t j = 0; j < kNumLimbs; ++j) {
    +    StoreU(And(LoadU(d, t + j * N), mask), d, out + j * N);
    +  }
    +}
    +
    +}  // namespace detail
    +
    +// Montgomery modular multiplication, mirroring WideMul: the same limb layout
    +// (limb i of an operand at [i * Lanes(d)]), and a and b must be below n. The
    +// result is a * b * R^{-1} mod n with R = 2^(52 * kNumLimbs), which is below n
    +// when n < R. `n` must be odd, and n0 must come from MontgomeryN0 applied to
    +// its low limb: compute that once per modulus and reuse it.
    +//
    +// To multiply in Montgomery form, represent x as x * R mod n (which the caller
    +// computes once per value, e.g. from R^2 mod n) and multiply the
    +// representations.
    +template <size_t kNumLimbs>
    +struct Montgomery {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = kNumLimbs;
    +  // The accumulator (kNumLimbs + 2 limbs) and the tentative difference.
    +  static constexpr size_t kScratchLimbs = 2 * kNumLimbs + 2;
    +
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    detail::CiosMul<kNumLimbs>(d, a, b, n, n0, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52).
    +template <size_t kBits>
    +using MontgomeryBits =
    +    Montgomery<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;

    DivCeil(kBits, kWideMulLimbBits) is more readable.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:13 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {
    +    if (scratch != nullptr) {
    +      KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +      return;
    +    }
    +  }
    +  CombaMul<kNumLimbs>(d, a, b, out);
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kNumLimbs-limb unsigned integers into 2*kNumLimbs limbs. `d`
    +// must be a u64 vector descriptor; `a`, `b` and `out` point to arrays of at
    +// least kNumLimbs*N, kNumLimbs*N and 2*kNumLimbs*N elements respectively, N
    +// being Lanes(d). All input limbs must be < 2^52, as MulAdd52* requires; only
    +// the low 52 bits of each are used. `out` must not overlap `a` or `b`.
    +//
    +// kNumLimbs is limited so that the per-limb accumulators cannot overflow 64
    +// bits: each holds at most kNumLimbs products < 2^52, plus the carry from the
    +// previous limb, which is itself below kNumLimbs * (2^52 + 1). 1024 therefore
    +// leaves ample headroom below 2^64.
    +template <size_t kNumLimbs>
    +struct WideMul {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = 2 * kNumLimbs;
    +  // Limbs of T per lane required by the Karatsuba overload below; zero when
    +  // this size does not use Karatsuba.
    +  static constexpr size_t kScratchLimbs = detail::MulScratchLimbs<kNumLimbs>();
    +
    +  // Comba: no scratch, always available. This is also what the recursive calls
    +  // fall back to for small or odd sizes.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out) {
    +    detail::CombaMul<kNumLimbs>(d, a, b, out);
    +  }
    +
    +  // Karatsuba: fewer multiplies above kWideMulKaratsubaMinLimbs limbs, but the
    +  // caller must supply scratch of kScratchLimbs * Lanes(d) elements. Nothing is
    +  // allocated here, and `scratch` must not overlap `a`, `b` or `out`.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    static_assert(kScratchLimbs != 0,
    +                  "this size does not use Karatsuba; call Mul without scratch");
    +    detail::KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52), so e.g.
    +// `WideMulBits<256>` multiplies 256-bit values held as 5 limbs each.
    +template <size_t kBits>
    +using WideMulBits = WideMul<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +namespace detail {}  // namespace detail
    +
    +// ------------------------------ Montgomery
    +
    +// Returns -x^{-1} mod 2^52 for every lane, given the low limb of the modulus,
    +// which must be odd. This is the constant that makes the low limb of T + m*N
    +// vanish, so callers compute it once per modulus and reuse it for every
    +// multiplication.
    +template <class D, HWY_IF_U64_D(D)>
    +HWY_INLINE Vec<D> MontgomeryN0(D d, Vec<D> n0) {
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> two = Set(d, 2);
    +  // Newton iteration for the inverse modulo 2^52. Each step doubles the number
    +  // of correct bits, starting from 3 (x*x = 1 mod 8 for odd x), so six steps
    +  // cover 3, 6, 12, 24, 48 and 96 bits. MulAdd52Lo is the low 52 bits of a
    +  // product, which is exact here because every value is below 2^52.
    +  Vec<D> x = n0;
    +  for (int i = 0; i < 6; ++i) {
    +    const Vec<D> t = MulAdd52Lo(n0, x, zero);  // n0 * x mod 2^52
    +    // 2 - t mod 2^52: negate modulo 2^64, add, then mask.
    +    const Vec<D> complement = And(Add(Sub(zero, t), two), mask);
    +    x = MulAdd52Lo(x, complement, zero);
    +  }
    +  return And(Sub(zero, x), mask);  // -x mod 2^52
    +}
    +
    +namespace detail {
    +
    +// out = a * b * R^{-1} mod n by CIOS (Koc): alternate one row of the product
    +// with one step of the reduction, so the working array is only kNumLimbs + 2
    +// limbs and no full 2*kNumLimbs product is needed. Scratch is kTotal limbs for
    +// the accumulator plus kNumLimbs for the tentative difference.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CiosMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                        const TFromD<D>* HWY_RESTRICT b,
    +                        const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                        TFromD<D>* HWY_RESTRICT out,
    +                        TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kTotal = kNumLimbs + 2;
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const t = scratch;
    +  TFromD<D>* const diff = t + kTotal * N;
    +  for (size_t j = 0; j < kTotal; ++j) {
    +    StoreU(zero, d, t + j * N);
    +  }
    +
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const Vec<D> bv = LoadU(d, b + i * N);
    +    // t += a * b[i], with the low and high halves of each product separate.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> av = LoadU(d, a + j * N);
    +      const Vec<D> lo = MulAdd52Lo(av, bv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + j * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(av, bv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + kNumLimbs * N);
    +      StoreU(ShiftRight<kWideMulLimbBits>(sum), d, t + (kNumLimbs + 1) * N);
    +    }
    +
    +    // m = t[0] * n0 mod 2^52, then t += m * n and shift down by one limb. The
    +    // low limb of t cancels exactly by construction of n0, so it is dropped,
    +    // but its sum can still carry into the next limb; that is why `lo` below
    +    // adds t[0] rather than starting from zero.
    +    const Vec<D> m = MulAdd52Lo(LoadU(d, t), n0, zero);
    +    const Vec<D> n0v = LoadU(d, n);
    +    {
    +      const Vec<D> lo = MulAdd52Lo(m, n0v, LoadU(d, t));
    +      carry = Add(ShiftRight<kWideMulLimbBits>(lo), MulAdd52Hi(m, n0v, zero));
    +    }
    +    for (size_t j = 1; j < kNumLimbs; ++j) {
    +      const Vec<D> nv = LoadU(d, n + j * N);
    +      const Vec<D> lo = MulAdd52Lo(m, nv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + (j - 1) * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(m, nv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + (kNumLimbs - 1) * N);
    +      StoreU(Add(LoadU(d, t + (kNumLimbs + 1) * N),
    +                 ShiftRight<kWideMulLimbBits>(sum)),
    +             d, t + kNumLimbs * N);
    +    }
    +  }
    +
    +  // r = t[0..kNumLimbs) with an extra top limb is below 2n, so one conditional
    +  // subtraction suffices when n < R/2; a second pass makes it correct for any
    +  // odd n below R, where the value is then below 3n. Both take the borrow from
    +  // bit 63 of the wrapped difference, as SubInto does.
    +  for (int pass = 0; pass < 2; ++pass) {
    +    Vec<D> borrow = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> sub = Add(LoadU(d, n + j * N), borrow);
    +      const Vec<D> d_j = Sub(LoadU(d, t + j * N), sub);
    +      borrow = ShiftRight<63>(d_j);
    +      StoreU(And(d_j, mask), d, diff + j * N);
    +    }
    +    const Vec<D> top = Sub(LoadU(d, t + kNumLimbs * N), borrow);
    +    // The top limb is zero or one, but keep the invariant of limbs < 2^52.
    +    const Vec<D> top_masked = And(top, mask);
    +    const Mask<D> keep_diff = Eq(ShiftRight<63>(top), zero);
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      StoreU(IfThenElse(keep_diff, LoadU(d, diff + j * N), LoadU(d, t + j * N)),
    +             d, t + j * N);
    +    }
    +    StoreU(IfThenElse(keep_diff, top_masked, LoadU(d, t + kNumLimbs * N)), d,
    +           t + kNumLimbs * N);
    +  }
    +
    +  for (size_t j = 0; j < kNumLimbs; ++j) {
    +    StoreU(And(LoadU(d, t + j * N), mask), d, out + j * N);
    +  }
    +}
    +
    +}  // namespace detail
    +
    +// Montgomery modular multiplication, mirroring WideMul: the same limb layout
    +// (limb i of an operand at [i * Lanes(d)]), and a and b must be below n. The
    +// result is a * b * R^{-1} mod n with R = 2^(52 * kNumLimbs), which is below n
    +// when n < R. `n` must be odd, and n0 must come from MontgomeryN0 applied to
    +// its low limb: compute that once per modulus and reuse it.
    +//
    +// To multiply in Montgomery form, represent x as x * R mod n (which the caller
    +// computes once per value, e.g. from R^2 mod n) and multiply the
    +// representations.
    +template <size_t kNumLimbs>
    +struct Montgomery {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = kNumLimbs;
    +  // The accumulator (kNumLimbs + 2 limbs) and the tentative difference.
    +  static constexpr size_t kScratchLimbs = 2 * kNumLimbs + 2;
    +
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    detail::CiosMul<kNumLimbs>(d, a, b, n, n0, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52).
    +template <size_t kBits>
    +using MontgomeryBits =
    +    Montgomery<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +// out = R^2 mod n, with R = 2^(52 * kNumLimbs). This is the constant needed to
    +// enter Montgomery form, so the caller can convert without any modular
    +// arithmetic of its own:
    +//
    +//   ToMontgomery(x)   = Montgomery<>::Mul(x, r2, ...)
    +//   FromMontgomery(y) = Montgomery<>::Mul(y, one, ...)   // one = {1, 0, ...}
    +//
    +// n must be odd and below R, as for Montgomery<>::Mul. Both conversions are
    +// then Montgomery products, and no separate modular multiplication is required.
    +//
    +// Computed as 104*kNumLimbs modular doublings starting from 1, which is
    +// (2^(52*kNumLimbs))^2 mod n. Like the reduction, it is branch-free: the carry
    +// out of the top limb and the borrow of the conditional subtraction are
    +// combined into one per-lane select. Scratch is 2*kNumLimbs limbs per lane.
    +template <size_t kNumLimbs, class D, HWY_IF_U64_D(D)>
    +HWY_INLINE void MontgomeryR2(D d, const TFromD<D>* HWY_RESTRICT n,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const r = scratch;
    +  TFromD<D>* const diff = r + kNumLimbs * N;
    +  for (size_t j = 0; j < kNumLimbs; ++j) {
    +    StoreU(j == 0 ? Set(d, 1) : zero, d, r + j * N);

    More clear to pull Store(Set(d,1), d, p) out of the loop, then start from j=1 and always write 0.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:14 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {
    +    if (scratch != nullptr) {
    +      KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +      return;
    +    }
    +  }
    +  CombaMul<kNumLimbs>(d, a, b, out);
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kNumLimbs-limb unsigned integers into 2*kNumLimbs limbs. `d`
    +// must be a u64 vector descriptor; `a`, `b` and `out` point to arrays of at
    +// least kNumLimbs*N, kNumLimbs*N and 2*kNumLimbs*N elements respectively, N
    +// being Lanes(d). All input limbs must be < 2^52, as MulAdd52* requires; only
    +// the low 52 bits of each are used. `out` must not overlap `a` or `b`.
    +//
    +// kNumLimbs is limited so that the per-limb accumulators cannot overflow 64
    +// bits: each holds at most kNumLimbs products < 2^52, plus the carry from the
    +// previous limb, which is itself below kNumLimbs * (2^52 + 1). 1024 therefore
    +// leaves ample headroom below 2^64.
    +template <size_t kNumLimbs>
    +struct WideMul {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = 2 * kNumLimbs;
    +  // Limbs of T per lane required by the Karatsuba overload below; zero when
    +  // this size does not use Karatsuba.
    +  static constexpr size_t kScratchLimbs = detail::MulScratchLimbs<kNumLimbs>();
    +
    +  // Comba: no scratch, always available. This is also what the recursive calls
    +  // fall back to for small or odd sizes.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out) {
    +    detail::CombaMul<kNumLimbs>(d, a, b, out);
    +  }
    +
    +  // Karatsuba: fewer multiplies above kWideMulKaratsubaMinLimbs limbs, but the
    +  // caller must supply scratch of kScratchLimbs * Lanes(d) elements. Nothing is
    +  // allocated here, and `scratch` must not overlap `a`, `b` or `out`.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    static_assert(kScratchLimbs != 0,
    +                  "this size does not use Karatsuba; call Mul without scratch");
    +    detail::KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52), so e.g.
    +// `WideMulBits<256>` multiplies 256-bit values held as 5 limbs each.
    +template <size_t kBits>
    +using WideMulBits = WideMul<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +namespace detail {}  // namespace detail
    +
    +// ------------------------------ Montgomery
    +
    +// Returns -x^{-1} mod 2^52 for every lane, given the low limb of the modulus,
    +// which must be odd. This is the constant that makes the low limb of T + m*N
    +// vanish, so callers compute it once per modulus and reuse it for every
    +// multiplication.
    +template <class D, HWY_IF_U64_D(D)>
    +HWY_INLINE Vec<D> MontgomeryN0(D d, Vec<D> n0) {
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> two = Set(d, 2);
    +  // Newton iteration for the inverse modulo 2^52. Each step doubles the number
    +  // of correct bits, starting from 3 (x*x = 1 mod 8 for odd x), so six steps
    +  // cover 3, 6, 12, 24, 48 and 96 bits. MulAdd52Lo is the low 52 bits of a
    +  // product, which is exact here because every value is below 2^52.
    +  Vec<D> x = n0;
    +  for (int i = 0; i < 6; ++i) {
    +    const Vec<D> t = MulAdd52Lo(n0, x, zero);  // n0 * x mod 2^52
    +    // 2 - t mod 2^52: negate modulo 2^64, add, then mask.
    +    const Vec<D> complement = And(Add(Sub(zero, t), two), mask);
    +    x = MulAdd52Lo(x, complement, zero);
    +  }
    +  return And(Sub(zero, x), mask);  // -x mod 2^52
    +}
    +
    +namespace detail {
    +
    +// out = a * b * R^{-1} mod n by CIOS (Koc): alternate one row of the product
    +// with one step of the reduction, so the working array is only kNumLimbs + 2
    +// limbs and no full 2*kNumLimbs product is needed. Scratch is kTotal limbs for
    +// the accumulator plus kNumLimbs for the tentative difference.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CiosMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                        const TFromD<D>* HWY_RESTRICT b,
    +                        const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                        TFromD<D>* HWY_RESTRICT out,
    +                        TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kTotal = kNumLimbs + 2;
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const t = scratch;
    +  TFromD<D>* const diff = t + kTotal * N;
    +  for (size_t j = 0; j < kTotal; ++j) {
    +    StoreU(zero, d, t + j * N);
    +  }
    +
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const Vec<D> bv = LoadU(d, b + i * N);
    +    // t += a * b[i], with the low and high halves of each product separate.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> av = LoadU(d, a + j * N);
    +      const Vec<D> lo = MulAdd52Lo(av, bv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + j * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(av, bv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + kNumLimbs * N);
    +      StoreU(ShiftRight<kWideMulLimbBits>(sum), d, t + (kNumLimbs + 1) * N);
    +    }
    +
    +    // m = t[0] * n0 mod 2^52, then t += m * n and shift down by one limb. The
    +    // low limb of t cancels exactly by construction of n0, so it is dropped,
    +    // but its sum can still carry into the next limb; that is why `lo` below
    +    // adds t[0] rather than starting from zero.
    +    const Vec<D> m = MulAdd52Lo(LoadU(d, t), n0, zero);
    +    const Vec<D> n0v = LoadU(d, n);
    +    {
    +      const Vec<D> lo = MulAdd52Lo(m, n0v, LoadU(d, t));
    +      carry = Add(ShiftRight<kWideMulLimbBits>(lo), MulAdd52Hi(m, n0v, zero));
    +    }
    +    for (size_t j = 1; j < kNumLimbs; ++j) {
    +      const Vec<D> nv = LoadU(d, n + j * N);
    +      const Vec<D> lo = MulAdd52Lo(m, nv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + (j - 1) * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(m, nv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + (kNumLimbs - 1) * N);
    +      StoreU(Add(LoadU(d, t + (kNumLimbs + 1) * N),
    +                 ShiftRight<kWideMulLimbBits>(sum)),
    +             d, t + kNumLimbs * N);
    +    }
    +  }
    +
    +  // r = t[0..kNumLimbs) with an extra top limb is below 2n, so one conditional
    +  // subtraction suffices when n < R/2; a second pass makes it correct for any
    +  // odd n below R, where the value is then below 3n. Both take the borrow from
    +  // bit 63 of the wrapped difference, as SubInto does.
    +  for (int pass = 0; pass < 2; ++pass) {
    +    Vec<D> borrow = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> sub = Add(LoadU(d, n + j * N), borrow);
    +      const Vec<D> d_j = Sub(LoadU(d, t + j * N), sub);
    +      borrow = ShiftRight<63>(d_j);
    +      StoreU(And(d_j, mask), d, diff + j * N);
    +    }
    +    const Vec<D> top = Sub(LoadU(d, t + kNumLimbs * N), borrow);
    +    // The top limb is zero or one, but keep the invariant of limbs < 2^52.
    +    const Vec<D> top_masked = And(top, mask);
    +    const Mask<D> keep_diff = Eq(ShiftRight<63>(top), zero);
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      StoreU(IfThenElse(keep_diff, LoadU(d, diff + j * N), LoadU(d, t + j * N)),
    +             d, t + j * N);
    +    }
    +    StoreU(IfThenElse(keep_diff, top_masked, LoadU(d, t + kNumLimbs * N)), d,
    +           t + kNumLimbs * N);
    +  }
    +
    +  for (size_t j = 0; j < kNumLimbs; ++j) {
    +    StoreU(And(LoadU(d, t + j * N), mask), d, out + j * N);
    +  }
    +}
    +
    +}  // namespace detail
    +
    +// Montgomery modular multiplication, mirroring WideMul: the same limb layout
    +// (limb i of an operand at [i * Lanes(d)]), and a and b must be below n. The
    +// result is a * b * R^{-1} mod n with R = 2^(52 * kNumLimbs), which is below n
    +// when n < R. `n` must be odd, and n0 must come from MontgomeryN0 applied to
    +// its low limb: compute that once per modulus and reuse it.
    +//
    +// To multiply in Montgomery form, represent x as x * R mod n (which the caller
    +// computes once per value, e.g. from R^2 mod n) and multiply the
    +// representations.
    +template <size_t kNumLimbs>
    +struct Montgomery {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = kNumLimbs;
    +  // The accumulator (kNumLimbs + 2 limbs) and the tentative difference.
    +  static constexpr size_t kScratchLimbs = 2 * kNumLimbs + 2;
    +
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    detail::CiosMul<kNumLimbs>(d, a, b, n, n0, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52).
    +template <size_t kBits>
    +using MontgomeryBits =
    +    Montgomery<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +// out = R^2 mod n, with R = 2^(52 * kNumLimbs). This is the constant needed to
    +// enter Montgomery form, so the caller can convert without any modular
    +// arithmetic of its own:
    +//
    +//   ToMontgomery(x)   = Montgomery<>::Mul(x, r2, ...)
    +//   FromMontgomery(y) = Montgomery<>::Mul(y, one, ...)   // one = {1, 0, ...}
    +//
    +// n must be odd and below R, as for Montgomery<>::Mul. Both conversions are
    +// then Montgomery products, and no separate modular multiplication is required.
    +//
    +// Computed as 104*kNumLimbs modular doublings starting from 1, which is
    +// (2^(52*kNumLimbs))^2 mod n. Like the reduction, it is branch-free: the carry
    +// out of the top limb and the borrow of the conditional subtraction are
    +// combined into one per-lane select. Scratch is 2*kNumLimbs limbs per lane.
    +template <size_t kNumLimbs, class D, HWY_IF_U64_D(D)>
    +HWY_INLINE void MontgomeryR2(D d, const TFromD<D>* HWY_RESTRICT n,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const r = scratch;
    +  TFromD<D>* const diff = r + kNumLimbs * N;
    +  for (size_t j = 0; j < kNumLimbs; ++j) {
    +    StoreU(j == 0 ? Set(d, 1) : zero, d, r + j * N);
    +  }
    +
    +  for (size_t i = 0; i < 104 * kNumLimbs; ++i) {
    +    // (carry, r) = 2 * r.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> rv = LoadU(d, r + j * N);
    +      const Vec<D> sum = Add(Add(rv, rv), carry);
    +      StoreU(And(sum, mask), d, r + j * N);
    +      carry = ShiftRight<kWideMulLimbBits>(sum);
    +    }
    +    // r -= n when (carry, r) >= n; keep the difference in `diff` meanwhile.
    +    Vec<D> borrow = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> sub = Add(LoadU(d, n + j * N), borrow);
    +      const Vec<D> d_j = Sub(LoadU(d, r + j * N), sub);
    +      borrow = ShiftRight<63>(d_j);
    +      StoreU(And(d_j, mask), d, diff + j * N);
    +    }
    +    const Vec<D> top = Sub(carry, borrow);
    +    const Mask<D> keep_diff = Eq(ShiftRight<63>(top), zero);
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      StoreU(IfThenElse(keep_diff, LoadU(d, diff + j * N), LoadU(d, r + j * N)),

    Also BlendedStore or MaskedLoadOr here (we only want to update if !keep_diff - might want to negate it via Ne).

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:16 UTC
    Code Review
    hwy/contrib/multiprec/multiprec_test.cc:1
    @@ -0,0 +1,496 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include <type_traits>
    +
    +#include "hwy/aligned_allocator.h"
    +#include "hwy/base.h"
    +
    +// clang-format off
    +#undef HWY_TARGET_INCLUDE
    +#define HWY_TARGET_INCLUDE "hwy/contrib/multiprec/multiprec_test.cc"  // NOLINT
    +// clang-format on
    +#include "hwy/foreach_target.h"  // IWYU pragma: keep
    +#include "hwy/highway.h"
    +// After highway.h:
    +#include "hwy/contrib/multiprec/multiprec-inl.h"
    +#include "hwy/tests/test_util-inl.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +namespace {
    +
    +// The bit-width alias rounds up to whole 52-bit limbs, and the widest supported
    +// size stays within the accumulator limit.
    +static_assert(std::is_same<WideMulBits<128>, WideMul<3>>::value,

    Prefer IsSame<T1, T2>().

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:18 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {
    +    if (scratch != nullptr) {
    +      KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +      return;
    +    }
    +  }
    +  CombaMul<kNumLimbs>(d, a, b, out);
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kNumLimbs-limb unsigned integers into 2*kNumLimbs limbs. `d`
    +// must be a u64 vector descriptor; `a`, `b` and `out` point to arrays of at
    +// least kNumLimbs*N, kNumLimbs*N and 2*kNumLimbs*N elements respectively, N
    +// being Lanes(d). All input limbs must be < 2^52, as MulAdd52* requires; only
    +// the low 52 bits of each are used. `out` must not overlap `a` or `b`.
    +//
    +// kNumLimbs is limited so that the per-limb accumulators cannot overflow 64
    +// bits: each holds at most kNumLimbs products < 2^52, plus the carry from the
    +// previous limb, which is itself below kNumLimbs * (2^52 + 1). 1024 therefore
    +// leaves ample headroom below 2^64.
    +template <size_t kNumLimbs>
    +struct WideMul {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = 2 * kNumLimbs;
    +  // Limbs of T per lane required by the Karatsuba overload below; zero when
    +  // this size does not use Karatsuba.
    +  static constexpr size_t kScratchLimbs = detail::MulScratchLimbs<kNumLimbs>();
    +
    +  // Comba: no scratch, always available. This is also what the recursive calls
    +  // fall back to for small or odd sizes.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out) {
    +    detail::CombaMul<kNumLimbs>(d, a, b, out);
    +  }
    +
    +  // Karatsuba: fewer multiplies above kWideMulKaratsubaMinLimbs limbs, but the
    +  // caller must supply scratch of kScratchLimbs * Lanes(d) elements. Nothing is
    +  // allocated here, and `scratch` must not overlap `a`, `b` or `out`.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    static_assert(kScratchLimbs != 0,
    +                  "this size does not use Karatsuba; call Mul without scratch");
    +    detail::KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52), so e.g.
    +// `WideMulBits<256>` multiplies 256-bit values held as 5 limbs each.
    +template <size_t kBits>
    +using WideMulBits = WideMul<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +namespace detail {}  // namespace detail
    +
    +// ------------------------------ Montgomery
    +
    +// Returns -x^{-1} mod 2^52 for every lane, given the low limb of the modulus,
    +// which must be odd. This is the constant that makes the low limb of T + m*N
    +// vanish, so callers compute it once per modulus and reuse it for every
    +// multiplication.
    +template <class D, HWY_IF_U64_D(D)>
    +HWY_INLINE Vec<D> MontgomeryN0(D d, Vec<D> n0) {
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> two = Set(d, 2);
    +  // Newton iteration for the inverse modulo 2^52. Each step doubles the number
    +  // of correct bits, starting from 3 (x*x = 1 mod 8 for odd x), so six steps
    +  // cover 3, 6, 12, 24, 48 and 96 bits. MulAdd52Lo is the low 52 bits of a
    +  // product, which is exact here because every value is below 2^52.
    +  Vec<D> x = n0;
    +  for (int i = 0; i < 6; ++i) {
    +    const Vec<D> t = MulAdd52Lo(n0, x, zero);  // n0 * x mod 2^52
    +    // 2 - t mod 2^52: negate modulo 2^64, add, then mask.
    +    const Vec<D> complement = And(Add(Sub(zero, t), two), mask);
    +    x = MulAdd52Lo(x, complement, zero);
    +  }
    +  return And(Sub(zero, x), mask);  // -x mod 2^52
    +}
    +
    +namespace detail {
    +
    +// out = a * b * R^{-1} mod n by CIOS (Koc): alternate one row of the product
    +// with one step of the reduction, so the working array is only kNumLimbs + 2
    +// limbs and no full 2*kNumLimbs product is needed. Scratch is kTotal limbs for
    +// the accumulator plus kNumLimbs for the tentative difference.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CiosMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                        const TFromD<D>* HWY_RESTRICT b,
    +                        const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                        TFromD<D>* HWY_RESTRICT out,
    +                        TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kTotal = kNumLimbs + 2;
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const t = scratch;
    +  TFromD<D>* const diff = t + kTotal * N;
    +  for (size_t j = 0; j < kTotal; ++j) {
    +    StoreU(zero, d, t + j * N);
    +  }
    +
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const Vec<D> bv = LoadU(d, b + i * N);
    +    // t += a * b[i], with the low and high halves of each product separate.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> av = LoadU(d, a + j * N);
    +      const Vec<D> lo = MulAdd52Lo(av, bv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + j * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(av, bv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + kNumLimbs * N);
    +      StoreU(ShiftRight<kWideMulLimbBits>(sum), d, t + (kNumLimbs + 1) * N);
    +    }
    +
    +    // m = t[0] * n0 mod 2^52, then t += m * n and shift down by one limb. The
    +    // low limb of t cancels exactly by construction of n0, so it is dropped,
    +    // but its sum can still carry into the next limb; that is why `lo` below
    +    // adds t[0] rather than starting from zero.
    +    const Vec<D> m = MulAdd52Lo(LoadU(d, t), n0, zero);
    +    const Vec<D> n0v = LoadU(d, n);
    +    {
    +      const Vec<D> lo = MulAdd52Lo(m, n0v, LoadU(d, t));
    +      carry = Add(ShiftRight<kWideMulLimbBits>(lo), MulAdd52Hi(m, n0v, zero));
    +    }
    +    for (size_t j = 1; j < kNumLimbs; ++j) {
    +      const Vec<D> nv = LoadU(d, n + j * N);
    +      const Vec<D> lo = MulAdd52Lo(m, nv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + (j - 1) * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(m, nv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + (kNumLimbs - 1) * N);
    +      StoreU(Add(LoadU(d, t + (kNumLimbs + 1) * N),
    +                 ShiftRight<kWideMulLimbBits>(sum)),
    +             d, t + kNumLimbs * N);
    +    }
    +  }
    +
    +  // r = t[0..kNumLimbs) with an extra top limb is below 2n, so one conditional
    +  // subtraction suffices when n < R/2; a second pass makes it correct for any
    +  // odd n below R, where the value is then below 3n. Both take the borrow from
    +  // bit 63 of the wrapped difference, as SubInto does.
    +  for (int pass = 0; pass < 2; ++pass) {

    I think the second pass is wasted work because we already have the overflow/top limb in top.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:19 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in

    Looks like we return + 4. With the direct-into-out change, can also halve this.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:21 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result

    I think the negative is fine because we wrap around?

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:21 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {
    +    if (scratch != nullptr) {
    +      KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +      return;
    +    }
    +  }
    +  CombaMul<kNumLimbs>(d, a, b, out);
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kNumLimbs-limb unsigned integers into 2*kNumLimbs limbs. `d`
    +// must be a u64 vector descriptor; `a`, `b` and `out` point to arrays of at
    +// least kNumLimbs*N, kNumLimbs*N and 2*kNumLimbs*N elements respectively, N
    +// being Lanes(d). All input limbs must be < 2^52, as MulAdd52* requires; only
    +// the low 52 bits of each are used. `out` must not overlap `a` or `b`.
    +//
    +// kNumLimbs is limited so that the per-limb accumulators cannot overflow 64
    +// bits: each holds at most kNumLimbs products < 2^52, plus the carry from the
    +// previous limb, which is itself below kNumLimbs * (2^52 + 1). 1024 therefore
    +// leaves ample headroom below 2^64.
    +template <size_t kNumLimbs>
    +struct WideMul {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = 2 * kNumLimbs;
    +  // Limbs of T per lane required by the Karatsuba overload below; zero when
    +  // this size does not use Karatsuba.
    +  static constexpr size_t kScratchLimbs = detail::MulScratchLimbs<kNumLimbs>();
    +
    +  // Comba: no scratch, always available. This is also what the recursive calls
    +  // fall back to for small or odd sizes.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out) {
    +    detail::CombaMul<kNumLimbs>(d, a, b, out);
    +  }
    +
    +  // Karatsuba: fewer multiplies above kWideMulKaratsubaMinLimbs limbs, but the
    +  // caller must supply scratch of kScratchLimbs * Lanes(d) elements. Nothing is
    +  // allocated here, and `scratch` must not overlap `a`, `b` or `out`.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    static_assert(kScratchLimbs != 0,
    +                  "this size does not use Karatsuba; call Mul without scratch");
    +    detail::KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52), so e.g.
    +// `WideMulBits<256>` multiplies 256-bit values held as 5 limbs each.
    +template <size_t kBits>
    +using WideMulBits = WideMul<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +namespace detail {}  // namespace detail

    Can remove :)

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:22 UTC
    Code Review
    hwy/contrib/multiprec/multiprec_test.cc:1
    @@ -0,0 +1,496 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include <type_traits>
    +
    +#include "hwy/aligned_allocator.h"
    +#include "hwy/base.h"
    +
    +// clang-format off
    +#undef HWY_TARGET_INCLUDE
    +#define HWY_TARGET_INCLUDE "hwy/contrib/multiprec/multiprec_test.cc"  // NOLINT
    +// clang-format on
    +#include "hwy/foreach_target.h"  // IWYU pragma: keep
    +#include "hwy/highway.h"
    +// After highway.h:
    +#include "hwy/contrib/multiprec/multiprec-inl.h"
    +#include "hwy/tests/test_util-inl.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +namespace {
    +
    +// The bit-width alias rounds up to whole 52-bit limbs, and the widest supported
    +// size stays within the accumulator limit.
    +static_assert(std::is_same<WideMulBits<128>, WideMul<3>>::value,
    +              "128 / 52 rounds up to 3 limbs");
    +static_assert(std::is_same<WideMulBits<256>, WideMul<5>>::value,
    +              "256 / 52 rounds up to 5 limbs");
    +static_assert(WideMulBits<2048>::kNumResultLimbs == 80,
    +              "2048 bits is 40 limbs, so 80 limbs of result");
    +
    +template <size_t kNumLimbs>
    +struct TestWideMul {
    +  template <typename T, class D>
    +  HWY_NOINLINE void operator()(T /*unused*/, D d) {
    +    const size_t N = Lanes(d);
    +    constexpr size_t kResultLimbs = 2 * kNumLimbs;
    +
    +    AlignedFreeUniquePtr<T[]> a[kNumLimbs];
    +    AlignedFreeUniquePtr<T[]> b[kNumLimbs];
    +    AlignedFreeUniquePtr<T[]> expected[kResultLimbs];
    +    for (size_t i = 0; i < kNumLimbs; ++i) {
    +      a[i] = AllocateAligned<T>(N);
    +      b[i] = AllocateAligned<T>(N);
    +      HWY_ASSERT(a[i] && b[i]);
    +    }
    +    for (size_t k = 0; k < kResultLimbs; ++k) {
    +      expected[k] = AllocateAligned<T>(N);
    +      HWY_ASSERT(expected[k]);
    +    }
    +
    +    // Two rounds: random limbs, then all-ones limbs, i.e. the largest
    +    // representable inputs, which exercise every carry (and also squaring).
    +    for (size_t round = 0; round < 2; ++round) {
    +      RandomState rng(12345);
    +      for (size_t i = 0; i < kNumLimbs; ++i) {
    +        for (size_t l = 0; l < N; ++l) {
    +          if (round == 0) {
    +            a[i][l] = static_cast<T>(Random64(&rng) & kWideMulLimbMask);
    +            b[i][l] = static_cast<T>(Random64(&rng) & kWideMulLimbMask);
    +          } else {
    +            a[i][l] = static_cast<T>(kWideMulLimbMask);
    +            b[i][l] = static_cast<T>(kWideMulLimbMask);
    +          }
    +        }
    +      }
    +
    +      // Scalar reference, one lane at a time: accumulate the low and high
    +      // halves of each 128-bit product per output limb, then ripple the
    +      // carries.
    +      for (size_t l = 0; l < N; ++l) {
    +        uint64_t low[kResultLimbs - 1] = {0};
    +        uint64_t high[kResultLimbs - 1] = {0};
    +        for (size_t i = 0; i < kNumLimbs; ++i) {
    +          for (size_t j = 0; j < kNumLimbs; ++j) {
    +            uint64_t hi;
    +            const uint64_t lo = Mul128(a[i][l], b[j][l], &hi);
    +            low[i + j] += lo & kWideMulLimbMask;
    +            high[i + j] +=
    +                (lo >> kWideMulLimbBits) | (hi << (64 - kWideMulLimbBits));
    +          }
    +        }
    +        uint64_t carry = 0;
    +        for (size_t k = 0; k + 1 < kResultLimbs; ++k) {
    +          const uint64_t sum = low[k] + carry;
    +          expected[k][l] = static_cast<T>(sum & kWideMulLimbMask);
    +          carry = (sum >> kWideMulLimbBits) + high[k];
    +        }
    +        expected[kResultLimbs - 1][l] =
    +            static_cast<T>(carry & kWideMulLimbMask);
    +      }
    +
    +      // The API works on flat arrays of T: vector types are sizeless on SVE and
    +      // RVV, so they cannot be stored in arrays.
    +      AlignedFreeUniquePtr<T[]> va = AllocateAligned<T>(kNumLimbs * N);
    +      AlignedFreeUniquePtr<T[]> vb = AllocateAligned<T>(kNumLimbs * N);
    +      AlignedFreeUniquePtr<T[]> vout = AllocateAligned<T>(kResultLimbs * N);
    +      HWY_ASSERT(va && vb && vout);
    +      for (size_t i = 0; i < kNumLimbs; ++i) {
    +        CopyBytes(a[i].get(), va.get() + i * N, N * sizeof(T));
    +        CopyBytes(b[i].get(), vb.get() + i * N, N * sizeof(T));
    +      }
    +
    +      WideMul<kNumLimbs>::Mul(d, va.get(), vb.get(), vout.get());
    +      for (size_t k = 0; k < kResultLimbs; ++k) {
    +        for (size_t l = 0; l < N; ++l) {
    +          HWY_ASSERT_EQ(expected[k][l], vout[k * N + l]);
    +        }
    +      }
    +
    +      // Karatsuba, for the sizes that use it: needs scratch, and must agree
    +      // with the same reference.
    +      if constexpr (WideMul<kNumLimbs>::kScratchLimbs != 0) {
    +        constexpr size_t kScratchLimbs = WideMul<kNumLimbs>::kScratchLimbs;
    +        AlignedFreeUniquePtr<T[]> scratch =
    +            AllocateAligned<T>(kScratchLimbs * N);
    +        HWY_ASSERT(scratch != nullptr);
    +        for (size_t i = 0; i < kResultLimbs * N; ++i) vout[i] = T{0};
    +        WideMul<kNumLimbs>::Mul(d, va.get(), vb.get(), vout.get(),
    +                                scratch.get());
    +        for (size_t k = 0; k < kResultLimbs; ++k) {
    +          for (size_t l = 0; l < N; ++l) {
    +            HWY_ASSERT_EQ(expected[k][l], vout[k * N + l]);
    +          }
    +        }
    +      }
    +    }
    +  }
    +};
    +
    +// Independent reference: schoolbook with 128-bit partial products added
    +// limb-by-limb with ripple carry (different structure from the limb-based
    +// kernel, so agreement is meaningful).
    +template <size_t kLimbs>
    +void RefWideMul(const uint64_t* HWY_RESTRICT a, const uint64_t* HWY_RESTRICT b,
    +                uint64_t* HWY_RESTRICT out) {
    +  for (size_t k = 0; k < 2 * kLimbs; ++k) out[k] = 0;
    +  for (size_t i = 0; i < kLimbs; ++i) {
    +    for (size_t j = 0; j < kLimbs; ++j) {
    +      uint64_t hi;
    +      const uint64_t lo = Mul128(a[i], b[j], &hi);
    +      const size_t k = i + j;
    +      // Add lo at limb k.
    +      const uint64_t t0 = out[k] + lo;
    +      uint64_t carry = (t0 < lo) ? 1 : 0;
    +      out[k] = t0;
    +      // Add hi plus that carry at limb k+1.
    +      const uint64_t t1 = out[k + 1] + hi;
    +      uint64_t c = (t1 < hi) ? 1 : 0;
    +      const uint64_t t2 = t1 + carry;
    +      c += (t2 < carry) ? 1 : 0;
    +      out[k + 1] = t2;
    +      carry = c;
    +      // Ripple the remaining carry.
    +      for (size_t m = k + 2; carry != 0 && m < 2 * kLimbs; ++m) {
    +        const uint64_t t = out[m] + carry;
    +        carry = (t < carry) ? 1 : 0;
    +        out[m] = t;
    +      }
    +    }
    +  }
    +}
    +
    +// ---- Montgomery reference: modular arithmetic on 52-bit limbs by binary
    +// double-and-add, i.e. no Montgomery and no R. Independent of the CIOS kernel,
    +// so agreement is meaningful. All values are below n < 2^(52*kNumLimbs), so
    +// scalar 64-bit arithmetic suffices.
    +
    +// r = 2r mod n, in place; requires r < n. `carry` is the bit shifted out of the
    +// top limb (0 or 1), which SubIfGeRef needs to compare correctly.
    +template <size_t kNumLimbs>
    +uint64_t DoubleModRef(uint64_t* r) {
    +  uint64_t carry = 0;
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const uint64_t t = (r[i] << 1) | carry;
    +    carry = r[i] >> (kWideMulLimbBits - 1);
    +    r[i] = t & kWideMulLimbMask;
    +  }
    +  return carry;
    +}
    +
    +// r = (extra, r) - n if that is non-negative; requires (extra, r) < 2n.
    +template <size_t kNumLimbs>
    +void SubIfGeRef(uint64_t* r, const uint64_t* n, uint64_t extra) {
    +  uint64_t diff[kNumLimbs];
    +  uint64_t borrow = 0;
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const uint64_t sub = n[i] + borrow;
    +    diff[i] = (r[i] - sub) & kWideMulLimbMask;
    +    borrow = r[i] < sub ? 1 : 0;
    +  }
    +  if (extra >= borrow) {  // no borrow out, so r >= n
    +    for (size_t i = 0; i < kNumLimbs; ++i) r[i] = diff[i];
    +  }
    +}
    +
    +// r = r + a mod n; requires r, a < n.
    +template <size_t kNumLimbs>
    +void AddModRef(uint64_t* r, const uint64_t* a, const uint64_t* n) {
    +  uint64_t carry = 0;
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const uint64_t t = r[i] + a[i] + carry;
    +    r[i] = t & kWideMulLimbMask;
    +    carry = t >> kWideMulLimbBits;
    +  }
    +  SubIfGeRef<kNumLimbs>(r, n, carry);
    +}
    +
    +// out = a * b mod n.
    +template <size_t kNumLimbs>
    +void MulModRef(const uint64_t* a, const uint64_t* b, const uint64_t* n,
    +               uint64_t* out) {
    +  uint64_t r[kNumLimbs] = {};
    +  for (int bit = 52 * static_cast<int>(kNumLimbs) - 1; bit >= 0; --bit) {
    +    SubIfGeRef<kNumLimbs>(r, n, DoubleModRef<kNumLimbs>(r));
    +    if ((b[bit / 52] >> (bit % 52)) & 1) AddModRef<kNumLimbs>(r, a, n);
    +  }
    +  for (size_t i = 0; i < kNumLimbs; ++i) out[i] = r[i];
    +}
    +
    +// out = a mod n for any a below 2^(52*kNumLimbs). The multiplier must be
    +// below n, so `a` is the multiplier and 1 the multiplicand: each step then
    +// only adds 1, which is below n.
    +template <size_t kNumLimbs>
    +void ModRef(const uint64_t* a, const uint64_t* n, uint64_t* out) {
    +  uint64_t one[kNumLimbs] = {};
    +  one[0] = 1;
    +  MulModRef<kNumLimbs>(one, a, n, out);
    +}
    +
    +// out = 2^(52*kNumLimbs) mod n, i.e. R mod n.
    +template <size_t kNumLimbs>
    +void RModNRef(const uint64_t* n, uint64_t* out) {
    +  uint64_t r[kNumLimbs] = {};
    +  r[0] = 1;
    +  for (int i = 0; i < 52 * static_cast<int>(kNumLimbs); ++i) {
    +    SubIfGeRef<kNumLimbs>(r, n, DoubleModRef<kNumLimbs>(r));
    +  }
    +  for (size_t i = 0; i < kNumLimbs; ++i) out[i] = r[i];
    +}
    +
    +template <size_t kBits>
    +struct TestWideMulLimbs {
    +  HWY_NOINLINE void operator()() {
    +    constexpr size_t kLimbs = kBits / 64;
    +    uint64_t a[kLimbs];
    +    uint64_t b[kLimbs];
    +    uint64_t actual[2 * kLimbs];
    +    uint64_t expected[2 * kLimbs];
    +
    +    RandomState rng(6789);
    +    for (int trial = 0; trial < 20; ++trial) {
    +      for (size_t i = 0; i < kLimbs; ++i) {
    +        a[i] = Random64(&rng);
    +        b[i] = Random64(&rng);
    +      }
    +      WideMulLimbs<kBits>(a, b, actual);
    +      RefWideMul<kLimbs>(a, b, expected);
    +      for (size_t k = 0; k < 2 * kLimbs; ++k) {
    +        HWY_ASSERT_EQ(expected[k], actual[k]);
    +      }
    +    }
    +
    +    // Maximum inputs: (2^kBits - 1)^2.
    +    for (size_t i = 0; i < kLimbs; ++i) a[i] = ~uint64_t{0};
    +    WideMulLimbs<kBits>(a, a, actual);

    Args are HWY_RESTRICT - maybe they do not all have to be. Only out and scratch have to/should be.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:24 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {
    +    if (scratch != nullptr) {
    +      KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +      return;
    +    }
    +  }
    +  CombaMul<kNumLimbs>(d, a, b, out);
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kNumLimbs-limb unsigned integers into 2*kNumLimbs limbs. `d`
    +// must be a u64 vector descriptor; `a`, `b` and `out` point to arrays of at
    +// least kNumLimbs*N, kNumLimbs*N and 2*kNumLimbs*N elements respectively, N
    +// being Lanes(d). All input limbs must be < 2^52, as MulAdd52* requires; only
    +// the low 52 bits of each are used. `out` must not overlap `a` or `b`.
    +//
    +// kNumLimbs is limited so that the per-limb accumulators cannot overflow 64
    +// bits: each holds at most kNumLimbs products < 2^52, plus the carry from the
    +// previous limb, which is itself below kNumLimbs * (2^52 + 1). 1024 therefore
    +// leaves ample headroom below 2^64.
    +template <size_t kNumLimbs>
    +struct WideMul {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = 2 * kNumLimbs;
    +  // Limbs of T per lane required by the Karatsuba overload below; zero when
    +  // this size does not use Karatsuba.
    +  static constexpr size_t kScratchLimbs = detail::MulScratchLimbs<kNumLimbs>();
    +
    +  // Comba: no scratch, always available. This is also what the recursive calls
    +  // fall back to for small or odd sizes.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out) {
    +    detail::CombaMul<kNumLimbs>(d, a, b, out);
    +  }
    +
    +  // Karatsuba: fewer multiplies above kWideMulKaratsubaMinLimbs limbs, but the
    +  // caller must supply scratch of kScratchLimbs * Lanes(d) elements. Nothing is
    +  // allocated here, and `scratch` must not overlap `a`, `b` or `out`.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    static_assert(kScratchLimbs != 0,
    +                  "this size does not use Karatsuba; call Mul without scratch");
    +    detail::KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52), so e.g.
    +// `WideMulBits<256>` multiplies 256-bit values held as 5 limbs each.
    +template <size_t kBits>
    +using WideMulBits = WideMul<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +namespace detail {}  // namespace detail
    +
    +// ------------------------------ Montgomery
    +
    +// Returns -x^{-1} mod 2^52 for every lane, given the low limb of the modulus,
    +// which must be odd. This is the constant that makes the low limb of T + m*N
    +// vanish, so callers compute it once per modulus and reuse it for every
    +// multiplication.
    +template <class D, HWY_IF_U64_D(D)>
    +HWY_INLINE Vec<D> MontgomeryN0(D d, Vec<D> n0) {
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> two = Set(d, 2);
    +  // Newton iteration for the inverse modulo 2^52. Each step doubles the number
    +  // of correct bits, starting from 3 (x*x = 1 mod 8 for odd x), so six steps
    +  // cover 3, 6, 12, 24, 48 and 96 bits. MulAdd52Lo is the low 52 bits of a
    +  // product, which is exact here because every value is below 2^52.
    +  Vec<D> x = n0;
    +  for (int i = 0; i < 6; ++i) {
    +    const Vec<D> t = MulAdd52Lo(n0, x, zero);  // n0 * x mod 2^52
    +    // 2 - t mod 2^52: negate modulo 2^64, add, then mask.
    +    const Vec<D> complement = And(Add(Sub(zero, t), two), mask);
    +    x = MulAdd52Lo(x, complement, zero);
    +  }
    +  return And(Sub(zero, x), mask);  // -x mod 2^52
    +}
    +
    +namespace detail {
    +
    +// out = a * b * R^{-1} mod n by CIOS (Koc): alternate one row of the product
    +// with one step of the reduction, so the working array is only kNumLimbs + 2
    +// limbs and no full 2*kNumLimbs product is needed. Scratch is kTotal limbs for
    +// the accumulator plus kNumLimbs for the tentative difference.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CiosMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                        const TFromD<D>* HWY_RESTRICT b,
    +                        const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                        TFromD<D>* HWY_RESTRICT out,
    +                        TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kTotal = kNumLimbs + 2;
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const t = scratch;
    +  TFromD<D>* const diff = t + kTotal * N;
    +  for (size_t j = 0; j < kTotal; ++j) {
    +    StoreU(zero, d, t + j * N);
    +  }
    +
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const Vec<D> bv = LoadU(d, b + i * N);
    +    // t += a * b[i], with the low and high halves of each product separate.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> av = LoadU(d, a + j * N);
    +      const Vec<D> lo = MulAdd52Lo(av, bv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);

    I think we should only do the carry propagation once, outside the loop - the nails leave plenty of headroom, and as-is we have a dependency between the write to carry and consuming it in the loop.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:26 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {
    +    if (scratch != nullptr) {
    +      KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +      return;
    +    }
    +  }
    +  CombaMul<kNumLimbs>(d, a, b, out);
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kNumLimbs-limb unsigned integers into 2*kNumLimbs limbs. `d`
    +// must be a u64 vector descriptor; `a`, `b` and `out` point to arrays of at
    +// least kNumLimbs*N, kNumLimbs*N and 2*kNumLimbs*N elements respectively, N
    +// being Lanes(d). All input limbs must be < 2^52, as MulAdd52* requires; only
    +// the low 52 bits of each are used. `out` must not overlap `a` or `b`.
    +//
    +// kNumLimbs is limited so that the per-limb accumulators cannot overflow 64
    +// bits: each holds at most kNumLimbs products < 2^52, plus the carry from the
    +// previous limb, which is itself below kNumLimbs * (2^52 + 1). 1024 therefore
    +// leaves ample headroom below 2^64.
    +template <size_t kNumLimbs>
    +struct WideMul {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = 2 * kNumLimbs;
    +  // Limbs of T per lane required by the Karatsuba overload below; zero when
    +  // this size does not use Karatsuba.
    +  static constexpr size_t kScratchLimbs = detail::MulScratchLimbs<kNumLimbs>();
    +
    +  // Comba: no scratch, always available. This is also what the recursive calls
    +  // fall back to for small or odd sizes.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out) {
    +    detail::CombaMul<kNumLimbs>(d, a, b, out);
    +  }
    +
    +  // Karatsuba: fewer multiplies above kWideMulKaratsubaMinLimbs limbs, but the
    +  // caller must supply scratch of kScratchLimbs * Lanes(d) elements. Nothing is
    +  // allocated here, and `scratch` must not overlap `a`, `b` or `out`.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    static_assert(kScratchLimbs != 0,
    +                  "this size does not use Karatsuba; call Mul without scratch");
    +    detail::KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52), so e.g.
    +// `WideMulBits<256>` multiplies 256-bit values held as 5 limbs each.
    +template <size_t kBits>
    +using WideMulBits = WideMul<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +namespace detail {}  // namespace detail
    +
    +// ------------------------------ Montgomery
    +
    +// Returns -x^{-1} mod 2^52 for every lane, given the low limb of the modulus,
    +// which must be odd. This is the constant that makes the low limb of T + m*N
    +// vanish, so callers compute it once per modulus and reuse it for every
    +// multiplication.
    +template <class D, HWY_IF_U64_D(D)>
    +HWY_INLINE Vec<D> MontgomeryN0(D d, Vec<D> n0) {
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> two = Set(d, 2);
    +  // Newton iteration for the inverse modulo 2^52. Each step doubles the number
    +  // of correct bits, starting from 3 (x*x = 1 mod 8 for odd x), so six steps
    +  // cover 3, 6, 12, 24, 48 and 96 bits. MulAdd52Lo is the low 52 bits of a
    +  // product, which is exact here because every value is below 2^52.
    +  Vec<D> x = n0;
    +  for (int i = 0; i < 6; ++i) {
    +    const Vec<D> t = MulAdd52Lo(n0, x, zero);  // n0 * x mod 2^52
    +    // 2 - t mod 2^52: negate modulo 2^64, add, then mask.
    +    const Vec<D> complement = And(Add(Sub(zero, t), two), mask);
    +    x = MulAdd52Lo(x, complement, zero);
    +  }
    +  return And(Sub(zero, x), mask);  // -x mod 2^52
    +}
    +
    +namespace detail {
    +
    +// out = a * b * R^{-1} mod n by CIOS (Koc): alternate one row of the product
    +// with one step of the reduction, so the working array is only kNumLimbs + 2
    +// limbs and no full 2*kNumLimbs product is needed. Scratch is kTotal limbs for
    +// the accumulator plus kNumLimbs for the tentative difference.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CiosMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                        const TFromD<D>* HWY_RESTRICT b,
    +                        const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                        TFromD<D>* HWY_RESTRICT out,
    +                        TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kTotal = kNumLimbs + 2;
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const t = scratch;
    +  TFromD<D>* const diff = t + kTotal * N;
    +  for (size_t j = 0; j < kTotal; ++j) {
    +    StoreU(zero, d, t + j * N);
    +  }
    +
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const Vec<D> bv = LoadU(d, b + i * N);
    +    // t += a * b[i], with the low and high halves of each product separate.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> av = LoadU(d, a + j * N);
    +      const Vec<D> lo = MulAdd52Lo(av, bv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + j * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(av, bv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + kNumLimbs * N);
    +      StoreU(ShiftRight<kWideMulLimbBits>(sum), d, t + (kNumLimbs + 1) * N);
    +    }
    +
    +    // m = t[0] * n0 mod 2^52, then t += m * n and shift down by one limb. The
    +    // low limb of t cancels exactly by construction of n0, so it is dropped,
    +    // but its sum can still carry into the next limb; that is why `lo` below
    +    // adds t[0] rather than starting from zero.
    +    const Vec<D> m = MulAdd52Lo(LoadU(d, t), n0, zero);
    +    const Vec<D> n0v = LoadU(d, n);
    +    {
    +      const Vec<D> lo = MulAdd52Lo(m, n0v, LoadU(d, t));
    +      carry = Add(ShiftRight<kWideMulLimbBits>(lo), MulAdd52Hi(m, n0v, zero));
    +    }
    +    for (size_t j = 1; j < kNumLimbs; ++j) {
    +      const Vec<D> nv = LoadU(d, n + j * N);
    +      const Vec<D> lo = MulAdd52Lo(m, nv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + (j - 1) * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(m, nv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + (kNumLimbs - 1) * N);
    +      StoreU(Add(LoadU(d, t + (kNumLimbs + 1) * N),
    +                 ShiftRight<kWideMulLimbBits>(sum)),
    +             d, t + kNumLimbs * N);
    +    }
    +  }
    +
    +  // r = t[0..kNumLimbs) with an extra top limb is below 2n, so one conditional
    +  // subtraction suffices when n < R/2; a second pass makes it correct for any
    +  // odd n below R, where the value is then below 3n. Both take the borrow from
    +  // bit 63 of the wrapped difference, as SubInto does.
    +  for (int pass = 0; pass < 2; ++pass) {
    +    Vec<D> borrow = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> sub = Add(LoadU(d, n + j * N), borrow);
    +      const Vec<D> d_j = Sub(LoadU(d, t + j * N), sub);
    +      borrow = ShiftRight<63>(d_j);
    +      StoreU(And(d_j, mask), d, diff + j * N);
    +    }
    +    const Vec<D> top = Sub(LoadU(d, t + kNumLimbs * N), borrow);
    +    // The top limb is zero or one, but keep the invariant of limbs < 2^52.
    +    const Vec<D> top_masked = And(top, mask);
    +    const Mask<D> keep_diff = Eq(ShiftRight<63>(top), zero);
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      StoreU(IfThenElse(keep_diff, LoadU(d, diff + j * N), LoadU(d, t + j * N)),
    +             d, t + j * N);
    +    }
    +    StoreU(IfThenElse(keep_diff, top_masked, LoadU(d, t + kNumLimbs * N)), d,
    +           t + kNumLimbs * N);
    +  }
    +
    +  for (size_t j = 0; j < kNumLimbs; ++j) {
    +    StoreU(And(LoadU(d, t + j * N), mask), d, out + j * N);
    +  }
    +}
    +
    +}  // namespace detail
    +
    +// Montgomery modular multiplication, mirroring WideMul: the same limb layout
    +// (limb i of an operand at [i * Lanes(d)]), and a and b must be below n. The
    +// result is a * b * R^{-1} mod n with R = 2^(52 * kNumLimbs), which is below n
    +// when n < R. `n` must be odd, and n0 must come from MontgomeryN0 applied to
    +// its low limb: compute that once per modulus and reuse it.
    +//
    +// To multiply in Montgomery form, represent x as x * R mod n (which the caller
    +// computes once per value, e.g. from R^2 mod n) and multiply the
    +// representations.
    +template <size_t kNumLimbs>
    +struct Montgomery {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = kNumLimbs;
    +  // The accumulator (kNumLimbs + 2 limbs) and the tentative difference.
    +  static constexpr size_t kScratchLimbs = 2 * kNumLimbs + 2;
    +
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    detail::CiosMul<kNumLimbs>(d, a, b, n, n0, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52).
    +template <size_t kBits>
    +using MontgomeryBits =
    +    Montgomery<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +// out = R^2 mod n, with R = 2^(52 * kNumLimbs). This is the constant needed to
    +// enter Montgomery form, so the caller can convert without any modular
    +// arithmetic of its own:
    +//
    +//   ToMontgomery(x)   = Montgomery<>::Mul(x, r2, ...)
    +//   FromMontgomery(y) = Montgomery<>::Mul(y, one, ...)   // one = {1, 0, ...}
    +//
    +// n must be odd and below R, as for Montgomery<>::Mul. Both conversions are
    +// then Montgomery products, and no separate modular multiplication is required.
    +//
    +// Computed as 104*kNumLimbs modular doublings starting from 1, which is
    +// (2^(52*kNumLimbs))^2 mod n. Like the reduction, it is branch-free: the carry
    +// out of the top limb and the borrow of the conditional subtraction are
    +// combined into one per-lane select. Scratch is 2*kNumLimbs limbs per lane.
    +template <size_t kNumLimbs, class D, HWY_IF_U64_D(D)>
    +HWY_INLINE void MontgomeryR2(D d, const TFromD<D>* HWY_RESTRICT n,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const r = scratch;
    +  TFromD<D>* const diff = r + kNumLimbs * N;
    +  for (size_t j = 0; j < kNumLimbs; ++j) {
    +    StoreU(j == 0 ? Set(d, 1) : zero, d, r + j * N);
    +  }
    +
    +  for (size_t i = 0; i < 104 * kNumLimbs; ++i) {
    +    // (carry, r) = 2 * r.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> rv = LoadU(d, r + j * N);
    +      const Vec<D> sum = Add(Add(rv, rv), carry);
    +      StoreU(And(sum, mask), d, r + j * N);
    +      carry = ShiftRight<kWideMulLimbBits>(sum);
    +    }
    +    // r -= n when (carry, r) >= n; keep the difference in `diff` meanwhile.
    +    Vec<D> borrow = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> sub = Add(LoadU(d, n + j * N), borrow);
    +      const Vec<D> d_j = Sub(LoadU(d, r + j * N), sub);
    +      borrow = ShiftRight<63>(d_j);
    +      StoreU(And(d_j, mask), d, diff + j * N);
    +    }
    +    const Vec<D> top = Sub(carry, borrow);
    +    const Mask<D> keep_diff = Eq(ShiftRight<63>(top), zero);
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      StoreU(IfThenElse(keep_diff, LoadU(d, diff + j * N), LoadU(d, r + j * N)),
    +             d, r + j * N);
    +    }
    +  }
    +
    +  for (size_t j = 0; j < kNumLimbs; ++j) {
    +    StoreU(LoadU(d, r + j * N), d, out + j * N);
    +  }
    +}
    +
    +// Scratch limbs per lane needed by MontgomeryR2 (the working value and the
    +// tentative difference).
    +template <size_t kNumLimbs>
    +constexpr size_t MontgomeryR2ScratchLimbs() {
    +  return 2 * kNumLimbs;
    +}
    +
    +namespace detail {
    +
    +// Unpacks kNumLimbs 52-bit limbs from kLimbs little-endian 64-bit limbs.
    +template <size_t kNumLimbs, size_t kLimbs>
    +HWY_INLINE void UnpackLimbs52(const uint64_t* HWY_RESTRICT limbs,
    +                              uint64_t* HWY_RESTRICT out) {
    +  static_assert((kNumLimbs - 1) * kWideMulLimbBits < kLimbs * 64,
    +                "the 52-bit limbs do not fit in the 64-bit limbs");
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const size_t bit = i * kWideMulLimbBits;
    +    const size_t limb = bit / 64;
    +    const size_t offset = bit % 64;
    +    uint64_t v = limbs[limb] >> offset;
    +    if (offset + kWideMulLimbBits > 64) {
    +      v |= (limb + 1 < kLimbs ? limbs[limb + 1] : uint64_t{0}) << (64 - offset);
    +    }
    +    out[i] = v & kWideMulLimbMask;
    +  }
    +}
    +
    +// Packs kNumLimbs 52-bit limbs into kLimbs little-endian 64-bit limbs.
    +template <size_t kNumLimbs, size_t kLimbs>
    +HWY_INLINE void PackLimbs52(const uint64_t* HWY_RESTRICT in,
    +                            uint64_t* HWY_RESTRICT limbs) {
    +  size_t src = 0;
    +  size_t src_bit = 0;
    +  for (size_t j = 0; j < kLimbs; ++j) {
    +    uint64_t v = 0;
    +    size_t dst_bit = 0;
    +    size_t need = 64;
    +    while (need != 0 && src < kNumLimbs) {
    +      const size_t avail = kWideMulLimbBits - src_bit;
    +      const size_t take = HWY_MIN(need, avail);
    +      const uint64_t part = (in[src] >> src_bit) & ((uint64_t{1} << take) - 1);
    +      v |= part << dst_bit;
    +      dst_bit += take;
    +      need -= take;
    +      src_bit += take;
    +      if (src_bit == kWideMulLimbBits) {
    +        ++src;
    +        src_bit = 0;
    +      }
    +    }
    +    limbs[j] = v;
    +  }
    +}
    +
    +// Scalar Comba over 52-bit limbs; the same math as the vector kernel, one lane
    +// at a time.
    +template <size_t kNumLimbs>
    +HWY_INLINE void ScalarCombaMul(const uint64_t* HWY_RESTRICT a,
    +                               const uint64_t* HWY_RESTRICT b,
    +                               uint64_t* HWY_RESTRICT out) {
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  uint64_t carry = 0;
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    uint64_t lo = carry;
    +    uint64_t hi = 0;
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      uint64_t p_hi;
    +      const uint64_t p_lo = Mul128(a[i], b[k - i], &p_hi);
    +      lo += p_lo & kWideMulLimbMask;
    +      hi += (p_lo >> kWideMulLimbBits) | (p_hi << (64 - kWideMulLimbBits));
    +    }
    +    out[k] = lo & kWideMulLimbMask;
    +    carry = (lo >> kWideMulLimbBits) + hi;
    +  }
    +  out[kNumOutLimbs - 1] = carry & kWideMulLimbMask;
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kBits-bit unsigned integers, both given as little-endian
    +// 64-bit limbs (kBits/64 each), and writes the 2*kBits/64-limb product. This is
    +// a scalar convenience over the 52-bit limb core, e.g. for u128/u192/u256; it
    +// does not use the vector unit. kBits must be a multiple of 64.
    +//
    +// The top of the result may be a partial 52-bit limb (e.g. a 128-bit product
    +// has 256 bits, so its 5th limb holds 48 bits); the remaining bits are zero
    +// because the product fits.
    +template <size_t kBits>
    +HWY_INLINE void WideMulLimbs(const uint64_t* HWY_RESTRICT a,
    +                             const uint64_t* HWY_RESTRICT b,
    +                             uint64_t* HWY_RESTRICT out) {
    +  static_assert(kBits % 64 == 0, "kBits must be a multiple of 64");
    +  constexpr size_t kLimbs = kBits / 64;
    +  constexpr size_t kNumLimbs =
    +      (kBits + kWideMulLimbBits - 1) / kWideMulLimbBits;
    +  uint64_t a52[kNumLimbs];

    Why split into 52 bits if we are going to use scalar code? I think we can use full 64x64 muls in scalar code.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:27 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {
    +    if (scratch != nullptr) {
    +      KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +      return;
    +    }
    +  }
    +  CombaMul<kNumLimbs>(d, a, b, out);
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kNumLimbs-limb unsigned integers into 2*kNumLimbs limbs. `d`
    +// must be a u64 vector descriptor; `a`, `b` and `out` point to arrays of at
    +// least kNumLimbs*N, kNumLimbs*N and 2*kNumLimbs*N elements respectively, N
    +// being Lanes(d). All input limbs must be < 2^52, as MulAdd52* requires; only
    +// the low 52 bits of each are used. `out` must not overlap `a` or `b`.
    +//
    +// kNumLimbs is limited so that the per-limb accumulators cannot overflow 64
    +// bits: each holds at most kNumLimbs products < 2^52, plus the carry from the
    +// previous limb, which is itself below kNumLimbs * (2^52 + 1). 1024 therefore
    +// leaves ample headroom below 2^64.
    +template <size_t kNumLimbs>
    +struct WideMul {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = 2 * kNumLimbs;
    +  // Limbs of T per lane required by the Karatsuba overload below; zero when
    +  // this size does not use Karatsuba.
    +  static constexpr size_t kScratchLimbs = detail::MulScratchLimbs<kNumLimbs>();
    +
    +  // Comba: no scratch, always available. This is also what the recursive calls
    +  // fall back to for small or odd sizes.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out) {
    +    detail::CombaMul<kNumLimbs>(d, a, b, out);
    +  }
    +
    +  // Karatsuba: fewer multiplies above kWideMulKaratsubaMinLimbs limbs, but the
    +  // caller must supply scratch of kScratchLimbs * Lanes(d) elements. Nothing is
    +  // allocated here, and `scratch` must not overlap `a`, `b` or `out`.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    static_assert(kScratchLimbs != 0,
    +                  "this size does not use Karatsuba; call Mul without scratch");
    +    detail::KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52), so e.g.
    +// `WideMulBits<256>` multiplies 256-bit values held as 5 limbs each.
    +template <size_t kBits>
    +using WideMulBits = WideMul<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +namespace detail {}  // namespace detail
    +
    +// ------------------------------ Montgomery
    +
    +// Returns -x^{-1} mod 2^52 for every lane, given the low limb of the modulus,
    +// which must be odd. This is the constant that makes the low limb of T + m*N
    +// vanish, so callers compute it once per modulus and reuse it for every
    +// multiplication.
    +template <class D, HWY_IF_U64_D(D)>
    +HWY_INLINE Vec<D> MontgomeryN0(D d, Vec<D> n0) {
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> two = Set(d, 2);
    +  // Newton iteration for the inverse modulo 2^52. Each step doubles the number
    +  // of correct bits, starting from 3 (x*x = 1 mod 8 for odd x), so six steps
    +  // cover 3, 6, 12, 24, 48 and 96 bits. MulAdd52Lo is the low 52 bits of a
    +  // product, which is exact here because every value is below 2^52.
    +  Vec<D> x = n0;
    +  for (int i = 0; i < 6; ++i) {
    +    const Vec<D> t = MulAdd52Lo(n0, x, zero);  // n0 * x mod 2^52
    +    // 2 - t mod 2^52: negate modulo 2^64, add, then mask.
    +    const Vec<D> complement = And(Add(Sub(zero, t), two), mask);
    +    x = MulAdd52Lo(x, complement, zero);
    +  }
    +  return And(Sub(zero, x), mask);  // -x mod 2^52
    +}
    +
    +namespace detail {
    +
    +// out = a * b * R^{-1} mod n by CIOS (Koc): alternate one row of the product
    +// with one step of the reduction, so the working array is only kNumLimbs + 2
    +// limbs and no full 2*kNumLimbs product is needed. Scratch is kTotal limbs for
    +// the accumulator plus kNumLimbs for the tentative difference.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CiosMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                        const TFromD<D>* HWY_RESTRICT b,
    +                        const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                        TFromD<D>* HWY_RESTRICT out,
    +                        TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kTotal = kNumLimbs + 2;
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const t = scratch;
    +  TFromD<D>* const diff = t + kTotal * N;
    +  for (size_t j = 0; j < kTotal; ++j) {
    +    StoreU(zero, d, t + j * N);
    +  }
    +
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const Vec<D> bv = LoadU(d, b + i * N);
    +    // t += a * b[i], with the low and high halves of each product separate.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> av = LoadU(d, a + j * N);
    +      const Vec<D> lo = MulAdd52Lo(av, bv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + j * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(av, bv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + kNumLimbs * N);
    +      StoreU(ShiftRight<kWideMulLimbBits>(sum), d, t + (kNumLimbs + 1) * N);
    +    }
    +
    +    // m = t[0] * n0 mod 2^52, then t += m * n and shift down by one limb. The
    +    // low limb of t cancels exactly by construction of n0, so it is dropped,
    +    // but its sum can still carry into the next limb; that is why `lo` below
    +    // adds t[0] rather than starting from zero.
    +    const Vec<D> m = MulAdd52Lo(LoadU(d, t), n0, zero);
    +    const Vec<D> n0v = LoadU(d, n);
    +    {
    +      const Vec<D> lo = MulAdd52Lo(m, n0v, LoadU(d, t));
    +      carry = Add(ShiftRight<kWideMulLimbBits>(lo), MulAdd52Hi(m, n0v, zero));
    +    }
    +    for (size_t j = 1; j < kNumLimbs; ++j) {
    +      const Vec<D> nv = LoadU(d, n + j * N);
    +      const Vec<D> lo = MulAdd52Lo(m, nv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + (j - 1) * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(m, nv, zero));
    +    }
    +    {
    +      const Vec<D> sum = Add(LoadU(d, t + kNumLimbs * N), carry);
    +      StoreU(And(sum, mask), d, t + (kNumLimbs - 1) * N);
    +      StoreU(Add(LoadU(d, t + (kNumLimbs + 1) * N),
    +                 ShiftRight<kWideMulLimbBits>(sum)),
    +             d, t + kNumLimbs * N);
    +    }
    +  }
    +
    +  // r = t[0..kNumLimbs) with an extra top limb is below 2n, so one conditional
    +  // subtraction suffices when n < R/2; a second pass makes it correct for any
    +  // odd n below R, where the value is then below 3n. Both take the borrow from
    +  // bit 63 of the wrapped difference, as SubInto does.
    +  for (int pass = 0; pass < 2; ++pass) {
    +    Vec<D> borrow = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> sub = Add(LoadU(d, n + j * N), borrow);
    +      const Vec<D> d_j = Sub(LoadU(d, t + j * N), sub);
    +      borrow = ShiftRight<63>(d_j);
    +      StoreU(And(d_j, mask), d, diff + j * N);
    +    }
    +    const Vec<D> top = Sub(LoadU(d, t + kNumLimbs * N), borrow);
    +    // The top limb is zero or one, but keep the invariant of limbs < 2^52.
    +    const Vec<D> top_masked = And(top, mask);
    +    const Mask<D> keep_diff = Eq(ShiftRight<63>(top), zero);
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      StoreU(IfThenElse(keep_diff, LoadU(d, diff + j * N), LoadU(d, t + j * N)),
    +             d, t + j * N);
    +    }
    +    StoreU(IfThenElse(keep_diff, top_masked, LoadU(d, t + kNumLimbs * N)), d,
    +           t + kNumLimbs * N);
    +  }
    +
    +  for (size_t j = 0; j < kNumLimbs; ++j) {
    +    StoreU(And(LoadU(d, t + j * N), mask), d, out + j * N);
    +  }
    +}
    +
    +}  // namespace detail
    +
    +// Montgomery modular multiplication, mirroring WideMul: the same limb layout
    +// (limb i of an operand at [i * Lanes(d)]), and a and b must be below n. The
    +// result is a * b * R^{-1} mod n with R = 2^(52 * kNumLimbs), which is below n
    +// when n < R. `n` must be odd, and n0 must come from MontgomeryN0 applied to
    +// its low limb: compute that once per modulus and reuse it.
    +//
    +// To multiply in Montgomery form, represent x as x * R mod n (which the caller
    +// computes once per value, e.g. from R^2 mod n) and multiply the
    +// representations.
    +template <size_t kNumLimbs>
    +struct Montgomery {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = kNumLimbs;
    +  // The accumulator (kNumLimbs + 2 limbs) and the tentative difference.
    +  static constexpr size_t kScratchLimbs = 2 * kNumLimbs + 2;
    +
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    detail::CiosMul<kNumLimbs>(d, a, b, n, n0, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52).
    +template <size_t kBits>
    +using MontgomeryBits =
    +    Montgomery<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +// out = R^2 mod n, with R = 2^(52 * kNumLimbs). This is the constant needed to
    +// enter Montgomery form, so the caller can convert without any modular
    +// arithmetic of its own:
    +//
    +//   ToMontgomery(x)   = Montgomery<>::Mul(x, r2, ...)
    +//   FromMontgomery(y) = Montgomery<>::Mul(y, one, ...)   // one = {1, 0, ...}
    +//
    +// n must be odd and below R, as for Montgomery<>::Mul. Both conversions are
    +// then Montgomery products, and no separate modular multiplication is required.
    +//
    +// Computed as 104*kNumLimbs modular doublings starting from 1, which is
    +// (2^(52*kNumLimbs))^2 mod n. Like the reduction, it is branch-free: the carry
    +// out of the top limb and the borrow of the conditional subtraction are
    +// combined into one per-lane select. Scratch is 2*kNumLimbs limbs per lane.
    +template <size_t kNumLimbs, class D, HWY_IF_U64_D(D)>
    +HWY_INLINE void MontgomeryR2(D d, const TFromD<D>* HWY_RESTRICT n,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const r = scratch;
    +  TFromD<D>* const diff = r + kNumLimbs * N;
    +  for (size_t j = 0; j < kNumLimbs; ++j) {
    +    StoreU(j == 0 ? Set(d, 1) : zero, d, r + j * N);
    +  }
    +
    +  for (size_t i = 0; i < 104 * kNumLimbs; ++i) {
    +    // (carry, r) = 2 * r.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> rv = LoadU(d, r + j * N);
    +      const Vec<D> sum = Add(Add(rv, rv), carry);
    +      StoreU(And(sum, mask), d, r + j * N);
    +      carry = ShiftRight<kWideMulLimbBits>(sum);
    +    }
    +    // r -= n when (carry, r) >= n; keep the difference in `diff` meanwhile.
    +    Vec<D> borrow = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> sub = Add(LoadU(d, n + j * N), borrow);
    +      const Vec<D> d_j = Sub(LoadU(d, r + j * N), sub);
    +      borrow = ShiftRight<63>(d_j);
    +      StoreU(And(d_j, mask), d, diff + j * N);
    +    }
    +    const Vec<D> top = Sub(carry, borrow);
    +    const Mask<D> keep_diff = Eq(ShiftRight<63>(top), zero);
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      StoreU(IfThenElse(keep_diff, LoadU(d, diff + j * N), LoadU(d, r + j * N)),
    +             d, r + j * N);
    +    }
    +  }
    +
    +  for (size_t j = 0; j < kNumLimbs; ++j) {
    +    StoreU(LoadU(d, r + j * N), d, out + j * N);
    +  }
    +}
    +
    +// Scratch limbs per lane needed by MontgomeryR2 (the working value and the
    +// tentative difference).
    +template <size_t kNumLimbs>
    +constexpr size_t MontgomeryR2ScratchLimbs() {
    +  return 2 * kNumLimbs;
    +}
    +
    +namespace detail {
    +
    +// Unpacks kNumLimbs 52-bit limbs from kLimbs little-endian 64-bit limbs.
    +template <size_t kNumLimbs, size_t kLimbs>
    +HWY_INLINE void UnpackLimbs52(const uint64_t* HWY_RESTRICT limbs,
    +                              uint64_t* HWY_RESTRICT out) {
    +  static_assert((kNumLimbs - 1) * kWideMulLimbBits < kLimbs * 64,
    +                "the 52-bit limbs do not fit in the 64-bit limbs");
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const size_t bit = i * kWideMulLimbBits;
    +    const size_t limb = bit / 64;
    +    const size_t offset = bit % 64;
    +    uint64_t v = limbs[limb] >> offset;
    +    if (offset + kWideMulLimbBits > 64) {
    +      v |= (limb + 1 < kLimbs ? limbs[limb + 1] : uint64_t{0}) << (64 - offset);
    +    }
    +    out[i] = v & kWideMulLimbMask;
    +  }
    +}
    +
    +// Packs kNumLimbs 52-bit limbs into kLimbs little-endian 64-bit limbs.
    +template <size_t kNumLimbs, size_t kLimbs>
    +HWY_INLINE void PackLimbs52(const uint64_t* HWY_RESTRICT in,
    +                            uint64_t* HWY_RESTRICT limbs) {
    +  size_t src = 0;
    +  size_t src_bit = 0;
    +  for (size_t j = 0; j < kLimbs; ++j) {
    +    uint64_t v = 0;
    +    size_t dst_bit = 0;
    +    size_t need = 64;
    +    while (need != 0 && src < kNumLimbs) {
    +      const size_t avail = kWideMulLimbBits - src_bit;
    +      const size_t take = HWY_MIN(need, avail);
    +      const uint64_t part = (in[src] >> src_bit) & ((uint64_t{1} << take) - 1);
    +      v |= part << dst_bit;
    +      dst_bit += take;
    +      need -= take;
    +      src_bit += take;
    +      if (src_bit == kWideMulLimbBits) {
    +        ++src;
    +        src_bit = 0;
    +      }
    +    }
    +    limbs[j] = v;
    +  }
    +}
    +
    +// Scalar Comba over 52-bit limbs; the same math as the vector kernel, one lane
    +// at a time.
    +template <size_t kNumLimbs>
    +HWY_INLINE void ScalarCombaMul(const uint64_t* HWY_RESTRICT a,
    +                               const uint64_t* HWY_RESTRICT b,
    +                               uint64_t* HWY_RESTRICT out) {
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  uint64_t carry = 0;
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    uint64_t lo = carry;
    +    uint64_t hi = 0;
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      uint64_t p_hi;
    +      const uint64_t p_lo = Mul128(a[i], b[k - i], &p_hi);
    +      lo += p_lo & kWideMulLimbMask;
    +      hi += (p_lo >> kWideMulLimbBits) | (p_hi << (64 - kWideMulLimbBits));
    +    }
    +    out[k] = lo & kWideMulLimbMask;
    +    carry = (lo >> kWideMulLimbBits) + hi;
    +  }
    +  out[kNumOutLimbs - 1] = carry & kWideMulLimbMask;
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kBits-bit unsigned integers, both given as little-endian
    +// 64-bit limbs (kBits/64 each), and writes the 2*kBits/64-limb product. This is
    +// a scalar convenience over the 52-bit limb core, e.g. for u128/u192/u256; it
    +// does not use the vector unit. kBits must be a multiple of 64.
    +//
    +// The top of the result may be a partial 52-bit limb (e.g. a 128-bit product
    +// has 256 bits, so its 5th limb holds 48 bits); the remaining bits are zero
    +// because the product fits.
    +template <size_t kBits>
    +HWY_INLINE void WideMulLimbs(const uint64_t* HWY_RESTRICT a,
    +                             const uint64_t* HWY_RESTRICT b,
    +                             uint64_t* HWY_RESTRICT out) {
    +  static_assert(kBits % 64 == 0, "kBits must be a multiple of 64");
    +  constexpr size_t kLimbs = kBits / 64;
    +  constexpr size_t kNumLimbs =
    +      (kBits + kWideMulLimbBits - 1) / kWideMulLimbBits;
    +  uint64_t a52[kNumLimbs];
    +  uint64_t b52[kNumLimbs];
    +  uint64_t r52[2 * kNumLimbs];
    +  detail::UnpackLimbs52<kNumLimbs, kLimbs>(a, a52);

    Seems like callers should have some way to access the Unpack API (better yet, vectorized).

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:28 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {
    +    if (scratch != nullptr) {
    +      KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +      return;
    +    }
    +  }
    +  CombaMul<kNumLimbs>(d, a, b, out);
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kNumLimbs-limb unsigned integers into 2*kNumLimbs limbs. `d`
    +// must be a u64 vector descriptor; `a`, `b` and `out` point to arrays of at
    +// least kNumLimbs*N, kNumLimbs*N and 2*kNumLimbs*N elements respectively, N
    +// being Lanes(d). All input limbs must be < 2^52, as MulAdd52* requires; only
    +// the low 52 bits of each are used. `out` must not overlap `a` or `b`.
    +//
    +// kNumLimbs is limited so that the per-limb accumulators cannot overflow 64
    +// bits: each holds at most kNumLimbs products < 2^52, plus the carry from the
    +// previous limb, which is itself below kNumLimbs * (2^52 + 1). 1024 therefore
    +// leaves ample headroom below 2^64.
    +template <size_t kNumLimbs>
    +struct WideMul {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = 2 * kNumLimbs;
    +  // Limbs of T per lane required by the Karatsuba overload below; zero when
    +  // this size does not use Karatsuba.
    +  static constexpr size_t kScratchLimbs = detail::MulScratchLimbs<kNumLimbs>();
    +
    +  // Comba: no scratch, always available. This is also what the recursive calls
    +  // fall back to for small or odd sizes.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out) {
    +    detail::CombaMul<kNumLimbs>(d, a, b, out);
    +  }
    +
    +  // Karatsuba: fewer multiplies above kWideMulKaratsubaMinLimbs limbs, but the
    +  // caller must supply scratch of kScratchLimbs * Lanes(d) elements. Nothing is
    +  // allocated here, and `scratch` must not overlap `a`, `b` or `out`.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    static_assert(kScratchLimbs != 0,
    +                  "this size does not use Karatsuba; call Mul without scratch");
    +    detail::KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52), so e.g.
    +// `WideMulBits<256>` multiplies 256-bit values held as 5 limbs each.
    +template <size_t kBits>
    +using WideMulBits = WideMul<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +namespace detail {}  // namespace detail
    +
    +// ------------------------------ Montgomery
    +
    +// Returns -x^{-1} mod 2^52 for every lane, given the low limb of the modulus,
    +// which must be odd. This is the constant that makes the low limb of T + m*N
    +// vanish, so callers compute it once per modulus and reuse it for every
    +// multiplication.
    +template <class D, HWY_IF_U64_D(D)>
    +HWY_INLINE Vec<D> MontgomeryN0(D d, Vec<D> n0) {
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> two = Set(d, 2);
    +  // Newton iteration for the inverse modulo 2^52. Each step doubles the number
    +  // of correct bits, starting from 3 (x*x = 1 mod 8 for odd x), so six steps
    +  // cover 3, 6, 12, 24, 48 and 96 bits. MulAdd52Lo is the low 52 bits of a
    +  // product, which is exact here because every value is below 2^52.
    +  Vec<D> x = n0;
    +  for (int i = 0; i < 6; ++i) {
    +    const Vec<D> t = MulAdd52Lo(n0, x, zero);  // n0 * x mod 2^52
    +    // 2 - t mod 2^52: negate modulo 2^64, add, then mask.
    +    const Vec<D> complement = And(Add(Sub(zero, t), two), mask);
    +    x = MulAdd52Lo(x, complement, zero);
    +  }
    +  return And(Sub(zero, x), mask);  // -x mod 2^52
    +}
    +
    +namespace detail {
    +
    +// out = a * b * R^{-1} mod n by CIOS (Koc): alternate one row of the product
    +// with one step of the reduction, so the working array is only kNumLimbs + 2
    +// limbs and no full 2*kNumLimbs product is needed. Scratch is kTotal limbs for
    +// the accumulator plus kNumLimbs for the tentative difference.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CiosMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                        const TFromD<D>* HWY_RESTRICT b,
    +                        const TFromD<D>* HWY_RESTRICT n, Vec<D> n0,
    +                        TFromD<D>* HWY_RESTRICT out,
    +                        TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kTotal = kNumLimbs + 2;
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +
    +  TFromD<D>* const t = scratch;
    +  TFromD<D>* const diff = t + kTotal * N;
    +  for (size_t j = 0; j < kTotal; ++j) {
    +    StoreU(zero, d, t + j * N);
    +  }
    +
    +  for (size_t i = 0; i < kNumLimbs; ++i) {
    +    const Vec<D> bv = LoadU(d, b + i * N);
    +    // t += a * b[i], with the low and high halves of each product separate.
    +    Vec<D> carry = zero;
    +    for (size_t j = 0; j < kNumLimbs; ++j) {
    +      const Vec<D> av = LoadU(d, a + j * N);
    +      const Vec<D> lo = MulAdd52Lo(av, bv, LoadU(d, t + j * N));
    +      const Vec<D> sum = Add(lo, carry);
    +      StoreU(And(sum, mask), d, t + j * N);
    +      carry = Add(ShiftRight<kWideMulLimbBits>(sum), MulAdd52Hi(av, bv, zero));

    We should fuse the Add() into the MulAdd52Hi instead of passing zero.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:31 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;

    Longer names would be useful here.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:33 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};

    Rather than zero-init then add, we can copy z0 and z2 directly into the two halves.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:34 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {

    Supporting odd kNumLimbs seems important because crypto bignums often use pow2 and pow2 / 52 / 2 is odd .

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:37 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));

    Here And(carry_a, carry_b) is the condition for adding 1. I think we can just add And(carry_a, carry_b) directly.

    jan-wassenberg jan-wassenberg commented on code on Sep 21, 2026 15:41 UTC
    Code Review
    hwy/contrib/multiprec/multiprec-inl.h:1
    @@ -0,0 +1,661 @@
    +// Copyright 2026 Google LLC
    +// SPDX-License-Identifier: Apache-2.0
    +//
    +// Licensed under the Apache License, Version 2.0 (the "License");
    +// you may not use this file except in compliance with the License.
    +// You may obtain a copy of the License at
    +//
    +//      http://www.apache.org/licenses/LICENSE-2.0
    +//
    +// Unless required by applicable law or agreed to in writing, software
    +// distributed under the License is distributed on an "AS IS" BASIS,
    +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +// See the License for the specific language governing permissions and
    +// limitations under the License.
    +
    +// Per-target include guard
    +#if defined(HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_) == \
    +    defined(HWY_TARGET_TOGGLE)  // NOLINT
    +#ifdef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#undef HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#else
    +#define HIGHWAY_HWY_CONTRIB_MULTIPREC_MULTIPREC_INL_H_
    +#endif
    +
    +#include <stddef.h>
    +#include <stdint.h>
    +
    +#include "hwy/highway.h"
    +
    +HWY_BEFORE_NAMESPACE();
    +namespace hwy {
    +namespace HWY_NAMESPACE {
    +
    +// Fixed-width unsigned integer multiplication for arbitrary precision.
    +//
    +// Limbs are 52 bits: the largest width for which the IFMA MulAdd52Lo/Hi ops are
    +// exact, since for inputs < 2^52 the two together return the full 104-bit
    +// product exactly. They exist on every target (native HWY_NATIVE_MULADD52 where
    +// available, the generic fallback otherwise), so there is no separate code
    +// path. The 12 bits left over in each 64-bit word are what GMP calls nails;
    +// here they are simply unused.
    +//
    +// Layout is SoA in both directions: limb i (little-endian) of each operand
    +// lives at a[i * N .. i * N + N), where N = Lanes(d). The lanes hold
    +// independent multiplications, which is how crypto (several RSA/ECC instances
    +// in parallel) uses this.
    +//
    +// Operands, results and scratch are arrays of T (= TFromD<D>), not arrays of
    +// vectors: vector types are sizeless on SVE and RVV, so they cannot be stored
    +// in arrays. The kernel therefore keeps only a few vector locals live and
    +// Loads/Stores around them.
    +//
    +// This header only multiplies. Reduction, in particular Montgomery, is the next
    +// layer callers need - that is why the directory is multiprec rather than
    +// wide_mul - but it is not implemented here yet.
    +
    +constexpr size_t kWideMulLimbBits = 52;
    +constexpr uint64_t kWideMulLimbMask = (uint64_t{1} << kWideMulLimbBits) - 1;
    +
    +namespace detail {
    +
    +// out = a * b, both kNumLimbs limbs, using Comba's method: for each output limb
    +// k, sum the products a[i] * b[k-i]. Only three vectors are live at a time (the
    +// carry and the low/high accumulator pair), so this does not spill even for
    +// large kNumLimbs, unlike accumulating all 2*kNumLimbs-1 columns at once.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void CombaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                         const TFromD<D>* HWY_RESTRICT b,
    +                         TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kNumOutLimbs = 2 * kNumLimbs;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +
    +  Vec<D> carry = Zero(d);
    +  for (size_t k = 0; k < kNumOutLimbs - 1; ++k) {
    +    // Sum the low and high halves of each product separately; both accumulators
    +    // fit in 64 bits because there are at most kNumLimbs terms, each < 2^52.
    +    Vec<D> lo = carry;
    +    Vec<D> hi = Zero(d);
    +    const size_t i_begin = k >= kNumLimbs - 1 ? k - (kNumLimbs - 1) : 0;
    +    const size_t i_end = HWY_MIN(k, kNumLimbs - 1);
    +    for (size_t i = i_begin; i <= i_end; ++i) {
    +      const Vec<D> av = LoadU(d, a + i * N);
    +      const Vec<D> bv = LoadU(d, b + (k - i) * N);
    +      lo = MulAdd52Lo(av, bv, lo);
    +      hi = MulAdd52Hi(av, bv, hi);
    +    }
    +    StoreU(And(lo, mask), d, out + k * N);
    +    carry = Add(ShiftRight<kWideMulLimbBits>(lo), hi);
    +  }
    +  // The product has at most 104 * kNumLimbs bits, so the remaining carry fits
    +  // in the top limb.
    +  StoreU(And(carry, mask), d, out + (kNumOutLimbs - 1) * N);
    +}
    +
    +// out[i] = a[i] + b[i] for i < kCount, returning the carry-out (0 or 1 per
    +// lane) rather than storing it. Both operands must be < 2^52.
    +template <class D>
    +HWY_INLINE Vec<D> AddLimbsCarry(D d, const TFromD<D>* HWY_RESTRICT a,
    +                                const TFromD<D>* HWY_RESTRICT b, size_t kCount,
    +                                TFromD<D>* HWY_RESTRICT out) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kCount; ++i) {
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, a + i * N), LoadU(d, b + i * N)), carry);
    +    StoreU(And(sum, mask), d, out + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  return carry;
    +}
    +
    +// dst[kOffset + i] += src[i] for i < kCount, clamped so nothing is written at
    +// or past kTotal, with carry ripple. kOffset indexes the destination, and the
    +// same convention is used by AddIntoIf and SubInto below.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> sum = Add(
    +        Add(LoadU(d, dst + (kOffset + i) * N), LoadU(d, src + i * N)), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] += src[i] where `condition` is 1, for i < kCount, with carry
    +// ripple. `condition` is 0 or 1 per lane, so no branch is taken and secrets do
    +// not affect control flow.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void AddIntoIf(D d, TFromD<D>* HWY_RESTRICT dst,
    +                          const TFromD<D>* HWY_RESTRICT src, Vec<D> condition) {
    +  const size_t N = Lanes(d);
    +  constexpr size_t kUsed =
    +      kCount <= kTotal - kOffset ? kCount : kTotal - kOffset;
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  // 0 - condition is either 0 or all-ones, which turns the addend on or off.
    +  const Vec<D> select = Sub(Zero(d), condition);
    +  Vec<D> carry = Zero(d);
    +  for (size_t i = 0; i < kUsed; ++i) {
    +    const Vec<D> addend = And(LoadU(d, src + i * N), select);
    +    const Vec<D> sum =
    +        Add(Add(LoadU(d, dst + (kOffset + i) * N), addend), carry);
    +    StoreU(And(sum, mask), d, dst + (kOffset + i) * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +  for (size_t i = kOffset + kUsed; i < kTotal; ++i) {
    +    const Vec<D> sum = Add(LoadU(d, dst + i * N), carry);
    +    StoreU(And(sum, mask), d, dst + i * N);
    +    carry = ShiftRight<kWideMulLimbBits>(sum);
    +  }
    +}
    +
    +// dst[kOffset + i] -= src[i] for i < kCount, zero-extending src; the result
    +// must be non-negative. Same kOffset convention as AddInto.
    +template <size_t kOffset, size_t kCount, size_t kTotal, class D>
    +HWY_INLINE void SubInto(D d, TFromD<D>* HWY_RESTRICT dst,
    +                        const TFromD<D>* HWY_RESTRICT src) {
    +  const size_t N = Lanes(d);
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  Vec<D> borrow = Zero(d);
    +  for (size_t i = 0; i < kTotal; ++i) {
    +    const Vec<D> sv = i < kCount ? LoadU(d, src + i * N) : Zero(d);
    +    const Vec<D> sub = Add(sv, borrow);
    +    const Vec<D> diff = Sub(LoadU(d, dst + (kOffset + i) * N), sub);
    +    // Both operands are below 2^52, so an underflow sets bit 63 of the wrapped
    +    // difference: no comparison (and hence no mask) is needed.
    +    borrow = ShiftRight<63>(diff);
    +    StoreU(And(diff, mask), d, dst + (kOffset + i) * N);
    +  }
    +}
    +
    +// Karatsuba pays off above this many limbs, and only for even counts (see
    +// MulRec).
    +constexpr size_t kWideMulKaratsubaMinLimbs = 8;
    +
    +// Scratch limbs per lane that Karatsuba needs for a given size. The layout
    +// below is z0 and z2 (kMid = kNumLimbs limbs each), s and t (kHalf each), st
    +// (kMid + 2) and one limb holding the constant 1, i.e. 4*kNumLimbs + 3 in
    +// total; the child's requirement is added once because the three recursive
    +// products run one after another. Zero when the size does not use Karatsuba.
    +template <size_t kNumLimbs>
    +constexpr size_t MulScratchLimbs() {
    +  return (kNumLimbs < kWideMulKaratsubaMinLimbs || (kNumLimbs & 1) != 0)
    +             ? 0
    +             : 4 * kNumLimbs + 4 + MulScratchLimbs<kNumLimbs / 2>();
    +}
    +
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch);
    +
    +// out = a * b by Karatsuba: split into two halves of kHalf limbs and recurse at
    +// kHalf, never at kHalf + 1, so the recursion stays on the same size and the
    +// base case is Comba. The carries of a_lo + a_hi and b_lo + b_hi are tracked
    +// separately (as 0/1 vectors) and folded back in with masked adds, instead of
    +// growing the summed operands to kHalf + 1 limbs.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void KaratsubaMul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +  constexpr size_t kHalf = kNumLimbs / 2;
    +  constexpr size_t kMid = 2 * kHalf;
    +  constexpr size_t kTotal = 2 * kNumLimbs;
    +  const size_t N = Lanes(d);
    +
    +  // All buffers are arrays of T, which is what makes this portable to targets
    +  // whose vector types are sizeless:
    +  //   z0, z2: kMid limbs each; s, t: kHalf each; st: kMid + 2; one: 1 limb;
    +  //   child: the child's own scratch.
    +  TFromD<D>* const z0 = scratch;
    +  TFromD<D>* const z2 = z0 + kMid * N;
    +  TFromD<D>* const s = z2 + kMid * N;
    +  TFromD<D>* const t = s + kHalf * N;
    +  TFromD<D>* const st = t + kHalf * N;
    +  TFromD<D>* const one = st + (kMid + 2) * N;
    +  TFromD<D>* const child = one + N;
    +
    +  // z0 = a_lo * b_lo, z2 = a_hi * b_hi.
    +  MulRec<kHalf>(d, a, b, z0, child);
    +  MulRec<kHalf>(d, a + kHalf * N, b + kHalf * N, z2, child);
    +
    +  // s = a_lo + a_hi, t = b_lo + b_hi, kHalf limbs each, with the carry kept
    +  // aside rather than stored.
    +  const Vec<D> carry_a = AddLimbsCarry(d, a, a + kHalf * N, kHalf, s);
    +  const Vec<D> carry_b = AddLimbsCarry(d, b, b + kHalf * N, kHalf, t);
    +
    +  // st = s * t, and the two limbs above kMid start at zero.
    +  MulRec<kHalf>(d, s, t, st, child);
    +  const Vec<D> zero = Zero(d);
    +  for (size_t i = kMid; i < kMid + 2; ++i) {
    +    StoreU(zero, d, st + i * N);
    +  }
    +
    +  // z1 = s*t - z0 - z2 = a_lo*b_hi + a_hi*b_lo, at limb 0 of st.
    +  SubInto<0, kMid, kMid + 2>(d, st, z0);
    +  SubInto<0, kMid, kMid + 2>(d, st, z2);
    +
    +  // s*t also contains carry_a * t * B^kHalf, carry_b * s * B^kHalf and
    +  // carry_a * carry_b * B^kMid, which the two subtractions above did not remove
    +  // because they were not part of z0 or z2.
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, t, carry_a);
    +  AddIntoIf<kHalf, kHalf, kMid + 2>(d, st, s, carry_b);
    +  StoreU(Set(d, uint64_t{1}), d, one);
    +  AddIntoIf<kMid, 1, kMid + 2>(d, st, one, And(carry_a, carry_b));
    +
    +  // out = z0 + z1 * B^kHalf + z2 * B^kMid.
    +  for (size_t i = 0; i < kTotal * N; ++i) out[i] = TFromD<D>{0};
    +  AddInto<0, kMid, kTotal>(d, out, z0);
    +  AddInto<kMid, kMid, kTotal>(d, out, z2);
    +  AddInto<kHalf, kMid + 2, kTotal>(d, out, st);
    +}
    +
    +// Dispatches to Karatsuba when the size is even and large enough and scratch is
    +// available, else Comba. `if constexpr` keeps Karatsuba out of odd sizes, whose
    +// split would not be balanced.
    +template <size_t kNumLimbs, class D>
    +HWY_INLINE void MulRec(D d, const TFromD<D>* HWY_RESTRICT a,
    +                       const TFromD<D>* HWY_RESTRICT b,
    +                       TFromD<D>* HWY_RESTRICT out,
    +                       TFromD<D>* HWY_RESTRICT scratch) {
    +  if constexpr (kNumLimbs >= kWideMulKaratsubaMinLimbs &&
    +                (kNumLimbs & 1) == 0) {
    +    if (scratch != nullptr) {
    +      KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +      return;
    +    }
    +  }
    +  CombaMul<kNumLimbs>(d, a, b, out);
    +}
    +
    +}  // namespace detail
    +
    +// Multiplies two kNumLimbs-limb unsigned integers into 2*kNumLimbs limbs. `d`
    +// must be a u64 vector descriptor; `a`, `b` and `out` point to arrays of at
    +// least kNumLimbs*N, kNumLimbs*N and 2*kNumLimbs*N elements respectively, N
    +// being Lanes(d). All input limbs must be < 2^52, as MulAdd52* requires; only
    +// the low 52 bits of each are used. `out` must not overlap `a` or `b`.
    +//
    +// kNumLimbs is limited so that the per-limb accumulators cannot overflow 64
    +// bits: each holds at most kNumLimbs products < 2^52, plus the carry from the
    +// previous limb, which is itself below kNumLimbs * (2^52 + 1). 1024 therefore
    +// leaves ample headroom below 2^64.
    +template <size_t kNumLimbs>
    +struct WideMul {
    +  static_assert(kNumLimbs >= 1, "need at least one limb");
    +  static_assert(kNumLimbs <= 1024, "accumulators may overflow");
    +  static constexpr size_t kNumResultLimbs = 2 * kNumLimbs;
    +  // Limbs of T per lane required by the Karatsuba overload below; zero when
    +  // this size does not use Karatsuba.
    +  static constexpr size_t kScratchLimbs = detail::MulScratchLimbs<kNumLimbs>();
    +
    +  // Comba: no scratch, always available. This is also what the recursive calls
    +  // fall back to for small or odd sizes.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out) {
    +    detail::CombaMul<kNumLimbs>(d, a, b, out);
    +  }
    +
    +  // Karatsuba: fewer multiplies above kWideMulKaratsubaMinLimbs limbs, but the
    +  // caller must supply scratch of kScratchLimbs * Lanes(d) elements. Nothing is
    +  // allocated here, and `scratch` must not overlap `a`, `b` or `out`.
    +  template <class D, HWY_IF_U64_D(D)>
    +  static HWY_INLINE void Mul(D d, const TFromD<D>* HWY_RESTRICT a,
    +                             const TFromD<D>* HWY_RESTRICT b,
    +                             TFromD<D>* HWY_RESTRICT out,
    +                             TFromD<D>* HWY_RESTRICT scratch) {
    +    static_assert(kScratchLimbs != 0,
    +                  "this size does not use Karatsuba; call Mul without scratch");
    +    detail::KaratsubaMul<kNumLimbs>(d, a, b, out, scratch);
    +  }
    +};
    +
    +// Bit-width form of the API above: kNumLimbs = ceil(kBits / 52), so e.g.
    +// `WideMulBits<256>` multiplies 256-bit values held as 5 limbs each.
    +template <size_t kBits>
    +using WideMulBits = WideMul<(kBits + kWideMulLimbBits - 1) / kWideMulLimbBits>;
    +
    +namespace detail {}  // namespace detail
    +
    +// ------------------------------ Montgomery
    +
    +// Returns -x^{-1} mod 2^52 for every lane, given the low limb of the modulus,
    +// which must be odd. This is the constant that makes the low limb of T + m*N
    +// vanish, so callers compute it once per modulus and reuse it for every
    +// multiplication.
    +template <class D, HWY_IF_U64_D(D)>
    +HWY_INLINE Vec<D> MontgomeryN0(D d, Vec<D> n0) {
    +  const Vec<D> mask = Set(d, kWideMulLimbMask);
    +  const Vec<D> zero = Zero(d);
    +  const Vec<D> two = Set(d, 2);
    +  // Newton iteration for the inverse modulo 2^52. Each step doubles the number
    +  // of correct bits, starting from 3 (x*x = 1 mod 8 for odd x), so six steps
    +  // cover 3, 6, 12, 24, 48 and 96 bits. MulAdd52Lo is the low 52 bits of a
    +  // product, which is exact here because every value is below 2^52.
    +  Vec<D> x = n0;

    I think we can get this to === 1 mod 32 (5 correct bits) with Xor(Add(Add(n0, n0), n0), Set(d, 2)). Then we only have to loop/double 4 times to get 80 > 52 bits.

    jan-wassenberg jan-wassenberg requested changes on Sep 21, 2026 15:42 UTC
    Changes Requested Reviewer

    Some more comments :)
    If there is a domain expert here, their input would be very welcome.

    Assignees
    tvost2 tvost2
    Labels
    risk: low confidence: 89.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 48.9% (MEDIUM) · Higher = larger blast radius
    48.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.2% · Lower = rushed or shallow review
    89.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 5.3% · Safe to merge
    5.3%
    Repository