Skip to content
systemcoding.dev
Performance

Restructure Loops So Compilers Can Vectorise Reductions, Gathers and Early Exits

Rewrite float reductions, indirect gathers and early-exit loops in C so GCC and Clang vectorize them, using partial sums and blocked scans.

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

The previous post showed how to ask GCC and Clang for vectorization and read their reports. This one deals with the loops that the reports reject: sums of floats, loops that read through an index array, and loops that stop at the first match. Each fails for a specific, nameable reason, and each has a rewrite that preserves the meaning while handing the vectorizer something it can prove safe. We work through three cases in C with GCC 15 and Clang 20 on x86-64 at -O3 -march=x86-64-v3, and say at each step what the compiler's report would say before and after. The aim is source changes, not compiler flags that loosen floating-point rules for the whole file.

Reductions: floating-point sums

A sum is a reduction, a loop that folds an array into one value:

c
float sum_plain(const float *a, int n)
{
    float s = 0.0f;
    for (int i = 0; i < n; ++i)
        s += a[i];
    return s;
}

To vectorize it, the compiler must keep several partial sums, one per lane, and add them at the end. That changes the order of the additions, and floating-point addition is not associative, so the final value can differ in the low bits. The language rules say the compiler must produce the result of the source order, so GCC and Clang decline unless you allow reassociation. The reports say so, for example loop not vectorized: cannot prove it is safe to reorder floating-point operations in Clang.

The restructuring that avoids any flag is to write the partial sums yourself, which makes the new order part of the program's meaning:

sum4.cc
#include <stdio.h>

float sum_partial(const float *a, int n)
{
    float s0 = 0.0f, s1 = 0.0f, s2 = 0.0f, s3 = 0.0f;
    int i = 0;
    for (; i + 4 <= n; i += 4) {
        s0 += a[i];
        s1 += a[i + 1];
        s2 += a[i + 2];
        s3 += a[i + 3];
    }
    float s = (s0 + s1) + (s2 + s3);
    for (; i < n; ++i)
        s += a[i];
    return s;
}

int main(void)
{
    float a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    printf("%.1f\n", sum_partial(a, 10));
    return 0;
}
Text
55.0

The four accumulators are independent, so the compiler can map them onto the four lanes of one vector register without changing the program's semantics. The SLP vectorizer, which looks for independent scalar operations on adjacent data, recognizes the four adds in the loop body and merges them. With four floats it targets a 128-bit register, and for wider vectors you use eight or sixteen accumulators, matching the width of the target. The order of operations is now fixed by the source, so the result is deterministic across vector widths only if you keep the same number of accumulators.

An integer reduction needs none of this. Integer addition wraps and is associative, so sum += a[i] on int32_t vectorizes directly, and the report shows it. A signed overflow is undefined behavior, which also lets the compiler assume it does not happen.

If you accept reassociation for one loop, say so locally. With OpenMP SIMD support enabled by -fopenmp-simd, add #pragma omp simd reduction(+:s) above the loop, and the compiler may reorder additions in that loop only. The pragma post in this cluster covers it.

Gathers: reading through an index array

A gather reads elements from positions given by another array:

c
void gather(float *out, const float *src, const int *idx, int n)
{
    for (int i = 0; i < n; ++i)
        out[i] = src[idx[i]];
}

The loads from src go to unrelated addresses, so one vector load cannot fetch them. AVX2 provides gather instructions, vgatherdps for floats with 32-bit indices, which load each lane from its own address. GCC and Clang can use them when the target has AVX2, and the cost model decides whether it pays: on several processors a gather is not much faster than eight scalar loads, because each lane is still a separate memory access. The compilers often skip gathers on tuning for those cores, with a remark such as loop not vectorized: the cost-model indicates that vectorization is not beneficial.

