Skip to content
systemcoding.dev
Performance

The Complete Guide to SIMD Programming With Intrinsics

Learn SIMD from scratch with C intrinsics for SSE, AVX2 and ARM NEON: loads, arithmetic, masks, shuffles, reductions, tails, dispatch, testing and pitfalls.

26 min read
Summarize in AI
Flat illustration of a CPU core with its cache levels and main memory, with the Intel, Apple and Arm logos.

SIMD, single instruction multiple data, is the most direct way a program can use the arithmetic hardware in a modern processor. One instruction operates on a whole register of values, four floats, eight 32-bit integers or sixteen bytes, and the cores in laptops, servers and phones can start several such instructions every cycle. Compilers can generate SIMD code from plain loops, and often do, but when they do not, or when you need a particular instruction, you write it yourself with intrinsics: C functions that the compiler turns into exactly one machine instruction each. This guide teaches that skill from the beginning. It covers the vocabulary, the toolchain setup for x86-64 and AArch64, the first loop, loads and alignment, arithmetic and masks, reductions, shuffles, integer width changes, the AVX2 lane rule, ARM NEON equivalents, loop tails, floating-point surprises, run-time dispatch, testing, and the places SIMD does not help. All code is C11 and is written against the Intel Intrinsics Guide and the Arm Intrinsics reference. It builds with GCC 15 or Clang 20, and nothing here depends on a benchmark figure, because speed depends on your machine and your data, and you should measure it.

What SIMD is

A scalar instruction, such as an integer add, reads two registers and writes one. A SIMD instruction reads two vector registers and writes one, but each register holds several values, called lanes, and the operation happens in every lane at once. A 128-bit register can be read as four 32-bit floats, two 64-bit doubles, four 32-bit integers, eight 16-bit integers or sixteen bytes, and the instruction you pick decides how the bits are split. The lanes are independent: the result in lane 3 depends only on lane 3 of the inputs, never on lane 2.

The speedup potential comes from width. A 128-bit unit does four float operations in the time of one, and a 256-bit unit does eight. The limit is that every lane does the same operation, so SIMD fits data-parallel work: arrays of numbers, pixels, audio samples, bytes of text. It does not fit work where each element needs a different decision, unless you turn the decision into a mask, as a later section shows.

The instruction sets you will meet:

NamePlatformRegister sizeNotes
SSE, SSE2x86-64128 bitsSSE2 is guaranteed on every x86-64 processor
SSE3, SSSE3, SSE4.1, SSE4.2x86-64128 bitsadded shuffles, blends, string compare; common but not guaranteed
AVX, AVX2x86-64256 bitsAVX2 adds 256-bit integer operations; widely available since 2013
FMA3x86-64128 or 256 bitsfused multiply-add, a separate feature flag
AVX-512some x86-64512 bitsadds mask registers; support varies by CPU model
NEONAArch64, some Armv7128 bitsmandatory on AArch64
SVE, SVE2some AArch64128 to 2048 bits, chosen by hardwarelength-agnostic programming
RISC-V VRISC-Vimplementation definedlength-agnostic
WebAssembly SIMDWebAssembly128 bitsportable across browsers and runtimes

This guide works in detail with SSE2, AVX2 and NEON, since together they cover the machines most developers use, and says how the ideas carry to AVX-512 and SVE.

Intrinsics, auto-vectorization or assembly

You have three ways to produce SIMD code. Auto-vectorization asks the compiler to find the parallelism in plain loops, and for simple array loops GCC and Clang succeed at -O3, or at -O2 in recent GCC. It needs no source change, works on every target, and gives no guarantee. Intrinsics name the instruction in C, and the compiler still allocates registers, schedules instructions and inlines the function, so you get control without writing assembly. Assembly gives total control and no help.

The sensible order is to write the plain loop, read the compiler's vectorization report, try restrict and restructuring if it declined, and use intrinsics when you need a guarantee or an instruction the compiler never emits, such as byte shuffles, saturating arithmetic or specific permutations. Another post in this cluster compares the three approaches in detail. The rest of this guide assumes you decided on intrinsics.

Headers, types and naming

On x86, include <immintrin.h>, which pulls in every intrinsic header for the features the compiler is allowed to use. The vector types are __m128 (four floats), __m128d (two doubles), __m128i (any integer lanes, 128 bits), and the 256-bit __m256, __m256d and __m256i. The integer types carry no lane width, so the instruction name says how to interpret the bits.

