SIMD Vectors

Description

boost::safe_numbers::simd::vec<T, N> holds N values of a safe type T and checks a whole vector at a time. Each operation computes every lane without branching, builds a mask of the lanes where the scalar operation would report an error, and tests that mask once. A loop over vectors therefore pays one error branch per vector operation instead of one per element.

C26 adds `<simd>` (`std::simd::vec`), but only the standard integer, character, and floating-point types are vectorizable, and its lane operations have no overflow detection. `simd::vec` wraps a vector of the basis type and adds the checks, so it follows the C26 interface closely while keeping every rule of the scalar safe types.

The header is opt-in and is not part of the convenience header <boost/safe_numbers.hpp>:

#include <boost/safe_numbers/simd.hpp>

This release supports the unsigned element types u8, u16, u32, u64, the signed element types i8, i16, i32, i64, and their policy forms (sat_u32, strict_i64, basic_i32<H>, and so on).

The Semantic Rule

For every policy, lane i of a vector operation equals the scalar operation on lane i. When the scalar loop over i = 0 …​ N - 1 would throw or exit, the vector operation throws the same exception type with the same message as the lowest failing lane, and produces no result.

  • throw_exception elements throw exactly what the scalar type throws.

  • saturate elements clamp every failing lane, branch free. Division and modulo by zero still throw std::domain_error, as in the scalar types.

  • strict elements call std::exit(EXIT_FAILURE).

  • User defined handlers are called once for every failing lane, in lane order, with exactly the arguments the scalar type passes, and their return values become those lanes.

When the error mask has any lane set, the vector replays the scalar operation lane by lane on a cold, out of line path. The exception classification, the messages, and the handler arguments therefore come from the scalar types themselves.

Compound assignment and ++/-- compute the result before storing it, so a vector that throws is left unchanged.

Backends

Backend Selected when Lane storage

std::simd

The standard library provides <simd>: today GCC 16 libstdc with `-std=c26` on x86 (SSE2 or later)

std::simd::vec<basis_type, N>

Portable fallback

Every other C++20 configuration, or whenever BOOST_SAFE_NUMBERS_SIMD_FORCE_ARRAY_BACKEND is defined

std::array<basis_type, N> with lane loops written for auto vectorization

BOOST_SAFE_NUMBERS_HAS_STD_SIMD is defined when the std::simd backend is in use. Detection uses cpp_lib_simd or libstdc's `__glibcxx_simd`, because libstdc 16 does not define cpp_lib_simd. Both backends run the same safe number logic, and the interface is identical except for the std::simd::vec conversions listed below.

The default lane count N is implementation defined: one native register on the std::simd backend and 16 bytes worth of lanes on the fallback. Use an explicit N whenever the layout matters, for example in a data structure or a file format.

The fallback is a correctness first implementation. With GCC and Clang at -O2 on x86-64 and ARM64, its addition and saturating addition vectorize with a single error branch (none for saturation), while multiplication and 64-bit lanes are partly or entirely scalar, and GCC may call the multiplication kernel out of line. On the std::simd backend (GCC 16, x86-64, -O2), checked addition, subtraction, and multiplication compile to vector lane operations, one mask extraction, and one branch, with no calls on the path that does not fail.

With AVX-512, GCC 16’s <simd> pads a vector whose lane count is not a power of two with zero lanes, and its / and % may divide those lanes too, which raises SIGFPE. simd::vec divides lane by lane in exactly that configuration, and uses the vector division everywhere else.

GCC 16’s <simd> returns 32-byte vectors from internal helpers when AVX is not enabled, which -Wpsabi reports at the end of the translation unit even for plain std::simd code. Under -Werror, add -Wno-psabi or #pragma GCC diagnostic ignored "-Wpsabi" to translation units that use vectors of 32 bytes or more (including the 64-bit lanes the 32-bit multiplication check widens into).

Synopsis

#include <boost/safe_numbers/simd.hpp>

namespace boost::safe_numbers::simd {

template <typename T, int N = /* implementation defined */>
class vec
{
public:
    using value_type = T;
    using basis_type = typename T::basis_type;
    using mask_type = /* std::simd::mask<basis_type, N> or a fallback mask with the same interface */;

