Skip to content

Add a Function

This tutorial adds a new function, absdiff, which computes the absolute difference \(|a_i - b_i|\) of two registers, for all datatypes and all mask variants. At the end, absdiff exists in the three APIs on every ISA, is tested and is documented. It runs at L3 (scalar fallback) everywhere: Add an Implementation then makes it fast.

absdiff is now a MIPP function

The function of this tutorial was then added to MIPP along the same steps: its entries in the registries are the reference to compare with. It differs from the tutorial on two points: the scalar reference of the integer types subtracts on the unsigned type (the difference modulo \(2^n\), without the undefined behavior of a signed overflow), so the test inputs of step 6 need no restriction, and the generic implementation of the floating-point types is abs(a - b) (absdiff_float in generic_emu_templates.json). To follow the tutorial, give the function another name, such as absdiff2.

Step File (in generator/) Required
1. Declare the interface helpers_headers/registry_interfaces.json Yes
2. Assign a category helpers_headers/registry_categories.json Yes
3. Write the scalar reference helpers_headers/registry_scalar_implems.json Yes
4. Document the function helpers_headers/funcs_docs.json Recommended
5. Generate and test none Yes
6. Set the test properties helpers_tests/tests_specs.json If the default inputs do not suit the function

The top-level keys of every JSON file are sorted alphabetically: insert the new entries at their place (the json-structure audit warns otherwise).


Step 1: Declare the Interface

In helpers_headers/registry_interfaces.json:

"absdiff": {
    "proto_ref": "ret_reg_2args_reg",
    "datatypes": "all_datatypes",
    "horizontal": false,
    "variants": ["u", "m", "z", "s"]
}
Field Values
proto_ref A prototype of registry_protos.json. ret_reg_2args_reg takes two registers and returns one. See Choosing a Prototype.
datatypes An alias of DATATYPES_MAP (generator/helpers_headers/tools.py): all_datatypes, all_float, all_int (signed), all_uint, all_int_uint, all_64bit, all_32bit, all_16bit, all_8bit, or pair aliases for conversions (all_datatypes_cart_prod, all_datatypes_same_size, all_float_to_int_same_size, all_datatypes_widenning, all_datatypes_narrowing, all_int_uint_widenning and all_int_uint_narrowing for the integers only, ...), defined in generator/helpers_headers/datatypes.py. An explicit list such as ["float32", "float64"] is also accepted.
horizontal true for reductions across the lanes of a register (hadd, hmax), false otherwise. A horizontal function needs a template in generic_emu_templates_lmulh.json and an entry with "mode": "horiz_lmul" in generic_emu_implems_lmulh.json (see hadd): without them, its LMUL > 1 versions (software LMUL) are panic stubs.
variants Variants generated for the function, as a list of u (unmasked, always present), m (Merge-Masked), z (Zero-Masked) and s (Source-Masked): ["u"] for no mask variant, ["u", "m", "z", "s"] for all of them. The lists used are in the table below (Masking Semantics).
cpp_name Optional. Name of the C++ function when it differs from the C name: get_k is exposed as mipp::get.
cpp_ret Optional. Return type of the C++ functions when it differs from the C one: bool for the tests of masks (any, all, none, testz) and get_k, whose C functions return an int32_t or a lane of the mask. The C++ body converts the result with details::mask_lane (its bits, not its value).
lane_crossing Optional, false by default. true for a function whose lanes of the result come from other lanes (reverse, slide, ziplo...): its LMUL > 1 versions (software LMUL) need a template in generic_emu_templates_lmulh.json and an entry with "mode": "horiz_lmul" in generic_emu_implems_lmulh.json (see reverse; the generation fails without them), since the function on each half of the group would be wrong, and its half-vectors by mask go through the scalar d2 function (unless generic_ldiv_mask.json or <isa>_ldiv_mask.json gives one). See Code Generation, step 6.
forms Optional. Scalar forms of the function: one string per form, one letter per data register of the prototype, v (register) or s (scalar). "forms": ["vs", "sv"] adds absdiff_vs(r, s) and absdiff_sv(s, r): functions of their own, derived when the registry is loaded (helpers_headers/forms.py), with the category, the variants and a scalar reference derived from the ones of absdiff, a generic body (absdiff(vd0, set1(s0)), at the level of absdiff) and C++ overloads of mipp::absdiff. A native body is written in an ISA file under the name of the form ("absdiff_vs": [...], with s0 for the scalar). The scalar reference of the base must read the registers lane by lane (vd1.vd[i]).

Lists used for variants, with the number of functions that use each one:

variants Merge-Masked (m) Zero-Masked (z) Source-Masked (s) Functions
["u", "m", "z", "s"] yes yes yes 149
["u", "m", "z"] yes yes — 4
["u", "z", "s"] — yes yes 3
["u", "z"] — yes — 23
["u"] — — — 69

The names of the generated functions are derived from this entry: mipp_absdiff_float32, mipp_absdiff_float32_maskz, mipp_absdiff_float32_m2 in C, mipp::absdiff in C++.

Choosing a Prototype

Each prototype of registry_protos.json describes the return value and the arguments:

"ret_reg_2args_reg": {
    "ret": { "type": "reg", "fixeddatatype": false, "charac": "WO" },
    "args": [
        { "type": "reg", "fixeddatatype": false, "charac": "RO" },
        { "type": "reg", "fixeddatatype": false, "charac": "RO" }
    ]
}
Field Values
type reg (data register), msk (mask register), val (scalar), ptr (pointer), regout (data register written by the function, an argument only: a pointer in C, a reference in C++, as the fields of loadu_unzip3 or the exponents of frexp), valout (scalar written by the function through a pointer that may be null, an argument only: NULL accepted in C, nullptr by default in C++, as the extremum of argmin or the number of lanes read by loadu_ff), Nele (array of one scalar per lane), or false for a void return.
fixeddatatype false when the parameter follows the datatype of the function (the first type of a pair for the arguments, the second one for the return value), or a fixed type: a datatype (int32 for a shift count, uint32, ...), a category (uint / int: the unsigned / signed integer type of the same width, details::uint_of<T> / details::int_of<T> in C++: the indices of permute, the exponents of ldexp), par / ret (the first / second type of the pair: gather and scatter are generated for pairs "data,index", their result has the type of the data and their index the type of the index).
lmul (argument) ratio: the argument has one lane per lane of the function, so its LMUL is the LMUL of the function times size(second type) / size(first type) (the index of gather and scatter). The function is not generated for the LMULs where this LMUL does not exist.
charac RO (read) or WO (written).
lmul Return value only, optional. LMUL of the returned register relative to the one of the arguments: same (default), down (one step below, m1 → d2), up (one step above, d2 → m1) or a fixed LMUL (d2, m1, ... m8). Used by lo and hi (down), combine (up), wcvt and wmul (up), ncvt, ncvts and ncvtsrshiftround (down). The function is only generated for the LMULs where the returned LMUL exists.
changes_type Return value only, optional. true when the datatype of the result differs from the one of the argument (wcvt, wmul, ncvt, ncvts, ncvtsrshiftround): the LMUL change then keeps the number of lanes with wider or narrower elements. Without it, down and up split or join the registers.
offset_lmul Pointers only, optional. When an LMUL > 1 function calls the function of half the LMUL on each half, the pointer of the second call is advanced by one half (default true). false passes the same pointer to the two halves (gather and scatter, whose indices give the offsets); "stride" advances it by one half times the stride s0 (loadu_strided, storeu_strided).
ldiv Prototype level (next to ret and args), optional. false: the functions of this prototype have no half-vector (d2) version (the _noldiv prototypes of compress, expand...). Default true.

Add a prototype only if none fits. The names follow the pattern ret_<return>_<n>args_<arguments>.

Object API

The C and C++ Functional APIs are generated for any prototype. The C++ Object API (generator/helpers_headers/obj_generator.py) handles automatically the functions that take registers and int32_t values and return a register, like absdiff: it generates mipp::absdiff(Vd, Vd) and the masked overloads. Functions with other prototypes (loads, stores, reductions, comparisons, conversions) have a dedicated branch in obj_generator.py; a new function of that kind needs one too.


Step 2: Assign a Category

In helpers_headers/registry_categories.json, add the function to one of the categories (or more, see below):