Names follow a pattern: _mm for 128-bit or _mm256 for 256-bit, then the operation, then a type suffix. ps is packed single (floats), pd packed double, epi32 packed 32-bit signed integers, epu8 packed unsigned bytes, si128 the whole register as bits. So _mm_add_ps adds four floats, _mm_add_epi32 adds four 32-bit integers, _mm256_add_epi8 adds thirty-two bytes, and _mm_adds_epu8 adds sixteen unsigned bytes with saturation, clamping at 255 instead of wrapping.

On Arm, include <arm_neon.h>. The types are named by element and count: float32x4_t, int32x4_t, uint8x16_t, and on AArch64 float64x2_t. Names follow v for vector, then the operation, then q for the 128-bit form, then the element type: vaddq_f32 adds four floats, vld1q_f32 loads four, vqaddq_u8 adds sixteen unsigned bytes with saturation.

The authoritative references are the Intel Intrinsics Guide, which lets you search by name or instruction and lists the CPUID feature each requires, and the Arm Intrinsics documentation on the Arm developer site. Use them constantly. Memorizing intrinsic names is a waste, and looking up each one takes seconds.

Compiler flags and feature detection

The x86-64 baseline includes SSE and SSE2 only. Using any other instruction set requires telling the compiler it may emit those instructions, and the program must then run only on processors that have them. There are three ways, in increasing order of care.

Compile the whole program for a feature level: -mavx2 for AVX2, -mfma for fused multiply-add, or -march=x86-64-v3, which names the level that includes AVX2, FMA, BMI1, BMI2 and a few others, defined in the x86-64 psABI and accepted by GCC 11 and later and Clang 12 and later. -march=native uses everything the build machine has, and is for local experiments only. The resulting binary will crash with an illegal instruction on a processor without the features.

Mark individual functions with __attribute__((target("avx2"))). The function may use AVX2 intrinsics even when the rest of the file is compiled for the baseline, and the program can choose at run time whether to call it.

Check the CPU at run time with __builtin_cpu_supports("avx2"), available in GCC and Clang for x86, after __builtin_cpu_init() if you call it before constructors run. A dispatcher looks like this:

dispatch.cc
#include <immintrin.h>
#include <stddef.h>
#include <stdio.h>

static float sum_scalar(const float *a, size_t n)
{
    float s = 0.0f;
    for (size_t i = 0; i < n; ++i) s += a[i];
    return s;
}

__attribute__((target("avx2")))
static float sum_avx2(const float *a, size_t n)
{
    __m256 acc = _mm256_setzero_ps();
    size_t i = 0;
    for (; i + 8 <= n; i += 8)
        acc = _mm256_add_ps(acc, _mm256_loadu_ps(a + i));
    float lanes[8];
    _mm256_storeu_ps(lanes, acc);
    float s = ((lanes[0] + lanes[1]) + (lanes[2] + lanes[3]))
            + ((lanes[4] + lanes[5]) + (lanes[6] + lanes[7]));
    for (; i < n; ++i) s += a[i];
    return s;
}

static float sum(const float *a, size_t n)
{
    if (__builtin_cpu_supports("avx2"))
        return sum_avx2(a, n);
    return sum_scalar(a, n);
}

int main(void)
{
    float a[11];
    for (int i = 0; i < 11; ++i) a[i] = (float)(i + 1);
    printf("sum = %.1f\n", sum(a, 11));
    return 0;
}
Text
sum = 66.0

The sum of 1 through 11 is 66. The program runs correctly on any x86-64 machine, whether or not it has AVX2, because the AVX2 function is only called when the CPU reports the feature. GCC also offers __attribute__((target_clones("avx2","default"))), which builds both versions and selects one when the program loads, with no hand-written dispatch.

On AArch64, NEON is always present, so there is nothing to detect. Optional extensions such as the dot-product instructions and SVE are tested with getauxval(AT_HWCAP) on Linux and compile-time macros such as __ARM_FEATURE_DOTPROD. Compile for them with -march=armv8.2-a+dotprod and similar strings. On 32-bit Armv7, NEON needs -mfpu=neon and a hard-float ABI.

Your first loop

The standard first exercise adds two arrays. Process four floats per step with SSE, and finish the last zero to three elements with scalar code:

