[Git][ghc/ghc][wip/sjakobi/T25450-march-native] Implement -march=native for x86/x86_64
Simon Jakobi pushed to branch wip/sjakobi/T25450-march-native at Glasgow Haskell Compiler / GHC Commits: b92e3dd2 by Simon Jakobi at 2026-11-21T17:05:23+01:00 Implement -march=native for x86/x86_64 Add a -march=native flag that probes the host CPU and enables the matching CPU-feature DynFlags, so it affects both the NCG and the LLVM backend. Detected features are folded additively into the existing flags, so explicit -m... options are never disabled. The probe is a small C shim over GCC/Clang's __builtin_cpu_supports. It deviates from the builtin for FMA and GFNI, as documented in compiler/cbits/host_cpu_features_x86.c. The C shim and its Haskell decoder share the list of probed features in compiler/HostCpuFeaturesX86.h. The RTS exports the runtime symbols behind the builtin (__cpu_model & co.) so GHCi's runtime linker can load the ghc library where GHCi links statically, e.g. on Windows or musl. Two of the exports are weak references, because not every toolchain defines them. __cpu_features2 is missing before GCC 11 and LLVM 12. __cpu_indicator_init_local exists only with the musl GCC patch carried by Alpine and Gentoo (aports 0013-libgcc_s.patch), which makes __builtin_cpu_init call that alias. A strong reference would break the RTS link with the toolchains that lack the symbol. They also never emit references to it, so their NULL table entry is inert. The flag is registered in expected-undocumented-flags.txt due to #27321. Thanks to @aratamizuki for pointing out the macOS AVX-512 XSAVE quirk and for testing! Closes #25450 Assisted-by: Claude Fable 5.2 - - - - - 17 changed files: - + changelog.d/march-native - compiler/GHC/Driver/DynFlags.hs - compiler/GHC/Driver/Session.hs - compiler/GHC/Platform/CpuFeatures.hs - + compiler/GHC/Platform/HostCpuFeatures.hs - + compiler/HostCpuFeaturesX86.h - + compiler/cbits/host_cpu_features_x86.c - compiler/ghc.cabal.in - docs/users_guide/expected-undocumented-flags.txt - docs/users_guide/using.rst - rts/RtsSymbols.c - testsuite/tests/codeGen/should_gen_asm/all.T - + testsuite/tests/codeGen/should_gen_asm/march-native-enables-popcnt.asm - + testsuite/tests/codeGen/should_gen_asm/march-native-enables-popcnt.hs - testsuite/tests/driver/all.T - + testsuite/tests/driver/march_native_unsupported_arch.hs - + testsuite/tests/driver/march_native_unsupported_arch.stderr Changes: ===================================== changelog.d/march-native ===================================== @@ -0,0 +1,5 @@ +section: compiler +synopsis: Add :ghc-flag:`-march=native`, which on x86 and x86_64 enables the + CPU features of the machine running GHC. +issues: #25450 +mrs: !16126 ===================================== compiler/GHC/Driver/DynFlags.hs ===================================== @@ -446,7 +446,7 @@ data DynFlags = DynFlags { interactivePrint :: Maybe String, -- Machine dependent flags (-m\<blah> stuff) - cpuFeatures :: EnumSet CpuFeature, -- ^ The @-m\<feature\>@ flags that were passed. + cpuFeatures :: EnumSet CpuFeature, -- ^ The CPU features requested by @-m...@ flags. -- See Note [CPU features] in GHC.Platform.CpuFeatures. la664 :: Bool, -- ^ Enable LA664 instructions ===================================== compiler/GHC/Driver/Session.hs ===================================== @@ -1,4 +1,5 @@ {-# LANGUAGE CPP #-} +{-# LANGUAGE MultiWayIf #-} ------------------------------------------------------------------------------- -- @@ -229,6 +230,8 @@ import GHC.Platform.CpuFeatures import GHC.Platform.Ways import GHC.Platform.Profile import GHC.Platform.ArchOS +import GHC.Platform.Host (hostPlatformArch) +import GHC.Platform.HostCpuFeatures (hostX86CpuFeatures) import GHC.Unit.Types import GHC.Unit.Parser @@ -1709,6 +1712,7 @@ dynamic_flags_deps = [ (setDumpFlag Opt_D_dump_faststrings) ------ Machine dependent (-m<blah>) stuff --------------------------- + , make_ord_flag defGhcFlag "march=native" (NoArg enableHostCpuFeatures) , make_ord_flag defGhcFlag "mla664" (noArg (\d -> d { la664 = True })) @@ -2934,6 +2938,17 @@ setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag) setCpuFeature :: CpuFeature -> DynFlags -> DynFlags setCpuFeature feat dflags = dflags { cpuFeatures = EnumSet.insert feat (cpuFeatures dflags) } +-- | @-march=native@: enable the CPU features of the host GHC is running on. +enableHostCpuFeatures :: DynP () +enableHostCpuFeatures = do + arch <- platformArch . targetPlatform <$> liftEwM getCmdLineState + if | arch /= ArchX86 && arch /= ArchX86_64 + -> addErr "-march=native is only supported on x86 and x86_64 targets" + | arch /= hostPlatformArch + -> addErr "-march=native is not supported when the target architecture differs from the host's" + | otherwise + -> upd $ \d -> d { cpuFeatures = cpuFeatures d `mappend` hostX86CpuFeatures } + -- | The @-m\<feature\>@ flag for a 'CpuFeature'. cpuFeatureFlagDep :: CpuFeature -> (Deprecation, Flag (CmdLineP DynFlags)) cpuFeatureFlagDep feat = ===================================== compiler/GHC/Platform/CpuFeatures.hs ===================================== @@ -64,8 +64,9 @@ others: We keep two representations: - A. 'DynFlags' records the set of flags that were passed, as an - 'EnumSet' of 'CpuFeature'. Nothing is implied at this stage. + A. 'DynFlags' records the set of requested features, as an 'EnumSet' of + 'CpuFeature': one per -m<feature> flag passed, plus the features of the + host under -march=native. Nothing is implied at this stage. B. 'initCpuFeatures' turns this set into a 'CpuFeatures' value, applying the implications and the baseline of the target architecture. This ===================================== compiler/GHC/Platform/HostCpuFeatures.hs ===================================== @@ -0,0 +1,41 @@ +{-# LANGUAGE CPP #-} + +module GHC.Platform.HostCpuFeatures + ( hostX86CpuFeatures + ) where + +import GHC.Prelude + +import GHC.Data.EnumSet (EnumSet) +import qualified GHC.Data.EnumSet as EnumSet +import GHC.Platform.CpuFeatures (CpuFeature(..)) + +import Data.Word (Word64) +import System.IO.Unsafe (unsafePerformIO) + +#include "HostCpuFeaturesX86.h" + +#define GHC_X86_FEATURE_CONS(feat, cond) feat : + +-- | The features of the table in @HostCpuFeaturesX86.h@, in row order. +probedX86CpuFeatures :: [CpuFeature] +probedX86CpuFeatures = GHC_X86_PROBED_FEATURES(GHC_X86_FEATURE_CONS) [] + +-- | The host's x86 CPU features. +hostX86CpuFeatures :: EnumSet CpuFeature +hostX86CpuFeatures = unsafePerformIO $ do + mask <- hostX86CpuFeatureMask + pure $ EnumSet.fromList + [ feat + | (bit, feat) <- zip [0 ..] probedX86CpuFeatures + , testBit mask bit + ] +{-# NOINLINE hostX86CpuFeatures #-} + +#if defined(javascript_HOST_ARCH) +hostX86CpuFeatureMask :: IO Word64 +hostX86CpuFeatureMask = pure 0 +#else +foreign import ccall unsafe "ghc_host_x86_cpu_feature_mask" + hostX86CpuFeatureMask :: IO Word64 +#endif ===================================== compiler/HostCpuFeaturesX86.h ===================================== @@ -0,0 +1,24 @@ +/* The x86 features that -march=native probes. Each row pairs a CpuFeature + constructor with the C condition (see cbits/host_cpu_features_x86.c) that + detects the feature on the host. SSE and SSE2 are not probed: they are + GHC's x86 baseline. + + Row i is bit i of the mask that ghc_host_x86_cpu_feature_mask returns and + GHC.Platform.HostCpuFeatures decodes, so the table can hold at most 64 + rows. */ +#define GHC_X86_PROBED_FEATURES(F) \ + F(Feat_SSE3, SUPPORTS("sse3")) \ + F(Feat_SSSE3, SUPPORTS("ssse3")) \ + F(Feat_SSE4, SUPPORTS("sse4.1")) \ + F(Feat_SSE4_2, SUPPORTS("sse4.2")) \ + F(Feat_AVX, SUPPORTS("avx")) \ + F(Feat_AVX2, SUPPORTS("avx2")) \ + F(Feat_AVX512F, SUPPORTS("avx512f")) \ + F(Feat_AVX512BW, SUPPORTS("avx512bw")) \ + F(Feat_AVX512CD, SUPPORTS("avx512cd")) \ + F(Feat_AVX512DQ, SUPPORTS("avx512dq")) \ + F(Feat_AVX512VL, SUPPORTS("avx512vl")) \ + F(Feat_BMI, SUPPORTS("bmi")) \ + F(Feat_BMI2, SUPPORTS("bmi2")) \ + F(Feat_FMA, SUPPORTS_FMA) \ + F(Feat_GFNI, SUPPORTS_GFNI) ===================================== compiler/cbits/host_cpu_features_x86.c ===================================== @@ -0,0 +1,56 @@ +#include <HsFFI.h> + +/* Runtime x86 CPU feature detection backing GHC.Platform.HostCpuFeatures + (-march=native). + + The __builtin_cpu_* calls below compile to references to libgcc/compiler-rt + symbols (__cpu_model & co.), which GHCi's runtime linker can only resolve + because the RTS exports them: see RTS_X86_CPU_MODEL_SYMBOLS in + rts/RtsSymbols.c. */ + +#include "HostCpuFeaturesX86.h" + +#if defined(__i386__) || defined(__x86_64__) + +#define SUPPORTS(name) __builtin_cpu_supports(name) + +/* FMA is usable only when the OS saves the AVX register state. However + compiler-rt's cpu_model/x86.c reports "fma" from the raw CPUID bit. */ +#define SUPPORTS_FMA (SUPPORTS("fma") && SUPPORTS("avx")) + +/* GFNI joined the __builtin_cpu_supports feature lists later than the + other features here (GCC 11; compiler-rt's cpu_model in LLVM 12). + Under an older bootstrap compiler we conservatively report no GFNI. */ +#if (defined(__clang_major__) && __clang_major__ >= 12) \ + || (!defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 11) +#define SUPPORTS_GFNI SUPPORTS("gfni") +#else +#define SUPPORTS_GFNI 0 +#endif + +HsWord64 ghc_host_x86_cpu_feature_mask(void) +{ + __builtin_cpu_init(); + + HsWord64 mask = 0; + int bit = 0; + +#define GHC_X86_PROBE(feat, cond) \ + if (cond) { mask |= (HsWord64)1 << bit; } \ + bit++; + + GHC_X86_PROBED_FEATURES(GHC_X86_PROBE) + +#undef GHC_X86_PROBE + + return mask; +} + +#else + +HsWord64 ghc_host_x86_cpu_feature_mask(void) +{ + return 0; +} + +#endif ===================================== compiler/ghc.cabal.in ===================================== @@ -32,6 +32,7 @@ extra-source-files: GHC/Builtin/primops.txt.pp Unique.h CodeGen.Platform.h + HostCpuFeaturesX86.h -- Shared with rts via hard-link at configure time. This is safer -- for Windows, where symlinks don't work out of the box, so we -- can't just commit some in git. @@ -186,6 +187,7 @@ Library c-sources: cbits/cutils.c cbits/genSym.c + cbits/host_cpu_features_x86.c cbits/keepCAFsForGHCi.c hs-source-dirs: @@ -690,6 +692,7 @@ Library GHC.Platform.AArch64 GHC.Platform.Constants GHC.Platform.CpuFeatures + GHC.Platform.HostCpuFeatures GHC.Platform.LA64 GHC.Platform.NoRegs GHC.Platform.PPC ===================================== docs/users_guide/expected-undocumented-flags.txt ===================================== @@ -74,6 +74,7 @@ -instantiated-with -keep-hi-file -keep-o-file +-march=native -n -no-keep-hi-file -no-keep-o-file ===================================== docs/users_guide/using.rst ===================================== @@ -1887,6 +1887,30 @@ Some flags only make sense for particular target platforms. so this flag has no effect when used with the :ref:`native code generator <native-code-gen>` or the :ref:`LLVM backend <llvm-code-gen>`. +.. ghc-flag:: -march=native + :shortdesc: (x86 only) Enable the CPU features of the host + :type: dynamic + :category: platform-options + + (x86 only) Probe the CPU of the machine running GHC and enable the + corresponding ``-m...`` CPU-feature options (for example ``-msse4.2``, + ``-mavx2``, ``-mbmi2``, ``-mfma``). The detected features apply to both the + :ref:`native code generator <native-code-gen>` and the + :ref:`LLVM backend <llvm-code-gen>`. + + The detected features are enabled in addition to any ``-m...`` options + given explicitly, regardless of their order on the command line. + + .. warning:: + + Code compiled with ``-march=native`` may use instructions that are not + available on other CPUs, and is therefore not portable to a different + machine. + + The flag is rejected on other targets. A cross-compiler also rejects it + when its target architecture differs from the one GHC itself runs on, since + the probed CPU then says nothing about the target. + Haddock ------- ===================================== rts/RtsSymbols.c ===================================== @@ -1045,6 +1045,35 @@ extern char **environ; #define RTS_ARM_OUTLINE_ATOMIC_SYMBOLS #endif +// libgcc/compiler-rt symbols behind __builtin_cpu_supports and +// __builtin_cpu_init, which compiler/cbits/host_cpu_features_x86.c uses +// (-march=native). Without them the runtime linker cannot load the ghc +// library's object code, e.g. for plugins in a statically linked GHCi. +#if defined(i386_HOST_ARCH) || defined(x86_64_HOST_ARCH) + +// Weak: missing before GCC 11 and LLVM 12. +extern StgWord __cpu_features2[] __attribute__((weak)); + +// Alpine's and Gentoo's musl GCCs patch __builtin_cpu_init to call this +// alias of __cpu_indicator_init. Weak: other musl toolchains lack it. +#if defined(linux_HOST_OS) && !defined(__GLIBC__) +extern void __cpu_indicator_init_local(void) __attribute__((weak)); +#define RTS_X86_CPU_INIT_LOCAL_SYMBOLS \ + SymI_NeedsProto(__cpu_indicator_init_local) +#else +#define RTS_X86_CPU_INIT_LOCAL_SYMBOLS +#endif + +#define RTS_X86_CPU_MODEL_SYMBOLS \ + SymI_NeedsProto(__cpu_indicator_init) \ + SymI_NeedsDataProto(__cpu_model) \ + SymI_NeedsDataProto(__cpu_features2) \ + RTS_X86_CPU_INIT_LOCAL_SYMBOLS + +#else +#define RTS_X86_CPU_MODEL_SYMBOLS +#endif + // Symbols defined by libc #define RTS_LIBC_SYMBOLS \ SymI_HasProto_redirect(atexit, atexit, STRENGTH_STRONG, SYM_TYPE_CODE) /* See Note [Strong symbols] */ \ @@ -1205,6 +1234,7 @@ RTS_OPENBSD_ONLY_SYMBOLS RTS_LIBC_SYMBOLS RTS_LIBGCC_SYMBOLS RTS_ARCH_LIBGCC_SYMBOLS +RTS_X86_CPU_MODEL_SYMBOLS RTS_FINI_ARRAY_SYMBOLS RTS_LIBFFI_SYMBOLS RTS_ARM_OUTLINE_ATOMIC_SYMBOLS @@ -1260,6 +1290,7 @@ void initLinkerRtsSyms (StrHashTable *symhash) { RTS_OPENBSD_ONLY_SYMBOLS RTS_LIBGCC_SYMBOLS RTS_ARCH_LIBGCC_SYMBOLS + RTS_X86_CPU_MODEL_SYMBOLS RTS_FINI_ARRAY_SYMBOLS RTS_LIBFFI_SYMBOLS RTS_ARM_OUTLINE_ATOMIC_SYMBOLS ===================================== testsuite/tests/codeGen/should_gen_asm/all.T ===================================== @@ -17,6 +17,9 @@ test('msse-option-order', [unless(arch('x86_64') or arch('i386'), skip), when(unregisterised(), skip)], compile_grep_asm, ['hs', False, '-msse4.2 -msse2']) test('mavx-should-enable-popcnt', [unless(arch('x86_64') or arch('i386'), skip), when(unregisterised(), skip)], compile_grep_asm, ['hs', False, '-mavx']) +test('march-native-enables-popcnt', + [unless((arch('x86_64') or arch('i386')) and have_cpu_feature('sse4_2'), skip), + when(unregisterised(), skip)], compile_grep_asm, ['hs', False, '-march=native']) test('avx512-int64-mul', [unless(arch('x86_64'), skip), when(unregisterised(), skip)], compile_grep_asm, ['hs', True, '-mavx512dq -mavx512vl']) test('avx512-int64-minmax', [unless(arch('x86_64'), skip), ===================================== testsuite/tests/codeGen/should_gen_asm/march-native-enables-popcnt.asm ===================================== @@ -0,0 +1 @@ +popcnt(?![0-9]) \ No newline at end of file ===================================== testsuite/tests/codeGen/should_gen_asm/march-native-enables-popcnt.hs ===================================== @@ -0,0 +1,9 @@ +-- On a host with SSE4.2, `-march=native` should enable `popcnt`. +import Data.Bits + +{-# NOINLINE foo #-} +foo :: Int -> Int +foo x = 1 + popCount x + +main :: IO () +main = print (foo 42) ===================================== testsuite/tests/driver/all.T ===================================== @@ -223,6 +223,11 @@ test('T9938B', [], makefile_test, []) test('T9963', exit_code(1), run_command, ['{compiler} --interactive -ignore-dot-ghci --print-libdir']) +test('march_native_unsupported_arch', + [when(arch('x86_64') or arch('i386'), skip)], + compile_fail, + ['-march=native']) + test('T10219', normal, run_command, # `-x hspp` in make mode should work. # Note: need to specify `-x hspp` before the filename. ===================================== testsuite/tests/driver/march_native_unsupported_arch.hs ===================================== @@ -0,0 +1 @@ +module M where ===================================== testsuite/tests/driver/march_native_unsupported_arch.stderr ===================================== @@ -0,0 +1,2 @@ +ghc: on the commandline: -march=native is only supported on x86 and x86_64 targets +Usage: For basic information, try the `--help' option. View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/b92e3dd2b6fa837bad871d081ffcfd8a... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/b92e3dd2b6fa837bad871d081ffcfd8a... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Simon Jakobi (@sjakobi)