Category Functions
arithmetic (37) absdiff, add, add_vs, adds, adds_vs, avg, div, div2, div4, div_sv, div_vs, dot2, dot4, dot4us, fmadd, fmadd_vsv, fmadd_vvs, fmsub, fmsub_vsv, fmsub_vvs, fnmadd, fnmadd_vsv, fnmadd_vvs, fnmsub, fnmsub_vsv, fnmsub_vvs, mul, mul_vs, mulhi, sub, sub_sv, sub_vs, subs, subs_sv, subs_vs, wmul, wpadd
combine (6) combine, combine_k, hi, hi_k, lo, lo_k
comparison (20) cmpeq, cmpeq_vs, cmpge, cmpge_sv, cmpge_vs, cmpgt, cmpgt_sv, cmpgt_vs, cmple, cmple_sv, cmple_vs, cmplt, cmplt_sv, cmplt_vs, cmpneq, cmpneq_vs, isfinite, isinf, isnan, signbit
complex (7) cabs, cdiv, cfmadd, cmul, cmulconj, cnorm, conj
convert (9) cvt, cvtceil, cvtfloor, cvtround, cvtroundeven, ncvt, ncvts, ncvtsrshiftround, wcvt
load (18) firstn, gather, iota, load, loadu, loadu_expand, loadu_ff, loadu_strided, loadu_unzip, loadu_unzip2, loadu_unzip3, loadu_unzip4, set, set0, set0_k, set1, set1_k, set_k
logic (36) all, andb, andb_k, andb_vs, andnb, andnb_k, andnb_sv, andnb_vs, any, byteswap, clz, ctz, lshift, lshift_vs, msb, none, notb, notb_k, orb, orb_k, orb_vs, popcount, rotl, rotl_vs, rotr, rotr_vs, rshift, rshift_vs, rshiftl, rshiftl_vs, rshiftround, rshiftround_vs, testz, xorb, xorb_k, xorb_vs
math (47) abs, acos, acosh, asin, asinh, atan, atan2, atan2_sv, atan2_vs, atanh, cbrt, ceil, copysign, copysign_vs, cos, cosh, erf, exp, expm1, floor, frexp, getexp, hypot, hypot_sv, hypot_vs, ldexp, log, log10, log1p, log2, neg, pow, pow2, pow_sv, pow_vs, rcp, round, roundeven, rsqrt, sin, sinh, sqrt, tan, tanh, trunc, xorsign, xorsign_vs
rearrangement (39) bcast, bcast_b128, compress, dupeven, dupodd, expand, insert, loadu_unzip, loadu_unzip2, loadu_unzip3, loadu_unzip4, permute, permute2, permute_b128, reverse, reverse_b128, rotate, rotate_b128, slide, slide_b128, slidedown, slidedown_b128, slideup, slideup_b128, storeu_zip, storeu_zip2, storeu_zip3, storeu_zip4, swap2, unzip, unziphi, unziphi_b128, unziplo, unziplo_b128, zip, ziphi, ziphi_b128, ziplo, ziplo_b128
reduction (14) all, any, argmax, argmin, count, findfirst, findlast, hadd, hadds, hmax, hmin, hmul, none, testz
reinterpret (4) cast, cast_k, tovd, tovm
selection (9) clamp, clamp_vss, max, max_vs, min, min_vs, select, select_sv, select_vs
store (14) get, get_k, getfirst, scatter, store, storent, storeu, storeu_compress, storeu_strided, storeu_zip, storeu_zip2, storeu_zip3, storeu_zip4, storeuf_compress
"arithmetic": [
    "add",
    "adds",
    "absdiff"
]

The category sets the location of the generated headers (mipp/internal/.../functions/arithmetic/absdiff.h), the test files (tests/src/obj/arithmetic/absdiff.cpp) and the grouping in the Function Support pages. A function in none gets a dead-code warning.