add_sse.cc
#include <stddef.h>
#include <stdio.h>
#include <xmmintrin.h>

void add_sse(const float *a, const float *b, float *out, size_t n)
{
    size_t i = 0;
    for (; i + 4 <= n; i += 4) {
        __m128 va = _mm_loadu_ps(a + i);
        __m128 vb = _mm_loadu_ps(b + i);
        _mm_storeu_ps(out + i, _mm_add_ps(va, vb));
    }
    for (; i < n; ++i)
        out[i] = a[i] + b[i];
}

int main(void)
{
    float a[7] = {1, 2, 3, 4, 5, 6, 7};
    float b[7] = {10, 20, 30, 40, 50, 60, 70};
    float c[7];
    add_sse(a, b, c, 7);
    for (int i = 0; i < 7; ++i) printf("%.0f ", c[i]);
    printf("\n");
    return 0;
}
Text
11 22 33 44 55 66 77 

Three things to notice. The loop condition is i + 4 <= n, which cannot wrap around for unsigned n, where i < n - 3 would misbehave for n below 3. The loads and stores are the unaligned forms, which work on any address. And the tail loop handles the leftovers, here the last three elements of seven. Compile with plain gcc -O2, and in the assembly you will find movups loads, an addps and a movups store.

Loads, stores and alignment

Moving data between memory and registers is half of most SIMD kernels. On x86, _mm_load_ps requires a 16-byte aligned address and faults otherwise, and _mm_loadu_ps accepts any address. On processors from the last decade, an unaligned load from an address that is in fact aligned runs at the same speed as an aligned load, so the practical difference is that unaligned loads that straddle a cache line boundary cost extra. A 32-byte AVX load crosses a 64-byte cache line boundary whenever its offset inside the line is greater than 32, so aligning buffers to 32 or 64 bytes removes the penalty entirely.

Allocate aligned buffers with aligned_alloc(32, size), where size must be a multiple of the alignment in C11, or posix_memalign, or alignas(32) on arrays. Aligned intrinsics also act as an assertion, since a misaligned pointer faults, which can help catch bugs but turns a harmless mistake into a crash, so start with the unaligned forms and switch only for measured gains.

Other load forms matter. _mm_set1_ps(x) broadcasts a scalar to all lanes, useful for constants. _mm_set_ps(e3, e2, e1, e0) builds a vector from four scalars, with the arguments in reverse lane order, which is a classic source of bugs: the first argument is the highest lane. _mm_setr_ps(e0, e1, e2, e3) takes them in memory order, and is the safer choice. _mm_load_ss loads one float into the low lane and zeroes the rest. Non-temporal stores, _mm_stream_ps, write around the cache, and they suit large output arrays you will not read again soon; they require aligned addresses and are followed by _mm_sfence() when other threads must see the data.

On NEON, vld1q_f32(ptr) loads four consecutive floats from any element-aligned address, vst1q_f32 stores them, vdupq_n_f32(x) broadcasts, and the structure loads vld2q_f32, vld3q_f32 and vld4q_f32 deinterleave pairs, triples and quads on the way in. Deinterleaving an array of RGB bytes into three registers with vld3q_u8 is one instruction where SSE needs a sequence of shuffles.

Arithmetic, comparisons and masks

Arithmetic maps one to one. For floats: _mm_add_ps, _mm_sub_ps, _mm_mul_ps, _mm_div_ps, _mm_sqrt_ps, _mm_min_ps, _mm_max_ps, and the approximate reciprocal _mm_rcp_ps and reciprocal square root _mm_rsqrt_ps, which are fast and have about twelve bits of precision, commonly refined with one Newton step. For integers, add and subtract come in each width, _mm_add_epi8 through _mm_add_epi64. Multiplication is where the instruction set has gaps: _mm_mullo_epi16 gives the low 16 bits of 16-bit products, _mm_mul_epu32 multiplies the even 32-bit lanes into 64-bit results, and a full 32-bit _mm_mullo_epi32 exists only from SSE4.1.

Comparisons produce masks. _mm_cmpgt_ps(a, b) sets each result lane to all ones if the lane of a is greater than the lane of b, and to all zeros otherwise. A mask in an integer vector register is just bits, so you combine it with _mm_and_ps, _mm_andnot_ps and _mm_or_ps. A select, the vector form of cond ? x : y, is (mask & x) | (~mask & y):

