Add support for AVX2 and runtime feature detection (#174)

- [x] run unit tests
- [x] run all samples
This commit is contained in:
Ethan Rutherford 2026-10-04 00:14:34 +02:00 • committed by GitHub
commit e77352cd60
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
53 changed files with 4681 additions and 3376 deletions

View file

@ -5,6 +5,114 @@
#include "simd.h"
#include "platform.h"
#include <stdbool.h>
#include <stdint.h>
static b3AtomicInt b3_simdWidth;
#if defined( B3_SIMD_HAS_WIDTH_8 )
#if defined( _MSC_VER )
#include <intrin.h>
#endif
// This code enables runtime dispatch to AVX2.
// Inspired by https://github.com/simdjson/simdjson/blob/master/src/internal/isadetection.h
static void b3CpuId( unsigned int leaf, unsigned int subLeaf, unsigned int registers[4] )
{
#if defined( _MSC_VER )
int info[4];
__cpuidex( info, (int)leaf, (int)subLeaf );
registers[0] = (unsigned int)info[0];
registers[1] = (unsigned int)info[1];
registers[2] = (unsigned int)info[2];
registers[3] = (unsigned int)info[3];
#else
// clang cpuid.h can give the rbx swap register the same register as the leaf input, clobbering rbx
__asm__ volatile( "cpuid"
: "=a"( registers[0] ), "=b"( registers[1] ), "=c"( registers[2] ), "=d"( registers[3] )
: "a"( leaf ), "c"( subLeaf ) );
#endif
}
static uint64_t b3GetExtendedControlRegister( void )
{
#if defined( _MSC_VER ) && !defined( __clang__ )
return _xgetbv( 0 );
#else
uint32_t low, high;
__asm__ volatile( "xgetbv" : "=a"( low ), "=d"( high ) : "c"( 0 ) );
return ( (uint64_t)high << 32 ) | low;
#endif
}
static bool b3HasAVX2( void )
{
unsigned int registers[4];
b3CpuId( 0, 0, registers );
if ( registers[0] < 7 )
{
return false;
}
b3CpuId( 1, 0, registers );
unsigned int osxsaveAndAvx = ( 1u << 27 ) | ( 1u << 28 );
if ( ( registers[2] & osxsaveAndAvx ) != osxsaveAndAvx )
{
return false;
}
if ( ( b3GetExtendedControlRegister() & 6 ) != 6 )
{
return false;
}
b3CpuId( 7, 0, registers );
return ( registers[1] & ( 1u << 5 ) ) != 0;
}
#endif
static int b3DetectSIMDWidth( void )
{
#if defined( B3_SIMD_HAS_WIDTH_8 )
return b3HasAVX2() ? 8 : 4;
#else
return 4;
#endif
}
int b3GetSIMDWidth( void )
{
int width = b3AtomicLoadInt( &b3_simdWidth );
if ( width == 0 )
{
width = b3DetectSIMDWidth();
b3AtomicStoreInt( &b3_simdWidth, width );
}
return width;
}
bool b3IsAVX2Available( void )
{
return b3DetectSIMDWidth() == 8;
}
void b3SetSIMDWidth( int width )
{
B3_ASSERT( width == 0 || width == 4 || width == 8 );
if ( width == 8 && b3DetectSIMDWidth() != 8 )
{
width = 4;
}
b3AtomicStoreInt( &b3_simdWidth, width );
}
#if defined( B3_SIMD_SSE2 )
#define B3_TRANSPOSE3( C1, C2, C3 ) \