A function may be listed in several categories: loadu_unzip2 is a rearrangement and a load. Its main category, which sets the location of its headers, tests and page, is then given in registry_interfaces.json ("main_category": "rearrangement"; without it, the generator stops); the other categories include it in their headers (#include <mipp/cpp/cat/load.hpp> gives loadu_unzip2) and list it in the documentation and the API Explorer.


Step 3: Write the Scalar Reference

In helpers_headers/registry_scalar_implems.json:

"absdiff": [
    {
        "type": "element-wide",
        "datatypes": "all_defs",
        "variants": [],
        "implem": [
            "res.vd[i] = %!pred_cond!% (vd0.vd[i] > vd1.vd[i] ? vd0.vd[i] - vd1.vd[i] : vd1.vd[i] - vd0.vd[i]) %!pred_alt!%;"
        ]
    }
]

This implementation defines what the function computes. It is the L3 fallback of every ISA, and the generated tests compare every API against it. The generator stops if a declared function has no scalar implementation, or if the implementation does not cover exactly the declared datatypes.

Field Values
type element-wide: implem is the body of a loop over the lanes, generated by MIPP (i is the lane index, vd0.vd[i] the lane of the first argument, res.vd[i] the lane of the result). vector-wide: implem is the whole function body, for reductions and permutations (see hadd in the same file).
datatypes all_defs (the datatypes of the interface), an alias, or a list. Several entries can split the datatypes, for instance one body for all_int and one for all_float.
variants [] generates every variant allowed by the variants of the interface. A list such as ["u", "z"] restricts the entry to these variants, so that another entry can give a different body for the others (as store does).
implem The code, as a list of lines. It may use the templating DSL (%s<tr>%, %N<tp>%, ...).

%!pred_cond!% and %!pred_alt!% implement the mask variants: they expand to nothing in the unmasked version, and to the test of the mask lane and the value of an inactive lane (first operand, zero or source register) in the masked versions. Put them around the whole expression, as above.

The reference follows C rules

The scalar reference is compiled as C or C++: the overflow of a signed integer is undefined behavior there, while SIMD instructions wrap around. Results then differ on overflow. Step 6 shows how to keep such inputs out of the tests.


Step 4: Document the Function

In helpers_headers/funcs_docs.json, a short description and an optional LaTeX formula, used by the Function Support pages and the API Explorer:

"absdiff": {
    "description": "Computes the absolute difference of two vector registers element-wise.",
    "latex": "\\text{res}_i = |vd0_i - vd1_i|"
}

Step 5: Generate and Test

From generator/ (see Setup):

./gen_mipp_headers.py --simd-ext neon avx    # or without --simd-ext for all ISAs
./gen_mipp_tests.py

The generator writes, among others:

  • the public headers <mipp/c/fun/absdiff.h>, <mipp/cpp/fun/absdiff.hpp> and <mipp/obj/fun/absdiff.hpp>;
  • implementation headers per ISA, for instance mipp/internal/simd_ext/neon/c/functions/arithmetic/absdiff.h (in fine granularity, one per mask variant and LMUL: .../arithmetic/u/m1/absdiff.h, see Header Layout), where every resolved function carries a comment with its level:
static inline vd_neon_float32_m1_t mipp_neon_absdiff_float32_m1(const vd_neon_float32_m1_t vd0, const vd_neon_float32_m1_t vd1) {
    // Level 3 (Scalar Fallback)
    ...

Inside an ISA, the LMUL 1 functions are named with _m1; mipp_neon_absdiff_float32 is an alias that calls mipp_neon_absdiff_float32_m1 (Code Generation).

Then build the tests and run those of absdiff (see Build and Run the Unit Tests, and Faster Iterations to build fewer tests):

cd ../tests
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_UNITY_BUILD=ON -DCMAKE_CXX_FLAGS="-march=native"
cmake --build build -j4
./build/bin/run-tests "[absdiff]"

At this stage the tests pass on every target, but they prove little: at L3, the function under test calls the scalar reference itself. They check that the function is declared, dispatched and callable in the three APIs, for every datatype, LMUL and mask variant.

Finally, regenerate the documentation pages with ./gen_mipp_docs.py: absdiff gets its Function Support page and appears in the API Explorer.


Step 6: Set the Test Properties

Without an entry in helpers_tests/tests_specs.json, the default properties apply: uniform random inputs, over the whole range of the integer datatypes and in [-1, 1] for the floating-point ones, and an exact comparison with the scalar reference. For absdiff, this default is wrong for the signed integers, and the tests show it as soon as a SIMD implementation exists. With the NEON implementation of the next tutorial:

REQUIRE( mipp_get_int32_m1(rres, i) == mipp_scalar_get_int32_m1(sres, i) )
with expansion:
  -2069792195 == 2069792195 (0x7b5e85c3)

The two inputs were so far apart that \(a - b\) does not fit in an int32_t: the SIMD code wrapped around, the scalar reference did something else. This is not a bug of the function but of the test inputs. Restrict the input domain of the signed types so that the difference always fits:

"absdiff": {
    "domain": {
        "by_datatype": {
            "int8":  { "min": -60, "max": 60 },
            "int16": { "min": -16000, "max": 16000 },
            "int32": { "min": -1000000000, "max": 1000000000 },
            "int64": { "min": -1000000000000, "max": 1000000000000 }
        }
    }
}

Add this entry under the functions key of tests_specs.json and regenerate the tests: with the native implementation, all the absdiff tests pass again.

Other common properties:

Property Use
tolerance and "comparison": "tolerance" Floating-point results that may differ in the last bits (math functions).
overflow_check Skip the comparison of the lanes where add, sub or mul overflows, instead of restricting the domain. Currently applied in the C tests only.
nan_inf_skip With a tolerance, skip the lanes where the difference with the reference is NaN or infinite.
disabled and disabled_reason Comment out the generated test (the reason is printed in the file).
support_obj false if the function has no C++ Object API overload.

The domain can also depend on the ISA (by_define, e.g. MIPP_AVX2) and on the mask variant (unmasked, maskm, maskz, masks keys). All the properties are described in Test Specifications, and the default entry of tests_specs.json gives the default value of the main ones.


Next Step

absdiff now works everywhere, but at L3: the registers are copied to arrays and processed lane by lane. Add an Implementation gives it a native NEON implementation and a generic implementation for the other ISAs.