select.cc
#include <stdio.h>
#include <xmmintrin.h>

int main(void)
{
    float in[4] = {-1.5f, 2.0f, -3.0f, 4.5f};
    __m128 v = _mm_loadu_ps(in);
    __m128 zero = _mm_setzero_ps();
    __m128 neg = _mm_cmplt_ps(v, zero);                 // lanes where v < 0
    __m128 clamped = _mm_andnot_ps(neg, v);             // keep v where not negative, else 0
    float out[4];
    _mm_storeu_ps(out, clamped);
    printf("%.1f %.1f %.1f %.1f\n", out[0], out[1], out[2], out[3]);
    return 0;
}
Text
0.0 2.0 0.0 4.5

This is the vector form of x < 0 ? 0 : x. _mm_andnot_ps(a, b) computes (~a) & b, with the first operand inverted, another detail that trips people. SSE4.1 adds _mm_blendv_ps(a, b, mask), which selects b where the mask's top bit is set, in one instruction, and AVX-512 replaces masks in vector registers with dedicated mask registers k0 to k7, so that most operations take a mask argument directly. The branches of scalar code become masks in SIMD code: compute both sides, then select.

NaN comparisons are false in all ordered compares, so _mm_cmplt_ps gives zero for a NaN lane, and your "negative" test treats NaN as not negative. Decide what you want for NaN and use _mm_cmpunord_ps to test for it if it matters.

Reductions and horizontal operations

A reduction combines all lanes into one value, such as a sum or a maximum. The efficient pattern keeps the lanes independent for the whole loop and combines them once at the end, because operations across lanes are slower than operations between registers. A sum of an array has a vector accumulator, and after the loop, a horizontal add.

SSE2 has no instruction that sums the four lanes of one register. The usual sequence uses two shuffles and two adds:

hsum.cc
#include <stdio.h>
#include <xmmintrin.h>

static inline float hsum_ps(__m128 v)
{
    __m128 sh   = _mm_shuffle_ps(v, v, _MM_SHUFFLE(2, 3, 0, 1)); // v1 v0 v3 v2
    __m128 sums = _mm_add_ps(v, sh);                              // v0+v1, v0+v1, v2+v3, v2+v3
    __m128 hi   = _mm_movehl_ps(sums, sums);                      // v2+v3 in lane 0
    return _mm_cvtss_f32(_mm_add_ss(sums, hi));                   // (v0+v1) + (v2+v3)
}

int main(void)
{
    __m128 v = _mm_setr_ps(1.0f, 2.0f, 3.0f, 4.0f);
    printf("hsum = %.1f\n", hsum_ps(v));
    return 0;
}
Text
hsum = 10.0

_MM_SHUFFLE(2, 3, 0, 1) builds an immediate that tells _mm_shuffle_ps to take lane 1 for result lane 0, lane 0 for result lane 1, lane 3 for result lane 2 and lane 2 for result lane 3. After the first add, lanes 0 and 2 each hold a pair sum, and _mm_movehl_ps moves the upper pair into the lower position so one scalar add finishes the job. SSE3 offers _mm_hadd_ps, which is shorter to write and not faster on most cores, since it decodes to shuffles internally.

A loop with one accumulator has a dependency chain: each add waits for the previous add. Floating-point add has a latency of several cycles, and a core can start more than one add per cycle, so one accumulator wastes most of the unit. Use several independent accumulators, four is typical, and combine them at the end:

c
__m256 a0 = _mm256_setzero_ps(), a1 = _mm256_setzero_ps();
__m256 a2 = _mm256_setzero_ps(), a3 = _mm256_setzero_ps();
for (; i + 32 <= n; i += 32) {
    a0 = _mm256_add_ps(a0, _mm256_loadu_ps(p + i));
    a1 = _mm256_add_ps(a1, _mm256_loadu_ps(p + i + 8));
    a2 = _mm256_add_ps(a2, _mm256_loadu_ps(p + i + 16));
    a3 = _mm256_add_ps(a3, _mm256_loadu_ps(p + i + 24));
}
__m256 acc = _mm256_add_ps(_mm256_add_ps(a0, a1), _mm256_add_ps(a2, a3));

The exact number of accumulators comes from the latency and throughput of the instruction on your target core, which Intel's manual, Agner Fog's tables and Arm's optimization guides publish.