Do not fight that. The useful restructurings reduce the need for a gather. If the indices are a permutation applied repeatedly, apply it once and store the result in the new order. If the access is a table lookup of small range, replace it with arithmetic or a smaller table that fits in registers. If you control the data layout, store it so the loop reads contiguous elements: this is the array of structs to struct of arrays change from earlier in this cluster. If the gather is unavoidable, call the intrinsic _mm256_i32gather_ps(src, vindex, 4) directly, so the choice is explicit.

The write-side counterpart, a scatter out[idx[i]] = in[i], has no AVX2 instruction at all. Vectorizing it needs AVX-512, and with duplicate indices the result depends on the order of the writes, so compilers rarely attempt it. Leave scatters scalar.

Early exits: stopping at the first match

A search loop leaves as soon as it finds something:

c
int find_first(const int *a, int n, int key)
{
    for (int i = 0; i < n; ++i)
        if (a[i] == key)
            return i;
    return -1;
}

A vector loop would examine eight elements before knowing whether the first one already matched, so it would read elements beyond the match, which may be past the end of the array or on an unmapped page. The loop also has an exit that depends on data, so the trip count is unknown. GCC 14 added vectorization of some loops with an early break, when it can prove the extra reads are safe, for instance when the array's bounds are known to the compiler. Clang's loop vectorizer has traditionally refused loops with data-dependent exits and reports loop not vectorized: could not determine number of loop iterations. Both rely on conditions you cannot count on, so restructure the loop into blocks.

Split the work into fixed-size chunks. Inside a chunk, run a branch-free inner loop that the compiler can vectorize, then test the chunk's result once:

find_blocked.cc
#include <stdio.h>

#define BLOCK 8

int find_first_blocked(const int *a, int n, int key)
{
    int i = 0;
    for (; i + BLOCK <= n; i += BLOCK) {
        int hit = 0;
        for (int j = 0; j < BLOCK; ++j)
            hit |= (a[i + j] == key);          // no early exit inside the block
        if (hit) {
            for (int j = 0; j < BLOCK; ++j)    // locate it, scalar
                if (a[i + j] == key)
                    return i + j;
        }
    }
    for (; i < n; ++i)
        if (a[i] == key)
            return i;
    return -1;
}

int main(void)
{
    int a[20];
    for (int i = 0; i < 20; ++i) a[i] = i * 3;
    printf("%d %d\n", find_first_blocked(a, 20, 33), find_first_blocked(a, 20, 34));
    return 0;
}
Text
11 -1

The array holds multiples of 3, so 33 is at index 11 and 34 is absent. The inner loop over BLOCK elements has a constant trip count of 8 and no exit, and it accumulates with |=, a reduction on integers that is always safe. Compilers fully unroll or vectorize it into a compare and a mask test. The outer loop reads whole blocks that lie inside the array, since the condition is i + BLOCK <= n, so no read goes out of bounds. The scalar tail handles the last few elements.

The design is the standard shape for vectorized searches, and the library memchr implementation in glibc works the same way, with a vector compare per block and a mask extraction to find the position.

Other blockers worth knowing

Non-unit strides, such as a[2*i], vectorize through interleaving instructions on most targets but with lower efficiency, and the report says not beneficial when the cost model rejects it. Loop-carried dependencies, such as a[i] = a[i-1] + b[i], are true recurrences and cannot vectorize in the obvious way, though a prefix sum has a parallel algorithm that you must write by hand. Calls to non-inlined functions block vectorization, so keep helpers static inline. Mixed element sizes, such as a char array converted to float, create widening conversions the compiler can handle but at a cost in lanes.

A workflow

  1. Compile with the report flags on and find the loop's message.

  2. Match the message to a cause: reordering of floats, unknown trip count, possible alias, cost model.

  3. Apply the matching rewrite: partial sums, blocked scan, restrict, or a data layout change.

  4. Recompile, read the report again, and check the assembly for packed instructions.

  5. Time the result against the scalar build on data of the real size.

If the loop vectorized but did not get faster, the loop is probably limited by memory, and the vector width does not matter.

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.