Port an SSE Intrinsics Loop to AVX2
Convert a 128-bit SSE integer loop to 256-bit AVX2: new types, a step of eight, the -mavx2 flag, runtime dispatch and the lane-crossing trap.

Moving a loop from SSE to AVX2 doubles the vector width from 128 to 256 bits, which means eight 32-bit values per instruction instead of four. The change is mostly mechanical: new type names, new function prefixes, a step of eight in place of four. But three things bite, and they are the reason this deserves its own post: the instruction set must be enabled and checked at run time, many AVX2 operations work on two independent 128-bit halves and cannot move data between them, and reductions need an explicit step to merge the halves. This post ports an integer array sum from SSE to AVX2 in C, and then covers dispatch. Unlike the first loop in this cluster, which added floats, this one uses 32-bit integers, because integer arithmetic on 256-bit registers needs AVX2 while float arithmetic needs only AVX. Code builds with GCC 15 or Clang 20 for x86-64.
The SSE version
The starting loop sums an array of int32_t with four lanes of partial sums and combines them at the end:
#include <emmintrin.h> // SSE2 integer intrinsics
#include <stddef.h>
#include <stdint.h>
int64_t sum_sse(const int32_t *a, size_t n)
{
__m128i acc = _mm_setzero_si128();
size_t i = 0;
for (; i + 4 <= n; i += 4) {
__m128i v = _mm_loadu_si128((const __m128i *)(a + i));
acc = _mm_add_epi32(acc, v);
}
int32_t lanes[4];
_mm_storeu_si128((__m128i *)lanes, acc);
int64_t total = (int64_t)lanes[0] + lanes[1] + lanes[2] + lanes[3];
for (; i < n; ++i)
total += a[i];
return total;
}The accumulators are 32-bit lanes, so the sum can overflow a lane if the array is large or its values are big. The code widens each lane to 64 bits only at the end, which is fine for modest inputs and wrong for arrays whose partial sums exceed 2^31. A production version would widen as it goes, with _mm_cvtepi32_epi64, or flush the accumulator periodically.
The AVX2 version
Every piece has a 256-bit counterpart:
| SSE2 | AVX2 |
|---|---|
#include <emmintrin.h> | #include <immintrin.h> |
__m128i | __m256i |
_mm_setzero_si128() | _mm256_setzero_si256() |
_mm_loadu_si128 | _mm256_loadu_si256 |
_mm_add_epi32 | _mm256_add_epi32 |
_mm_storeu_si128 | _mm256_storeu_si256 |
| step 4 | step 8 |
#include <immintrin.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
int64_t sum_avx2(const int32_t *a, size_t n)
{
__m256i acc = _mm256_setzero_si256();
size_t i = 0;
for (; i + 8 <= n; i += 8) {
__m256i v = _mm256_loadu_si256((const __m256i *)(a + i));
acc = _mm256_add_epi32(acc, v);
}
// merge the two 128-bit halves, then reduce the four lanes
__m128i lo = _mm256_castsi256_si128(acc);
__m128i hi = _mm256_extracti128_si256(acc, 1);
__m128i s = _mm_add_epi32(lo, hi);
int32_t lanes[4];
_mm_storeu_si128((__m128i *)lanes, s);
int64_t total = (int64_t)lanes[0] + lanes[1] + lanes[2] + lanes[3];
for (; i < n; ++i)
total += a[i];
return total;
}
int main(void)
{
int32_t a[19];
for (int i = 0; i < 19; ++i) a[i] = i + 1;
printf("sum = %lld\n", (long long)sum_avx2(a, 19));
return 0;
}sum = 190Build it with gcc -O2 -mavx2 sum_avx2.c. The sum of 1 through 19 is 190, which exercises two full vector iterations (16 elements) and a three-element tail. Without -mavx2, GCC reports that the target specific option mismatch or that the intrinsic needs the avx2 feature, because the compiler refuses to emit instructions the selected target may not support.
The reduction merges the halves
An AVX2 register is two 128-bit halves, and a good part of the instruction set treats them separately. The reduction above shows the usual pattern: _mm256_castsi256_si128 takes the low half at no cost, since it is a reinterpretation, _mm256_extracti128_si256(acc, 1) pulls out the high half, and an ordinary 128-bit add combines them. After that the four-lane reduction proceeds as in the SSE version.
Operations that are lane-local include the shuffle and unpack families. _mm256_unpacklo_epi32 interleaves the low elements of each 128-bit half separately, so it does not produce the same result as concatenating two 128-bit unpacks into one long vector. _mm256_hadd_epi32, the horizontal add, adds adjacent pairs within each half, so a naive port of an SSE horizontal sum to 256 bits gives a result in which the halves are still separate. The fix for data that must cross halves is a lane-crossing instruction, such as _mm256_permute2x128_si256 or _mm256_permutevar8x32_epi32, and each has a higher latency than in-lane operations. Intel's Intrinsics Guide marks the latency and throughput of each.
The rule of thumb for a port: element-wise arithmetic, such as add, multiply, min and compare, ports with a rename, and anything that rearranges elements needs a careful rewrite and a test.
Enable and check at run time
Not every x86-64 processor supports AVX2. Intel's Haswell introduced it in 2013 and AMD's Excavator and Zen cores have it, but some low-power chips and old machines do not. The operating system must also support saving the wider registers, which every current OS does. A binary that executes an AVX2 instruction on an unsupported processor dies with an illegal instruction signal.
Compiling the whole program with -mavx2 makes the compiler use AVX2 everywhere, including in ordinary code, so the whole binary requires it. The safer pattern is runtime dispatch: build the AVX2 function with a per-function target attribute and pick it after checking the CPU:
__attribute__((target("avx2")))
int64_t sum_avx2(const int32_t *a, size_t n); // body as above, no -mavx2 needed
int64_t sum_dispatch(const int32_t *a, size_t n)
{
if (__builtin_cpu_supports("avx2"))
return sum_avx2(a, n);
return sum_sse(a, n);
}__builtin_cpu_supports("avx2") is available in GCC and Clang and reads the CPUID information, which the runtime initializes at program start. The target("avx2") attribute lets the compiler use AVX2 inside that one function. Intrinsics inside a function with the matching target attribute compile without the global flag. Keep sum_sse as the baseline, since SSE2 is guaranteed, and the program runs everywhere.
GCC also has function multiversioning, __attribute__((target_clones("avx2","default"))), which generates both versions and picks one at load time through a resolver, with no manual dispatch code.
Mixing SSE and AVX code
Mixing legacy SSE instructions and 256-bit AVX instructions can cost a performance penalty on some processors when the upper halves of the registers are dirty. The compiler inserts vzeroupper at function boundaries when it compiles AVX code to avoid this. Mixed code from different sources, such as a hand-written assembly routine, may need the _mm256_zeroupper() intrinsic before calling into SSE code. The transition penalties are documented in Intel's optimization manual and covered in the AVX-SSE transition post earlier in this site's assembly cluster.
Alignment
Unaligned 256-bit loads work on every AVX2 processor. A 32-byte load that straddles a cache line boundary costs more, and with 64-byte lines, one in every two 32-byte-aligned loads at the wrong offset would cross, so aligning buffers to 32 bytes avoids all of them. aligned_alloc(32, size) with a size that is a multiple of 32 gives you aligned storage, and _mm256_load_si256 then asserts the alignment, with a fault on violation.
Frequency and throttling
Some processors lower their clock when they execute heavy 256-bit or 512-bit instructions. The effect was significant on early AVX-512 server parts, and it is smaller on recent designs. Vendor documentation describes the license levels for each generation. For AVX2 integer adds, the effect is mild on current hardware, and the way to know is to measure your own code on your own target with the whole workload, not just the kernel.
Testing
Test the AVX2 function against the SSE or scalar version on every array length from 0 to 40, which covers each tail length from 0 to 7 several times, and on data with negative values. Run the check on a machine that supports AVX2 and, for the dispatcher, force the fallback path by setting an environment switch in test builds, so that both paths are exercised in CI.