Integer lanes, widening, narrowing and saturation

Integer SIMD is where the instruction sets show their character. Operations exist for 8, 16, 32 and 64-bit lanes, and many have a saturating variant that clamps to the type's range instead of wrapping, which is what image and audio processing usually wants. Adding unsigned bytes with saturation:

sat.cc
#include <emmintrin.h>
#include <stdint.h>
#include <stdio.h>

int main(void)
{
    uint8_t a[16] = {250, 100, 10, 255, 0, 128, 200, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    uint8_t b[16] = {10, 100, 10, 1, 0, 128, 100, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    uint8_t wrap[16], sat[16];
    __m128i va = _mm_loadu_si128((const __m128i *)a);
    __m128i vb = _mm_loadu_si128((const __m128i *)b);
    _mm_storeu_si128((__m128i *)wrap, _mm_add_epi8(va, vb));
    _mm_storeu_si128((__m128i *)sat,  _mm_adds_epu8(va, vb));
    for (int i = 0; i < 8; ++i)
        printf("%3u + %3u: wrap %3u, saturate %3u\n", a[i], b[i], wrap[i], sat[i]);
    return 0;
}
Text
250 +  10: wrap   4, saturate 255
100 + 100: wrap 200, saturate 200
 10 +  10: wrap  20, saturate  20
255 +   1: wrap   0, saturate 255
  0 +   0: wrap   0, saturate   0
128 + 128: wrap   0, saturate 255
200 + 100: wrap  44, saturate 255
  1 +   1: wrap   2, saturate   2

Sixteen pixels brighten in one instruction with no overflow. The plain _mm_add_epi8 wraps modulo 256, so 250 plus 10 gives 4.

Widening and narrowing convert between lane widths. To widen unsigned bytes to 16-bit lanes in SSE2, interleave with zeros: _mm_unpacklo_epi8(v, _mm_setzero_si128()) turns the low eight bytes into eight 16-bit values, and _mm_unpackhi_epi8 does the high eight. SSE4.1 adds _mm_cvtepu8_epi16 which does it in one step, and AVX2 has 256-bit forms. Narrowing uses pack instructions with saturation, such as _mm_packus_epi16, which turns eight signed 16-bit values into unsigned bytes, clamping to 0 to 255. NEON has vmovl_u8 to widen, vmovn_u16 to narrow, and vqmovn_u16 to narrow with saturation, which are more regular than their x86 counterparts.

Multiplying integers and keeping precision usually means widening first, so sum-of-products kernels convert bytes to 16-bit lanes, multiply, and accumulate in 32 bits. The instruction _mm_madd_epi16 multiplies pairs of 16-bit values and adds adjacent products into 32-bit lanes, a ready-made building block for dot products. Another post in this cluster covers overflow of 32-bit accumulators in the integer sum, which is the standard pitfall: sums of many values overflow a lane unless you widen as you go.

Shuffles and permutations

A shuffle rearranges lanes within or between registers. It is how you transpose, reverse, interleave and broadcast individual lanes. On SSE, _mm_shuffle_ps(a, b, imm) takes two result lanes from a and two from b, with the selectors in the immediate, which must be a compile-time constant. Reversing four floats:

shuf.cc
#include <stdio.h>
#include <xmmintrin.h>

int main(void)
{
    __m128 v = _mm_setr_ps(1.0f, 2.0f, 3.0f, 4.0f);
    __m128 r = _mm_shuffle_ps(v, v, _MM_SHUFFLE(0, 1, 2, 3));
    float out[4];
    _mm_storeu_ps(out, r);
    printf("%.0f %.0f %.0f %.0f\n", out[0], out[1], out[2], out[3]);
    return 0;
}
Text
4 3 2 1

_MM_SHUFFLE(z, y, x, w) lists the source lane for result lanes 3, 2, 1 and 0 in that order, so (0, 1, 2, 3) says result lane 0 comes from lane 3, lane 1 from lane 2, lane 2 from lane 1 and lane 3 from lane 0. Reading the macro from left to right gives the lanes from high to low, a rule that is easy to forget.

For bytes, _mm_shuffle_epi8 (SSSE3, pshufb) takes a second register of indices and picks a byte from the first for each position, which makes it a 16-entry table lookup applied to sixteen inputs at once. That one instruction underlies fast base64, hex and UTF-8 routines, popcount by nibble tables and many parsers. NEON's vqtbl1q_u8 does the same, and AVX-512 VBMI extends it to larger tables.

Lane-crossing needs care. When the data to move sits in different registers or far apart, you chain unpack, shuffle, blend and permute instructions. Keep a table of the common patterns at hand, derived from the Intel Intrinsics Guide.

AVX2 and the lane rule

AVX and AVX2 widen the registers to 256 bits, and most instructions work on two independent 128-bit halves, called lanes by Intel's documentation, which is a different use of the word from the element lanes above. Element-wise arithmetic works across the whole register, so _mm256_add_epi32 adds eight pairs. But shuffle and unpack instructions mostly operate within each 128-bit half, so _mm256_shuffle_ps rearranges the lower four floats and the upper four floats separately, with the same immediate in both, and cannot move a value from the upper half to the lower. A port of an SSE shuffle sequence to AVX2 by renaming the functions gives wrong answers for this reason.

Instructions that cross the halves exist and cost more: _mm256_permute2x128_si256 selects 128-bit halves from two registers, _mm256_permutevar8x32_epi32 moves any of the eight 32-bit lanes to any position using an index vector, and _mm256_extracti128_si256 and _mm256_castsi256_si128 split a register in two. A reduction of a 256-bit accumulator extracts the high half, adds it to the low half, and finishes with the 128-bit sequence.

A second rule concerns mixing instruction encodings. Executing legacy SSE instructions while the upper halves of the 256-bit registers hold nonzero data can cost a transition penalty on some Intel cores. Compilers insert vzeroupper before returning from functions that use 256-bit registers, and hand-written code that mixes the two must do the same with _mm256_zeroupper(). Intel's optimization manual describes the penalty.

FMA, fused multiply-add, is its own feature flag. _mm256_fmadd_ps(a, b, c) computes a * b + c with a single rounding, and it needs -mfma in addition to -mavx2, and a separate runtime check with __builtin_cpu_supports("fma"). Processors that have AVX2 have FMA in practice, but test both anyway.

ARM NEON equivalents

If you know SSE, NEON reads like a more regular cousin. A rough translation table for common operations on four floats:

OperationSSENEON (AArch64)
Load four floats_mm_loadu_ps(p)vld1q_f32(p)
Store four floats_mm_storeu_ps(p, v)vst1q_f32(p, v)
Broadcast_mm_set1_ps(x)vdupq_n_f32(x)
Add_mm_add_ps(a, b)vaddq_f32(a, b)
Multiply_mm_mul_ps(a, b)vmulq_f32(a, b)
Fused multiply-add_mm_fmadd_ps(a, b, c)vfmaq_f32(c, a, b)
Compare greater_mm_cmpgt_ps(a, b)vcgtq_f32(a, b)
Select by maskblend, or and/andnot/orvbslq_f32(mask, a, b)
Horizontal sumshuffle and addvaddvq_f32(v)
Byte table lookup_mm_shuffle_epi8vqtbl1q_u8

Note the argument order of the fused multiply-add: NEON puts the accumulator first. The compare gives a mask, and vbslq_f32 is the bitwise select, with the mask as its first argument. A complete NEON loop is the dot product from the NEON post in this cluster:

dot_neon.cc
#include <arm_neon.h>
#include <stddef.h>

float dot_neon(const float *a, const float *b, size_t n)
{
    float32x4_t acc = vdupq_n_f32(0.0f);
    size_t i = 0;
    for (; i + 4 <= n; i += 4)
        acc = vfmaq_f32(acc, vld1q_f32(a + i), vld1q_f32(b + i));
    float sum = vaddvq_f32(acc);
    for (; i < n; ++i)
        sum += a[i] * b[i];
    return sum;
}

For the arrays {1,2,3,4,5,6,7,8} and all-twos, the function returns 72, since every product is twice the element and the elements sum to 36. NEON loads accept any element-aligned address, so there is no aligned and unaligned pair to choose between. The structure loads and stores, vld3q_u8 for pixel data, are the feature x86 lacks. For the integer dot product on recent cores, vdotq_s32 (the SDOT instruction, from the dot-product extension) multiplies groups of four bytes and accumulates into 32-bit lanes, which is what quantized neural network code uses.

Apple silicon runs the same code as other AArch64 cores. Windows on Arm and Android use the same intrinsics from the same header.

Handling the tail

Arrays are rarely a multiple of the vector width, so every vector loop needs a plan for the last few elements. There are four, and the choice shapes the code.

The scalar tail is the default: after the main loop, finish element by element. It is simple, always correct, and costs a few extra branches. Its drawback is code duplication, since the tail repeats the loop body's logic, and any bug has two homes.

Padding avoids the tail entirely by allocating arrays rounded up to the vector width and filling the extra elements with a value that does not change the result, such as zero for a sum. The loop then runs over whole vectors only. This needs control of the allocation, and a rule that every writer maintains the padding. A separate post in this cluster covers it.

An overlapping final vector handles the end of an idempotent operation: process the last full vector at the end of the array, even though it overlaps elements already processed. It is fine for min, max and element-wise transforms that write a pure function of the input, and wrong for sums, and wrong for in-place operations that read their own output.

Masked or predicated loads and stores handle the tail in the same loop body. AVX-512 has masked loads such as _mm512_maskz_loadu_ps(mask, p), which load only the lanes whose mask bit is set and zero the rest, without reading or faulting on the others. SVE has predicate registers: the loop for (i = 0; i < n; i += svcntw()) { svbool_t pg = svwhilelt_b32(i, n); ... } builds a predicate that is true for the lanes still inside the array, and every load, operation and store takes it. On those targets the tail disappears, and the same binary runs on hardware with different vector lengths.

Never read past the end of the allocation to fill a final vector. It is undefined behavior in C, AddressSanitizer reports it, and a load that crosses into an unmapped page faults. Libraries such as glibc get away with reading aligned vectors that straddle the end of a string because they know the page granularity, and your code should not copy that trick unless you can state the same guarantee.

Data layout for SIMD

Vector loads want consecutive elements. A loop over an array of structs reads one field of each struct with a stride, and a vector load cannot fetch it without a gather or shuffles. The remedy is the struct-of-arrays layout, which keeps each field in its own contiguous array, as discussed in the data layout posts of this cluster. With it, loading four x-coordinates is one _mm_loadu_ps.

AVX2 provides gather instructions, _mm256_i32gather_ps(base, indices, scale), which load each lane from base + indices[i] * scale. They make indirect access possible, but a gather performs one memory access per lane, and on several microarchitectures it is not much faster than eight scalar loads, so they pay off only when the alternative is expensive shuffling. Scatters, writes to computed addresses, have no AVX2 instruction and arrive with AVX-512 and SVE. If you find yourself gathering in a hot loop, reconsider the layout first.

Floating-point behavior

SIMD changes floating-point results in four ways you must know.

Order of summation. A vector sum adds in a different order from a left-to-right loop, since each lane accumulates every fourth or eighth element. Floating-point addition is not associative, so results can differ in the low bits. Compare to a reference with a relative tolerance, never with ==, and keep the same vector width if you need reproducible results between runs, since a different width means a different association.

Fused multiply-add. a * b + c with FMA rounds once, where separate multiply and add round twice. Results differ slightly from the unfused version and are usually more accurate. If you need to match another implementation bit for bit, use the same choice in both.

Denormals. Subnormal floating-point numbers, those smaller than the smallest normal value, are slow to process on many cores, sometimes by a large factor, because they trap to microcode. Audio and signal-processing code that decays toward zero hits them. Intel and Arm cores let you flush them to zero: on x86, _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON) and _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON) set the control bits in MXCSR for the current thread. That changes results slightly, so enable it deliberately and per thread.