    static constexpr auto error_policy {T::error_policy};
    static constexpr std::integral_constant<int, N> size {};

    // Zero in every lane
    constexpr vec() noexcept = default;

    // Broadcast: only the exact element type
    template <typename U> requires std::is_same_v<U, T>
    explicit constexpr vec(U x) noexcept;

    // Lane i is gen(std::integral_constant<int, i>{}); gen must return exactly T
    template <typename G>
    explicit constexpr vec(G&& gen);

    // Raw lane interop on every backend
    explicit constexpr vec(const std::array<basis_type, N>& lanes) noexcept;
    explicit constexpr operator std::array<basis_type, N>() const noexcept;

    // Only when BOOST_SAFE_NUMBERS_HAS_STD_SIMD is defined
    explicit constexpr vec(const std::simd::vec<basis_type, N>& lanes) noexcept;
    explicit constexpr operator std::simd::vec<basis_type, N>() const noexcept;

    // Lane conversion as the scalar types convert; an out of range lane throws
    // std::domain_error whatever the policy
    template <typename U>
    explicit constexpr vec(const vec<U, N>& other);

    // Read only lane access. Precondition: 0 <= i < N
    constexpr T operator[](int i) const noexcept;

    // Compound assignment for + - * / %, and for unsigned elements & | ^ << >>, with a vec or a T
    template <typename U> constexpr vec& operator+=(const U& rhs);
    // ...