NaN and signed zero. Min and max intrinsics return the second operand if either is NaN, which is not symmetric, so _mm_max_ps(a, b) and _mm_max_ps(b, a) differ when one input is NaN. Check the Intel Intrinsics Guide's pseudocode for each instruction.

Testing SIMD code

SIMD bugs hide at boundaries and in rarely used lanes. A test plan that catches nearly all of them:

  1. Write a scalar reference implementation, simple and obviously correct, and keep it in the code base as the oracle.

  2. Test lengths from 0 to at least three times the vector width plus one, which exercises every tail length and the transition between loop and tail. For 8-wide vectors that means 0 to 25.

  3. Use input data with distinct values in every lane, such as the index itself, so a swapped lane shows up. All-equal data hides shuffle bugs.

  4. Include edge values: zeros, negative numbers, the maximum and minimum of the type, NaN and infinity for floats.

  5. Compare integer results exactly, and float results with a relative tolerance chosen from the algorithm.

  6. Test unaligned starting addresses, by passing buffer + 1, buffer + 3 and so on, to catch accidental use of aligned loads.

  7. Run under AddressSanitizer and UndefinedBehaviorSanitizer, which catch out-of-bounds vector loads that happen to stay inside a mapped page.

  8. Run the dispatcher tests on each path. Add an environment variable or a function parameter that forces a code path, so CI can exercise the SSE, AVX2 and scalar versions on one machine.

For performance, benchmark each version on sizes that match your real workload, from tiny arrays that expose call overhead, through sizes that fit in cache, to sizes far beyond the last-level cache, where memory bandwidth dominates and all versions converge. Warm up, repeat, report the median, and prevent the compiler from deleting the work by consuming the result. perf stat shows instructions per cycle and cache misses, which tell you whether you are limited by arithmetic or by memory.

Why SIMD sometimes does not help

A loop that streams through a large array does very little work per byte, and the cost is dominated by memory bandwidth. Adding two arrays reads two floats and writes one for each addition, so a scalar loop may already saturate the memory system, and a vector loop issues fewer instructions but waits on the same memory. In such cases SIMD saves instructions and power rather than time. The roofline reasoning is simple: compare the arithmetic intensity of the loop, operations per byte moved, with the ratio your machine can sustain, which you can estimate from published peak numbers and your own measurement of memory bandwidth.

Other limits: very short loops, where setup and the tail dominate; code with unpredictable per-element control flow, which turns into masks that do both sides' work; and data that needs gathers. Some processors lower their clock when they execute dense wide-vector code, an effect that was large on early AVX-512 server parts and is smaller on later ones, and that vendors document in their optimization guides. For a kernel that is a small part of a larger program, a lower frequency can cost the rest of the program more than the kernel gains.