    constexpr vec& operator++();
    constexpr vec operator++(int);
    constexpr vec& operator--();
    constexpr vec operator--(int);
    constexpr vec operator+() const noexcept;
};

// Arithmetic: + - * / % with the element's error policy
// Unsigned elements only: << >> and the bitwise & | ^ ~
// Signed elements only: unary -
// Comparisons: == != < <= > >= return mask_type
// Each binary operator also accepts (vec, T) and (T, vec), which broadcast the element.

// Free function families, as for the scalar types
template <typename T, int N> constexpr vec<T, N> saturating_add(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr std::pair<vec<T, N>, typename vec<T, N>::mask_type> overflowing_add(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr std::optional<vec<T, N>> checked_add(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> strict_add(const vec<T, N>&, const vec<T, N>&) noexcept;
// ... and likewise for sub, mul, div, mod, and for unsigned elements shl, shr

// Exact results in lanes twice as wide (8, 16, and 32-bit lanes)
template <typename T, int N> constexpr auto widening_add(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr auto widening_mul(const vec<T, N>&, const vec<T, N>&) noexcept;

// Policy chosen at the call site
template <overflow_policy Policy, typename T, int N> constexpr auto add(const vec<T, N>&, const vec<T, N>&);
// ... and likewise sub, mul, div, mod, and for unsigned elements shl, shr

// Lane algorithms
template <typename T, int N> constexpr vec<T, N> select(const typename vec<T, N>::mask_type&, const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> min(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> max(const vec<T, N>&, const vec<T, N>&) noexcept;
template <typename T, int N> constexpr vec<T, N> clamp(const vec<T, N>& v, const vec<T, N>& lo, const vec<T, N>& hi) noexcept;

// Reductions: reduce folds left in lane order with the element's operation
template <typename T, int N, typename BinaryOperation = std::plus<>> constexpr T reduce(const vec<T, N>&, BinaryOperation = {});
template <typename T, int N> constexpr T reduce_min(const vec<T, N>&) noexcept;
template <typename T, int N> constexpr T reduce_max(const vec<T, N>&) noexcept;

// Mask reductions (std::simd's own on the std::simd backend)
using /* ... */::all_of;
using /* ... */::any_of;
using /* ... */::none_of;
using /* ... */::reduce_count;
using /* ... */::reduce_min_index;
using /* ... */::reduce_max_index;

// Loads and stores of exactly the element type
template <typename V, typename R> constexpr V unchecked_load(R&& r) noexcept;
template <typename V, typename It> constexpr V unchecked_load(It first, std::iter_difference_t<It> n) noexcept;
template <typename V, typename R> constexpr V partial_load(R&& r) noexcept;
template <typename V, typename It> constexpr V partial_load(It first, std::iter_difference_t<It> n) noexcept;
template <typename T, int N, typename R> constexpr void unchecked_store(const vec<T, N>&, R&& r) noexcept;
template <typename T, int N, typename It> constexpr void unchecked_store(const vec<T, N>&, It first, std::iter_difference_t<It> n) noexcept;
template <typename T, int N, typename R> constexpr void partial_store(const vec<T, N>&, R&& r) noexcept;
template <typename T, int N, typename It> constexpr void partial_store(const vec<T, N>&, It first, std::iter_difference_t<It> n) noexcept;

} // namespace boost::safe_numbers::simd

Element Types and Mixing

The element type and its error policy are part of the vector type, and mixing follows the scalar rules exactly:

  • Operations take two vectors of the same element type and lane count, or a vector and one value of its element type, which is broadcast.

  • Mixed widths (vec<u32, 4> + vec<u16, 4>), mixed signedness (vec<i32, 4> + vec<u32, 4>), mixed policies (vec<u32, 4> + vec<sat_u32, 4>), mixed lane counts (vec<u32, 4> + vec<u32, 8>), and built-in operands (v + 1U) are compile time errors with a static_assert message.

  • u128 and i128 elements are rejected, because std::simd has no 128-bit lanes, and so are the bounded types.

  • Unary minus is rejected for unsigned elements, and the bitwise and shift operators for signed elements, as for the scalar types.

  • The converting constructor converts between widths and policies of one signedness only. The scalar types never convert between signed and unsigned, so neither do the vectors.

A mask_type is keyed on the lane size, so a mask from a vector of u64 can not select between vectors of u32 on either backend.

Construction, Loads, and Stores

The loads and stores read and write contiguous ranges of exactly the element type (std::array, std::vector, std::span, built-in arrays), or an iterator and a count. Lanes are copied through each element’s conversion to its basis type, so there is no reinterpret_cast and the copies compile to vector loads and stores.

  • unchecked_load and unchecked_store require at least N elements; a range with a static extent shorter than N is a compile time error.

  • partial_load reads min(size, N) elements and zero fills the remaining lanes; partial_store writes min(size, N) lanes.

Built-in data moves through the raw lane conversions, vec(const std::array<basis_type, N>&) and operator std::array<basis_type, N>(), which never check anything because every basis value is a valid lane.

Unsigned Operations

Operation Error lanes Error under throw_exception

`, `+

The sum wraps

std::overflow_error

-, --

The difference would be negative

std::underflow_error

*

The product exceeds the maximum

std::overflow_error

/, %

The divisor is zero

std::domain_error (also under saturate)

<<

bit_width(lhs) + rhs >= digits, as in the scalar types

std::overflow_error

>>

rhs >= digits

std::overflow_error

&, |, ^, ~

Never

None

Every lane computation is free of undefined behavior. Lanes narrower than int multiply in lanes of twice their width, because u16 * u16 promotes to a signed int in which 65535 * 65535 overflows. Shift counts are sanitized before shifting, and a zero divisor lane takes the error path before any lane is divided.

The 64-bit multiplication has no 128-bit lane to widen into, so it splits each operand into 32-bit halves held in 64-bit lanes. The product overflows exactly when both high halves are nonzero, when the cross term ah * bl + al * bh reaches 2^32, or when adding the shifted cross term to al * bl carries out. Every operation stays in vector lanes on every target, so the speed of each one follows the vector instructions of the target and the standard library.

The overflowing_* functions return the wrapped lanes and the error mask, and checked_* return std::nullopt when any lane fails. Division and modulo still throw std::domain_error on a zero divisor in the saturating_* and overflowing_* families, exactly as the scalar functions do.

Signed Operations

Operation Error lanes Error under throw_exception

`, `-`, `*`, `+, --

The exact result is above the maximum, or below the minimum

std::overflow_error or std::underflow_error respectively

/, %

The divisor is zero

std::domain_error (also under saturate)

/, %

min / -1 and min % -1

std::overflow_error

unary -

-min

std::domain_error

saturate elements clamp toward the side the exact result left the range on: to the maximum or the minimum for +, -, and *, to the maximum for min / -1 and -min, and to 0, the mathematical result, for min % -1. A user defined handler receives exactly the scalar arguments, including error_kind::overflow for -min, where throw_exception reports std::domain_error.

Signed lane arithmetic would be undefined behavior on overflow, so every lane computation avoids it:

  • Addition, subtraction, negation, ++, and -- run in the unsigned lanes of the same width, where they wrap, and convert back. The overflow test is the sign test of the scalar types: an addition overflows when the operands share a sign that the result does not.

  • Lanes of 8, 16, and 32 bits multiply exactly in signed lanes of twice their width and compare the product with the limits.

  • 64-bit lanes multiply the magnitudes with the unsigned 32-bit split. The magnitude of a positive product may reach 2^63 - 1 and that of a negative product 2^63, so min * 1 fits and min * -1 does not.

  • Before any lane is divided, a zero divisor takes the error path, and the min / -1 lanes divide by 1 instead (min / 1 is min and min % 1 is 0, which are the wrapped values overflowing_div and overflowing_mod return).

The saturating_*, overflowing_*, checked_*, and strict_* families cover add, sub, mul, div, and mod, as for the scalar signed types; there are no shift functions. overflowing_div and overflowing_mod flag the min / -1 lanes, and widening_add and widening_mul return lanes of i16, i32, or i64.

Deferred Checking

The overflowing_* functions never branch on the error, so a loop can accumulate the masks and test them once at the end:

auto errors {vec4::mask_type{false}};
for (/* each step */)
{
    const auto [next, overflowed] {simd::overflowing_add(sum, values)};
    sum = next;
    errors = errors || overflowed;
}

if (any_of(errors))
{
    // handle the overflow once
}

Example

Example 1. This example demonstrates checked vector arithmetic, the overflowing and saturating forms, deferred checking, and loads and stores.
// Copyright 2026 Matt Borland
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt


#include <boost/safe_numbers/simd.hpp>
#include <boost/safe_numbers/iostream.hpp>
#include <array>
#include <iostream>
#include <stdexcept>

int main()
{
    using namespace boost::safe_numbers;
    using vec4 = simd::vec<u32, 4>;

    // Lanes load from a contiguous range of exactly the element type
    const std::array<u32, 4> prices {u32{100U}, u32{250U}, u32{3'000'000'000U}, u32{7U}};
    const std::array<u32, 4> counts {u32{3U}, u32{2U}, u32{2U}, u32{10U}};

    const auto p {simd::unchecked_load<vec4>(prices)};
    const auto c {simd::unchecked_load<vec4>(counts)};

    // One check covers every lane: lane 2 overflows, so the whole multiplication
    // throws exactly what the scalar u32 operation throws
    try
    {
        const auto totals {p * c};
        static_cast<void>(totals);
    }
    catch (const std::overflow_error& e)
    {
        std::cout << "Error: " << e.what() << '\n';
    }

    // overflowing_mul returns the wrapped lanes and a mask of the lanes that overflowed
    const auto [wrapped, overflowed] {simd::overflowing_mul(p, c)};
    for (int i {}; i < vec4::size(); ++i)
    {
        std::cout << "lane " << i << ": " << wrapped[i] << (overflowed[i] ? " (overflowed)" : "") << '\n';
    }

    // The error policy comes from the element type: sat_u32 lanes clamp instead
    using sat_vec4 = simd::vec<sat_u32, 4>;
    const auto clamped {sat_vec4{p} * sat_vec4{c}};
    std::cout << "saturated lane 2: " << clamped[2] << '\n';

    // Deferred checking: accumulate the masks and test once at the end
    auto sum {vec4{}};
    auto errors {vec4::mask_type{false}};
    for (int step {}; step < 3; ++step)
    {
        const auto [next, carry] {simd::overflowing_add(sum, p)};
        sum = next;
        errors = errors || carry;
    }

    std::cout << "lanes that overflowed while summing: " << reduce_count(errors) << '\n';

    // Elementwise operations without errors store straight back to safe values
    std::array<u32, 4> out {};
    simd::unchecked_store(simd::min(p, c * u32{50U}), out);
    std::cout << "min(p, 50 * c) =";
    for (const auto x : out)
    {
        std::cout << ' ' << x;
    }
    std::cout << '\n';

    return 0;
}

Output:

Error: Overflow detected in u32 multiplication
lane 0: 300
lane 1: 500
lane 2: 1705032704 (overflowed)
lane 3: 70
saturated lane 2: 4294967295
lanes that overflowed while summing: 1
min(p, 50 * c) = 100 100 100 7
Example 2. This example demonstrates signed vector arithmetic, where the lowest failing lane decides between overflow and underflow, together with the overflowing and saturating forms, negation, and division.
// Copyright 2026 Matt Borland
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt


#include <boost/safe_numbers/simd.hpp>
#include <boost/safe_numbers/iostream.hpp>
#include <array>
#include <cstdint>
#include <iostream>
#include <limits>
#include <stdexcept>

int main()
{
    using namespace boost::safe_numbers;
    using vec4 = simd::vec<i32, 4>;

    // Balances and the changes to apply to them
    const std::array<i32, 4> balances {i32{1'000}, i32{-2'147'483'000}, i32{2'000'000'000}, i32{-50}};
    const std::array<i32, 4> changes {i32{-250}, i32{-1'000}, i32{500'000'000}, i32{75}};

    const auto b {simd::unchecked_load<vec4>(balances)};
    const auto c {simd::unchecked_load<vec4>(changes)};

    // Lane 1 underflows and lane 2 overflows. The lowest failing lane decides what is
    // thrown, exactly as a scalar loop over the lanes would.
    try
    {
        const auto totals {b + c};
        static_cast<void>(totals);
    }
    catch (const std::underflow_error& e)
    {
        std::cout << "Error: " << e.what() << '\n';
    }

    // overflowing_add returns the wrapped lanes and a mask of the lanes that failed
    const auto [wrapped, failed] {simd::overflowing_add(b, c)};
    for (int i {}; i < vec4::size(); ++i)
    {
        std::cout << "lane " << i << ": " << wrapped[i] << (failed[i] ? " (out of range)" : "") << '\n';
    }

    // sat_i32 lanes clamp toward the side the result left the range on
    using sat_vec4 = simd::vec<sat_i32, 4>;
    const auto clamped {sat_vec4{b} + sat_vec4{c}};
    std::cout << "saturated:";
    for (int i {}; i < sat_vec4::size(); ++i)
    {
        std::cout << ' ' << clamped[i];
    }
    std::cout << '\n';

    // Negation and division are checked too: -min and min / -1 do not fit
    const vec4 lowest {i32{std::numeric_limits<std::int32_t>::min()}};
    try
    {
        const auto negated {-lowest};
        static_cast<void>(negated);
    }
    catch (const std::domain_error& e)
    {
        std::cout << "Error: " << e.what() << '\n';
    }

    const auto [quotients, overflowed] {simd::overflowing_div(lowest, vec4{i32{-1}})};
    std::cout << "lanes where min / -1 overflowed: " << reduce_count(overflowed)
              << " (wrapped quotient " << quotients[0] << ")\n";

    // As for the scalar signed types, bitwise and shift operators do not compile:
    // b & c;  // static_assert: Bitwise AND is deliberately disabled for signed safe integers

    return 0;
}

Output:

Error: Underflow detected in i32 addition
lane 0: 750
lane 1: 2147483296 (out of range)
lane 2: -1794967296 (out of range)
lane 3: 25
saturated: 750 -2147483648 2147483647 25
Error: Overflow in i32 unary minus operator
lanes where min / -1 overflowed: 4 (wrapped quotient -2147483648)

Limitations

These are not supported yet:

  • Floating-point element types.

  • u128 and i128 elements, since std::simd has no 128-bit lanes.

  • Bounded element types.

  • CUDA and SYCL device code, which have no <simd>.

  • The C++20 module.

  • <cmath> and <bit> style functions for vectors (GCC 16 implements neither [simd.math] nor [simd.bit]).

  • Formatting and stream I/O for vectors, and debugger pretty printers.

  • Masked loads, stores, and reductions.