Portable SIMD layers

Intrinsics tie code to an instruction set, and maintaining SSE, AVX2 and NEON copies of every kernel is expensive. Portable layers write the kernel once. Highway, from Google, provides a C++ API with target dispatch built in. xsimd offers C++ types that map to the available instruction set at compile time. SIMDe implements x86 and NEON intrinsics in terms of each other and of portable code, so existing code ports with a header change. GCC and Clang offer generic vector extensions, typedef float v4sf __attribute__((vector_size(16)));, with operators on vector types that compile to SIMD on any target. Rust's std::simd, covered in its own post, is the portable API in that language. C++26 standardizes std::simd in <simd>, and it is arriving in compilers over time.

Use a portable layer when you must support several targets and your kernels are ordinary arithmetic. Reach for architecture-specific intrinsics for the operations that portable layers do not cover, such as byte shuffles with runtime indices, and keep both behind one function interface.

Who this does not fit

Beginners who have not profiled. SIMD is an optimization, and the first step is to find where time goes. If a function takes two percent of the run time, vectorizing it cannot give more than two percent.

Code that must run on unknown hardware without dispatch. If you cannot control the CPU and cannot afford run-time checks, stay with the baseline instruction set, SSE2 on x86-64 and NEON on AArch64, or ship separate binaries.

Teams that cannot maintain it. Intrinsics code is dense, hard to review, and needs one version per instruction set. Without tests and a scalar reference, it becomes a liability. If the compiler vectorizes the loop acceptably, leave it alone.

Memory-bound workloads. Check the arithmetic intensity before investing. The data layout posts in this cluster may give more than wider vectors.

Interpreted languages. Python, JavaScript and the JVM languages reach SIMD through libraries, such as NumPy, whose inner loops are already vectorized. Calling those libraries is the route there.

Reference: a minimal toolkit

Taskx86-64AArch64
Header<immintrin.h><arm_neon.h>
BaselineSSE2NEON
Check feature at run time__builtin_cpu_supports("avx2")getauxval(AT_HWCAP)
Per-function feature__attribute__((target("avx2")))separate file built with -march=armv8.2-a+dotprod
Look up an intrinsicIntel Intrinsics GuideArm Intrinsics reference
See what the compiler did-S -masm=intel, objdump -d-S, objdump -d
Vectorization report-fopt-info-vec, -Rpass=loop-vectorizesame
Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.