[Git][ghc/ghc][wip/sjakobi/T25450-march-native] Implement -march=native for x86/x86_64
by Simon Jakobi (@sjakobi) 21 Nov '26
by Simon Jakobi (@sjakobi) 21 Nov '26
21 Nov '26
Simon Jakobi pushed to branch wip/sjakobi/T25450-march-native at Glasgow Haskell Compiler / GHC
Commits:
9322eda4 by Simon Jakobi at 2026-11-21T17:57:07+01:00
Implement -march=native for x86/x86_64
-march=native probes the host CPU and enables the corresponding -m...
CPU-feature flags, for both the NCG and the LLVM backend.
The probe is a C shim over GCC/Clang's __builtin_cpu_supports. The RTS
exports the libgcc/compiler-rt symbols behind the builtin, so that
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 some toolchains lack them. Those toolchains never
emit references to them either, so their NULL table entries are inert.
As a side effect, every x86 Haskell program now links libgcc's
cpuinfo.o (about 5 KB with GCC 13) and runs its CPUID constructor at
start-up.
The march_native_matches_cc test checks the probe against the C
compiler's -march=native, except for GFNI, BMI and BMI2.
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
- - - - -
19 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/Makefile
- testsuite/tests/driver/all.T
- + testsuite/tests/driver/march_native_matches_cc.hs
- + 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/Makefile
=====================================
@@ -502,6 +502,15 @@ withRtsOpts:
T3364:
-"$(TEST_HC)" $(TEST_HC_OPTS) -H
+# GHC and the C compiler should detect the same host CPU features.
+.PHONY: march_native_matches_cc
+march_native_matches_cc:
+ "$(TEST_HC)" $(TEST_HC_OPTS) -march=native -E -cpp march_native_matches_cc.hs -o ghc.out
+ "$(TEST_CC)" $(TEST_CC_OPTS) -march=native -E -x c march_native_matches_cc.hs > cc.out
+ sed -n 's/^\(feat [a-z0-9.]*\).*/\1/p' ghc.out > ghc.feats
+ sed -n 's/^\(feat [a-z0-9.]*\).*/\1/p' cc.out > cc.feats
+ diff -u ghc.feats cc.feats
+
.PHONY: T706
T706:
cp T706a.hs T706.hs
=====================================
testsuite/tests/driver/all.T
=====================================
@@ -223,6 +223,15 @@ 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('march_native_matches_cc',
+ [unless(arch('x86_64') or arch('i386'), skip), when(config.cross, skip)],
+ makefile_test, [])
+
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_matches_cc.hs
=====================================
@@ -0,0 +1,38 @@
+-- Not a Haskell module: see the march_native_matches_cc rule in the Makefile.
+-- GFNI is not listed: a GHC built with an older C compiler does not detect it.
+#if defined(__SSE3__)
+feat sse3
+#endif
+#if defined(__SSSE3__)
+feat ssse3
+#endif
+#if defined(__SSE4_1__)
+feat sse4.1
+#endif
+#if defined(__SSE4_2__)
+feat sse4.2
+#endif
+#if defined(__AVX__)
+feat avx
+#endif
+#if defined(__AVX2__)
+feat avx2
+#endif
+#if defined(__AVX512F__)
+feat avx512f
+#endif
+#if defined(__AVX512BW__)
+feat avx512bw
+#endif
+#if defined(__AVX512CD__)
+feat avx512cd
+#endif
+#if defined(__AVX512DQ__)
+feat avx512dq
+#endif
+#if defined(__AVX512VL__)
+feat avx512vl
+#endif
+#if defined(__FMA__)
+feat fma
+#endif
=====================================
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/9322eda411cc3aad26ac3078d66991a…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/9322eda411cc3aad26ac3078d66991a…
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
1
0
[Git][ghc/ghc][wip/sjakobi/T25450-march-native] Implement -march=native for x86/x86_64
by Simon Jakobi (@sjakobi) 21 Nov '26
by Simon Jakobi (@sjakobi) 21 Nov '26
21 Nov '26
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/b92e3dd2b6fa837bad871d081ffcfd8…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/b92e3dd2b6fa837bad871d081ffcfd8…
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
1
0
[Git][ghc/ghc][wip/T27737] Expermimentally disable case-binder unfoldings in Gentle phase
by Simon Peyton Jones (@simonpj) 21 Nov '26
by Simon Peyton Jones (@simonpj) 21 Nov '26
21 Nov '26
Simon Peyton Jones pushed to branch wip/T27737 at Glasgow Haskell Compiler / GHC
Commits:
f4e950c7 by Simon Peyton Jones at 2026-11-21T14:49:42+00:00
Expermimentally disable case-binder unfoldings in Gentle phase
Provoked by #28164.
---- Problem ----------
f x = join j y = ...(case x of K a b c -> e)..... in
case x of K a b c ->
...
Here we can float out that (case x of K a b c -> c)
But if we float out the inner case x past the join point
we get
f x = case x of K a b c ->
join j y = ...(case x of K a b c -> e)..... in
...
Now we simplify the inner case (which is normally good)
f x = case x of K a b c ->
join j y = ...e..... in
...
but now we can't float e.
---- Solution ----------
Don't add local unfoldings inside case alternatives, before FloatOut.
A tiny, one-line change.
- - - - -
6 changed files:
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- + testsuite/tests/simplCore/should_compile/T28164S.hs
- testsuite/tests/simplCore/should_compile/all.T
- + testsuite/tests/simplCore/should_run/T28164R.hs
- + testsuite/tests/simplCore/should_run/T28164R.stdout
- testsuite/tests/simplCore/should_run/all.T
Changes:
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -3785,30 +3785,24 @@ simplAlt env _scrut' imposs_deflt_cons case_bndr' bndr_swap' cont' (Alt DEFAULT
; (floats, rhs') <- simplExprF env' rhs cont'
; return (DEFAULT, [], floats, rhs') }
-simplAlt env _scrut' _ case_bndr' bndr_swap' cont' (Alt (LitAlt lit) bndrs rhs)
+simplAlt env _scrut' _ case_bndr' bndr_swap' cont' (Alt lit_alt@(LitAlt {}) bndrs rhs)
= assert (null bndrs) $
- do { let env' = addAltUnfoldings env case_bndr' bndr_swap' (Lit lit)
+ do { let env' = addAltUnfoldings env case_bndr' bndr_swap' lit_alt []
; (floats, rhs') <- simplExprF env' rhs cont'
- ; return (LitAlt lit, [], floats, rhs') }
+ ; return (lit_alt, [], floats, rhs') }
-simplAlt env scrut' _ case_bndr' bndr_swap' cont' (Alt (DataAlt con) vs rhs)
+simplAlt env scrut' _ case_bndr' bndr_swap' cont' (Alt data_alt@(DataAlt con) vs rhs)
= do { -- See Note [Adding evaluatedness info to pattern-bound variables]
-- and Note [DataAlt occ info]
; let vs_with_info = adjustFieldsIdInfo scrut' case_bndr' bndr_swap' con vs
+ ; (env', vs') <- simplBinders env vs_with_info
-- Adjust evaluated-ness and occ-info flags before `simplBinders`
-- because the latter extends the in-scope set, which propagates this
-- adjusted info to use sites.
- ; (env', vs') <- simplBinders env vs_with_info
-
- -- Bind the case-binder to (con args)
- ; let inst_tys' = tyConAppArgs (idType case_bndr')
- con_app :: OutExpr
- con_app = mkConApp2 con inst_tys' vs'
- env'' = addAltUnfoldings env' case_bndr' bndr_swap' con_app
-
+ ; let env'' = addAltUnfoldings env' case_bndr' bndr_swap' data_alt vs'
; (floats, rhs') <- simplExprF env'' rhs cont'
- ; return (DataAlt con, vs', floats, rhs') }
+ ; return (data_alt, vs', floats, rhs') }
{- Note [Adding evaluatedness info to pattern-bound variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -3911,12 +3905,17 @@ addDefaultUnfoldings env case_bndr bndr_swap imposs_deflt_cons
| otherwise = env1
-addAltUnfoldings :: SimplEnv -> OutId -> BinderSwapDecision -> OutExpr -> SimplEnv
-addAltUnfoldings env case_bndr bndr_swap con_app
+addAltUnfoldings :: SimplEnv -> OutId -> BinderSwapDecision
+ -> AltCon -> [OutVar] -> SimplEnv
+addAltUnfoldings env case_bndr bndr_swap con bndrs
= env2
where
- con_app_unf = mk_simple_unf con_app
- env1 = addBinderUnfolding env case_bndr con_app_unf
+ -- Add unfolding for case_bndr
+ -- See #28164
+ env1 | seCaseCase env || null bndrs
+ = addBinderUnfolding env case_bndr con_app_unf
+ | otherwise
+ = env
-- See Note [Add unfolding for scrutinee]
-- e.g. case (x |> co) of K a b -> blah
@@ -3929,6 +3928,18 @@ addAltUnfoldings env case_bndr bndr_swap con_app
| otherwise = env1
+ -- Bind the case-binder to (con args)
+ con_app_unf :: Unfolding
+ con_app_unf = mk_simple_unf con_app
+
+ con_app :: OutExpr
+ con_app = case con of
+ DEFAULT -> pprPanic "addAltUnfoldings" (ppr case_bndr)
+ LitAlt lit -> Lit lit
+ DataAlt con -> mkConApp2 con inst_tys bndrs
+ where
+ inst_tys = tyConAppArgs (idType case_bndr)
+
-- Force the opts, so that the whole SimplEnv isn't retained
!opts = seUnfoldingOpts env
mk_simple_unf = mkSimpleUnfolding opts
=====================================
testsuite/tests/simplCore/should_compile/T28164S.hs
=====================================
@@ -0,0 +1,17 @@
+{-# LANGUAGE BangPatterns #-}
+module T28164S where
+
+-- step is lazy in k (the x < 0 branch), so its worker takes k boxed.
+-- At -O2 liberate-case peels hash's first iteration, which puts a
+-- `case k of I# y` in the body of go's join points; go's exit also takes
+-- k apart.
+{-# NOINLINE step #-}
+step :: Int -> Int -> Int
+step k x
+ | x < 0 = 0
+ | otherwise = go (hash 0 0)
+ where
+ hash !i !acc | i == k = acc
+ | otherwise = hash (i + 1) (acc * 131 + x + i)
+ go !j | j < 1000 = j * k
+ | otherwise = go (j `quot` 7)
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -634,3 +634,6 @@ test('T27737a', normal, compile, ['-O'])
test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
+
+# T28164S: the idea is there should be only one 'case k' in 'step'
+test('T28164S', grep_errmsg(r'case k'), compile, ['-O2 -ddump-simpl'])
=====================================
testsuite/tests/simplCore/should_run/T28164R.hs
=====================================
@@ -0,0 +1,35 @@
+module Main (main) where
+
+import System.Environment (getArgs)
+
+data T = T ![Int] !Int !Int
+
+{-# NOINLINE work #-}
+work :: [Int] -> [Int] -> Int -> Int -> [Int]
+work sh ss o v = [ x * o + v + y | x <- sh, y <- ss ]
+
+{-# INLINE expensive #-}
+expensive :: [Int] -> T -> [Int]
+expensive sh (T ss o v) = work sh ss o v
+
+{-# INLINE z #-}
+z :: [Int] -> T -> T -> Int
+z sh (T ss _ v) (T _ _ v')
+ | v == 1, v' == 1 = sum ss
+z sh t t' = sum (expensive sh t) + sum (expensive sh t')
+
+{-# NOINLINE mkT #-}
+mkT :: Int -> T
+mkT n = T [1 .. n] 3 5
+
+c :: T
+c = mkT 1000
+
+{-# NOINLINE f #-}
+f :: T -> Int
+f a = z [1 .. 100] a c
+
+main :: IO ()
+main = do
+ [n] <- map read <$> getArgs
+ print (sum [ f (T [k] 0 2) | k <- [1 .. n] ])
=====================================
testsuite/tests/simplCore/should_run/T28164R.stdout
=====================================
@@ -0,0 +1 @@
+13142050000
=====================================
testsuite/tests/simplCore/should_run/all.T
=====================================
@@ -126,3 +126,4 @@ test('T27005', [], multimod_compile_and_run, ['T27005', '-O'])
test('T27705', [extra_hc_opts('+RTS -M500M -RTS')], multimod_compile_and_run,
['T27705', '-O2 -fexpose-all-unfoldings'])
test('T28163', normal, compile_and_run, ['-O'])
+test('T28164R', normal, compile_and_run, ['-O'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/f4e950c72027226fa8fdf6ce37cd4ac…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/f4e950c72027226fa8fdf6ce37cd4ac…
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
1
0
[Git][ghc/ghc][wip/T27737] Expermimentally disable case-binder unfoldings in Gentle phase
by Simon Peyton Jones (@simonpj) 21 Nov '26
by Simon Peyton Jones (@simonpj) 21 Nov '26
21 Nov '26
Simon Peyton Jones pushed to branch wip/T27737 at Glasgow Haskell Compiler / GHC
Commits:
8cafe4c3 by Simon Peyton Jones at 2026-11-21T14:08:20+00:00
Expermimentally disable case-binder unfoldings in Gentle phase
Provoked by #28164.
---- Problem ----------
f x = join j y = ...(case x of K a b c -> e)..... in
case x of K a b c ->
...
Here we can float out that (case x of K a b c -> c)
But if we float out the inner case x past the join point
we get
f x = case x of K a b c ->
join j y = ...(case x of K a b c -> e)..... in
...
Now we simplify the inner case (which is normally good)
f x = case x of K a b c ->
join j y = ...e..... in
...
but now we can't float e.
---- Solution ----------
Don't add local unfoldings inside case alternatives, before FloatOut.
A tiny, one-line change.
- - - - -
6 changed files:
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- + testsuite/tests/simplCore/should_compile/T28164S.hs
- testsuite/tests/simplCore/should_compile/all.T
- + testsuite/tests/simplCore/should_run/T28164R.hs
- + testsuite/tests/simplCore/should_run/T28164R.stdout
- testsuite/tests/simplCore/should_run/all.T
Changes:
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -3916,7 +3916,8 @@ addAltUnfoldings env case_bndr bndr_swap con_app
= env2
where
con_app_unf = mk_simple_unf con_app
- env1 = addBinderUnfolding env case_bndr con_app_unf
+ env1 | seCaseCase env = addBinderUnfolding env case_bndr con_app_unf
+ | otherwise = env
-- See Note [Add unfolding for scrutinee]
-- e.g. case (x |> co) of K a b -> blah
=====================================
testsuite/tests/simplCore/should_compile/T28164S.hs
=====================================
@@ -0,0 +1,17 @@
+{-# LANGUAGE BangPatterns #-}
+module T28164S where
+
+-- step is lazy in k (the x < 0 branch), so its worker takes k boxed.
+-- At -O2 liberate-case peels hash's first iteration, which puts a
+-- `case k of I# y` in the body of go's join points; go's exit also takes
+-- k apart.
+{-# NOINLINE step #-}
+step :: Int -> Int -> Int
+step k x
+ | x < 0 = 0
+ | otherwise = go (hash 0 0)
+ where
+ hash !i !acc | i == k = acc
+ | otherwise = hash (i + 1) (acc * 131 + x + i)
+ go !j | j < 1000 = j * k
+ | otherwise = go (j `quot` 7)
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -634,3 +634,6 @@ test('T27737a', normal, compile, ['-O'])
test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
+
+# T28164S: the idea is there should be only one 'case k' in 'step'
+test('T28164S', grep_errmsg(r'case k'), compile, ['-O2 -ddump-simpl'])
=====================================
testsuite/tests/simplCore/should_run/T28164R.hs
=====================================
@@ -0,0 +1,35 @@
+module Main (main) where
+
+import System.Environment (getArgs)
+
+data T = T ![Int] !Int !Int
+
+{-# NOINLINE work #-}
+work :: [Int] -> [Int] -> Int -> Int -> [Int]
+work sh ss o v = [ x * o + v + y | x <- sh, y <- ss ]
+
+{-# INLINE expensive #-}
+expensive :: [Int] -> T -> [Int]
+expensive sh (T ss o v) = work sh ss o v
+
+{-# INLINE z #-}
+z :: [Int] -> T -> T -> Int
+z sh (T ss _ v) (T _ _ v')
+ | v == 1, v' == 1 = sum ss
+z sh t t' = sum (expensive sh t) + sum (expensive sh t')
+
+{-# NOINLINE mkT #-}
+mkT :: Int -> T
+mkT n = T [1 .. n] 3 5
+
+c :: T
+c = mkT 1000
+
+{-# NOINLINE f #-}
+f :: T -> Int
+f a = z [1 .. 100] a c
+
+main :: IO ()
+main = do
+ [n] <- map read <$> getArgs
+ print (sum [ f (T [k] 0 2) | k <- [1 .. n] ])
=====================================
testsuite/tests/simplCore/should_run/T28164R.stdout
=====================================
@@ -0,0 +1 @@
+13142050000
=====================================
testsuite/tests/simplCore/should_run/all.T
=====================================
@@ -126,3 +126,4 @@ test('T27005', [], multimod_compile_and_run, ['T27005', '-O'])
test('T27705', [extra_hc_opts('+RTS -M500M -RTS')], multimod_compile_and_run,
['T27705', '-O2 -fexpose-all-unfoldings'])
test('T28163', normal, compile_and_run, ['-O'])
+test('T28164R', normal, compile_and_run, ['-O'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/8cafe4c3f3841620a4439a3e08f0544…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/8cafe4c3f3841620a4439a3e08f0544…
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
1
0
[Git][ghc/ghc][wip/T27737] 103 commits: Don't report -XStrict-generated bangs under -Wredundant-bang-patterns
by Simon Peyton Jones (@simonpj) 21 Nov '26
by Simon Peyton Jones (@simonpj) 21 Nov '26
21 Nov '26
Simon Peyton Jones pushed to branch wip/T27737 at Glasgow Haskell Compiler / GHC
Commits:
cc533b66 by Sasha Bogicevic at 2026-10-31T09:18:15-04:00
Don't report -XStrict-generated bangs under -Wredundant-bang-patterns
The -XStrict flag causes the desugarer to insert bang patterns.
These are not user-written, so -Wredundant-bang-patterns must not
report them.
To achieve this, the desugarer now tracks whether it is desugaring
compiler-generated code (similar to the typechecker's 'tcl_in_gen_code').
Bangs inserted by -XStrict are given generated spans, which suppresses
the "redundant bang" warnings without otherwise affecting pattern-match
warnings.
Fixes #27323
- - - - -
13d38047 by Luite Stegeman at 2026-10-31T09:19:11-04:00
rts: tombstone Weak# copies that lose an evacuation race (#23160)
Mark the losing copy of a Weak# during an evacuation race in parallel
GC with stg_DEAD_WEAK_info. This ensures that the nonmoving GC
doesn't follow dangling pointers, leading to crashes.
Fixes #23160
- - - - -
63347328 by Zubin Duggal at 2026-10-31T09:19:52-04:00
ghci: Drop GHCi's exception context when rethrowing in ghc -e
Fixes #27847.
- - - - -
a85fef3f by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context in modifyIOError
Fixes #27851.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/446
- - - - -
1d60b591 by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context in mapException
Fixes #27851.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/446
- - - - -
3c029a1b by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in Handle reads
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
ab2b317a by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in hClose
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
f5abf277 by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in Windows openFile
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
d842c672 by Zubin Duggal at 2026-10-31T09:19:52-04:00
base: Preserve exception context when rethrowing exceptions in executablePath
Fixes #27875.
CLC proposal: https://github.com/haskell/core-libraries-committee/issues/447
- - - - -
c5a8bb9f by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Simplify a tc-trace which could crash the compiler
The trace formatted an error message, which prematurely
read the ExpType in a FunResCtxt.
Solution: don't put call the error message formatting
when tc-tracing.
- - - - -
ab49b1d2 by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Tiny comment change to uniqAway
- - - - -
6efe4ba3 by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Make niFixSubst idempotent
I discovered (when fixing #27994) that `niFixSubst` didn't actually
generate an idempotent subsitution despite its claims. It could
return a substitution that mentions domain variables on in its range,
when those variables are hidden inside the kind of a type variable
occurrence. As a result it can generate ill-kinded types. Boo!
The fix is simple, and uses deep substitution.
See Note [Finding the substitution fixpoint]
I don't think it actually /caused/ any bugs, so there is no
regression test.
- - - - -
3b60ae7e by Simon Peyton Jones at 2026-10-31T09:20:34-04:00
Fix a nasty bug in fundeps
This MR fixes #27994, which turned out to be very tricky.
See Note [Exploiting closed type famililes], especially (CF7). I was
ending up with TyVars (not TcTyVars) in the solver, because the
substitution computed in `getRelevantBranches` mixed the two.
The code was just too clever. I ended up simplifying it quite a bit.
For /closed/ families we no longer call `trimQtvs` (was `trim_qtvs`).
Open families still do use `trimQtvs`. See Note [trimQTvs]
This patch also fixes one other buglet in the same code.
* Over-saturated type families were being mis-handled.
See the new use of `saturatedFamApp_maybe`.
- - - - -
e4610f2d by Facundo Domínguez at 2026-10-31T09:21:24-04:00
Have haddock --incremental look for the module in -this-unit-id
- - - - -
bc6c0db6 by sheaf at 2026-10-31T09:22:20-04:00
mightBeFunTy: hotfix for #27979
ce01ccb6 refactored 'GHC.Types.RepType.mightBeFunTy' to look through
unary classes. That change introduced the helper function 'unwrap_type'
which was supposed to always return an unwrapped type, but its fallback
equation mistakenly returned the original type. This caused the
subsequent 'tyConAppTyCon_maybe' to fail in cases where it should
succeed (e.g. looking through foralls).
In this commit, we move all the unary class unwrapping logic into
'unwrapType' where it belonged from the start, and update the
documentation of 'unwrapType' to better explain what it should be used
for (#26695).
Fixes #27979 #26695
-------------------------
Metric Increase:
T5642
-------------------------
- - - - -
233cce46 by Alan Zimmerman at 2026-10-31T09:23:01-04:00
EPA: Tidy up ExactPrint.markAnnListA'
It takes an action which can modify the AnnList, but this
is never used. So remove it.
- - - - -
3594a908 by Sylvain Henry at 2026-10-31T09:23:51-04:00
gitmodules: ignore dirty libffi-clib submodule (#26785)
`./boot` runs autoreconf in libraries/libffi-clib, which leaves
`configure~` behind and rewrites the tracked `aclocal.m4` whenever the
local automake version differs from the one that generated it. Every
checkout then looks dirty. Ignore working-tree changes in the submodule
(`ignore = dirty`); a changed submodule commit is still reported.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
341223c0 by Rodrigo Mesquita at 2026-10-31T09:24:33-04:00
refactor: Keep the interactive Ids directly rather than Name
Removes things like
names <- map idName ids
map (\i -> let id = find (\x -> i==idName x) names) idso
and is more straightforward because there's less state going around (no
more updating HscEnv as an output)
It also kills `printTypeOfNames` completely, since now we just have the
Ids. No longer `lookupName` names to get back the ids...
```
printTypeOfName :: GHC.GhcMonad m => Name -> m ()
printTypeOfName n
= do maybe_tything <- GHC.lookupName n
case maybe_tything of
Nothing -> return ()
Just thing -> printTyThing thing
```
now is just `printTyThing . AnId`
Also:
```diff
- tythings <- catMaybes `liftM` mapM GHC.lookupName namesSorted
- docs <- mapM pprTypeAndContents [i | AnId i <- tythings]
+ docs <- mapM pprTypeAndContents idsSorted
```
(and yes, in ExecBreaks there are only Ids, no TyThings, bc they are
only constructed by the interpreter execution which can only bind ids.
for TyThings use runDecls which doesn't return execBreaks.)
There's some care to be had to make sure we use the "most refined" Ids,
whereas when using `Name`s we'd always fetch the most refined Id from
scratch.
Fixes #28052
- - - - -
54cf3c1e by sheaf at 2026-11-03T07:00:23-05:00
Consolidate all CPU feature handling
This commit introduces GHC.Platform.CpuFeatures which consolidates all
of the logic for implications between CPU feature flags (mainly X86):
- DynFlags now only records the set of -m<feature> flags that were
passed, as an EnumSet CpuFeature. That keeps it a simple record of
the flags the user passed, with no post-processing.
- GHC.Platform.CpuFeatures.initCpuFeatures turns this set into a
CpuFeatures value, applying all implications and the per-architecture
baseline. This is the single home for all of the feature implication
logic.
Some datatypes were reworked to better reflect the implication
structure in the types, e.g. SseAvxVersion has a strategically
placed 'FMA' boolean.
- The NCG, LLVM backend, StgToCmm, CPP defines and LLVM -mattr
flags all consult CpuFeatures, via targetCpuFeatures.
See Note [CPU features], which replaces
Note [Implications between X86 CPU feature flags].
Behaviour changes:
- x86 feature flags (-msse3, -mavx, -mavx512*, -mgfni, ...) passed
when targeting a non-x86 architecture no longer cause x86 CPP
macros (__SSE3__, __AVX512BW__, __GFNI__, ...) to be defined, nor
x86 attributes to be passed to LLVM.
- Error messages reported when required CPU features are not enabled
now print out the minimal set of flags required
(e.g. "-mavx512vl" rather than "-mavx512f -mavx512vl").
- - - - -
9af64305 by Luite Stegeman at 2026-11-03T07:01:23-05:00
rts: move stack check to the start of the stg_unpack_cstring thunks
fixes a deadlock
see #27272
- - - - -
a2208b21 by Simon Jakobi at 2026-11-03T07:02:05-05:00
Cmm: exclude the entry block from common block elimination
a1d8139054c had fixed #27722 only partially, because it didn't prevent
elimination of the entry block in later rounds, where the entry block is
no longer guaranteed to come first.
To close this loophole, we exclude the entry block from the CBE merge
logic. See Note [Retain entry block during common block elimination] for
details.
This also deletes a misleading comment regarding unreachable blocks: the
control-flow optimiser doesn't actually guarantee that no unreachable
blocks reach CBE.
Fixes #27722.
Assisted-by: Claude Fable 5.1
- - - - -
37ad4710 by Alan Zimmerman at 2026-11-03T07:02:46-05:00
EPA: Use AnnList for GADT declarations
Continuing the process of using AnnList to capture parser layout
- - - - -
56757900 by Sebastian Graf at 2026-11-04T20:36:47+01:00
Documentation for the Core data constructors
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
9f57c265 by Sylvain Henry at 2026-11-06T06:46:15-05:00
ghc-internal: avoid unnecessary allocations in bignum division (#27231)
Avoid unnecessary allocations in bignum division in the Haskell (native)
backend. The long-division loop used to allocate a fresh BigNat for the
partial product on every iteration, plus one more per quotient-digit
correction; it now subtracts the partial product in place and
materializes nothing.
The quotient-digit estimate is also refined against the second-highest
divisor word, so the add-back correction runs at most once per
iteration.
bignat_quotrem_normalized now requires a divisor of at least 2 words, so
bignat_quotrem dispatches 1-word divisors to bignat_quotrem_word.
See Note [Knuth division loop] and Note [Fused multiply-subtract for
long division] in GHC.Internal.Bignum.Backend.Native.
Measured on the new T27231 perf test (10000 native-backend 8192/2048-bit
Integer quotRem calls): bytes allocated drops from 305 MB to 52 MB (-83%).
Improvement on CI (x86-64-linux-deb13-int_native):
space_leak_001(normal) run/alloc 12,492,185,536 9,073,055,928 -27.4% GOOD
Metric Decrease:
space_leak_001
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply(a)anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
c5b80f4e by mangoiv at 2026-11-06T06:46:57-05:00
ci: build and test stage
Split up CI in a build and test stage:
1. in the build stage, just produce a bindist as well as running the
stage1 tests
2. in the test stage, install the bindist, then run the testsuite with
out of tree args
- - - - -
e4b1c892 by mangoiv at 2026-11-06T06:46:57-05:00
ci: reorder packaging and testing stages
- - - - -
19901b41 by mangoiv at 2026-11-06T06:46:57-05:00
ci: out of tree compiler does not imply no hadrian being available
- - - - -
83a860a7 by mangoiv at 2026-11-06T06:46:57-05:00
ci: don't do msys deps check on stage1 compiler
- - - - -
abf5b3af by mangoiv at 2026-11-06T06:46:57-05:00
testsuite: allow metric decreases on windows
Metric Decrease:
LinkableUsage01
MultiLayerModulesTH_OneShot
T10547
T12234
T12425
T13035
T13253-spj
T13820
T18140
T18730
T18923
T9198
TcPlugin_RewritePerf
mhu-perf
- - - - -
9185f1ab by mangoiv at 2026-11-06T06:46:57-05:00
ci: stop using ellipses in testsuite output and output env before invoking hadrian
- - - - -
bf9ece2b by Simon Jakobi at 2026-11-06T06:47:42-05:00
testsuite: Skip the changelog-d test in CI
Full-build validate jobs run the whole testsuite and thus repeated the
changelog validation that the dedicated lint-changelog job had already
reported in the early tool-lint stage.
Skip the test when GITLAB_CI is set, making lint-changelog the only CI
check of changelog.d while keeping the test available in local
testsuite runs.
Fixes #27325.
Assisted-by: Claude Fable 5
- - - - -
ef6adb30 by ARATA Mizuki at 2026-11-06T06:48:31-05:00
testsuite: Mark T367_letnoescape fragile for the optllvm way
It was marked broken, but it is now unexpectedly passing on aarch64-linux-deb13-validate+llvm.
Marking it fragile for now.
See #7292
- - - - -
1db5f9d7 by Rodrigo Mesquita at 2026-11-06T06:49:13-05:00
interp: Make resumeExec and ExecBreak use `Resume` directly
Previously, `Resume` contexts were just put directly in the global
interactive environment state, so they were only accessible through it.
However, in the context of multi-threaded debugging, in that many
threads may hit breakpoints, it no longer suffices to have a global
linear list of breakpoints hit. We need a per-breakpoint Resume context
and need to be able to wield it directly rather than going through a
global context.
The driving changes of this commit are:
- Put the Resume data in ExecBreak
- Make resumeExec receive a Resume as an argument
This also simplifies the interpreter in that we no longer necessarily
rely on the global interactive state to resume a thread. We can do it
directly from the ExecBreak.
The interactive context still maintains a stack of resumes, but
`resumeExec` can no longer pop the resume it resumes off of the
breakpoints stack, since it is no longer guaranteed to be resuming the
first in that list. Hence, callers of `resumeExec` must update ic_resume
on their own.
Fixes #28058
- - - - -
fd00a88c by Rodrigo Mesquita at 2026-11-06T06:49:54-05:00
Per-thread break-on exception (TSO_STOP_ON_EXCEPTION)
The `-fbreak-on-exception` flag allows the interactive interpreter to stop
when a synchronous exception is raised.
However, this is a global toggle backed by a global variable in the RTS
(rts_stop_on_exception) which is not compatible with a multi-threaded
debugger where we may want to stop if some threads raise a synchronous
exception but not other.
This commit makes -break-on-exception similar to step-next and step-out
where there is a per-thread toggle on each TSO (TSO_STOP_ON_EXCEPTION),
and that break-on-exception set in EvalOpts when resuming a statement
only affect the thread being resumed.
Fixes #28068
- - - - -
d735b507 by Andrea Vezzosi at 2026-11-06T06:50:35-05:00
driver: Don't let -dynamic unset -fsplit-sections
`addWay' WayDyn` used to unset Opt_SplitSections, so -fsplit-sections was
ignored if it came before -dynamic, but worked if it came after.
The -fsplit-sections -dynamic combination has legitimate uses, e.g. an
executable can be linked dynamically against libraries and still have dead code
from its own sources to eliminate. Or the same objects could be used for both
static archives and shared objects.
The removal of Opt_SplitSections was also motivated by problems on Darwin.
It is now done in `makeDynFlagsConsistent` instead, see Note [Split sections are not
supported on Mach-O].
For consistency, we also keep Opt_SplitSections when `dynamicNow` is activated.
There is a cost of larger .dyn_o (but not .so) files and slower link times (esp.
with ld.bfd), but does not seem significant enough to warrant special casing.
Fixes #28061
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
10e36bd2 by Alan Zimmerman at 2026-11-06T06:51:18-05:00
EPA: Use AnnList in AnnClassDecl
Capture parser layout
- - - - -
20334e1d by sheaf at 2026-11-06T06:52:06-05:00
Avoid panic in 'solveImplicationsUsingUnsatGiven'
Commit 52a4d1da refactored this code to use 'setWantedDict' which panics
for equality constraints. This commit fixes that by explicitly handling
HoleDest.
Fixes #28081
- - - - -
0423f413 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
testsuite: add tests for the IO manager lock-up of #21969
T21969a 'closeFdWith' takes every 'EventManager''s 'callbackTableVar'
inside 'uninterruptibleMask_' and only puts them back on the paths
that do not throw, so a throw from 'closeFd_' leaves those MVars
empty for good. Afterwards every 'threadWaitRead' and
'closeFdWith' on an fd in the same bucket blocks forever.
T21969b 'closeFdWith' runs the fd's callbacks while asynchronous exceptions
are uninterruptibly masked, so a callback that blocks makes the
thread calling it permanently unkillable.
T21969c 'closeFd_' drops the registrations before telling the backend to
forget the fd, so when the backend throws the fd is never closed
and the threads waiting on it are never woken.
T21969d the cleanup handler of 'threadWait' calls 'unregisterFd_', which
throws on backend errors. It runs inside the handler for the
asynchronous exception being delivered, so its exception replaces
that one: 'killThread' returns but 'ThreadKilled' never arrives.
T21969e an exception from re-arming an fd escapes the poll loop, and 'loop'
turns it into 'cleanup mgr': the 'EventManager' of that capability
is shut down and every thread using it is left blocked. This is
the lock-up of #21969 itself.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
5c197e2e by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Make the IO manager cope with errors from the polling backend (#21969)
Three changes in 'GHC.Internal.Event.Thread': 'closeFdWith' puts every
'callbackTableVar' back on the paths that throw too and no longer skips the
callbacks when 'close' fails, those callbacks now run under the 'mask_' of
'close_loop' rather than uninterruptibly masked, and the cleanup of
'threadWait' ignores a failure from 'unregisterFd_'.
This fixes T21969a, T21969b and T21969d, and clears their expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
cb765ded by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let backend errors abandon the close of a file descriptor (#21969)
'closeFd_' and 'closeFd' now ignore errors from telling the backend to forget
the fd: the registration is being torn down and the error says it is already
gone. 'registerFd_' still reports them (!10643), where the caller has to
learn that the registration did not happen. Both also test
'I.elEvent oldEls /= mempty' rather than 'oldEls /= mempty'.
This fixes T21969c, and clears its expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
9073bc43 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let a backend error take down a capability's IO manager (#21969)
A failure to re-arm an fd in 'selectCallbacks' is now handled the way
'registerFd_' handles one (!10643): the registrations are taken back out of
the callback table and returned, so their callbacks run and the waiting
threads find out for themselves instead of hanging. Checked on aarch64 Linux
(epoll) and aarch64 macOS (kqueue), 10 runs each way.
This fixes T21969e, and clears its expect_broken.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
cdff4e76 by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
Do not let the deregistration of threadWaitSTM throw either (#21969)
'threadWaitReadSTM' and 'threadWaitWriteSTM' return the action that gives up
interest in the fd as the second component of their pair, and it was
return (waitAction, unregisterFd_ mgr reg >> return ())
'unregisterFd_' talks to the polling backend, which throws on errors such as
ENOENT and EBADF -- which is how a backend reports an fd it no longer knows,
once that fd has been closed without going through 'closeFdWith'.
That is the same shape as the cleanup of 'threadWait', which the rest of this
series made quiet, and it is the same on both counts. There is nothing to
decide: the registration is being abandoned, and "the backend does not know
this fd" is the state the action is trying to reach. And it does harm: the
action is what a caller uses from the cleanup of a 'bracket', where an
exception out of it replaces whatever was being propagated.
It now goes through 'quietUnregisterFd', as the cleanup of 'threadWait' does,
and that function's comment covers both callers.
T21969f covers it, and is deterministic on both backends: dropping the only
registration changes the event set, so 'unregisterFd_' always reaches the
backend.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
a7ed305b by Kazu Yamamoto at 2026-11-07T08:06:59+09:00
testsuite: let T21969 run on FreeBSD, and unmark it (#21969, #25512)
T21969 now carries the descriptor from 'createPipe' instead of recovering it
with 'handleToFd', which rejects the 'DuplexHandle' that FreeBSD's
bidirectional pipes become and killed the test in setup there (#25512). The
expect_broken goes with it: with the descriptor problem out of the way the
test times out on master, so it can only be unmarked on top of this series.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
3074ae61 by Sylvain Henry at 2026-11-08T10:21:50-05:00
rts: heap census counts every small pinned object
Blocks of small pinned objects carry BF_LARGE as well as BF_PINNED but
hold many objects. heapCensusChain treated every BF_LARGE block whose
first object is an ARR_WORDS as holding that single object, a workaround
for the slop left by shrinkMutableByteArray# (#11627). So every heap
profile mode under-reported pinned byte arrays, i.e. ByteString payloads.
Shrinking now writes a slop marker that skipSlop understands (#19048,
#27585), so the block walk is safe for large and pinned blocks alike.
The block that a capability fills with small pinned objects stays
attached to the capability until it is full (see allocatePinned), so it
is on no generation list and the census never saw its objects. heapCensus
now walks cap->pinned_object_block too.
A pinned block is kept or freed as a whole (#28005), so dead pinned
objects are counted until their block is freed. T7275 gains one sample in
which its dead small arrays still show. The user guide and changelog
document this.
T7257 retains most of its pinned blocks and takes a census at every GC
(+RTS -i0 -hT), so walking every pinned object made it 7x slower and it
hit the CI timeout. It now runs 1000000 iterations instead of 5000000.
Metric Decrease:
T7257
Fixes #28000
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
16fd075a by Sylvain Henry at 2026-11-08T10:22:39-05:00
rts: fix GC CPU time accounting with idle GC threads (#26169)
stat_endGC summed gc_end_cpu - gc_start_cpu over every GC thread, but
only the threads that take part in a collection set these fields, and
new_gc_thread did not initialise them. With -qn below the capability
count, the first collection after setNumCapabilities added garbage to
the GC CPU time.
Let each participating thread add its own CPU time to an accumulator
in stat_endGCWorker, and let stat_endGC take the total. This removes
the loop over gc_threads, the reset from #21082 and the gc_end_cpu
field. Also drop the unused gc_end_elapsed field.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
0ef732e2 by Sylvain Henry at 2026-11-08T10:23:30-05:00
Serialized: encode numbers with LEB128
serializeWithData used the Binary instances of Data.Binary for the
numbers in a ConstrRep. They have a fixed width: 8 bytes for the
constructor index (an Int) and 5 bytes for a small Integer. Each
element of a [Int] cost 15 bytes.
Now the constructor representation is one unsigned LEB128 number that
also contains the index of an algebraic constructor, and the payloads
(Integer, Rational, Char) are LEB128 encoded. Most constructors take
one byte, and small numbers two. See Note [Serialized encoding].
Sizes measured by the T16841 test:
[1..100] :: [Int] 1509 -> 338 bytes
"helloworld" 119 -> 31 bytes
2^100 :: Integer 24 -> 16 bytes
Just True 18 -> 2 bytes
3.25 :: Double 11 -> 3 bytes
42 :: Int 6 -> 2 bytes
A new test, SerializedRoundTrip, round-trips values at the boundaries
of the encoding (negative numbers, big Integers, Rationals, Chars).
Follow-up to !16841 (#28002).
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
22344fbc by Sylvain Henry at 2026-11-08T10:24:21-05:00
docs: fix duplicate label in qualified_strings.rst
The file started with the label "multiline-strings", copied from
multiline_strings.rst. Sphinx warned about the duplicate label on every
build. Use the label "qualified-strings" instead.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
b7022624 by Alan Zimmerman at 2026-11-08T10:25:02-05:00
EPA: Use LHsLocalBinds instead of HsLocalBinds
This reverses an earlier change, and brings processing of local binds
into alignement with the exact printing principle that the LocatedA
contents provide the location and extent of the enclosed item,
together with any comments or context-specific trailing items like
commas or semi colons.
The internal TTG extension points only carry exact print annotations
related to printing the item within its bounds.
This change brings back the problem of EmptyLocalBinds, which by
definition cannot have a location. These get a noSrcSpan location,
which is ignored in the exact printing process.
- - - - -
bc2fae45 by Rodrigo Mesquita at 2026-11-08T18:37:40-05:00
Build EvalOpts once per exec rather than per breakpoint stop
We were unnecessarily constructing `eval_opts` in `handleRunStatus`
(which is run many times in a loop until we hit a breakpoint we care
about, e.g. when :steplocal), despite the `eval_opts` being constant
across all these runs.
So, construct `eval_opts` outside `handleRunStatus` and share the value
in all loop calls. The loop always uses the same eval_opts, so no point
in constructing them inside `handleRunStatus` from scratch every time.
I found out about the significance of this re-construction of `EvalOpts`
when I added a record update of `eval_opts` *after* the construction
from scratch inside `handleRunStatus` that regressed allocations
significantly.
This improves the performance of `interpreter_steplocal` on my machine:
Baseline
Test Metric value New value Change
-------------------------------------------------------------------------
interpreter_steplocal(ghci) ghc/alloc 459,845,696 449,843,480 -2.2%
Fixes #28068
- - - - -
ba579288 by Rodrigo Mesquita at 2026-11-08T18:38:21-05:00
refactor: move and order helper functions in GHCi.Run
A small refactor to the order of top-level functions in GHCi.Run
- - - - -
24927752 by Luite Stegeman at 2026-11-09T09:21:24-05:00
rts: add missing nonmoving write barrier in out-of-line array copies
The out-of-line entries stg_copyArrayzh/stg_copyMutableArrayzh (taken
whenever the element count of copyArray#/copyMutableArray# is not a
compile-time constant) didn't push the overwritten elements to the
nonmoving collector's remembered set.
Fixes #27376
- - - - -
6dbcca65 by Rodrigo Mesquita at 2026-11-09T09:22:06-05:00
interp: Set per-thread break flags consistently on eval/resume
Currently, the per-thread flags are:
- Single-step: Stop at the immediate next breakpoint in this thread
- Step-out: Stop at the next continuation with a breakpoint this thread
returns to.
- Break-on-exception: Stop the next time a synchronous exception is
raised in this thread.
Originally, these flags were all set globally across all threads. More
recently, these flags are set per-thread when `resume`ing that thread,
but globally when starting the evaluation of a new expression
(`evalStmt`).
With this commit, we now use per-TSO flags in both scenarios evaluating
expressions in the interpreter (`evalStmt` and `resumeStmt`).
- In `resumeStmt` we set the `EvalOpts` specifically in the `ThreadId`
being resumed.
- In `evalStmt`, we set the `EvalOpts` exclusively on the sandbox thread
we fork to evaluate the given expression
- When not using the sandbox thread (i.e. -fno-ghci-sandbox), we
don't support the debugger anyway, so the break flags are
irrelevant.
We do this by consistently calling `setBreakFlags` when starting,
resuming, or killing the evaluation.
See Note [Always setBreakFlags on running thread].
This slightly changes the behavior of evaluating a new expression in
the debugger (resuming a thread behaves the same as before). Namely,
`:step <expr>`, where <expr> forks a thread, will stop at the immediate
next breakpoint in the <expr> main thread, not on a breakpoint of any
forked thread.
NB: the forked thread may still stop at breakpoint, if it is enabled by
index specifically, and then :step-ing from that thread's breakpoint
will toggle per-thread stepping for that forked thread.
We will want to control stepping in "all threads, regardless of whether
we control them or if they were spawned by the debuggee" separately from
the commands which trigger evaluation of just an expression. Namely,
we'll likely want a "break at the next immediate breakpoint hit on ANY
thread" command that the user can execute before launching a debuggee
which is multi-threaded. This may even be the default for GHCi.
Towards #26064
Fixes #28080
- - - - -
19ff36f2 by Simon Jakobi at 2026-11-09T09:22:47-05:00
testsuite: Mark T8209 fragile for the ghci ways on FreeBSD and darwin
A shutdown race in the I/O manager intermittently fails T8209(ghci) on
x86_64-freebsd14-validate and aarch64-darwin-validate, recently killing
several Marge batches. Mark it fragile there until the race is fixed.
See #27948.
Assisted-by: Claude Opus 5.5
- - - - -
212c292f by Rajkumar Natarajan at 2026-11-11T13:54:08-05:00
document what ->>> stands for in heap profile
updates the profiling section of the user's guide to explain how types
are approximated when using -hy. Also adds haddocks to getTyDescription
with the same information.
Fixes #26754
- - - - -
c64fc319 by Jonathan at 2026-11-11T13:54:55-05:00
Fix AArch64 veneer target for relocations with an addend
Fixes #27807
The RTS linker would construct invalid relocation veneers on AArch64 if
the addend was non-zero, which typically caused SIGILL crashes. This
could be triggered by evaluating Template Haskell in a package with a
large number of dependencies using a static build of GHC.
- - - - -
cd4dce19 by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
testsuite: add a test for registerFd_ trusting the callback table (#27821)
registerFd001 shows a 'threadWaitRead' that never finishes after an fd is
closed with 'closeFd' rather than 'closeFdWith'. Darwin is the only platform
this reaches -- one-shot registrations are implemented but not used there
(#7651) -- so the test is expect_broken on Darwin only.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
5ab442ee by Kazu Yamamoto at 2026-11-11T13:55:45-05:00
registerFd_: always tell the polling backend (#27821)
Where the backend has no one-shot registrations, 'registerFd_' now tells it
about every registration, rather than only when the events differ from the
ones the callback table records: the table alone cannot say whether the
backend still knows the fd. The 'modify' it returns is unchanged. See Note
[Do not trust the callback table].
This fixes registerFd001 and clears its expect_broken.
Changelog wording from Duncan Coutts in review.
Co-Authored-By: Claude Opus 5 (1M context) <noreply(a)anthropic.com>
- - - - -
ab8b5b06 by Vladislav Zavialov at 2026-11-11T13:56:27-05:00
Curried contexts in prefix GADT constructors (#27424)
Prefix GADT constructor declarations now accept multiple consecutive
contexts, equivalent to a single conjoined context:
data G a where
MkCurried :: C a => (D a, E a) => G a
MkConjoined :: (C a, D a, E a) => G a
This is a step towards GHC Proposal #402 "Stable GADT constructor syntax".
To represent multiple contexts, the `con_mb_cxt` field of `ConDeclGADT` has
been replaced by `con_cxts`, which stores a list instead of a Maybe:
- con_mb_cxt :: Maybe (LHsContext pass)
+ con_cxts :: [LHsContext pass]
The rest of this patch follows from this change.
Note that in ConDeclH98, the optional context is still stored as a Maybe.
To accommodate this difference, a few helper functions were generalised over
a Foldable container `t`:
hsConDeclTheta :: Foldable t => t (LHsContext ...) -> [LHsType ...]
pprLHsContext :: (Foldable t, ...) => t (LHsContext ...) -> SDoc
repContexts :: Foldable t => t (LHsContext GhcRn) -> MetaM (Core (M TH.Cxt))
tcHsContext :: Foldable t => t (LHsContext GhcRn) -> TcM [PredType]
In practice, the instantiations of `t` are either `Maybe` or `[]`.
Record-style GADT constructors continue to accept at most one context.
`splitLHsGadtTy` accounts for this by splitting off only the first context
if it detects record syntax, leaving the offending part of the type in the
body for the renamer to reject later on.
Test cases: T12087a T27424a T27424b T27424c T27424d GadtConSigs_th_dump1
- - - - -
d2f135ff by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: cache register usage in liveness annotations
regUsageOfInstr allocates fresh register lists on every call, and on the
linear allocator path it was called three times per instruction: in the
backward liveness pass, in the forward liveness pass and in the allocator
itself. Store the usage computed by the backward pass in the Liveness
annotation and reuse it in the other passes (and in the graph allocator's
spill passes). patchRegsLiveInstr recomputes it for the patched
instruction.
See Note [Cached register usage in liveness annotations].
Part of #28008.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
ff0a5d32 by Sylvain Henry at 2026-11-11T13:57:22-05:00
NCG: describe register usage with a small DSL
This new register usage DSL (see Note [Register usage DSL] in
GHC.CmmToAsm.RegUsage) reduces allocation compared to the previous
list-based approach.
Fixes #28008.
Metric Decrease:
ManyAlternatives
T12707
T13035
T13379
T13960
T18698b
T19695
T21839c
T3064
T3294
T4801
T5321FD
T5321Fun
T783
T9198
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
51f38f3a by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock-library: fix the build of the spec and fixtures test suites
The documentation pipeline moved from String to Text (commit 202ed264141)
but the two test suites of haddock-library were left behind and no
longer compiled. They are not run by GHC's CI (see #16206), so this went
unnoticed.
The fixtures suite still has four pre-existing failures (list-blocks1,
table1, table4, table5) that are not addressed here.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
394d9d6d by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: parse backtick spans as monospaced text
A backtick span whose content is not a valid Haskell identifier, such as
`foo bar`, was rendered as plain text with literal backticks. It is now
parsed as monospaced text, like @foo bar@. A closed backtick span whose
whole content is one identifier keeps its meaning as a hyperlinked
identifier. A span such as `foldl' f z xs` is code: it is no longer read
as the identifier foldl between a backtick and a single quote. The
TeX-style form `foo' stays an identifier when no backtick closes the
span on the same line.
Code spans follow the CommonMark rules: a span opened by a run of N
backticks ends at the next run of exactly N backticks on the same line,
so ``x `plus` y`` is code "x `plus` y". One space is removed at each end
when both are present, and an unclosed opening run is plain text. The
content is literal: no markup is parsed and backslashes are kept, so
`\x -> x` renders as written.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Fixes #28090
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
7ae41c37 by Sylvain Henry at 2026-11-11T13:58:14-05:00
Use 'T' instead of `T' in Haddock comments next to backtick spans
With backtick code spans, a TeX-style quote `T' followed by a backtick on
the same line opens a code span up to that backtick. Use the 'T' form in
the Haddock comments where this happens.
See Note [Backtick code spans] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
ce96f0b6 by Sylvain Henry at 2026-11-11T13:58:14-05:00
haddock: do not parse backtick spans inside @...@
Text between @...@ is already code, so backtick code spans are no longer
parsed there. Thus in
@x <- f -- of type `M Bool`@
the backticks stay as text. Inline markup inside @...@, such as /.../,
passes this context down.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
744b3036 by Sylvain Henry at 2026-11-11T13:58:15-05:00
haddock: keep the backticks of infix identifiers inside @...@
A backticked identifier inside @...@ was always rendered without its
backticks, so @f `elem` xs@ rendered as "f elem xs". Now an identifier
in an infix application or an operator section, such as @f `elem` xs@
or @(`elem` xs)@, is parsed in infix form, as if written ``elem``, and
renders with its backticks and with elem linked. Elsewhere, as in
@`foldlM` :: ...@, the backticks still only mark the link.
See Note [Backticks in code] in Documentation.Haddock.Parser.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
0d8e1f8d by Sylvain Henry at 2026-11-11T13:59:05-05:00
PPC NCG: print non-standard NaN literals in target byte order
The PowerPC NCG printed a non-standard NaN literal byte by byte with
floatToBytes/doubleToBytes, which use the byte order of the host. This
is wrong when the host and the target have a different endianness (e.g.
from x86_64 to big-endian PowerPC). Print the bits with `.long`/`.quad`
instead, so that the assembler uses the target byte order.
Also make `ppr_item` print its argument: some clauses printed the
literal of `pprDataItem` instead.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
5a9db1ed by Sylvain Henry at 2026-11-11T13:59:05-05:00
Print all NaN literals as integer bits (#28101)
The x86 and PowerPC NCGs printed the quiet NaNs 0x7fc00000 and
0x7ff8000000000000 as `.float NaN`/`.double NaN`. GNU as and clang
encode these with all mantissa bits set, so constant-folded bit casts
of these values gave 0x7fffffff/0x7fffffffffffffff. The C backend
printed every NaN as `NAN`, losing its sign and payload.
Now the NCGs print all NaNs with `.long`/`.quad` and the C backend with
hs_bitcastword2float/hs_bitcastword642double.
See Note [Printing NaN literals].
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
b4ceb6a9 by mangoiv at 2026-11-11T13:59:47-05:00
ci: fix ghcup nightly script misbehaviour
- download all jobs instead of just the first 100
- stop using a canary job to detect whether it's a nightly or release
pipeline
- - - - -
aefa0c1b by Alan Zimmerman at 2026-11-11T14:00:28-05:00
EPA: Use AnnList in HsMultiIf
It introduces layout, capture it
- - - - -
d72505e4 by Simon Jakobi at 2026-11-12T15:26:14-05:00
testsuite: Fix T17088 flakiness and restore bug coverage
T17088 reads and prints a byte from an uninitialized array. Debug RTS
ways fill allocated memory with 0xaa, so the test can fail due to an
output mismatch unrelated to the pointer-tagging bug it covers.
Initialize the byte to zero to make the output deterministic.
The original bug requires the compacting collector and particular
compiler and RTS settings. Run the test only in the compacting_gc way
with -O1 and -A128k. Also disable STG lambda lifting because it removes
the closure shape needed to reproduce the pointer-tagging failure.
This makes the test reliable while ensuring it remains an effective
reproducer for #17088.
Closes #27534.
Assisted-by: gpt-5.6-sol via Codex CLI
- - - - -
5a7591b3 by David Eichmann at 2026-11-12T15:26:56-05:00
testsuite: Fix python type errors
These errors appear when using the VSCode python extension which uses
Pylance under the hood.
- - - - -
52f129f8 by David Eichmann at 2026-11-12T15:26:56-05:00
Add test modifier to test over all IO Managers
- - - - -
22e8b92a by David Eichmann at 2026-11-12T15:26:56-05:00
testsuite: include custom IO Manager in test name
- - - - -
82c34ccd by Simon Jakobi at 2026-11-12T15:27:40-05:00
Make T2464 actually test #ifdef'd pragmas
The test guarded a LANGUAGE EmptyDataDecls pragma behind #if, but
EmptyDataDecls is on by default since Haskell2010, so the module
compiled even when the guarded pragma was ignored. Guard MagicHash
instead, which is unlikely to be included in a future default language.
The test also checks that warnings from file-header pragmas are emitted
only once, even though the pragmas are parsed both before and after
CPP, using the -fffi deprecation warning as the canary. Use an
unrecognised warning flag instead, so the test no longer depends on a
deprecated flag that is about to be removed.
Context: #27939
Assisted-by: Claude Fable 5.1
- - - - -
419f2a12 by Simon Jakobi at 2026-11-12T15:27:40-05:00
Remove command-line flags deprecated in GHC 8.2 or earlier
Also remove the INCLUDE file-header pragma, which only expanded to
the now-removed -#include.
Closes #27939.
Assisted-by: Claude Fable 5.1
- - - - -
adc294d0 by Erik de Castro Lopo at 2026-11-12T15:28:21-05:00
TimerManager: publish only evaluated timeout queues (#9809)
The issue in #9809 was triggered by many threads registering timeouts
at the same time and those timeouts being stored as unevaluated thunks
in the shared list. When say 100,000 timeouts are registered at the
same time, the program can be slowed down considerably and the memory
usage grow unacceptably large.
The commit that caused the problem was 2d5eccdf1c, a 2013 change that
fixed #7653.
The fix is to add a modifyTimeouts function which applies an edit to a
copy of the list and fully evaluates the result before replacing the
shared list with a CAS operation.
Performance has improved for the threaded case and not regressed for
the single thread case:
Forked registrations of 100k timeouts (median of 5 runs):
-N4: 0.577 s, 428 MB -> 0.078 s, 39 MB
-N12: 1.227 s, 479 MB -> 0.127 s, 80 MB
Forked registrations of 1M timeouts on -N1 (median of 3 and 10 runs):
5.21 s (range 0.67-9.47 s), 1613 MB -> 0.67 s, 250 MB
Single-thread registrations are unchanged or slightly faster, and timer
latency during registration storms improves (p99 lateness of a 1 ms
threadDelay during 100k forked registrations on -N4: 302-394 ms ->
3.5-4.1 ms).
The registration code still runs in constant stack, so #7653 stays fixed;
T7653 and the concurrent, base and ghc-internal testsuites pass.
modifyTimeouts is OPAQUE so that the optimiser cannot expose the edit
function's inspection of the old queue next to the compare-and-swap and
replace the expected pointer with the evaluated queue, which would make the
compare-and-swap keep failing when the MutVar# holds a thunk or indirection.
Regression test T9809.hs included.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
b294b82f by Moritz Angermann at 2026-11-12T15:28:21-05:00
testsuite: give pause_resume_via_safe_ffi_concurrent 60s on Darwin CI
The 10s System.Timeout watchdog was a false deadlock: five serialized
1s pauses plus rts_pause waiting on threadDelay/timer-manager traffic
overruns that budget on loaded Mac runners. Keep a watchdog so a real
hang still fails.
- - - - -
1543f834 by Simon Jakobi at 2026-11-12T15:29:03-05:00
testsuite/README: Don't append new tests at the end of all.T
Patches that each add a test at the end of the same all.T conflict
with each other. Tests added elsewhere in the file usually merge cleanly.
Context: #26285
Assisted-by: Claude Opus 5.5
- - - - -
9ad25cb2 by Sven Tennie at 2026-11-14T06:20:13-05:00
hadrian: Add Stage3 cross-compiled target bindist (#26924)
Add a `binary-dist-stage3` Hadrian target that packages target
executables (produced by the stage2 compiler) into a separate
'_build/bindist-stage3/' folder, distinct from the stage2 regular or
cross-compiler bindist in '_build/bindist/'.
This allows a single CI pipeline job to produce both a cross-compiler
bindist (e.g. x86_64 -> RISC-V) and a target-architecture bindist (e.g.
RISC-V -> RISC-V) that can be installed and run natively on the target.
To avoid issues with stale files or race-conditions on them, generate
the `configure` script per stage in `_build/<stage>/distrib`
directories.
- - - - -
ca91017d by Sven Tennie at 2026-11-14T06:20:13-05:00
ci: Build Stage3 and Stage2 bindists for cross targets in one job (#26924)
Building the stage3 target bindist already produces most of the stage2
cross-compiler bindist as a byproduct, so building them in separate jobs
duplicates the build efforts for no benefit. Instead of a separate
CROSS_STAGE=3 job, the stage3 job now also builds and publishes the
stage2 bindist.
The stage3 tarball is named and versioned as if it were built natively
on the target (target triple prefix, non-cross opsys), so its artifact
name stays what downstream consumers already expect and no changes are
needed on their side.
For now, this is only enabled for the RISC-V job. Others can easily
follow.
- - - - -
71b41e09 by Sven Tennie at 2026-11-14T06:20:14-05:00
ci: model cross targets as structured TargetPlatform triples (#26924)
Storing the cross target as a raw triple forced ad-hoc parsing at every
use, and broke the single responsibility rule. Modelling it as a
structured `TargetPlatform`` instead, avoids parsing and provides a
clear separation of concerns.
- - - - -
8067c2f9 by Sven Tennie at 2026-11-14T06:20:14-05:00
ci: extract the cross smoke tests into a separate smoke_test command (#26924)
This reduces if-nesting and complexity of the main `test_hadrian`
command. The decision how to test is now made by the caller. This is a
fair choice, because most test cases can run under emulation - they are
just very slow then.
The Stage3 smoke test also checks that the target compiler does not report
itself as cross-compiling and, when supported, runs a small GHCi expression.
- - - - -
7ece99a7 by fendor at 2026-11-14T06:20:57-05:00
Add `-dep-json` flag to `ghc -M`
Add an optional flag to `ghc -M` that allows to write the dependency
information in JSON Lines format.
The JSON Lines format enables us to stream the output of the dependency
generation to a consumer.
The output of `-dep-json` is streamed to a temporary file and then
copied to the final destination to avoid partial writes.
Each line contains one of two possible json objects:
1. A Home Unit Dependency
* Contains the name of the home module, its unit, where it is
located, whether a preprocessor is used, and all of its imports.
Importantly, the imports include `-XExplicitLevelImports`
information.
* If requested via `-include-pkg-deps`, includes imports of external
units, e.g. modules from `base`.
* If requested via `-include-cpp-deps`, files included via CPP.
2. External Unit Dependency
* Only if `-include-pkg-deps` is given
* Contains unit-id, its package name and package id.
---
This PR refactors the Makefile generation to use phases appropriately.
We introduce an intermediate data structure that is generated based on
the module graph nodes, and only then generate the Makefile rules.
This allows the dep-json and dep-makefile generation to use the same
dependency processing.
- - - - -
0f6e0146 by fendor at 2026-11-14T06:20:57-05:00
Add multiple home unit support to `ghc -M`
Allows to process the module graph of multiple home units at once using
the same syntax as `--make` and `--interactive`:
ghc -M -unit @unitA -unit @unitB
The semantics are identical to `--make` and `--interactive`.
Each home unit can declare individually to use `-include-cpp-deps` and
`-include-pkg-deps`.
However, there can only be one output file, and `-dep-json` and
`-dep-makefile` can only be provided at the top of the cli invocation.
We introduce a new GHC API `doMkDepend` that allows to use multiple home
units conveniently.
The output of `-dep-json` and `-dep-makefile` does not change, since we
were careful to choose a format that supports multiple home units from
the start.
Single home units are still accepted like before with no changes.
- - - - -
5598e6a0 by fendor at 2026-11-14T06:20:57-05:00
Deprecate `doMkDependHS` in favour of `doMkDepend`
- - - - -
39f2943e by David Eichmann at 2026-11-14T06:21:41-05:00
rts: Expose getRtsSymbols() and store redirect labels and external symbols tag
- - - - -
aa159605 by David Eichmann at 2026-11-14T06:21:41-05:00
hadrian: when running tests, properly set have_gdb and have_readelf
- - - - -
ff826da4 by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite: add have_ldd() test modifier
- - - - -
b9f0b7e2 by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite driver: on windows, ensure PATH correctly contains mingw and ghc-pkg libraries
- - - - -
543c108e by David Eichmann at 2026-11-14T06:21:41-05:00
testsuite: driver now sets WAY_FLAGS variable for makefile tests
- - - - -
13408a2b by David Eichmann at 2026-11-14T06:21:41-05:00
Add golden test for rts/RtsSymbols.c
This test compares declared symbols against symbols observed
in the rts DSO (.so file).
- - - - -
38d421fb by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: look up a non-recursive let with the key order of the store
xtE stored a `Let (NonRec b r) e` with the body e as the first key and
the right-hand side r as the second key. lkE used the opposite order.
When a trie level holds one entry, GenMap compares the full keys with
(==), and the difference has no effect. When a trie level holds two
entries, a lookup of an expression with a non-recursive let fails. A
later insert of an equal expression then overwrites the first entry.
Now xtE stores the key in the order that lkE uses.
Effects of the bug: CSE did not share identical bindings when a module
had two different bindings that hold a non-recursive let or join point
(#27892). The pattern-match checker gave different representatives to
equal guard or view expressions, and thus reported spurious
non-exhaustive matches.
Fixes #27892.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
fa5bc4c0 by Sylvain Henry at 2026-11-16T16:02:22-05:00
CoreMap: ignore the multiplicities of binders
BndrMap keyed a binder on its type and on its multiplicity, and
eqDeBruijnExpr compared the multiplicities of lambda binders. But the
multiplicity of a let binder has no meaning (Note [Multiplicity of let
binders] in GHC.Types.Var), and Core-to-core passes do not keep the
multiplicities of lambda binders correct (Note [Linting linearity] in
GHC.Core.Lint). Thus the trie separated terms that are equal.
The key-order bug fixed in the previous commit hid this bug. With that
fix, the pattern-match checker gave different representatives to two
equal view expressions when one let came from the source and the other
let came from the beta-reduction of a linear lambda.
Now BndrMap is TypeMapG again, as before the linear types commit, and
eqDeBruijnExpr ignores the multiplicities of lambda binders. The
haddocks of CoreMap and eqCoreExpr state this contract.
Fixes #28095.
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
fa6b8c9e by Simon Peyton Jones at 2026-11-16T16:03:04-05:00
Swap visibilities in mkSymCo
As #28123 showed, `mkSymCo` was failing to swap visibility flags
in `ForAllCo`.
Fixing that in turn showed that the change to `mkEtaForAllMCo` that
allegedly fixed #27557 was utterly wrong, and should simply be un-done.
I have added some comments to document the invariants.
- - - - -
cbe0a6bf by fendor at 2026-11-17T09:25:55-05:00
Add support for streaming `ghc -M` to stdout
Adds the flags `-dep-json-stdout` and `-dep-makefile-stdout` which
streams dependency information line-by-line to stdout.
Each dependency generation can be redirected to separate outputs.
Providing any extra `-dep-{json,makefile}[-stdout]` disables the default
generation of the `Makefile` file.
Allows consumers to start processing the dependency information as it
comes in and not waiting for the dependency generation to finish.
`DepStream` abstracts over the possible output handles, which is either
a file or the stdout handle.
Writing to a file requires temporary file paths, thus `DepStream` must
provide a way to perform clean up when dependency processing finished or
when an error is thrown for any reason.
We further decouple the rendering and writing of the result from the
dependency generation, localising side effects and making the code
slightly more readable.
The testsuite now also handles `ghc -M` writing to stdout.
We add a test for each combination of writing to stdout and file,
except for writing both makefile and json.
While it probably works, is really undefined behaviour.
Closes #27937
- - - - -
fbd49db2 by Sylvain Henry at 2026-11-17T09:27:09-05:00
Link the on-demand iserv without --gc-sections
GHC links an iserv program each time a session needs the external
interpreter. The link is static, against the ghci library and the boot
libraries. Like all executable links, it passed -Wl,--gc-sections to a
GNU linker. On libraries built with -split-sections (the release
bindists), the section garbage collection of ld.bfd is the largest part
of that link: with binutils 2.45, the link takes 3 times longer with
--gc-sections than without. The program is temporary and its size is
not important. Thus the iserv link does not use --gc-sections. Other
executable links do not change.
In CI, each ext-interp or ghci-ext test takes 12 to 18 times longer in
the x86_64-linux-fedora43-release test job (split sections) than in the
x86_64-linux-deb13-validate test job (no split sections) on the same
runner, while a normal-way test takes the same time in both. This link
is most of that difference.
See Note [No --gc-sections for the on-demand iserv] in
GHC.Runtime.Interpreter.C.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
09c965e2 by mangoiv at 2026-11-17T09:27:51-05:00
ci: make tests-primops run on marge CI
test primops dispatch was disabled on the *full-ci
group label to avoid dispatching for some of its configs
but wasn't reenabled for marge ci runs which it ought to
run
Fixes #27765
- - - - -
83038fbe by David Eichmann at 2026-11-17T09:28:32-05:00
test driver refactor: replace `.format(**locals())` with f-string
- - - - -
e9551156 by Simon Peyton Jones at 2026-11-21T12:50:35+00:00
Core utilities in preparation for a Simplifier refactoring
This is the first of three commits for #27737. It contains small,
self-contained changes to Core utilities that the Simplifier refactoring
in the next commit relies on.
* `doCaseToLet` moves from GHC.Core.Opt.Simplify.Iteration to
GHC.Core.Utils, with new `mkFloatCase` and `okFloatCase`.
* A new, global, invariant on `GHC.Core.FloatCase`: a DEFAULT case-float
never has a scrutinee for which `doCaseToLet` holds; we use a let-float
instead (`mkFloatCase`). Nice-to-have rather than essential, but it
stops a needless case-float blocking the floating of a whole group.
See Note [The FloatCase invariant] in GHC.Core.
* `exprIsConApp_maybe`: fix a perf hole in `subst_bndr`, which built a
`Subst` unnecessarily; use `mkFloatCase` when looking through a
single-alternative case; `mkFieldSeqFloats` does not seq a strict field
whose argument is unlifted and ok-for-speculation.
* `mkSingleAltCase` skips `occCheckExpand` when no binder is a TyCoVar.
* New `GHC.Data.OrdList.allOL`.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
c38f35da by Simon Peyton Jones at 2026-11-21T12:50:35+00:00
Don't push `case` inside `let` in Gentle simplification
This MR refactors the Simplifier again. It was triggered by #27737,
in which a join point was lost, but that led me into a larger-scale
refactoring. This is the second of three commits: the first added
some Core utilities, and the third improves `simplOutExpr`.
I did this in dialogue with Claude but I have audited every line of
the new code, revising almost all of them.
Here are the highlights.
* The core of #27737 is that when `sm_case_case` is off (that is, in
the first "gentle" simplification), we should not do this transformation:
K[ let binds in e ] --> let binds in K[ e ]
See point (2) in Note [sm_case_case: switching off case continuations]
and discussion on #27737.
This is achieved by using `splitContForNoCaseCase` in the `Let`
case of `simplExprF1`. That in turn uses `splitContArgs` to split
the continuation into: a part to push inwards, and a part to keep
at the outside. The same split is used for `Case`, and for `runRW#`.
The invariant (COC-INV) is that when `sm_case_case` is off, the
SimplCont never contains Select, StrictBind or StrictArg.
* I refactored the Simplifier's `LetFloats` to use the GHC-wide data
type `GHC.Core.FloatBinds`. Much nicer! And it eliminates a nasty
impedance mismatch because `exprIsConApp_maybe` returns `FloatBinds`.
See Note [Using FloatBinds in SimplFloats] in GHC.Core.Opt.Simplify.Env.
A consequence is that the Simplifier can return a single-alternative
case as a `FloatCase`, rather than as an expression, so that the lets
in its alternative are not trapped inside it. That matters when
case-of-case is off: `rebuildWithFloats` can do case-of-known-constructor
on the result directly, instead of `exprIsConApp_maybe` walking down
through the case and all the lets every time, which was quadratic
(T18223). See Note [Floating single-alternative cases] in
GHC.Core.Opt.Simplify.Iteration.
The FloatCase is wrapped around its body only when the floats are
finally emitted, by `simplWrapFloats`, which uses `mkCase`, so we lose
none of the usual case tidying (case merging, identity case, etc).
See Note [Wrapping case-floats with mkCase] in GHC.Core.Opt.Simplify.Utils.
* `prepareBinding`/`doFloatFromRhs` is simpler: a group of floats
leaves the RHS of a let-binding only if every one is a let-binding
that we are prepared to float (lazy, or ok-for-speculation, etc);
case-floats and tick-floats never do. The per-group `FloatFlag`
machinery is gone. See Note [doFloatFromRhs] in GHC.Core.Opt.Simplify.Env.
* Casts. When case-of-case is off, `splitContArgs` pushes a cast
inwards only if it is followed by an application. Pushing a cast
into every alternative of a multi-way case duplicates the coercion
(quadratically, for a derived Generic `from`: T5642, T16577) and
defeats cast worker/wrapper.
See Note [Do not push a cast inwards unnecessarily] in GHC.Core.Opt.Simplify.Utils.
Smaller changes
* `contIsDupable` treats a `Select` with "unpacking alternatives"
(case x of K a b -> b, possibly nested) as dupable, so that CPR
unboxing cancels with the boxing instead of making a join point.
See Note [Duplicating unpacking continuations] in GHC.Core.Opt.Simplify.Utils.
* `reallyRebuildCase` does `prepareAlts` first, then splits into
`rebuildSingleAltCase` (no mkDupableCont needed) and `rebuildMultiAltCase`.
`simplAlt` returns the simplified alternative in pieces (con, bndrs,
floats, rhs) rather than floats that mention the alternative's binders.
* `makeTrivial` returns only let-bindings (type `OrdList CoreBind`), and
declines to bind an unlifted expression that is not ok-for-speculation.
See Note [Cannot trivialise] in GHC.Core.Opt.Simplify.Iteration.
* `abstractFloats` takes and returns `SimplFloats`; it is only ever given
let-bindings (a postcondition of `prepareBinding`), so the former panic
on a case-float (T27737a) cannot happen.
* A `Case`'s type is forced exactly when the `Case` is built, by
`returnCase`; see Note [Avoiding space leaks in OutType].
* Note [Floating a prefix of the floats] records an opportunity we
tried and did not keep.
Testsuite: new test T27737a; accept changed output for T20510
and show-bytecode-hpc.
Metric Decrease:
CoOpt_Read
T18730
T26425
T26989
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
ffc053c4 by Simon Peyton Jones at 2026-11-21T12:50:35+00:00
Improve simplOutExpr, and never push a continuation into simplified alternatives
This is the third of three commits for #27737.
* I improved `simplOutExpr` so that it is less ad-hoc, and occasionally
reduces Simplifier iterations. See new Note [Re-simplifying an OutExpr].
This was a bit more subtle than I had expected, as you'll see from
the Note, but the result is nice.
* Recognise and document a potential variable capture described in
Note [Rebuilding a case with simplified alternatives]. It doesn't actually
happen today, but it /could/ so the Note describes how it is avoided.
That in turn leads to some nice refactoring of `reallyRebuildCase`, allowing
me to get rid of `simplAltBinders`, `simplAltIdBinder` and `simplAltExprF`,
and some SimplAltFlag plumbing. Nice.
* `mkDupableCont` now duplicates a lazy, `exprIsDupable` argument instead of
let-binding it as `karg`, saving an iteration (T13056).
See Note [Duplicating small arguments].
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
37f7fce6 by Simon Peyton Jones at 2026-11-21T12:57:14+00:00
Add test for T28163
- - - - -
bd7ea987 by Simon Peyton Jones at 2026-11-21T13:53:49+00:00
Expermimentally disable case-binder unfoldings in Gentle phase
Provoked by #28164.
---- Problem ----------
f x = join j y = ...(case x of K a b c -> e)..... in
case x of K a b c ->
...
Here we can float out that (case x of K a b c -> c)
But if we float out the inner case x past the join point
we get
f x = case x of K a b c ->
join j y = ...(case x of K a b c -> e)..... in
...
Now we simplify the inner case (which is normally good)
f x = case x of K a b c ->
join j y = ...e..... in
...
but now we can't float e.
---- Solution ----------
Don't add local unfoldings inside case alternatives, before FloatOut.
A tiny, one-line change.
- - - - -
508 changed files:
- .gitignore
- .gitlab-ci.yml
- .gitlab/ci.sh
- .gitlab/common.sh
- .gitlab/generate-ci/gen_ci.hs
- .gitlab/jobs.yaml
- .gitlab/rel_eng/mk-ghcup-metadata/mk_ghcup_metadata.py
- .gitmodules
- + changelog.d/21969
- + changelog.d/26169.md
- + changelog.d/27821
- + changelog.d/27892
- + changelog.d/28002-leb128
- + changelog.d/28080
- + changelog.d/28081
- + changelog.d/28101
- + changelog.d/T26754
- + changelog.d/T27323
- changelog.d/T27722-cbe-entry-block.md
- + changelog.d/T27847
- + changelog.d/T27979
- + changelog.d/T27994
- + changelog.d/T28123
- + changelog.d/T9809-timer-manager-contention
- changelog.d/allow-gadt-prefix-con-parens
- + changelog.d/bignum-quotrem-no-alloc
- + changelog.d/caf-deadlock-27272
- + changelog.d/clc-446
- + changelog.d/clc-447
- + changelog.d/fix-aarch64-veneer-target-16686
- + changelog.d/fix-copyarray-nonmoving-barrier-27376
- + changelog.d/fix-heap-census-pinned-blocks.md
- + changelog.d/fix-nonmoving-weak-evacuation-race-23160
- + changelog.d/gadt-curried-contexts-27424
- + changelog.d/ghc-api-exec-break-resume
- + changelog.d/ghc-api-interactive-ids
- + changelog.d/iserv-no-gc-sections.md
- + changelog.d/make-depends-deprecate-doMkDependHS
- + changelog.d/make-depends-json
- + changelog.d/make-depends-multiple-home-units
- + changelog.d/make-depends-streaming-output
- + changelog.d/ncg-reg-usage.md
- + changelog.d/remove-long-deprecated-flags.md
- + changelog.d/split-sections-dynamic
- + changelog.d/stage3-cross-bindists
- compiler/GHC/Cmm/CallConv.hs
- compiler/GHC/Cmm/CommonBlockElim.hs
- compiler/GHC/CmmToAsm/AArch64/Instr.hs
- compiler/GHC/CmmToAsm/Config.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/LA64/Instr.hs
- compiler/GHC/CmmToAsm/PPC/Instr.hs
- compiler/GHC/CmmToAsm/PPC/Ppr.hs
- compiler/GHC/CmmToAsm/RV64/Instr.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs
- compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs
- compiler/GHC/CmmToAsm/Reg/Linear.hs
- compiler/GHC/CmmToAsm/Reg/Liveness.hs
- + compiler/GHC/CmmToAsm/RegUsage.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/CmmToAsm/X86/Ppr.hs
- compiler/GHC/CmmToC.hs
- compiler/GHC/CmmToLlvm/CodeGen.hs
- compiler/GHC/CmmToLlvm/Config.hs
- compiler/GHC/Core.hs
- compiler/GHC/Core/Coercion/Axiom.hs
- compiler/GHC/Core/Map/Expr.hs
- compiler/GHC/Core/Map/Type.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/Opt/OccurAnal.hs
- compiler/GHC/Core/Opt/Simplify/Env.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/Predicate.hs
- compiler/GHC/Core/SimpleOpt.hs
- compiler/GHC/Core/TyCo/FVs.hs
- compiler/GHC/Core/TyCo/Make.hs
- compiler/GHC/Core/TyCo/Subst.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Unify.hs
- compiler/GHC/Core/Utils.hs
- compiler/GHC/CoreToStg.hs
- compiler/GHC/Data/OrdList.hs
- compiler/GHC/Driver/Config/CmmToAsm.hs
- compiler/GHC/Driver/Config/CmmToLlvm.hs
- compiler/GHC/Driver/Config/Core/Opt/Simplify.hs
- compiler/GHC/Driver/Config/StgToCmm.hs
- compiler/GHC/Driver/Downsweep.hs
- compiler/GHC/Driver/DynFlags.hs
- compiler/GHC/Driver/Flags.hs
- compiler/GHC/Driver/MakeFile.hs
- compiler/GHC/Driver/Pipeline/Execute.hs
- compiler/GHC/Driver/Session.hs
- compiler/GHC/Driver/Session/Units.hs
- compiler/GHC/Hs/Binds.hs
- compiler/GHC/Hs/Decls.hs
- compiler/GHC/Hs/Dump.hs
- compiler/GHC/Hs/Expr.hs
- compiler/GHC/Hs/Type.hs
- compiler/GHC/Hs/Utils.hs
- compiler/GHC/HsToCore/Arrows.hs
- compiler/GHC/HsToCore/Expr.hs
- compiler/GHC/HsToCore/Expr.hs-boot
- compiler/GHC/HsToCore/Match.hs
- compiler/GHC/HsToCore/Match/Literal.hs
- compiler/GHC/HsToCore/Monad.hs
- compiler/GHC/HsToCore/Pmc.hs
- compiler/GHC/HsToCore/Pmc/Desugar.hs
- compiler/GHC/HsToCore/Quote.hs
- compiler/GHC/HsToCore/Ticks.hs
- compiler/GHC/HsToCore/Types.hs
- compiler/GHC/HsToCore/Utils.hs
- compiler/GHC/Iface/Ext/Ast.hs
- compiler/GHC/Linker/Executable.hs
- compiler/GHC/Parser.y
- compiler/GHC/Parser/Errors/Ppr.hs
- compiler/GHC/Parser/Errors/Types.hs
- compiler/GHC/Parser/Header.hs
- compiler/GHC/Parser/Lexer.x
- compiler/GHC/Parser/PostProcess.hs
- compiler/GHC/Parser/PostProcess/Haddock.hs
- compiler/GHC/Platform.hs
- + compiler/GHC/Platform/CpuFeatures.hs
- compiler/GHC/Platform/Ways.hs
- compiler/GHC/Rename/Bind.hs
- compiler/GHC/Rename/Expr.hs
- compiler/GHC/Rename/Module.hs
- compiler/GHC/Rename/Utils.hs
- compiler/GHC/Runtime/Context.hs
- compiler/GHC/Runtime/Debugger.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Eval/Types.hs
- compiler/GHC/Runtime/Heap/Inspect.hs
- compiler/GHC/Runtime/Interpreter/C.hs
- compiler/GHC/Stg/Make.hs
- compiler/GHC/StgToCmm/Closure.hs
- compiler/GHC/StgToCmm/Config.hs
- compiler/GHC/StgToCmm/Prim.hs
- compiler/GHC/SysTools/Cpp.hs
- compiler/GHC/Tc/Deriv/Functor.hs
- compiler/GHC/Tc/Deriv/Generate.hs
- compiler/GHC/Tc/Gen/Arrow.hs
- compiler/GHC/Tc/Gen/Expr.hs
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Gen/Match.hs
- compiler/GHC/Tc/Instance/Family.hs
- compiler/GHC/Tc/Module.hs
- compiler/GHC/Tc/Solver/Default.hs
- compiler/GHC/Tc/Solver/FunDeps.hs
- compiler/GHC/Tc/Solver/Monad.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/Tc/TyCl/PatSyn.hs
- compiler/GHC/Tc/Utils/Unify.hs
- compiler/GHC/Tc/Zonk/Type.hs
- compiler/GHC/ThToHs.hs
- compiler/GHC/Types/Literal/Floating.hs
- compiler/GHC/Types/RepType.hs
- compiler/GHC/Types/Tickish.hs
- compiler/GHC/Types/Var/Env.hs
- compiler/GHC/Utils/Json.hs
- compiler/Language/Haskell/Syntax/Decls.hs
- compiler/Language/Haskell/Syntax/Decls/Foreign.hs
- compiler/Language/Haskell/Syntax/Expr.hs
- compiler/Language/Haskell/Syntax/Type.hs
- compiler/ghc.cabal.in
- docs/users_guide/codegens.rst
- docs/users_guide/expected-undocumented-flags.txt
- docs/users_guide/exts/control.rst
- docs/users_guide/exts/ffi.rst
- docs/users_guide/exts/gadt_syntax.rst
- docs/users_guide/exts/pragmas.rst
- docs/users_guide/exts/qualified_strings.rst
- docs/users_guide/ghc.rst
- + docs/users_guide/make-depends-json-schema-1_0.json
- docs/users_guide/phases.rst
- docs/users_guide/profiling.rst
- docs/users_guide/separate_compilation.rst
- − docs/users_guide/what_glasgow_exts_does.rst
- ghc/GHCi/UI.hs
- ghc/GHCi/UI/Monad.hs
- ghc/Main.hs
- hadrian/doc/cross-compile.md
- hadrian/src/Base.hs
- hadrian/src/BindistConfig.hs
- hadrian/src/Builder.hs
- hadrian/src/Context.hs
- hadrian/src/Flavour.hs
- hadrian/src/Hadrian/Haskell/Hash.hs
- hadrian/src/Hadrian/Package.hs
- hadrian/src/Oracles/Flag.hs
- hadrian/src/Oracles/Setting.hs
- hadrian/src/Oracles/TestSettings.hs
- hadrian/src/Packages.hs
- hadrian/src/Rules/BinaryDist.hs
- hadrian/src/Rules/Generate.hs
- hadrian/src/Rules/Program.hs
- hadrian/src/Rules/Test.hs
- hadrian/src/Settings/Builders/DeriveConstants.hs
- hadrian/src/Settings/Builders/RunTest.hs
- hadrian/src/Settings/Packages.hs
- libraries/base/changelog.md
- libraries/base/src/Data/Foldable.hs
- libraries/base/tests/.gitignore
- + libraries/base/tests/T9809.hs
- libraries/base/tests/all.T
- libraries/ghc-boot/GHC/Serialized.hs
- libraries/ghc-heap/GHC/Exts/Heap/FFIClosures_ProfilingDisabled.hsc
- libraries/ghc-heap/GHC/Exts/Heap/FFIClosures_ProfilingEnabled.hsc
- libraries/ghc-heap/tests/parse_tso_flags.hs
- libraries/ghc-internal/src/GHC/Internal/Bignum/Backend/Native.hs
- libraries/ghc-internal/src/GHC/Internal/Conc/IO.hs
- libraries/ghc-internal/src/GHC/Internal/Control/Exception/Base.hs
- libraries/ghc-internal/src/GHC/Internal/Event/Manager.hs
- libraries/ghc-internal/src/GHC/Internal/Event/Thread.hs
- libraries/ghc-internal/src/GHC/Internal/Event/TimerManager.hs
- libraries/ghc-internal/src/GHC/Internal/Heap/Closures.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Handle/Internals.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Handle/Text.hs
- libraries/ghc-internal/src/GHC/Internal/IO/Handle/Windows.hs
- libraries/ghc-internal/src/GHC/Internal/System/Environment/ExecutablePath.hsc
- libraries/ghc-internal/src/GHC/Internal/System/IO/Error.hs
- libraries/ghci/GHCi/Debugger.hs
- libraries/ghci/GHCi/Run.hs
- rts/Exception.cmm
- rts/Interpreter.c
- rts/Interpreter.h
- rts/Linker.c
- rts/LinkerInternals.h
- rts/PrimOps.cmm
- rts/ProfHeap.c
- rts/RtsSymbols.c
- rts/RtsSymbols.h
- rts/RtsUtils.c
- rts/Stats.c
- rts/Stats.h
- rts/StgStdThunks.cmm
- rts/include/Cmm.h
- rts/include/Rts.h
- rts/include/rts/Constants.h
- + rts/include/rts/RtsSymbols.h
- rts/include/stg/MiscClosures.h
- rts/linker/PEi386.c
- rts/linker/elf_reloc_aarch64.c
- rts/rts.cabal
- rts/sm/Evac.c
- rts/sm/GC.c
- rts/sm/GCThread.h
- rts/sm/NonMovingMark.c
- testsuite/README.md
- testsuite/config/ghc
- testsuite/driver/junit.py
- testsuite/driver/my_typing.py
- testsuite/driver/runtests.py
- testsuite/driver/testglobals.py
- testsuite/driver/testlib.py
- testsuite/driver/testutil.py
- testsuite/mk/test.mk
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.hs
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.stdout
- + testsuite/tests/annotations/should_run/SerializedRoundTrip.stdout-ws-32
- testsuite/tests/annotations/should_run/T16841.stdout
- testsuite/tests/annotations/should_run/all.T
- + testsuite/tests/cmm/should_run/T27722.hs
- + testsuite/tests/cmm/should_run/T27722_cmm.cmm
- + testsuite/tests/cmm/should_run/T28101.hs
- + testsuite/tests/cmm/should_run/T28101.stdout
- + testsuite/tests/cmm/should_run/T28101_cmm.cmm
- testsuite/tests/cmm/should_run/all.T
- + testsuite/tests/codeGen/should_compile/T27979.hs
- + testsuite/tests/codeGen/should_compile/T27979.stderr
- testsuite/tests/codeGen/should_compile/all.T
- testsuite/tests/codeGen/should_gen_asm/all.T
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic1.asm
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic1.hs
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic2.asm
- + testsuite/tests/codeGen/should_gen_asm/split-sections-dynamic2.hs
- testsuite/tests/concurrent/should_run/T21969.hs
- + testsuite/tests/concurrent/should_run/T21969a.hs
- + testsuite/tests/concurrent/should_run/T21969a.stdout
- + testsuite/tests/concurrent/should_run/T21969b.hs
- + testsuite/tests/concurrent/should_run/T21969b.stdout
- + testsuite/tests/concurrent/should_run/T21969c.hs
- + testsuite/tests/concurrent/should_run/T21969c.stdout
- + testsuite/tests/concurrent/should_run/T21969d.hs
- + testsuite/tests/concurrent/should_run/T21969d.stdout
- + testsuite/tests/concurrent/should_run/T21969e.hs
- + testsuite/tests/concurrent/should_run/T21969e.stdout
- + testsuite/tests/concurrent/should_run/T21969f.hs
- + testsuite/tests/concurrent/should_run/T21969f.stdout
- testsuite/tests/concurrent/should_run/all.T
- + testsuite/tests/concurrent/should_run/registerFd001.hs
- + testsuite/tests/concurrent/should_run/registerFd001.stdout
- testsuite/tests/count-deps/CountDepsParser.stdout
- testsuite/tests/dmdanal/should_compile/T20510.stderr
- testsuite/tests/driver/Makefile
- testsuite/tests/driver/T2464.hs
- testsuite/tests/driver/T2464.stderr
- + testsuite/tests/driver/mkdepend/Makefile
- + testsuite/tests/driver/mkdepend/README.md
- + testsuite/tests/driver/mkdepend/T24384/A.hs
- + testsuite/tests/driver/mkdepend/T24384/C.hs
- + testsuite/tests/driver/mkdepend/T24384/C.hs-boot
- + testsuite/tests/driver/mkdepend/T24384/D.hs
- + testsuite/tests/driver/mkdepend/T24384/E.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-internal/DepInternal.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-internal/dep-internal.pkg
- + testsuite/tests/driver/mkdepend/T24384/dep-public/DepPublic.hs
- + testsuite/tests/driver/mkdepend/T24384/dep-public/dep-public.pkg
- + testsuite/tests/driver/mkdepend/T24384/dep/Dep.hs
- + testsuite/tests/driver/mkdepend/T24384/dep/dep.pkg
- + testsuite/tests/driver/mkdepend/T24384/foo.h
- + testsuite/tests/driver/mkdepend/T24384/lib/B.hs
- + testsuite/tests/driver/mkdepend/T24384/lib/B.hs-boot
- + testsuite/tests/driver/mkdepend/T24384/preproc.sh
- + testsuite/tests/driver/mkdepend/T24384a.stdout
- + testsuite/tests/driver/mkdepend/T24384b.stdout
- + testsuite/tests/driver/mkdepend/T24384c.stdout
- + testsuite/tests/driver/mkdepend/all.T
- + testsuite/tests/driver/mkdepend/format_json.sh
- + testsuite/tests/driver/mkdepend/format_makefile.sh
- + testsuite/tests/driver/mkdepend/mhu01/a/A/Base.hs
- + testsuite/tests/driver/mkdepend/mhu01/a/A/Base.hs-boot
- + testsuite/tests/driver/mkdepend/mhu01/a/A/TH.hs
- + testsuite/tests/driver/mkdepend/mhu01/a/Util.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/B/Normal.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/B/Splice.hs
- + testsuite/tests/driver/mkdepend/mhu01/b/Util.hs
- + testsuite/tests/driver/mkdepend/mhu01/c/C.hs
- + testsuite/tests/driver/mkdepend/mhu01/unitA
- + testsuite/tests/driver/mkdepend/mhu01/unitB
- + testsuite/tests/driver/mkdepend/mhu01/unitC
- + testsuite/tests/driver/mkdepend/mhu02/A.hs
- + testsuite/tests/driver/mkdepend/mhu02/B.hs
- + testsuite/tests/driver/mkdepend/mhu02/pp.sh
- + testsuite/tests/driver/mkdepend/mhu02/unitA
- + testsuite/tests/driver/mkdepend/mhu02/unitB
- + testsuite/tests/driver/mkdepend/mhu03/pkg/A.hs
- + testsuite/tests/driver/mkdepend/mhu03/pkg/pp.sh
- + testsuite/tests/driver/mkdepend/mhu03/unitA
- + testsuite/tests/driver/mkdepend/mkdepend01.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend01.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend01/A.hs
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01a.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01b.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01c.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu01d.stderr
- + testsuite/tests/driver/mkdepend/mkdepend_mhu02.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu03.dep-json
- + testsuite/tests/exceptions/T27851.hs
- + testsuite/tests/exceptions/T27851.stderr
- + testsuite/tests/exceptions/T27851b.hs
- + testsuite/tests/exceptions/T27851b.stderr
- + testsuite/tests/exceptions/T27851c.hs
- + testsuite/tests/exceptions/T27851c.stdout
- + testsuite/tests/exceptions/T27851d.hs
- + testsuite/tests/exceptions/T27851d.stdout
- + testsuite/tests/exceptions/T27851d.stdout-javascript-unknown-ghcjs
- testsuite/tests/exceptions/all.T
- testsuite/tests/ffi/should_run/T2594.hs
- testsuite/tests/ffi/should_run/ffi015.hs
- testsuite/tests/ffi/should_run/fptr01.hs
- testsuite/tests/ffi/should_run/fptrfail01.hs
- − testsuite/tests/gadt/T12087.stderr
- + testsuite/tests/gadt/T12087a.hs
- testsuite/tests/gadt/T12087.hs → testsuite/tests/gadt/T12087b.hs
- + testsuite/tests/gadt/T12087b.stderr
- + testsuite/tests/gadt/T27424a.hs
- + testsuite/tests/gadt/T27424b.hs
- + testsuite/tests/gadt/T27424b.stderr
- testsuite/tests/gadt/all.T
- testsuite/tests/ghc-api/exactprint/T22919.stderr
- testsuite/tests/ghc-api/exactprint/Test20239.stderr
- testsuite/tests/ghc-api/exactprint/ZeroWidthSemi.stderr
- testsuite/tests/ghc-e/should_fail/T18441fail7.stderr
- testsuite/tests/ghc-e/should_run/ghc-e005.stderr
- + testsuite/tests/ghci.debugger/scripts/RttiSharedTyVar.hs
- + testsuite/tests/ghci.debugger/scripts/RttiSharedTyVar.script
- + testsuite/tests/ghci.debugger/scripts/RttiSharedTyVar.stdout
- testsuite/tests/ghci.debugger/scripts/all.T
- + testsuite/tests/ghci.debugger/scripts/break037.hs
- + testsuite/tests/ghci.debugger/scripts/break037.script
- + testsuite/tests/ghci.debugger/scripts/break037.stdout
- testsuite/tests/ghci/linking/T25155_iserv_main.c
- + testsuite/tests/haddock/haddock_testsuite/IncrementalUnitId.hs
- testsuite/tests/haddock/haddock_testsuite/Makefile
- testsuite/tests/haddock/haddock_testsuite/all.T
- + testsuite/tests/haddock/haddock_testsuite/haddockIncrementalUnitId.stdout
- testsuite/tests/haddock/should_compile_flag_haddock/T17544.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T17544_kw.stderr
- testsuite/tests/haddock/should_compile_flag_haddock/T24221.stderr
- testsuite/tests/indexed-types/should_compile/all.T
- testsuite/tests/indexed-types/should_fail/SkolemOccursLoop.hs
- testsuite/tests/linters/all.T
- testsuite/tests/llvm/should_compile/all.T
- + testsuite/tests/llvm/should_compile/split-sections-darwin.hs
- testsuite/tests/module/mod185.stderr
- testsuite/tests/parser/should_compile/DumpParsedAst.stderr
- testsuite/tests/parser/should_compile/DumpParsedAstComments.stderr
- testsuite/tests/parser/should_compile/DumpRenamedAst.stderr
- testsuite/tests/parser/should_compile/DumpSemis.stderr
- testsuite/tests/parser/should_compile/DumpTypecheckedAst.stderr
- testsuite/tests/parser/should_compile/KindSigs.stderr
- testsuite/tests/parser/should_compile/T14189.stderr
- testsuite/tests/parser/should_compile/T15323.stderr
- testsuite/tests/parser/should_compile/T20452.stderr
- testsuite/tests/parser/should_compile/T20718.stderr
- testsuite/tests/parser/should_compile/T20846.stderr
- testsuite/tests/perf/compiler/hard_hole_fits.stderr
- testsuite/tests/perf/compiler/large-project/all.T
- + testsuite/tests/perf/compiler/large-project/large-project-mhu.sh
- + testsuite/tests/perf/should_run/T27231.hs
- + testsuite/tests/perf/should_run/T27231.stdout
- testsuite/tests/perf/should_run/T7257.hs
- testsuite/tests/perf/should_run/T7257.stdout
- testsuite/tests/perf/should_run/all.T
- + testsuite/tests/pmcheck/should_compile/T27323.hs
- + testsuite/tests/pmcheck/should_compile/T27323b.hs
- + testsuite/tests/pmcheck/should_compile/T27892a.hs
- + testsuite/tests/pmcheck/should_compile/T28095.hs
- testsuite/tests/pmcheck/should_compile/all.T
- testsuite/tests/primops/should_run/all.T
- testsuite/tests/printer/Makefile
- testsuite/tests/printer/T18791.stderr
- + testsuite/tests/printer/T27424c.hs
- testsuite/tests/printer/Test20297.hs
- testsuite/tests/printer/Test20297.stdout
- testsuite/tests/printer/Test24533.stdout
- testsuite/tests/printer/all.T
- testsuite/tests/profiling/should_run/T7275.stdout
- testsuite/tests/rts/Makefile
- testsuite/tests/rts/T17088.hs
- + testsuite/tests/rts/T23160.hs
- + testsuite/tests/rts/T23160.stdout
- + testsuite/tests/rts/T26169.hs
- + testsuite/tests/rts/T27272.hs
- + testsuite/tests/rts/T27272_gen.py
- + testsuite/tests/rts/T27376.hs
- + testsuite/tests/rts/T27376.stdout
- testsuite/tests/rts/all.T
- + testsuite/tests/rts/census_pinned.hs
- + testsuite/tests/rts/census_pinned.stdout-ws-32
- + testsuite/tests/rts/census_pinned.stdout-ws-64
- + testsuite/tests/rts/census_pinned.stdout-ws-64-mingw32
- testsuite/tests/rts/linker/Makefile
- + testsuite/tests/rts/linker/T27807.s
- + testsuite/tests/rts/linker/T27807.stdout
- testsuite/tests/rts/linker/all.T
- testsuite/tests/rts/pause-resume/all.T
- testsuite/tests/rts/pause-resume/pause_resume_via_safe_ffi_concurrent.hs
- + testsuite/tests/rts/symbols/Main.hs
- + testsuite/tests/rts/symbols/Makefile
- + testsuite/tests/rts/symbols/all.T
- + testsuite/tests/rts/symbols/dumpDeclaredSymbols.c
- + testsuite/tests/rts/symbols/rts-check-symbols.sh
- + testsuite/tests/rts/symbols/rts-check-symbols.stdout
- testsuite/tests/show-bytecode/show-bytecode-hpc.stdout
- + testsuite/tests/simplCore/should_compile/T27737a.hs
- + testsuite/tests/simplCore/should_compile/T27892.hs
- + testsuite/tests/simplCore/should_compile/T27892.stderr
- + testsuite/tests/simplCore/should_compile/T28095a.hs
- + testsuite/tests/simplCore/should_compile/T28095a.stderr
- testsuite/tests/simplCore/should_compile/all.T
- + testsuite/tests/simplCore/should_run/T28163.hs
- + testsuite/tests/simplCore/should_run/T28163.stdout
- testsuite/tests/simplCore/should_run/all.T
- testsuite/tests/th/GadtConSigs_th_dump1.hs
- testsuite/tests/th/GadtConSigs_th_dump1.stderr
- + testsuite/tests/th/T27424d.hs
- + testsuite/tests/th/T27424d.stderr
- testsuite/tests/th/all.T
- + testsuite/tests/typecheck/should_compile/T27994.hs
- + testsuite/tests/typecheck/should_compile/T27994a.hs
- + testsuite/tests/typecheck/should_compile/T27994b.hs
- testsuite/tests/typecheck/should_compile/all.T
- + testsuite/tests/unsatisfiable/T28081.hs
- testsuite/tests/unsatisfiable/all.T
- + testsuite/tests/vdq-rta/should_compile/T28123.hs
- testsuite/tests/vdq-rta/should_compile/all.T
- testsuite/tests/warnings/should_compile/Overflow.stderr-ws-32
- testsuite/tests/warnings/should_compile/Overflow.stderr-ws-64
- testsuite/tests/warnings/should_compile/T13256.stderr-ws-32
- testsuite/tests/warnings/should_compile/T13256.stderr-ws-64
- utils/check-exact/ExactPrint.hs
- utils/check-exact/Main.hs
- utils/check-exact/Transform.hs
- utils/check-exact/Utils.hs
- utils/haddock/CHANGES.md
- utils/haddock/doc/markup.rst
- utils/haddock/haddock-api/haddock-api.cabal
- utils/haddock/haddock-api/src/Haddock/Backends/Hoogle.hs
- utils/haddock/haddock-api/src/Haddock/Backends/Hyperlinker/Parser.hs
- utils/haddock/haddock-api/src/Haddock/Convert.hs
- utils/haddock/haddock-api/src/Haddock/GhcUtils.hs
- utils/haddock/haddock-api/src/Haddock/Interface.hs
- utils/haddock/haddock-api/src/Haddock/Interface/Rename.hs
- utils/haddock/haddock-library/CHANGES.md
- utils/haddock/haddock-library/fixtures/Fixtures.hs
- + utils/haddock/haddock-library/fixtures/examples/codeBackticks.input
- + utils/haddock/haddock-library/fixtures/examples/codeBackticks.parsed
- + utils/haddock/haddock-library/fixtures/examples/codeDoubleBackticks.input
- + utils/haddock/haddock-library/fixtures/examples/codeDoubleBackticks.parsed
- utils/haddock/haddock-library/haddock-library.cabal
- utils/haddock/haddock-library/src/Documentation/Haddock/Parser.hs
- utils/haddock/haddock-library/src/Documentation/Haddock/Parser/Identifier.hs
- utils/haddock/haddock-library/test/Documentation/Haddock/ParserSpec.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/17df08ba526ff4019279f2e93ea51b…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/17df08ba526ff4019279f2e93ea51b…
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
1
0
20 Nov '26
Simon Peyton Jones pushed to branch wip/case-bndr-unf at Glasgow Haskell Compiler / GHC
Commits:
bfe578d6 by Simon Peyton Jones at 2026-11-20T23:38:35+00:00
Add splitThunkCpr
This commit adds GHC.Core.Opt.WorkWrap.splitThunkCpr, which adds a form
of "thunk splitting" for strict bindings that have CPR information.
See Note [Thunk splitting] in WorkWrap.hs for the details.
It catches a previously-unrecognised optimisation opportunity
(see #28258) but it only helps in fairly obscure cases, so
I don't expect a big impact in practice.
As usually I did lots of refactoring along the way.
LLM disclosure: lots of interaction with Claude, but I wrote all the
code and comments.
- - - - -
9 changed files:
- compiler/GHC/Core/Opt/CprAnal.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/WorkWrap.hs
- compiler/GHC/Core/Opt/WorkWrap/Utils.hs
- compiler/GHC/Types/Cpr.hs
- compiler/GHC/Utils/Monad.hs
- + testsuite/tests/simplCore/should_compile/T28158.hs
- + testsuite/tests/simplCore/should_compile/T28158.stderr
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core/Opt/CprAnal.hs
=====================================
@@ -343,7 +343,7 @@ cprTransform env id args
-- Any local binding, except for data structure bindings
-- See Note [Efficient Top sigs in SigEnv]
| Just sig <- lookupSigEnv env id
- = applyCprTy (getCprSig sig) (length args)
+ = applyCprTy (cprSigType sig) (length args)
-- See Note [CPR for data structures]
| Just rhs <- cprDataStructureUnfolding_maybe id
= fst $ cprAnal env rhs
@@ -362,7 +362,7 @@ cprTransform env id args
= cprTransformDataConWork env con args
-- Imported function
| otherwise
- = applyCprTy (getCprSig (idCprSig id)) (length args)
+ = applyCprTy (cprSigType (idCprSig id)) (length args)
-- | Precise, hand-written CPR transformers for select Ids
cprTransformBespoke :: Id -> [(CprType, CoreArg)] -> Maybe CprType
@@ -870,27 +870,42 @@ Does f have the CPR property? Well, no.
However, if the strictness analyser has figured out (in a previous
iteration) that it's strict, then we DON'T need to forget the CPR info.
Instead we can retain the CPR info and do the thunk-splitting transform
-(see WorkWrap.splitThunk).
+(see Note [Thunk splitting] esp (B) CPR-led thunk splitting).
This made a big difference to PrelBase.modInt, which had something like
modInt = \ x -> let r = ... -> I# v in
...body strict in r...
-r's RHS isn't a value yet; but modInt returns r in various branches, so
-if r doesn't have the CPR property then neither does modInt
+r's RHS isn't a value yet; but `modInt` returns `r` in various branches, so
+if `r` doesn't have the CPR property then neither does `modInt`
+
Another case I found in practice (in Complex.magnitude), looks like this:
- let k = if ... then I# a else I# b
- in ... body strict in k ....
+ let k* = if ... then I# a else I# b
+ in ... body strict in k ....
(For this example, it doesn't matter whether k is returned as part of
the overall result; but it does matter that k's RHS has the CPR property.)
+
Left to itself, the simplifier will make a join point thus:
- let $j k = ...body strict in k...
- if ... then $j (I# a) else $j (I# b)
+ let $j k = ...body strict in k...
+ if ... then $j (I# a) else $j (I# b)
+
With thunk-splitting, we get instead
- let $j x = let k = I#x in ...body strict in k...
- in if ... then $j a else $j b
+ let k* = case (if ... then I# a else I# b) of I# z -> I# z
+ in ... body strict in k ....
+Now the simplifier should pull out the `case` to give
+ case (if ... then I# a else I# b) of I# z ->
+ let k = I# z in ... body strict in k ...
+Now case-of-if will give
+ let $j z = let k = I# z in ...body strict in k... in
+ if ... then $j a else $j b
This is much better; there's a good chance the I# won't get allocated.
+TL'DR: During CPR analysis we want to give `k` the CPR property in `body`.
+
+What if the type involved has more than one constructor? E.g.
+ let k* = if ... then Just a else Just b
+ in ... body strict in k ....
+That is good too: see (TS5) in Note [Thunk splitting]
-But what about botCpr? Consider
+Finally, what about botCpr? Consider
lvl = error "boom"
fac -1 = lvl
fac 0 = 1
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -51,7 +51,6 @@ import GHC.Types.Literal ( litIsLifted ) --, mkLitInt ) -- temporarily comment
import GHC.Types.SourceText
import GHC.Types.Id
import GHC.Types.Id.Info
-import GHC.Types.Cpr( isTopCprSig )
import GHC.Types.InlinePragma
import GHC.Types.Name ( mkSystemVarName, isExternalName, getOccFS )
import GHC.Types.Demand
@@ -1830,7 +1829,7 @@ simplNonRecE :: HasDebugCallStack
simplNonRecE env from_what bndr (rhs, rhs_se) body cont
| assertPpr (isId bndr && not (isJoinId bndr)) (ppr bndr) True
- , useStrictBind env from_what bndr
+ , useStrictBind env from_what bndr rhs
= -- Evaluate RHS strictly
simplExprF (rhs_se `setInScopeFromE` env) rhs
(StrictBind { sc_bndr = bndr, sc_body = body, sc_from = from_what
@@ -1865,11 +1864,10 @@ simplRecE env pairs body cont
; return (floats1 `addFloats` floats2, expr') }
-useStrictBind :: SimplEnv -> FromWhat -> InId -> Bool
+useStrictBind :: SimplEnv -> FromWhat -> InId -> InExpr -> Bool
-- Can we use a StrictBind continuation for this let-binding?
--- If so, return a binder that is suitable to become a lambda binder,
--- i.e. one satisfying `lamBndrInfoOK`; see (SB3) in Note [StrictBind]
-useStrictBind env from_what bndr
+-- See (SB3) in Note [StrictBind]
+useStrictBind env from_what bndr rhs
-- If we are coming from a beta-reduction (FromBeta) we must
-- establish the let-can-float invariant, so we must go via StrictBind
-- If not, the invariant holds already, and it's optional.
@@ -1880,6 +1878,10 @@ useStrictBind env from_what bndr
| not (isStrUsedDmd dmd_info)
= False
+ -- Not if the RHS is ok-for-spec; no benefit
+ | exprOkForSpeculation rhs
+ = False
+
-- Not if case-of-case is off
-- See (SB1) in Note [StrictBind]
| not (seCaseCase env)
@@ -1894,8 +1896,6 @@ useStrictBind env from_what bndr
| isStableUnfolding (unfoldingInfo info)
|| not (isEmptyRuleInfo (ruleInfo info))
|| not (isAlwaysActive (inlinePragmaActivation (inlinePragInfo info)))
- || not (isNopSig (dmdSigInfo info))
- || not (isTopCprSig (cprSigInfo info))
= False
| otherwise
@@ -4243,9 +4243,8 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
, alt') }
-- See Note [Duplicated env]
-{-
-Note [Do not add unfoldings to join points at birth]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [Do not add unfoldings to join points at birth]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (#15360)
case (case (case (case ...))) of
@@ -4316,7 +4315,7 @@ The simplifier will find
(Var v) with continuation
Select (pn -> rn) (
Select [I# a -> I# a] (
- StrictBind body Stop
+ StrictBind body Stop))
So we'll call mkDupableCont on
Select [I# a -> I# a] (StrictBind body Stop)
@@ -4455,7 +4454,7 @@ hack and bit us in multiple small and not-so-small ways
Consider this
case (case .. ) of c {
- I# c# -> ....c....
+ I# c# -> ....c.... }
If we make a join point with c but not c# we get
$j = \c -> ....c....
@@ -4655,30 +4654,43 @@ We simplify `rhs` with a StrictBind continuation that continues with
invariants] in GHC.Core. But a let-binder `x` usually has IdInfo that a
lambda binder may not have (an unfolding, arity, a demand signature...).
- So `useStrictBind_maybe` zaps that info, keeping only the occurrence info
- and the demand info. If it happens to stay as a let-binding arity info will
- be re-derived, so nothing is lost.
+ So when we duplicate StrictBind, in `mkDupableContWithDmds`, we use
+ `mkLamBndrFromLetBndr` to zap that info, keeping only the occurrence
+ info and the demand info.
- The exceptions are RULES, a stable unfolding, and a non-default inlining
- activation: these cannot be re-derived, and we have nowhere convenient to
- put them if `x` becomes a lambda binder. For example:
+ However, if the let-binder has
+ * RULES
+ * a stable unfolding
+ * a non-default inlining activation
+ we'd permanently lose these things if we lambda-bind it. For example:
let {-# NOINLINE x #-}
x! = case y of { ... }
in blah
- If we make a join point j x = blah, we have nowhere convenient
- to put that NOINLINE. Ditto INLINE or RULES. So in these cases we
- simply don't use StrictBind. It's very unusual, so no harm done.
- But it does happen; one example is this, in the Applicative (ST s)
- instance in GHC.Internal.Control.Monad.St.Lazy.Imp
+ If we make a join point j x = blah, we have nowhere convenient to put that
+ NOINLINE. Ditto INLINE or RULES. It's unusual. But it happens; one example
+ is the Applicative (ST s) instance in GHC.Internal.Control.Monad.St.Lazy.Imp
{-# NOINLINE res1 #-}
!res1 = unST fm s
- TL;DR: the sc_bndr::Id field in StrictBind always satisfies `lamBndrInfoOK`.
- This means that in the above example { x! = case y of ... } we won't
- float the `case y` out. And perhaps that's fine because of the NOINLNE.
- We could imagine instead imposing these conditions only when we /duplicate/
- the StrictBind, rather than when we /create/ it, but that would require a
- bigger refactor.
+ So in these cases we simply don't use StrictBind -- see `useStrictBind`. We
+ could imagine instead imposing these conditions only when we /duplicate/ the
+ StrictBind, rather than when we /create/ it, but that would require a bigger
+ refactor.
+
+ What if a thunk has a strictness signature, or CPR information? We
+ could make `useStrictBind` say False in these cases too, but that turns
+ out to be a net loss: keeping a thunk is worse than losing the strictness
+ information. Example, where f1,f2 are both strict:
+ let f* {- Str=<S> -} = case x of { True -> f1; False -> f2 }
+ in body
+ Keeping it as-is would use CBV for calls of `f` in `body`. But
+ allowing StrictBind would give us
+ join j f* = body
+ in case x of { True -> j f1; False -> j f2 }
+ which avoids the thunk. It's a trade-off.
+
+ For CPR info, see Note [Thunk splitting] in GHC.Core.Opt.WorkWrap,
+ especially (B) CPR-led thunk splitting.
Note [Join point abstraction] Historical note
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=====================================
compiler/GHC/Core/Opt/WorkWrap.hs
=====================================
@@ -598,13 +598,19 @@ tryWW ww_opts is_rec fn_id rhs
= splitFun ww_opts new_fn_id rhs
-- See Note [Thunk splitting]
- | isNonRec is_rec, is_thunk
- = splitThunk ww_opts is_rec new_fn_id rhs
+ | isNonRec is_rec -- See (TS4)
+ , is_thunk -- All join points go via splitFun
+ = do { -- Try strictness then CPR; see (TS5)
+ rhs' <- splitThunkStr ww_opts new_fn_id rhs `orElseM`
+ splitThunkCpr ww_opts new_fn_id rhs `orElseM`
+ return rhs
+ ; return [ (new_fn_id, rhs') ] }
| otherwise
= return [ (new_fn_id, rhs) ]
where
+ is_join = isJoinId fn_id
fn_info = idInfo fn_id
(wrap_dmds, _) = splitDmdSig (dmdSigInfo fn_info)
new_fn_id = zap_join_cpr $ zap_usage fn_id
@@ -613,14 +619,13 @@ tryWW ww_opts is_rec fn_id rhs
-- See Note [Zapping DmdEnv after Demand Analyzer] and
-- See Note [Zapping Used Once info in WorkWrap]
- zap_join_cpr id
- | isJoinId id = id `setIdCprSig` topCprSig
- | otherwise = id
+ zap_join_cpr id | is_join = id `setIdCprSig` topCprSig
+ | otherwise = id
-- See Note [Don't w/w join points for CPR]
- is_fun = notNull wrap_dmds || isJoinId fn_id
- is_thunk = not is_fun && not (exprIsHNF rhs) && not (isJoinId fn_id)
- && not (isUnliftedType (idType fn_id))
+ is_fun = notNull wrap_dmds || is_join
+ is_thunk = not (exprIsHNF rhs)
+ && not (isUnliftedType (idType fn_id))
{-
Note [Zapping DmdEnv after Demand Analyzer]
@@ -806,7 +811,7 @@ splitFun ww_opts fn_id rhs
(wrap_dmds, div) = splitDmdSig (dmdSigInfo fn_info)
- cpr_ty = getCprSig (cprSigInfo fn_info)
+ cpr_ty = cprSigType (cprSigInfo fn_info)
-- Arity of the CPR sig should match idArity when it's not a join point.
-- See Note [Arity trimming for CPR signatures] in GHC.Core.Opt.CprAnal
cpr = assertPpr (isJoinId fn_id || cpr_ty == topCprType || ct_arty cpr_ty == arityInfo fn_info)
@@ -957,114 +962,165 @@ the form [Demand=<L,1*(C(1,...(C(1,U))))>]
Note [Thunk splitting]
~~~~~~~~~~~~~~~~~~~~~~
-Suppose x is used strictly; never mind whether it has the CPR
-property. I'll use a '*' to mean "x* is demanded strictly".
-
- let
- x* = x-rhs
+The worker/wrapper split mainly affects let-bound /functions/. But we can also use
+demand and CPR information to improve let-bound /thunks/. Specifically:
+
+* (A) Demand-led thunk splitting:
+ If a thunk is demanded strictly, perhaps nestedly, we can turn it into a
+ case, perhaps nestedly. For example
+ let x :: (Int, Int)
+ {- Dmd = SP(S,L) -}
+ x = rhs
+ in body
+ We would ultimately like to get
+ case rhs of x { (a,b) ->
+ case a of { I# a# ->
+ body
+
+ This is much better: no thunk for `rhs`; and known-data-con unfoldings for `x`
+ and `a` inside `body`.
+
+* (B) CPR-led thunk splitting:
+ If a thunk has the (possibly-nested) CPR property /and/ is demanded strictly
+ at top level, we can again generate a case
+ let x :: (Int, Int)
+ {- Dmd = S, Cpr = (_, I# _) -}
+ x = rhs
+ in body
+ The CPR info says that if `x` is evaluated (which it is), it'll return a pair,
+ whose second component can very cheaply be evaluated to a (I# b#). We would
+ like to end up with
+ case rhs of x { (a,b) ->
+ case b of { I# b# ->
+ body
+ which is good for the same reasons as before. See (TS3) for an example.
+
+Implementation
+~~~~~~~~~~~~~~
+The worker/wrapper pass does not generate these nested case expressions directly.
+Instead it generates a regular let-binding but, since the binder is marked as
+strict, any `case` expressions in the RHS will float out. Specifically:
+
+(TS1) For (A), `splitThunkStr` generates the binding
+ let x* = case rhs of { (a,b) ->
+ case a of { I# a# ->
+ (I# a, b)
+ Now when the Simplifier floats the `case` expressions out, we get
+ case rhs of { (a,b) ->
+ case a of { I# a# ->
+ let x = (I# a, b)
in body
+ which is equivalent to the expression in (A) above.
-splitThunk transforms like this:
- let
- x* = let x = x-rhs in
- case x of { I# a -> I# a }
- in body
+ `splitThunkStr` also works on /absent/ thunks: see (TS6).
-This is a little strange: we are re-using the same `x` in the RHS; and
-the RHS takes `x` apart and reboxes it. But because the outer 'let' is
-strict, and the inner let mentions `x` only once, the simplifier
-transform it to
- case x-rhs of
- I# a -> let x* = I# a
- in body
-
-That is good: in `body` we know the form of `x`, which
- * gives the CPR property, and
- * allows case-of-case to happen on x
-
-Notes
-* I tried transforming like this:
- let
- x* = let x = x-rhs in
- case x of { I# a -> x }
- in body
- where I return `x` itself, rather than reboxing it. But this
- turned out to cause some regressions, which I never fully
- investigated.
-
-* Suppose x-rhs is itself a case:
- x-rhs = case e of { T -> I# e1; F -> I# e2 }
- Then we'll get
- join j a = let x* = I# a in body
- in case e of { T -> j e1; F -> j e2 }
- which is good (no boxing). But in the original, unsplit program
- we would transform
- let x* = case e of ... in body
- ==> join j2 x = body
- in case e of { T -> j2 (I# e1); F -> j (I# e2) }
+ Rather cleverly, `splitThunkStr` uses `mkWWstr_one`, the /existing/ function
+ argument w/w splitting function, to do the unpacking. This automatically
+ deals with nested strictness.
+
+(TS2) For (B), `splitThunkCpr` behaves exactly analogously, again
+ using `mkWWcpr_one` to do the unpacking. It works only for /demanded/ thunks.
+
+Wrinkles:
+
+(TS3) Here's an example of (B), thunk-splitting based on CPR information, in action.
+ Suppose we have
+ let x* = case e of { T -> Just e1; F -> Just e2 }
+ in body
+ If the Simplifier floats the `case` out, we get
+ join j2 x = body
+ in case e of { T -> j2 (Just e1); F -> j2 (Just e2) }
which is not good (boxing).
-* In fact, splitThunk uses the function argument w/w splitting
- function, mkWWstr_one, so that if x's demand is deeper (say U(U(L,L),L))
- then the splitting will go deeper too.
+ If we first do the thunk-splitting transformation, we get
+ let x* = case (case e of { T -> Just e1; F -> Just e2 }) of
+ Just a -> Just a
+ in body
-* For recursive thunks, the Simplifier is unable to float `x-rhs` out of
- `x*`'s RHS, because `x*` occurs freely in `x-rhs`, and will just change it
- back to the original definition, so we just split non-recursive thunks.
+ Now when the Simplifier floats we will get:
+ join j a = let x* = Just a in body
+ in case e of { T -> j e1; F -> j e2 }
+ which is much better (no boxing).
-Note [Thunk splitting for top-level binders]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Top-level bindings are never strict. Yet they can be absent, as T14270 shows:
-
- module T14270 (mkTrApp) where
- mkTrApp x y
- | Just ... <- ... typeRepKind x ...
- = undefined
- | otherwise
- = undefined
- typeRepKind = Tick scc undefined
-
-(T19180 is a profiling-free test case for this)
-Note that `typeRepKind` is not exported and its only use site in
-`mkTrApp` guards a bottoming expression. Thus, demand analysis
-figures out that `typeRepKind` is absent and splits the thunk to
-
- typeRepKind =
- let typeRepKind = Tick scc undefined in
- let typeRepKind = absentError in
- typeRepKind
-
-But now we have a local binding with an External Name
-(See Note [About the NameSorts]). That will trigger a CoreLint error, which we
-get around by localising the Id for the auxiliary bindings in 'splitThunk'.
+(TS4) We only do thunk-splitting for thunks that are non-recursive
+ For recursive thunks, the Simplifier is unable to float `x-rhs` out of
+ `x*`'s RHS, because `x*` occurs freely in `x-rhs`, and will just change it
+ back to the original definition.
+
+(TS5) Notice that (B) CPR-led thunk splitting can be useful:
+ * when multi-constructor data types are involved, so that the argument-unboxing
+ mechanism (A) is impotent. See the example in (TS3), which uses `Maybe`.
+ * when the binder is only demanded head-strictly, but CPR has nested information.
+
+ So (A) and (B) have complementary benefits. We might do even better by
+ /combining/ (A) and (B), but at the moment we try (A) first, and then try (B)
+ if (A) is impotent. Combining them would be more work.
+
+(TS6) We can also exploit /absence/. Consider
+ let x {-# Dmd = A #-} = rhs
+ in body
+ Generally speaking `x` will be absent becuase it is passed to functions that
+ don't use it, in which case worker/wrapper on those calls will make `x` unused.
+ But suppose `x` is absent inside a /lazy/ argument:
+ let f p = (fst p, 99) in
+ let x = rhs in
+ f (True, x)
+ Here f's argument is lazy, but `x` is definitely absent, and we could replace
+ `x` with an absent filler. Using (TS1) would give us
+ let x = absentError "urk" in ...
+ which is great.
+
+ So `splitThunkStr` works /regardless/ of the demand on `x`; whether it fires is
+ determined only by the `useful` flag returned by `mkWWstr_one`.
+
+(TS7) Adopting (TS6) leads to one other complication: a top-level binder with
+ an External Name (see Note [About the NameSorts]) can be Absent. If so,
+ it must not be used as a local binder in the `Let` created by `splitThunkStr`.
+ T19180 is a test case for this rather obscure situation.
+
+ Solution: use `localiseId` to localise the binder for the `Let`.
-}
--- | See Note [Thunk splitting].
---
--- splitThunk converts the *non-recursive* binding
+-- | splitThunkStr converts the *non-recursive* binding
-- x = e
-- into
--- x = let x' = e in
--- case x' of I# y -> let x' = I# y in x'
--- See comments above. Is it not beautifully short?
--- Moreover, it works just as well when there are
--- several binders, and if the binders are lifted
--- E.g. x = e
--- --> x = let x' = e in
--- case x' of (a,b) -> let x' = (a,b) in x'
--- Here, x' is a localised version of x, in case x is a
--- top-level Id with an External Name, because Lint rejects local binders with
--- External Names; see Note [About the NameSorts] in GHC.Types.Name.
---
--- How can we do thunk-splitting on a top-level binder? See
--- Note [Thunk splitting for top-level binders].
-splitThunk :: WwOpts -> RecFlag -> Var -> Expr Var -> UniqSM [(Var, Expr Var)]
-splitThunk ww_opts is_rec x rhs
- = assert (not (isJoinId x)) $
- do { let x' = localiseId x -- See comment above
- ; (useful,_args, wrap_fn, fn_arg)
- <- mkWWstr_one ww_opts x' NotMarkedStrict
- ; let res = [ (x, Let (NonRec x' rhs) (wrap_fn fn_arg)) ]
- ; if useful then assertPpr (isNonRec is_rec) (ppr x) -- The thunk must be non-recursive
- return res
- else return [(x, rhs)] }
+-- x = let x = e in
+-- case x of I# y -> I# y
+-- See Note [Thunk splitting].
+splitThunkStr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
+splitThunkStr ww_opts x rhs
+ = do { let x' = localiseId x -- See (TS7)
+ ; (useful, _transit_vars, wrap_fn, fn_arg) <- mkWWstr_one ww_opts x' NotMarkedStrict
+ -- Use mkWWstr_one: see (TS1) in Note [Thunk splitting]
+
+ ; if useful
+ then return (Just (Let (NonRec x' rhs) $
+ wrap_fn fn_arg))
+ else return Nothing }
+
+splitThunkCpr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
+-- See Note [Thunk splitting]
+-- Given x* = rhs, where x* is used outermost-strictly, and x* has a (nested) CPR
+-- property, say Just (Just _), return this new RHS:
+-- let x' = rhs in
+-- case x' of { Just p -> case p of { Just q -> -- Unpacking code
+-- Just (Just q) }} -- Repacking code
+-- Works for multi-constructor data types, where splitThunkStr will fail
+splitThunkCpr ww_opts x rhs
+ | isStrUsedDmd (idDemandInfo x) -- See (TS2)
+ = assertPpr (cprTypeArity cpr_type == 0) (ppr x) $ -- It's a thunk
+ do { (useful, _transit_vars, rebuild_result, unpacker) <- mkWWcpr_one ww_opts x cpr
+ -- Use mkWWcpr_one: see (TS2) in Note [Thunk splitting]
+ ; if useful
+ then return (Just (Let (NonRec x rhs) $
+ unpacker rebuild_result))
+ else return Nothing }
+
+ | otherwise
+ = return Nothing
+ where
+ cpr_type :: CprType
+ cpr_type = cprSigType (idCprSig x)
+ cpr :: Cpr
+ cpr = cprTypeCpr cpr_type
+
=====================================
compiler/GHC/Core/Opt/WorkWrap/Utils.hs
=====================================
@@ -8,7 +8,7 @@ A library for the ``worker\/wrapper'' back-end to the strictness analyser
{-# LANGUAGE ViewPatterns #-}
module GHC.Core.Opt.WorkWrap.Utils
- ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one
+ ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one, mkWWcpr_one
, needsVoidWorkerArg
, DataConPatContext(..)
, UnboxingDecision(..), canUnboxArg
@@ -230,8 +230,7 @@ mkWwBodies opts fun_id ww_arity arg_vars res_ty demands res_cpr
; let (work_args, work_marks) = unzip work_args_str
-- Do CPR w/w. See Note [Always do CPR w/w]
- ; (useful2, wrap_fn_cpr, work_fn_cpr)
- <- mkWWcpr_entry opts res_ty' res_cpr
+ ; (useful2, wrap_fn_cpr, work_fn_cpr) <- mkWWcpr_entry opts res_ty' res_cpr
; let (work_lam_args, work_call_args, work_call_str)
| needsVoidWorkerArg fun_id arg_vars work_args
@@ -985,6 +984,12 @@ mkWWstr opts args str_marks
-- * wrap_arg assumes work_args are in scope, and builds a ConApp that
-- reconstructs the RHS of wrap_var that we pass to the original RHS
-- See Note [Worker/wrapper for Strictness and Absence]
+--
+-- E.g. mkWWstr_one (x :: (Int,Int) with strictess saying to unbox the pair and second Int
+-- = ( True -- useful
+-- , [p,q#], -- work_args
+-- , \e -> case x of (p,q) -> case q of I# q# -> e -- wrap_fn
+-- , (p, I# q) ) -- wrap_arg
mkWWstr_one :: WwOpts
-> Var
-> StrictnessMark
@@ -1637,7 +1642,9 @@ mk_res_bndr body_ty = do
-- 1. A 'WwUse' capturing whether the split does anything useful.
-- 2. The list of transit variables (see the Note).
-- 3. The result builder expression for the wrapper. The original case binder if not useful.
--- 4. The result unpacking expression for the worker. 'nop_fn' if not useful.
+-- Assumes that the transit vars are in scope
+-- 4. The result unpacking expression for the worker. 'nop_fn' if not useful
+-- Brings the transit vars into scope
type CprWwResultOne = (WwUse, OrdList Var, CoreExpr , CoreExpr -> CoreExpr)
type CprWwResultMany = (WwUse, OrdList Var, [CoreExpr], CoreExpr -> CoreExpr)
@@ -1768,7 +1775,7 @@ To achieve said transformation, 'mkWWcpr_entry'
what belongs in the case scrutinee of the unpacker through the communicated
Id `r`: The unpacking expression will be free in that variable.
(This is a similar contract as that of 'mkWWstr_one' for strict args.)
- 3. 'mkWWstr_one' produces a bunch of *transit vars*: Those result variables
+ 3. 'mkWWcpr_one' produces a bunch of *transit vars*: Those result variables
that have to be transferred from the worker to the wrapper, where the
constructed result can be rebuilt, `a` and `b` above. Part (3) is
responsible for tupling them up in the worker and taking the tuple apart
=====================================
compiler/GHC/Types/Cpr.hs
=====================================
@@ -8,6 +8,7 @@
module GHC.Types.Cpr (
Cpr (ConCpr), topCpr, botCpr, flatConCpr, asConCpr,
CprType (..), topCprType, botCprType, flatConCprType,
+ cprTypeArity, cprTypeCpr,
lubCprType, applyCprTy, abstractCprTy, trimCprTy,
UnpackConFieldsResult (..), unpackConFieldsCpr,
CprSig (..), topCprSig, isTopCprSig, mkCprSigForArity, mkCprSig,
@@ -106,6 +107,12 @@ data CprType
-- 'ct_arty' arguments
}
+cprTypeArity :: CprType -> Arity
+cprTypeArity = ct_arty
+
+cprTypeCpr :: CprType -> Cpr
+cprTypeCpr = ct_cpr
+
instance Eq CprType where
a == b = ct_cpr a == ct_cpr b
&& (ct_arty a == ct_arty b || ct_cpr a == topCpr)
@@ -167,7 +174,7 @@ seqCprTy (CprType _ cpr) = seqCpr cpr
-- | The arity of the wrapped 'CprType' is the arity at which it is safe
-- to unleash. See Note [Understanding DmdType and DmdSig] in "GHC.Types.Demand"
-newtype CprSig = CprSig { getCprSig :: CprType }
+newtype CprSig = CprSig { cprSigType :: CprType }
deriving (Eq, Binary)
-- | Turns a 'CprType' computed for the particular 'Arity' into a 'CprSig'
=====================================
compiler/GHC/Utils/Monad.hs
=====================================
@@ -16,7 +16,7 @@ module GHC.Utils.Monad
, mapAccumLM
, mapSndM
, concatMapM
- , mapMaybeM
+ , mapMaybeM, orElseM
, anyM, allM, orM
, foldlM, foldlM_, foldrM, foldMapM
, whenM, unlessM
@@ -250,6 +250,14 @@ unlessM :: Monad m => m Bool -> m () -> m ()
unlessM condM acc = do { cond <- condM
; unless cond acc }
+-- | Monadic version of @orElse@
+infixr 4 `orElseM`
+orElseM :: Monad m => m (Maybe a) -> m a -> m a
+orElseM ma def = do { mb_r <- ma
+ ; case mb_r of
+ Just x -> return x
+ Nothing -> def }
+
-- | Like 'filterM', only it reverses the sense of the test.
filterOutM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a]
filterOutM p =
=====================================
testsuite/tests/simplCore/should_compile/T28158.hs
=====================================
@@ -0,0 +1,18 @@
+module T28158 where
+
+-- Here we miss CPR on y
+-- It's a bit of an obscure example, but still; see #28158
+f :: a -> a -> a -> [Int] -> [Int]
+f a b c xs = let y = case xs of
+ [0] -> Just a
+ [1] -> Just b
+ _ -> Just c
+ in h y (case y of
+ Just z -> reverse (reverse (reverse (
+ reverse (reverse (reverse (
+ reverse (reverse xs)))))))
+ Nothing -> xs++xs)
+
+h :: Maybe a -> b -> b
+h (Just y) e = h Nothing e
+h Nothing e = e
=====================================
testsuite/tests/simplCore/should_compile/T28158.stderr
=====================================
@@ -0,0 +1,47 @@
+
+==================== Tidy Core ====================
+Result size of Tidy Core
+ = {terms: 72, types: 76, coercions: 0, joins: 1/1}
+
+Rec {
+h = \ @a @b ds e ->
+ case ds of {
+ Nothing -> e;
+ Just y -> h Nothing e
+ }
+end Rec }
+
+f = \ @a a1 b c xs ->
+ join {
+ $j ww
+ = h (Just ww)
+ (reverse1
+ (reverse1
+ (reverse1
+ (reverse1
+ (reverse1 (reverse1 (reverse1 (reverse xs) []) []) []) [])
+ [])
+ [])
+ []) } in
+ case xs of {
+ [] -> jump $j c;
+ : ds ds1 ->
+ case ds of { I# ds2 ->
+ case ds2 of {
+ __DEFAULT -> jump $j c;
+ 0# ->
+ case ds1 of {
+ [] -> jump $j a1;
+ : ipv ipv1 -> jump $j c
+ };
+ 1# ->
+ case ds1 of {
+ [] -> jump $j b;
+ : ipv ipv1 -> jump $j c
+ }
+ }
+ }
+ }
+
+
+
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -636,3 +636,4 @@ test('T27962a', [extra_files(['T27962.hs'])], multimod_compile, ['T27962', '-v0
test('T27963', [grep_errmsg(r'f/42')], compile, ['-O -ddump-rule-firings'])
test('T27965', normal, compile, ['-O'])
test('T27965a', normal, compile, ['-O'])
+test('T28158', normal, compile, ['-O -dno-typeable-binds -dsuppress-all -dsuppress-uniques -ddump-simpl'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/bfe578d65058267134b03d49263c43d…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/bfe578d65058267134b03d49263c43d…
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
1
0
[Git][ghc/ghc][wip/T27212] Document and refactor eta-reduction documentation
by Simon Peyton Jones (@simonpj) 20 Nov '26
by Simon Peyton Jones (@simonpj) 20 Nov '26
20 Nov '26
Simon Peyton Jones pushed to branch wip/T27212 at Glasgow Haskell Compiler / GHC
Commits:
d2b9078f by Simon Peyton Jones at 2026-11-20T23:14:07+00:00
Document and refactor eta-reduction documentation
Triggered by #27212, this patch does several related things.
* #27212 suggested that `findRhsArity` should ask for eta-expansion
whenever the RHS's `manifestArity` is less than the arity it finds.
That is a misconception: it deliberately compares with `exprArity`,
which counts PAPs, so that we do not eta-expand PAPs (#9020).
Switching to `manifestArity` makes compile time worse in T13960
and T13056.
So this patch changes no code here; we continue to expand only to
increase `exprArity` not `manifestArity`. Instead it documents the
design in `findRhsArity`, `tryEtaExpandRhs`, `wantEtaExpansion` and
Note [Do not eta-expand PAPs] (which now records the #27212
experiment).
* Refactor GHC.Core.Opt.Arity.tryEtaReduce, which was hard to
understand:
- Accumulate an MCoercion rather than a Coercion, so the common
no-cast case builds no coercions at all.
- Separate equations of `go` for type and value arguments. For
value arguments, the new `getTrivialHead_maybe` looks through any
nesting of casts and floatable ticks, and `mkEtaReduceFunCo` builds
the coercion.
- Make the FunCo with `mkFunCo2` and compute its right-hand
FunTyFlag from the coercion kinds. The cast can turn a Type-kinded
argument into a Constraint-kinded one. New test T27212 covers this.
- `mkEtaReduceForAllMCo` builds the ForAllCo for type arguments. It
is tiresomely similar to `mkEtaForAllMCo`, but with the visibilities
the other way round (#24014). It will go away again once !17006
lands.
- New helper `mCoToCo` in GHC.Core.TyCo.Make.
* Drop the checks on multiplicity in `tryEtaReduce`, which sometimes
disabled eta-reduction. For example, (\x. K x) has type Int -> T,
but the data constructor has type K :: Int %1 -> T, so we used to
refuse to eta-reduce it to K.
But Note [Linting linearity] in GHC.Core.Lint (EXAMPLE 4) already
says that we do not preserve linearity under eta-reduction, so this
change just puts that claim into practice. See (EtaMult) in
Note [Eta reduction soundness].
Consequences in the testsuite:
- T18052a: the pattern-synonym builder (\x y. (x,y)) is now just (,).
- T21888a: the NOINLINE function (f x = Just x) becomes (f = Just),
so f loses its CPR signature. The test is about demands, not CPR.
* Tidy up the documentation of eta-reduction:
- Relabel the criteria in Note [Eta reduction soundness] as (EtaA),
(EtaS), (EtaR), (EtaE), (EtaT), (EtaJ), (EtaB) and (EtaW), and
update all references to them. Also fix references to point (2) of
Note [Eta reduction makes sense], which no longer exists.
- Replace the confused "never reduce arity" bullet with an example in
(EtaA), cross-referenced from Note [Arity robustness].
- Add historical notes (EtaMult) and (EtaBot).
- Label the equations in Note [Eta reduction with casted arguments]
(ECA1-4), and point to the code that implements them.
LLM disclosure: I interacted with Claude a lot for this MR, but I
wrote all the code and docs myself.
- - - - -
13 changed files:
- compiler/GHC/Core/Coercion.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/Opt/OccurAnal.hs
- compiler/GHC/Core/Opt/Simplify/Env.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/TyCo/Make.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Utils.hs
- testsuite/tests/dmdanal/sigs/T21888a.stderr
- testsuite/tests/printer/T18052a.stderr
- + testsuite/tests/simplCore/should_compile/T27212.hs
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core/Coercion.hs
=====================================
@@ -74,7 +74,7 @@ module GHC.Core.Coercion (
isReflCoVar_maybe, assertGoodForAllCo,
- coToMCo, kindCoToMKindCo,
+ coToMCo, kindCoToMKindCo, mCoToCo,
mkTransMCo, mkTransMCoL, mkTransMCoR, mkCastTyMCo, mkSymMCo,
mkFunResMCo, mkPiMCos,
isReflMCo, checkReflexiveMCo,
=====================================
compiler/GHC/Core/Opt/Arity.hs
=====================================
@@ -886,8 +886,14 @@ findRhsArity :: ArityOpts -> RecFlag -> Id -> CoreExpr
-- This implements the fixpoint loop for arity analysis
-- See Note [Arity analysis]
--
--- The Bool is True if the returned arity is greater than (exprArity rhs)
--- so the caller should do eta-expansion
+-- The Bool is True if
+-- the returned arity is greater than (exprArity rhs)
+-- so the caller should do eta-expansion
+-- NB: `exprArity`, not `manifestArity`:
+-- a PAP such as (\x. f x), where f has arity 3, has exprArity 3,
+-- so we do not eta-expand it to (\x y z. f x y z)
+-- See Note [Do not eta-expand PAPs] in GHC.Core.Opt.Simplify.Utils
+--
-- That Bool is never True for join points, which are never eta-expanded
--
-- Returns an SafeArityType that is guaranteed trimmed to typeArity of 'bndr'
@@ -903,10 +909,11 @@ findRhsArity opts is_rec bndr rhs
| otherwise
= (arity_increased, non_join_arity_type)
- -- arity_increased: eta-expand if we'll get more lambdas
- -- to the top of the RHS
+ -- arity_increased: eta-expand if the analysis finds a greater arity
+ -- than exprArity, which already takes account of PAPs
where
- old_arity = exprArity rhs
+ old_arity = exprArity rhs -- See Note [Do not eta-expand PAPs]
+ -- in GHC.Core.Opt.Simplify.Utils
init_env :: ArityEnv
init_env = findRhsArityEnv opts (isJoinId bndr)
@@ -2388,6 +2395,7 @@ mkEtaForAllMCo (Bndr tcv vis) ty mco
-- and is SymCo'd in `etaInfoAbs`. Hence the orientation of the visibility
-- flags. A bit of a brain-strain (#27557).
+
{-
************************************************************************
* *
@@ -2452,16 +2460,20 @@ perform eta reduction on an expression with n leading lambdas `\xs. e xs`
(checked in 'is_eta_reduction_sound' in 'tryEtaReduce', which focuses on the
case where `e` is trivial):
-(A) It is sound to eta-reduce n arguments as long as n does not exceed the
- `exprArity` of `e`. (Needs Arity analysis.)
- This criterion exploits information about how `e` is *defined*.
+(EtaA) It is sound to eta-reduce n arguments as long as n does not exceed the
+ `exprArity` of `e`. (Needs Arity analysis.) This criterion exploits information
+ about how `e` is *defined*. For example:
+ f = \xy. g x y ===> f = g
+ This eta-reduction is good only if `g` has arity at least 2, otherwise
+ f's arity will decrease from 2 to 1.
+ c.f. Note [Arity robustness] in GHC.Core.Opt.Simplify.Env.
- Example: If `e = \x. bot` then we know it won't diverge until it is called
- with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`.
+ Another example: If `e = \x. bot` then we know it won't diverge until it
+ is called with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`.
By contrast, it would be *unsound* to eta-reduce 2 args, `\x y. e x y` to `e`:
`e 42` diverges when `(\x y. e x y) 42` does not.
-(S) It is sound to eta-reduce n arguments in an evaluation context in which all
+(EtaS) It is sound to eta-reduce n arguments in an evaluation context in which all
calls happen with at least n arguments. (Needs Strictness analysis.)
NB: This treats evaluations like a call with 0 args.
NB: This criterion exploits information about how `e` is *used*.
@@ -2483,35 +2495,31 @@ case where `e` is trivial):
But it is unsound to eta-reduce the arg in `g2 (\x y. e x y)` to `g2 e`
when `e = \x. if x then bot else id`, because the latter will diverge when
the former would not. Fortunately, the strictness analyser will report
- "Not always called with two arguments" for `g2` and we won't eta-expand.
+ "Not always called with two arguments" for `g2` and we won't eta-reduce.
See Note [Eta reduction based on evaluation context] for the implementation
details. This criterion is tested extensively in T21261.
-(R) Note [Eta reduction in recursive RHSs] tells us that we should not
+(EtaR) Note [Eta reduction in recursive RHSs] tells us that we should not
eta-reduce `f` in its own RHS and describes our fix.
There we have `f = \x. f x` and we should not eta-reduce to `f=f`. Which
might change a terminating program (think @f `seq` e@) to a non-terminating
one.
-(E) (See fun_arity in tryEtaReduce.) As a perhaps special case on the
- boundary of (A) and (S), when we know that a fun binder `f` is in
- WHNF, we simply assume it has arity 1 and apply (A). Example:
+(EtaE) (See fun_arity in tryEtaReduce.) As a perhaps special case on the
+ boundary of (EtaA) and (EtaS), when we know that a fun binder `f` is in
+ WHNF, we simply assume it has arity 1 and apply (EtaA). Example:
g f = f `seq` \x. f x
Here it's sound eta-reduce `\x. f x` to `f`, because `f` can't be bottom
after the `seq`. This turned up in #7542.
- T. If the binders are all type arguments, it's always safe to eta-reduce,
- regardless of the arity of f.
- /\a b. f @a @b --> f
-
-2. Type and dictionary abstraction. Regardless of whether 'f' is a value, it
+(EtaT) Type and dictionary abstraction. Regardless of whether 'f' is a value, it
is always sound to reduce /type lambdas/, thus:
- (/\a -> f a) --> f
+ (/\a -> f @a) --> f
Moreover, we always want to, because it makes RULEs apply more often:
- This RULE: `forall g. foldr (build (/\a -> g a))`
+ This RULE: `forall g. foldr (build (/\a -> g @a))`
should match `foldr (build (/\b -> ...something complex...))`
- and the simplest way to do so is eta-reduce `/\a -> g a` in the RULE to `g`.
+ and the simplest way to do so is eta-reduce `/\a -> g @a` in the RULE to `g`.
More debatably, we extend this to dictionary arguments too, because the type
checker can insert these eta-expanded versions, with both type and dictionary
@@ -2523,18 +2531,25 @@ case where `e` is trivial):
And here are a few more technical criteria for when it is *not* sound to
eta-reduce that are specific to Core and GHC:
-(J) We may not undersaturate join points.
+(EtaJ) We may not undersaturate join points.
See Note [Invariants on join points] in GHC.Core, and #20599.
-(B) We may not undersaturate functions with no binding.
+(EtaB) We may not undersaturate functions with no binding.
See Note [Eta expanding primops].
-(W) We may not undersaturate StrictWorkerIds.
+(EtaW) We may not undersaturate StrictWorkerIds.
See Note [CBV Function Ids: overview] in GHC.Types.Id.Info.
-Here is a list of historic accidents surrounding unsound eta-reduction:
-* Consider
+Here is a list of historic notes surrounding unsound eta-reduction:
+
+(EtaMult) We used to disable eta-reduction if performing it would change multiplicity.
+ For example:
+ (\x. K x) :: Int -> T but K :: Int %1 -> T
+ But that (a) inhibits beneficial eta-reduction (b) costs extra work to check, and
+ now we don't even try. See Note [Linting linearity] in GHC.Core.Lint, esp EXAMPLE 4
+
+(EtaBot) Consider
f = \x.f x
h y = case (case y of { True -> f `seq` True; False -> False }) of
True -> ...; False -> ...
@@ -2548,16 +2563,6 @@ Here is a list of historic accidents surrounding unsound eta-reduction:
Result: seg-fault because the boolean case actually gets a function value.
See #1947.
-* Never *reduce* arity. For example
- f = \xy. g x y
- Then if h has arity 1 we don't want to eta-reduce because then
- f's arity would decrease, and that is bad
- [SG in 2022: I don't understand this point. There is no `h`, perhaps that
- should have been `g`. Even then, this proposed eta-reduction is invalid by
- criterion (A), which might actually be the point this anecdote is trying to
- make. Perhaps the "no arity decrease" idea is also related to
- Note [Arity robustness]?]
-
Note [Do not eta reduce PAPs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I considered eta-reducing if the result is a PAP:
@@ -2598,11 +2603,12 @@ This should be eta-reduced to
So we need to accumulate a coercion, pushing it inward (past
variable arguments only) thus:
- f (x |> co_arg) |> co --> (f |> (sym co_arg -> co)) x
- f (x:t) |> co --> (f |> (t -> co)) x
- f @ a |> co --> (f |> (forall a.co)) @ a
- f @ (g:t1~t2) |> co --> (f |> (t1~t2 => co)) @ (g:t1~t2)
-These are the equations for ok_arg.
+(ECA1) \x. f (x |> co_arg) |> co --> (f |> (sym co_arg -> co))
+(ECA2) \x. f (x:t) |> co --> (f |> (t -> co))
+(ECA3) \x. f (g:t1~#t2) |> co --> (f |> (t1~#t2 => co))
+(ECA4) \x. f @ a |> co --> (f |> (forall a.co))
+
+These are implemented by the `go` equations in `tryEtaReduce`
Note [Eta reduction with casted function]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -2620,7 +2626,7 @@ eta-expansion may be turned off (by sm_eta_expand).
Note [Eta reduction based on evaluation context]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Note [Eta reduction soundness], criterion (S) allows us to eta-reduce
+Note [Eta reduction soundness], criterion (EtaS) allows us to eta-reduce
`g (\x y. e x y)` to `g e` when we know that `g` always calls its parameter with
at least 2 arguments. So how do we read that off `g`'s demand signature?
@@ -2713,13 +2719,13 @@ tryEtaReduce :: UnVarSet -> [Var] -> CoreExpr -> SubDemand -> Maybe CoreExpr
-- and Note [Eta reduction makes sense] when that is the case.
-- and Note [Eta reduction based on evaluation context] for the `eval_sd` arg
tryEtaReduce rec_ids bndrs body eval_sd
- = go (reverse bndrs) body (mkRepReflCo (exprType body))
+ = go (reverse bndrs) body MRefl
where
- incoming_arity = count isId bndrs -- See Note [Eta reduction makes sense], point (2)
+ incoming_arity = count isId bndrs -- See (EtaA) in Note [Eta reduction soundness]
go :: [Var] -- Binders, innermost first, types [a3,a2,a1]
-> CoreExpr -- Of type tr
- -> Coercion -- Of type tr ~ ts
+ -> MCoercion -- Of type tr ~ ts
-> Maybe CoreExpr -- Of type a1 -> a2 -> a3 -> ts
-- See Note [Eta reduction with casted arguments]
-- for why we have an accumulating coercion
@@ -2729,19 +2735,37 @@ tryEtaReduce rec_ids bndrs body eval_sd
-- See Note [Eta reduction with casted function]
go bs (Cast e co1) co2
- = go bs e (co1 `mkTransCo` co2)
+ = go bs e (co1 `mkTransMCoR` co2)
go bs (Tick t e) co
| tickishFloatable t
= fmap (Tick t) $ go bs e co
-- Float app ticks: \x -> Tick t (e x) ==> Tick t e
- go (b : bs) (App fun arg) co
- | Just (co', ticks) <- ok_arg b arg co (exprType fun)
- = fmap (flip (foldr mkTick) ticks) $ go bs fun co'
- -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e
+ -- Implements (ECA4)
+ go all_bs@(b : bs) all_e@(App fun (Type arg_ty)) mco
+ | Just tv <- getTyVar_maybe arg_ty
+ , b == tv
+ , Just (bndr, body_ty) <- splitForAllForAllTyBinder_maybe (exprType fun)
+ = go bs fun (mkEtaReduceForAllMCo bndr body_ty tv mco)
- go remaining_bndrs fun co
+ | otherwise
+ = go_finish all_bs all_e mco
+ -- Want to go to the finish case; see the call
+ -- to (all isTyVar remaining_bndrs) there
+
+ -- Implements (ECA1), (ECA2), (ECA3)
+ go (b : bs) (App fun val_arg) mco
+ | Just (v, arg_mco, arg_ticks) <- getTrivialHead_maybe val_arg
+ , b == v
+ , Just co' <- mkEtaReduceFunCo (exprType fun) arg_mco mco
+ = fmap (flip (foldr mkTick) arg_ticks) $
+ go bs fun co'
+ -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e
+
+ go bs fun co = go_finish bs fun co
+
+ go_finish remaining_bndrs fun co
| all isTyVar remaining_bndrs
-- If all the remaining_bnrs are tyvars, then the etad_exp
-- will be trivial, which is what we want.
@@ -2752,7 +2776,7 @@ tryEtaReduce rec_ids bndrs body eval_sd
, remaining_bndrs `ltLength` bndrs
-- Only reply Just if /something/ has happened
, ok_fun fun
- , let used_vars = exprFreeVars fun `unionVarSet` tyCoVarsOfCo co
+ , let used_vars = exprFreeVars fun `unionVarSet` tyCoVarsOfMCo co
reduced_bndrs = mkVarSet (dropList remaining_bndrs bndrs)
-- reduced_bndrs are the ones we are eta-reducing away
, used_vars `disjointVarSet` reduced_bndrs
@@ -2761,10 +2785,10 @@ tryEtaReduce rec_ids bndrs body eval_sd
-- See Note [Eta reduction makes sense], intro and point (1)
-- NB: don't compute used_vars from exprFreeVars (mkCast fun co)
-- because the latter may be ill formed if the guard fails (#21801)
- = Just (mkLams (reverse remaining_bndrs) (mkCast fun co))
+ = Just (mkLams (reverse remaining_bndrs) (mkCastMCo fun co))
- go _remaining_bndrs _fun _ = -- pprTrace "tER fail" (ppr _fun $$ ppr _remaining_bndrs) $
- Nothing
+ | otherwise
+ = Nothing
---------------
-- See Note [Eta reduction makes sense], point (1)
@@ -2777,18 +2801,18 @@ tryEtaReduce rec_ids bndrs body eval_sd
---------------
-- See Note [Eta reduction soundness], this is THE place to check soundness!
is_eta_reduction_sound fun
- | fun `elemUnVarSet` rec_ids -- Criterion (R)
+ | fun `elemUnVarSet` rec_ids -- Criterion (EtaR)
= False -- Don't eta-reduce in fun in its own recursive RHSs
- | cantEtaReduceFun fun -- Criteria (J), (W), (B)
+ | cantEtaReduceFun fun -- Criteria (EtaJ), (EtaW), (EtaB)
= False -- Function can't be eta reduced to arity 0
-- without violating invariants of Core and GHC
| otherwise
= -- Check that eta-reduction won't make the program stricter...
- fun_arity fun >= incoming_arity -- Criterion (A) and (E)
- || all_calls_with_arity incoming_arity -- Criterion (S)
- || all ok_lam bndrs -- Criterion (T)
+ fun_arity fun >= incoming_arity -- Criterion (EtaA) and (EtaE)
+ || all_calls_with_arity incoming_arity -- Criterion (EtaS)
+ || all ok_lam bndrs -- Criterion (EtaT)
all_calls_with_arity n = isStrict (fst $ peelManyCalls n eval_sd)
-- See Note [Eta reduction based on evaluation context]
@@ -2797,57 +2821,76 @@ tryEtaReduce rec_ids bndrs body eval_sd
fun_arity fun
| arity > 0 = arity
| isEvaldUnfolding (idUnfolding fun) = 1
- -- See Note [Eta reduction soundness], criterion (E)
+ -- See Note [Eta reduction soundness], criterion (EtaE)
| otherwise = 0
where
arity = idArity fun
---------------
ok_lam v = isTyVar v || isEvId v
- -- See Note [Eta reduction makes sense], point (2)
-
- ---------------
- ok_arg :: Var -- Of type bndr_t
- -> CoreExpr -- Of type arg_t
- -> Coercion -- Of kind (t1~t2)
- -> Type -- Type (arg_t -> t1) of the function
- -- to which the argument is supplied
- -> Maybe (Coercion -- Of type (arg_t -> t1 ~ bndr_t -> t2)
- -- (and similarly for tyvars, coercion args)
- , [CoreTickish])
- -- See Note [Eta reduction with casted arguments]
- ok_arg bndr (Type arg_ty) co fun_ty
- | Just tv <- getTyVar_maybe arg_ty
- , bndr == tv = case splitForAllForAllTyBinder_maybe fun_ty of
- Just (Bndr _ vis, _) -> Just (fco, [])
- where !fco = mkForAllCo tv vis coreTyLamForAllTyFlag MRefl co
- -- The lambda we are eta-reducing always has visibility
- -- 'coreTyLamForAllTyFlag' which may or may not match
- -- the visibility on the inner function (#24014)
- Nothing -> pprPanic "tryEtaReduce: type arg to non-forall type"
- (text "fun:" <+> ppr bndr
- $$ text "arg:" <+> ppr arg_ty
- $$ text "fun_ty:" <+> ppr fun_ty)
- ok_arg bndr (Var v) co fun_ty
- | bndr == v
- , let mult = idMult bndr
- , Just (_af, fun_mult, _, _) <- splitFunTy_maybe fun_ty
- , mult `eqType` fun_mult -- There is no change in multiplicity, otherwise we must abort
- = Just (mkFunResCo Representational bndr co, [])
- ok_arg bndr (Cast e co_arg) co fun_ty
- | (ticks, Var v) <- stripTicksTop tickishFloatable e
- , Just (_, fun_mult, _, _) <- splitFunTy_maybe fun_ty
- , bndr == v
- , fun_mult `eqType` idMult bndr
- = Just (mkFunCoNoFTF Representational (multToCo fun_mult) (mkSymCo co_arg) co, ticks)
- -- The simplifier combines multiple casts into one,
- -- so we can have a simple-minded pattern match here
- ok_arg bndr (Tick t arg) co fun_ty
- | tickishFloatable t, Just (co', ticks) <- ok_arg bndr arg co fun_ty
- = Just (co', t:ticks)
-
- ok_arg _ _ _ _ = Nothing
+ -- See Note [Eta reduction soundness], point (EtaT)
+
+
+-----------------
+getTrivialHead_maybe :: CoreExpr -> Maybe (Id, MCoercion, [CoreTickish])
+-- (getTrivialHead_maybe e) returns (Just (fn, co,ts))
+-- if `e` looks like (Tick ts (fn |> co)) and ts are floatable
+-- So co :: fn_ty ~ arg_ty
+
+getTrivialHead_maybe (Var v)
+ = Just (v, MRefl, [])
+
+getTrivialHead_maybe (Cast e co_outer)
+ = do { (v, mco_inner, ticks) <- getTrivialHead_maybe e
+ ; return (v, mco_inner `mkTransMCoL` co_outer, ticks) }
+
+getTrivialHead_maybe (Tick t arg)
+ | tickishFloatable t
+ = do { (v, co, ticks) <- getTrivialHead_maybe arg
+ ; return (v, co, t:ticks) }
+
+getTrivialHead_maybe _ = Nothing
+
+-----------------
+mkEtaReduceFunCo :: Type -> MCoercion -> MCoercion -> Maybe MCoercion
+mkEtaReduceFunCo _ MRefl MRefl
+ = Just MRefl -- Very common case
+mkEtaReduceFunCo fun_ty arg_mco res_mco
+ | Just (ftf, mult, arg_ty, res_ty) <- splitFunTy_maybe fun_ty
+ -- fun_ty = arg_ty -> res_ty
+ -- sym arg_mco : arg_ty ~ inner_arg_ty
+ -- res_mco : res_ty ~ outer_res_ty
+ , let arg_co = mCoToCo Representational arg_ty arg_mco
+ res_co = mCoToCo Representational res_ty res_mco
+ mult_co = multToCo mult
+ ftf' = chooseFunTyFlag (coercionLKind arg_co) (coercionRKind res_co)
+ = Just (MCo (mkFunCo2 Representational ftf ftf' mult_co (mkSymCo arg_co) res_co))
+ -- (arg_ty -> res_ty) ~ (inner_arg_ty -> outer_res_ty)
+ | otherwise
+ = Nothing
+-----------------
+mkEtaReduceForAllMCo :: ForAllTyBinder -> Type -> TyVar -> MCoercion -> MCoercion
+-- Very similar to mkEtaForAllMCo, but with
+-- the visibilities the other way around. Tiresome.
+-- mkEtaReduceForAllMCo (forall a[vis]. body_ty) b (co :: ty1 ~ ty2)
+-- (where `b` may be free in `ty1` and `ty2`)
+-- = ForAllCo b[vis]~[spec]. (co :: ty1 ~ ty2)
+-- where `coreTyLamForAllTyFlag` is [spec]
+mkEtaReduceForAllMCo (Bndr fun_tv vis) body_ty tv mco
+ = case mco of
+ MRefl | isCoreTyLamForAllTyFlag vis
+ -- The lambda we are eta-reducing always has visibility
+ -- 'coreTyLamForAllTyFlag' which may or may not match the
+ -- visibility on the inner function (#24014)
+ -> MRefl
+ | otherwise
+ -> MCo $ mkForAllCo fun_tv vis coreTyLamForAllTyFlag MRefl refl_co
+ MCo co -> MCo $ mkForAllCo tv vis coreTyLamForAllTyFlag MRefl co
+ -- Tricky: `fun_tv` scopes over `body_ty` and hence over `refl_co`
+ -- but: `tv` scopes over `mco` and hence over `co`
+ where
+ refl_co = mkRepReflCo body_ty
{- *********************************************************************
* *
=====================================
compiler/GHC/Core/Opt/OccurAnal.hs
=====================================
@@ -42,7 +42,6 @@ import GHC.Core.Utils ( exprIsTrivial, isDefaultAlt, isExpandableApp,
import GHC.Core.Opt.Arity ( joinRhsArity, isOneShotBndr )
import GHC.Core.Coercion
import GHC.Core.Type
-import GHC.Core.TyCo.FVs ( tyCoVarsOfMCo )
import GHC.Data.Maybe( orElse )
import GHC.Data.Graph.Directed ( SCC(..), Node(..)
=====================================
compiler/GHC/Core/Opt/Simplify/Env.hs
=====================================
@@ -1240,6 +1240,8 @@ out_id so that its arity is visible in its RHS. Examples:
Example: `f = \x. f x`. See Note [Eta reduction in recursive RHSs] for how
we prevent that.
+c.f. (EtaA) in Note [Eta reduction soundness] in GHC.Core.Opt.Arity.
+
Note [Robust OccInfo]
~~~~~~~~~~~~~~~~~~~~~
It's important that we *do* retain the loop-breaker OccInfo, because
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -3143,7 +3143,7 @@ There have been various earlier versions of this patch:
case_bndr_evald_next _ = False
This patch was part of fixing #7542. See also
- Note [Eta reduction soundness], criterion (E) in GHC.Core.Utils.)
+ Note [Eta reduction soundness], criterion (EtaE) in GHC.Core.Opt.Arity.)
Further notes about case elimination
=====================================
compiler/GHC/Core/Opt/Simplify/Utils.hs
=====================================
@@ -2110,8 +2110,9 @@ tryEtaExpandRhs :: SimplEnv -> BindContext -> OutId -> OutExpr
tryEtaExpandRhs env bind_cxt bndr rhs
| seEtaExpand env -- If Eta-expansion is on
, wantEtaExpansion rhs -- and we'd like to eta-expand e
- , do_eta_expand -- and e's manifest arity is lower than
- -- what it could be
+ , do_eta_expand -- and arity analysis finds a greater arity
+ -- than (exprArity e); NB: not manifestArity
+ -- See Note [Do not eta-expand PAPs]
-- (never true for join points)
= -- Do eta-expansion.
assertPpr( not (isJoinBC bind_cxt) ) (ppr bndr) $
@@ -2130,7 +2131,8 @@ tryEtaExpandRhs env bind_cxt bndr rhs
(do_eta_expand, arity_type) = findRhsArity arity_opts is_rec bndr rhs
wantEtaExpansion :: CoreExpr -> Bool
--- Mostly True; but False of PAPs which will immediately eta-reduce again
+-- Mostly True; but False of trivial RHSs, and of PAPs at the top of the RHS
+-- (PAPs under value lambdas are dealt with by findRhsArity)
-- See Note [Which RHSs do we eta-expand?]
wantEtaExpansion (Cast e _) = wantEtaExpansion e
wantEtaExpansion (Tick _ e) = wantEtaExpansion e
@@ -2168,7 +2170,22 @@ seems like a Good idea.
Note [Do not eta-expand PAPs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-We used to have old_arity = manifestArity rhs, which meant that we
+We do not eta-expand a RHS that is a partial application (PAP). This
+is achieved in two places:
+
+(DEP1) A PAP at the top of the RHS, such as
+ f = g d -- g has arity 2
+ is rejected by `wantEtaExpansion`.
+
+(DEP2) A PAP under value lambdas, such as
+ f = \x. g x -- g has arity 3
+ is not eta-expanded because `findRhsArity` asks for eta-expansion
+ only if the arity it finds is greater than (exprArity rhs), and
+ `exprArity` takes account of PAPs: here (exprArity rhs) = 3.
+ Using `manifestArity` (which is 1 here) instead would eta-expand
+ to f = \x y z. g x y z.
+
+Up to 2014 we used old_arity = manifestArity rhs, which meant that we
would eta-expand even PAPs. But this gives no particular advantage,
and can lead to a massive blow-up in code size, exhibited by #9020.
Suppose we have a PAP
@@ -2184,6 +2201,17 @@ coercions and whatnot that eventually disappear again. For T9020, GHC
allocated 6.6G before, and 0.8G afterwards; and residency dropped from
1.8G to 45M.
+#27212 tried switching (DEP2) back to manifestArity, with these results:
+
+* T13960: bytestring's
+ cstring1 = \(a::Addr#) @r. cstring2 @r a -- cstring2 has arity 4
+ was eta-expanded to (\a @r k br s. cstring2 @r a k br s). That bigger
+ unfolding is inlined at every string literal, adding 6 terms per
+ literal; compile-time allocation went up by 9%.
+
+* T13056: a derived-instance method (\ @a d. lvl @a), where `lvl` is
+ bottoming, was eta-expanded, and then needlessly worker/wrappered.
+
Moreover, if we eta expand
f = g d ==> f = \x. g d x
that might in turn make g inline (if it has an inline pragma), which
=====================================
compiler/GHC/Core/TyCo/Make.hs
=====================================
@@ -58,7 +58,7 @@ module GHC.Core.TyCo.Make (
, mkAxInstCo
, mkTransCo, mkTransMCo, mkTransMCoL, mkTransMCoR
, mkProofIrrelCo
- , coToMCo, kindCoToMKindCo
+ , coToMCo, kindCoToMKindCo, mCoToCo
, mkCoherenceLeftCo, mkCoherenceRightCo, mkCoherenceRightMCo
, toPhantomCo, mkPhantomCo
, isReflCo, isReflMCo, isReflKindCo, isReflKindMCo, isReflCo_maybe
@@ -860,7 +860,7 @@ mkHomoForAllCos vs orig_co
= foldr go orig_co vs
where
go :: ForAllTyBinder -> Coercion -> Coercion
- go (Bndr var vis) co = mk_forall_co var vis vis MRefl co
+ go (Bndr var vis) co = mkForAllCoNonRefl var vis vis MRefl co
mkHomoForAllCo :: TyVar -> Coercion -> Coercion
-- Specialised for a single TyVar,
@@ -869,7 +869,7 @@ mkHomoForAllCo tv orig_co
| Just (ty, r) <- isReflCo_maybe orig_co
= mkReflCo r (mkForAllTy (Bndr tv vis) ty)
| otherwise
- = mk_forall_co tv vis vis MRefl orig_co
+ = mkForAllCoNonRefl tv vis vis MRefl orig_co
where
vis = coreTyLamForAllTyFlag
@@ -892,15 +892,15 @@ mkForAllCo v visL visR kind_co co
| Just refl_co <- isReflForAllCo v visL visR kind_co co
= refl_co
| otherwise
- = mk_forall_co v visL visR kind_co co
+ = mkForAllCoNonRefl v visL visR kind_co co
--- | `mk_forall_co` just builds a ForAllCo.
+-- | `mkForAllCoNonRefl` just builds a ForAllCo.
-- With debug on, it checks invariants (e.g. he kind of the tycovar should
-- be the left-hand kind of the kind coercion).
-- Callers should have done any isReflCo short-cutting.
-mk_forall_co :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag
- -> KindMCoercion -> Coercion -> Coercion
-mk_forall_co tcv visL visR kind_co co
+mkForAllCoNonRefl :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag
+ -> KindMCoercion -> Coercion -> Coercion
+mkForAllCoNonRefl tcv visL visR kind_co co
= assertGoodForAllCo tcv visL visR kind_co co $
assertPpr (not (isReflCo co && isReflMCo kind_co && visL `eqForAllVis` visR)) (ppr co) $
ForAllCo { fco_tcv = tcv, fco_visL = visL, fco_visR = visR
@@ -1289,6 +1289,10 @@ coToMCo :: Coercion -> MCoercion
coToMCo co | isReflCo co = MRefl
| otherwise = MCo co
+mCoToCo :: Role -> Type -> MCoercion -> Coercion
+mCoToCo role ty MRefl = mkReflCo role ty
+mCoToCo _ _ (MCo co) = co
+
kindCoToMKindCo :: KindCoercion -> KindMCoercion
-- Convert a KindCoercion to a KindMCoercion,
-- coToMCo doesn't eliminate GRefl, but kindCoToMCo can
=====================================
compiler/GHC/Core/Type.hs
=====================================
@@ -160,7 +160,7 @@ module GHC.Core.Type (
-- * Type free variables
tyCoVarsOfType, tyCoVarsOfTypes, tyCoVarsOfTypeDSet,
- coVarsOfType, coVarsOfTypes,
+ tyCoVarsOfMCo, coVarsOfType, coVarsOfTypes,
anyFreeVarsOfType, anyFreeVarsOfTypes,
noFreeVarsOfType,
=====================================
compiler/GHC/Core/Utils.hs
=====================================
@@ -2392,7 +2392,7 @@ canCollectArgsThroughTick id t
= tickishFloatable t || cantEtaReduceFun id
-- | Can we eta-reduce the given function?
--- See Note [Eta reduction soundness], criteria (B), (J), and (W).
+-- See Note [Eta reduction soundness], criteria (EtaB), (EtaJ), and (EtaW).
cantEtaReduceFun :: Id -> Bool
cantEtaReduceFun fun
= hasNoBinding fun -- (B)
=====================================
testsuite/tests/dmdanal/sigs/T21888a.stderr
=====================================
@@ -7,7 +7,7 @@ T21888a.wombat: <S!P(S)>b
==================== Cpr signatures ====================
-T21888a.f: 2
+T21888a.f:
T21888a.g: 1
T21888a.wombat: b
=====================================
testsuite/tests/printer/T18052a.stderr
=====================================
@@ -10,11 +10,11 @@ Dependent packages: [(normal, base-4.23.0.0)]
==================== Tidy Core ====================
Result size of Tidy Core
- = {terms: 24, types: 52, coercions: 0, joins: 0/0}
+ = {terms: 18, types: 46, coercions: 0, joins: 0/0}
--- RHS size: {terms: 7, types: 6, coercions: 0, joins: 0/0}
+-- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
T18052a.$b:||: :: forall {a} {b}. a -> b -> (a, b)
-T18052a.$b:||: = \ (@a) (@b) (x :: a) (y :: b) -> (x, y)
+T18052a.$b:||: = GHC.Internal.Tuple.(,)
-- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
(+++) :: forall {a}. [a] -> [a] -> [a]
=====================================
testsuite/tests/simplCore/should_compile/T27212.hs
=====================================
@@ -0,0 +1,17 @@
+module T27212 where
+
+import Unsafe.Coerce
+
+class Given a where given :: a
+newtype Gift a r = Gift (Given a => r)
+
+useIt :: Given Int => Int
+useIt = given + 1
+{-# NOINLINE useIt #-}
+
+foo :: [Int] -> [Int]
+foo xs = case unsafeEqualityProof @(Gift Int Int) @(Int -> Int) of
+ UnsafeRefl -> map (\y -> (Gift useIt :: Gift Int Int) y) xs
+ -- That (\y. glah y) can eta-reduce to `glah`
+ -- but doing doing so makes a FunCo coercion that crosses from
+ -- Type to constraint. Tricky.
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -631,3 +631,4 @@ test('T27936', normal, compile, [''])
test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
+test('T27212', normal, compile, ['-O'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/d2b9078f4e16715931df93d9dcb62c4…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/d2b9078f4e16715931df93d9dcb62c4…
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
1
0
[Git][ghc/ghc][wip/marge_bot_batch_merge_job] 12 commits: NCG: List each destination of a jump table once
by Marge Bot (@marge-bot) 20 Nov '26
by Marge Bot (@marge-bot) 20 Nov '26
20 Nov '26
Marge Bot pushed to branch wip/marge_bot_batch_merge_job at Glasgow Haskell Compiler / GHC
Commits:
64848f4d by Sylvain Henry at 2026-11-20T15:14:57-05:00
NCG: List each destination of a jump table once
jumpDestsOfInstr listed a block once per jump table entry that named
it. The linear register allocator makes a fixup block per listed
destination, so such a block got several fixup blocks. The patch of
the jump sends every entry to the first one. The other fixup blocks
were dead code, and the CFG had an edge to each of them.
jumpDestsOfInstr now lists each destination once, in every backend.
joinToTargets asserts it in debug builds.
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
b2219a50 by Andreas Klebinger at 2026-11-20T15:14:57-05:00
x86 ncg: Track the current block in NatM to keep the CFG in sync
The x86 NCG uses a CFG for code layout. When instruction selection
makes new blocks (word2Float#, cmpxchg loops, 64-bit shifts on i386),
it must add them to the CFG. Some sites did not. The CFG went out of
sync, the layout was bad, and the register allocator panicked when it
added fixup blocks (#27694, #27915).
NatM now keeps the current block in its state. Combinators update the
CFG and the current block together. See Note [Updating the CFG during
CodeGen] in GHC.CmmToAsm.Monad.
Other changes:
* -dasm-lint checks that the jumps in the code and the edges in the
CFG agree in both directions. This found a second desync: the CFG
did not follow the jumps that allocMoreStack retargets. The new
addPreentryBlock fixes it.
* The code must be emitted in generation order, because the CFG
records new blocks in that order. A store now generates the code of
its value before the code of its address, in the order it emits
them. Atomic operations take their address from the new
getNonClobberedAmode, so the code of their other operands cannot
clobber it.
Fixes #27694, #27915
Co-authored-by: Sylvain Henry <sylvain(a)haskus.fr>
Co-Authored-By: Claude Fable 5.1 <noreply(a)anthropic.com>
- - - - -
13a2136e by Sylvain Henry at 2026-11-20T15:14:57-05:00
x86 ncg: Maintain the CFG on i386
The i386 NCG now keeps its CFG in sync with the code (see the previous
commit), so backendMaintainsCfg is now True for i386. i386 gets the
CFG based code layout, dead code elimination and the -dasm-lint check,
like x86-64.
The compiler allocates more on i386: the CFG now goes through the
register allocator, branch shortcutting and optimizeCFG, which i386
skipped before. x86-64 already does this work.
Metric Increase:
CoOpt_Read
ManyAlternatives
T10421
T12425
T12707
T13056
T13253
T13253-spj
T13960
T15164
T15304
T15630
T15630a
T15703
T16577
T17516
T17836
T18140
T18282
T18304
T18698a
T18698b
T18730
T18923
T19695
T20049
T21839c
T24471
T26425
T26989
T5642
T6048
T783
T9233
T9630
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
52473d64 by Simon Peyton Jones at 2026-11-20T15:14:58-05:00
Redesign the noinline magic
The principal goal of this MR is to avoid `noinline` getting in the way
of strictness analysis and specialisation. It involves a bit of redesign.
Main idea:
* When simplifying `noinline (f e1 e2)`, switch off inlining when
simplifying `f`, but not when simplifying `e1` and `e2`.
* Mechanism: see `simplOutId`, the `noinlineIdKey` case
* If: we see `noinline (f e1) e2`, the simplifier moves the `e2` inside;
see the `splitContArgs` call. This is important so you can write
`noinline f e1 e2` and have it mean the same as `noinline (f e1 e2)`.
* Now `f` sees all its arguments, hence:
* Fixes #27724 (noinline inhibits specialisation)
* Fixes #23911 (noinline worsens demand signatures)
* Also fixes #27803 where we were not respecting `noinline` if the RHS
was trivial
See Note [noinlineId magic] for lots of specifics. It's surprisingly tricky!
For some reason a couple of perf tests allocate 1.2% less at compile time,n
namely T29872 and T8095. Geom mean decease of 0.1%
Metric Decrease:
T9872d
- - - - -
431241d7 by fendor at 2026-11-20T15:15:00-05:00
`ghc -M`: Add support for link nodes to json output
`LinkNode`s are part of the module graph and indicate that a certain
linking artefact is to be produced from other module graph nodes.
We expose `LinkNode`s in the output of `ghc -M -dep-json`, allowing
consumers to see when a linking artefact is to be produced.
Only the JSON output format of `ghc -M` supports `LinkNode` as it is
unclear how the Makefile output should be retrofitted to express the
dependencies, and whether it would require a feature guard.
Closes #28007
- - - - -
77efb8d4 by Ryan Scott at 2026-11-20T15:15:01-05:00
GHC.HsToCore.Quote: Quote \cases with the correct type
Previously, `\cases` expressions inside of Template Haskell quotes would
incorrectly use the `Match` type instead of `Clause` for the element type. We
now use `nonEmptyCoreList` when quoting `\cases`, which infers the correct type
automatically. This works because `\cases` has an invariant that the list of
clauses is always non-empty.
Fixes #27826.
- - - - -
0211a206 by Simon Peyton Jones at 2026-11-20T15:15:03-05:00
Better desugaring for bang patterns
Ticket #27862 showed that we were desugaring bang patterns in a
silly way, which led to bad code. This small fix makes it much
better.
I ended up refactoring `decomposeFirstPat` to be of type
(LPat -> LPat) instead of (Pat -> Pat)
which made it much easier to keep the locations correct.
On the way I also fixed #28137, a missing warning.
See Note [Tidying patterns] which has new (TP1) and (TP2)
and Note [Grouping equations] especially (GE1)
- - - - -
b4bdac1f by Hannes Siebenhandl at 2026-11-20T15:15:05-05:00
Use Set operations over Foldable operations
Use `O(log n)` operations over `O(n)` for all call-sites of `hsc_all_home_unit_ids`.
- - - - -
38ef56f6 by Alan Zimmerman at 2026-11-20T15:15:06-05:00
EPA: Use AnnList in DecBrl
Via updating the TTG extension point payload
- - - - -
0fca6f0d by David Eichmann at 2026-11-20T15:15:08-05:00
Fix race condition in IOManager test
- - - - -
5a5a886a by Simon Peyton Jones at 2026-11-20T15:15:09-05:00
Fix a zonking bug
As #28135 showed, we were failing to zonk some type-variable
binders before doing scoped-sort dependency analysis, resulting
in chaos.
The fix is easy.
- - - - -
47a96bb7 by mangoiv at 2026-11-20T15:15:10-05:00
ci: nightly push can run on any arch
- - - - -
131 changed files:
- .gitlab-ci.yml
- + changelog.d/27694
- + changelog.d/T27137
- + changelog.d/T27724
- + changelog.d/T27862
- + changelog.d/T28135
- + changelog.d/make-depends-link-nodes
- compiler/GHC/Builtin/WiredIn/Ids.hs
- compiler/GHC/Builtin/WiredIn/Prim.hs
- compiler/GHC/Builtin/WiredIn/Types/Box.hs
- compiler/GHC/CmmToAsm.hs
- compiler/GHC/CmmToAsm/AArch64/CodeGen.hs
- compiler/GHC/CmmToAsm/AArch64/Instr.hs
- compiler/GHC/CmmToAsm/BlockLayout.hs
- compiler/GHC/CmmToAsm/CFG.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/LA64/Instr.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/PPC/Instr.hs
- compiler/GHC/CmmToAsm/RV64/Instr.hs
- compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/Core/Opt/SetLevels.hs
- compiler/GHC/Core/Opt/Simplify/Env.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/TyCo/Make.hs
- compiler/GHC/Core/TyCo/Rep.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/CoreToIface.hs
- compiler/GHC/CoreToStg/Prep.hs
- compiler/GHC/Driver/Config/Core/Opt/Simplify.hs
- compiler/GHC/Driver/Downsweep.hs
- compiler/GHC/Driver/Make.hs
- compiler/GHC/Driver/MakeFile.hs
- compiler/GHC/Hs/Expr.hs
- compiler/GHC/HsToCore.hs
- compiler/GHC/HsToCore/Expr.hs
- compiler/GHC/HsToCore/Match.hs
- compiler/GHC/HsToCore/Match/Literal.hs
- compiler/GHC/HsToCore/Monad.hs
- compiler/GHC/HsToCore/Pmc.hs
- compiler/GHC/HsToCore/Pmc/Solver/Types.hs
- compiler/GHC/HsToCore/Quote.hs
- compiler/GHC/Iface/Load.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/Parser.y
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Instance/Class.hs
- compiler/GHC/Tc/Solver.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/Tc/Types/Origin.hs
- + distrib/configure.ac
- docs/users_guide/make-depends-json-schema-1_0.json
- libraries/ghc-internal/src/GHC/Internal/Exts.hs
- libraries/ghc-internal/src/GHC/Internal/Magic.hs
- testsuite/tests/ado/T22483.stderr
- + testsuite/tests/codeGen/should_compile/T27694.hs
- + testsuite/tests/codeGen/should_compile/T27694c.hs
- + testsuite/tests/codeGen/should_compile/T27694d.hs
- testsuite/tests/codeGen/should_compile/all.T
- + testsuite/tests/codeGen/should_run/T27694b.hs
- + testsuite/tests/codeGen/should_run/T27694b.stdout
- + testsuite/tests/codeGen/should_run/T27915.hs
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-32
- + testsuite/tests/codeGen/should_run/T27915.stdout-ws-64
- testsuite/tests/codeGen/should_run/all.T
- testsuite/tests/corelint/LintEtaExpand.hs
- + testsuite/tests/deSugar/should_compile/T27862.hs
- + testsuite/tests/deSugar/should_compile/T27862.stderr
- + testsuite/tests/deSugar/should_compile/T27862a.hs
- + testsuite/tests/deSugar/should_compile/T27862a.stderr
- + testsuite/tests/deSugar/should_compile/T27862b.hs
- + testsuite/tests/deSugar/should_compile/T27862b.stderr
- + testsuite/tests/deSugar/should_compile/T27862c.hs
- + testsuite/tests/deSugar/should_compile/T27862c.stderr
- + testsuite/tests/deSugar/should_compile/T27862d.hs
- + testsuite/tests/deSugar/should_compile/T27862d.stderr
- + testsuite/tests/deSugar/should_compile/T28137.hs
- + testsuite/tests/deSugar/should_compile/T28137.stderr
- testsuite/tests/deSugar/should_compile/all.T
- testsuite/tests/deSugar/should_run/dsrun008.stderr
- + testsuite/tests/dmdanal/should_compile/T23911.hs
- + testsuite/tests/dmdanal/should_compile/T23911.stderr
- testsuite/tests/dmdanal/should_compile/all.T
- testsuite/tests/driver/mkdepend/all.T
- + testsuite/tests/driver/mkdepend/mhu04/app/Main.hs
- + testsuite/tests/driver/mkdepend/mhu04/app/Utils.hs
- + testsuite/tests/driver/mkdepend/mhu04/lib/Lib.hs
- + testsuite/tests/driver/mkdepend/mhu04/lib/Lib/Internal.hs
- + testsuite/tests/driver/mkdepend/mhu04/unitApp
- + testsuite/tests/driver/mkdepend/mhu04/unitLib
- + testsuite/tests/driver/mkdepend/mhu05/app/Main.hs
- + testsuite/tests/driver/mkdepend/mhu05/lib/Lib.hs
- + testsuite/tests/driver/mkdepend/mhu05/lib/Lib/Internal.hs
- + testsuite/tests/driver/mkdepend/mhu05/test/Spec.hs
- + testsuite/tests/driver/mkdepend/mhu05/unitApp
- + testsuite/tests/driver/mkdepend/mhu05/unitLib
- + testsuite/tests/driver/mkdepend/mhu05/unitTest
- + testsuite/tests/driver/mkdepend/mkdepend02.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend02/Main.hs
- + testsuite/tests/driver/mkdepend/mkdepend_bkp_01/bkp01.bkp
- + testsuite/tests/driver/mkdepend/mkdepend_mhu04.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu04.dep-makefile
- + testsuite/tests/driver/mkdepend/mkdepend_mhu05.dep-json
- + testsuite/tests/driver/mkdepend/mkdepend_mhu05.dep-makefile
- testsuite/tests/interface-stability/base-exports.stdout
- testsuite/tests/interface-stability/base-exports.stdout-javascript-unknown-ghcjs
- testsuite/tests/interface-stability/base-exports.stdout-mingw32
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout
- testsuite/tests/interface-stability/ghc-experimental-exports.stdout-mingw32
- testsuite/tests/interface-stability/ghc-prim-exports.stdout
- testsuite/tests/interface-stability/ghc-prim-exports.stdout-mingw32
- testsuite/tests/pmcheck/should_compile/T24234.stderr
- testsuite/tests/rts/IOManager.hsc
- testsuite/tests/rts/all.T
- testsuite/tests/simplCore/should_compile/T18995.stderr
- + testsuite/tests/simplCore/should_compile/T27724a.hs
- + testsuite/tests/simplCore/should_compile/T27724a.stderr
- + testsuite/tests/simplCore/should_compile/T27803.hs
- + testsuite/tests/simplCore/should_compile/T27803.stderr
- testsuite/tests/simplCore/should_compile/all.T
- + testsuite/tests/th/T27826.hs
- testsuite/tests/th/all.T
- + testsuite/tests/typecheck/should_compile/T28135.hs
- testsuite/tests/typecheck/should_compile/all.T
- testsuite/tests/typecheck/should_fail/T17940.stderr
- testsuite/tests/typecheck/should_fail/tcfail203a.stderr
- utils/check-exact/ExactPrint.hs
- utils/genprimopcode/Main.hs
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/dc81dc01fdb57aae680f8e988144ed…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/dc81dc01fdb57aae680f8e988144ed…
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
1
0
[Git][ghc/ghc] Pushed new branch wip/romes/async-eval-resume
by Rodrigo Mesquita (@alt-romes) 20 Nov '26
by Rodrigo Mesquita (@alt-romes) 20 Nov '26
20 Nov '26
Rodrigo Mesquita pushed new branch wip/romes/async-eval-resume at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/romes/async-eval-resume
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
1
0
[Git][ghc/ghc][wip/T27212] 2 commits: Update comments and user manual
by Simon Peyton Jones (@simonpj) 20 Nov '26
by Simon Peyton Jones (@simonpj) 20 Nov '26
20 Nov '26
Simon Peyton Jones pushed to branch wip/T27212 at Glasgow Haskell Compiler / GHC
Commits:
d9a3ba31 by Simon Peyton Jones at 2026-11-20T17:45:03+00:00
Update comments and user manual
This commit addresses the comment-related suggestions in #27973
- - - - -
6cc40da9 by Simon Peyton Jones at 2026-11-20T17:45:04+00:00
Update eta-reduction documentation; ignore multiplicities
Triggered by #27212, this patch does several related things:
* Update documentation about eta expansion and reduction, especially
* Make it clear in `findRhsArity` that we eta expand only to increase
`exprArity`, not `manifestArity`. (The latter was a misconception of
#27212.)
* Relabel the criteria in Note [Eta reduction soundness] as (EtaA),
(EtaS), (EtaR), (EtaE), (EtaT), (EtaJ), (EtaB), (EtaW), fix references
to them (including stale references to a non-existent
Note [Eta reduction makes sense]), and add historical notes (EtaMult)
and (EtaBot).
* Refactor GHC.Core.Opt.Arity.tryEtaReduce, which was hard
to understand. New code is simpler and more efficient.
(Side note: this introduces a tiresome function `mkEtaReduceForAllMCo`
but it will go away again once !17006 lands.)
* As part of this refactor I dropped the tricky checks on multiplicity,
which sometimes disabled eta-reduction. Note [Linting linearity]
in GHC.Core.Lint already said that we don't try to preserve linearity
when doing eta-reduction, so the change here just executes that claim.
- - - - -
21 changed files:
- compiler/GHC/Core/Coercion.hs
- compiler/GHC/Core/Opt/Arity.hs
- compiler/GHC/Core/Opt/OccurAnal.hs
- compiler/GHC/Core/Opt/Pipeline.hs
- compiler/GHC/Core/Opt/Simplify/Env.hs
- compiler/GHC/Core/Opt/Simplify/Inline.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/Opt/SpecConstr.hs
- compiler/GHC/Core/Opt/Specialise.hs
- compiler/GHC/Core/TyCo/Make.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Utils.hs
- compiler/GHC/Driver/Config/Core/Opt/Simplify.hs
- compiler/Language/Haskell/Syntax/Binds/InlinePragma.hs
- docs/users_guide/debug-info.rst
- docs/users_guide/using-optimisation.rst
- testsuite/tests/dmdanal/sigs/T21888a.stderr
- testsuite/tests/printer/T18052a.stderr
- + testsuite/tests/simplCore/should_compile/T27212.hs
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core/Coercion.hs
=====================================
@@ -74,7 +74,7 @@ module GHC.Core.Coercion (
isReflCoVar_maybe, assertGoodForAllCo,
- coToMCo, kindCoToMKindCo,
+ coToMCo, kindCoToMKindCo, mCoToCo,
mkTransMCo, mkTransMCoL, mkTransMCoR, mkCastTyMCo, mkSymMCo,
mkFunResMCo, mkPiMCos,
isReflMCo, checkReflexiveMCo,
=====================================
compiler/GHC/Core/Opt/Arity.hs
=====================================
@@ -886,8 +886,14 @@ findRhsArity :: ArityOpts -> RecFlag -> Id -> CoreExpr
-- This implements the fixpoint loop for arity analysis
-- See Note [Arity analysis]
--
--- The Bool is True if the returned arity is greater than (exprArity rhs)
--- so the caller should do eta-expansion
+-- The Bool is True if
+-- the returned arity is greater than (exprArity rhs)
+-- so the caller should do eta-expansion
+-- NB: `exprArity`, not `manifestArity`:
+-- a PAP such as (\x. f x), where f has arity 3, has exprArity 3,
+-- so we do not eta-expand it to (\x y z. f x y z)
+-- See Note [Do not eta-expand PAPs] in GHC.Core.Opt.Simplify.Utils
+--
-- That Bool is never True for join points, which are never eta-expanded
--
-- Returns an SafeArityType that is guaranteed trimmed to typeArity of 'bndr'
@@ -903,10 +909,11 @@ findRhsArity opts is_rec bndr rhs
| otherwise
= (arity_increased, non_join_arity_type)
- -- arity_increased: eta-expand if we'll get more lambdas
- -- to the top of the RHS
+ -- arity_increased: eta-expand if the analysis finds a greater arity
+ -- than exprArity, which already takes account of PAPs
where
- old_arity = exprArity rhs
+ old_arity = exprArity rhs -- See Note [Do not eta-expand PAPs]
+ -- in GHC.Core.Opt.Simplify.Utils
init_env :: ArityEnv
init_env = findRhsArityEnv opts (isJoinId bndr)
@@ -2388,6 +2395,7 @@ mkEtaForAllMCo (Bndr tcv vis) ty mco
-- and is SymCo'd in `etaInfoAbs`. Hence the orientation of the visibility
-- flags. A bit of a brain-strain (#27557).
+
{-
************************************************************************
* *
@@ -2452,16 +2460,20 @@ perform eta reduction on an expression with n leading lambdas `\xs. e xs`
(checked in 'is_eta_reduction_sound' in 'tryEtaReduce', which focuses on the
case where `e` is trivial):
-(A) It is sound to eta-reduce n arguments as long as n does not exceed the
- `exprArity` of `e`. (Needs Arity analysis.)
- This criterion exploits information about how `e` is *defined*.
+(EtaA) It is sound to eta-reduce n arguments as long as n does not exceed the
+ `exprArity` of `e`. (Needs Arity analysis.) This criterion exploits information
+ about how `e` is *defined*. For example:
+ f = \xy. g x y ===> f = g
+ This eta-reduction is good only if `g` has arity at least 2, otherwise
+ f's arity will decrease from 2 to 1.
+ c.f. Note [Arity robustness] in GHC.Core.Opt.Simplify.Env.
- Example: If `e = \x. bot` then we know it won't diverge until it is called
- with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`.
+ Another example: If `e = \x. bot` then we know it won't diverge until it
+ is called with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`.
By contrast, it would be *unsound* to eta-reduce 2 args, `\x y. e x y` to `e`:
`e 42` diverges when `(\x y. e x y) 42` does not.
-(S) It is sound to eta-reduce n arguments in an evaluation context in which all
+(EtaS) It is sound to eta-reduce n arguments in an evaluation context in which all
calls happen with at least n arguments. (Needs Strictness analysis.)
NB: This treats evaluations like a call with 0 args.
NB: This criterion exploits information about how `e` is *used*.
@@ -2483,35 +2495,31 @@ case where `e` is trivial):
But it is unsound to eta-reduce the arg in `g2 (\x y. e x y)` to `g2 e`
when `e = \x. if x then bot else id`, because the latter will diverge when
the former would not. Fortunately, the strictness analyser will report
- "Not always called with two arguments" for `g2` and we won't eta-expand.
+ "Not always called with two arguments" for `g2` and we won't eta-reduce.
See Note [Eta reduction based on evaluation context] for the implementation
details. This criterion is tested extensively in T21261.
-(R) Note [Eta reduction in recursive RHSs] tells us that we should not
+(EtaR) Note [Eta reduction in recursive RHSs] tells us that we should not
eta-reduce `f` in its own RHS and describes our fix.
There we have `f = \x. f x` and we should not eta-reduce to `f=f`. Which
might change a terminating program (think @f `seq` e@) to a non-terminating
one.
-(E) (See fun_arity in tryEtaReduce.) As a perhaps special case on the
- boundary of (A) and (S), when we know that a fun binder `f` is in
- WHNF, we simply assume it has arity 1 and apply (A). Example:
+(EtaE) (See fun_arity in tryEtaReduce.) As a perhaps special case on the
+ boundary of (EtaA) and (EtaS), when we know that a fun binder `f` is in
+ WHNF, we simply assume it has arity 1 and apply (EtaA). Example:
g f = f `seq` \x. f x
Here it's sound eta-reduce `\x. f x` to `f`, because `f` can't be bottom
after the `seq`. This turned up in #7542.
- T. If the binders are all type arguments, it's always safe to eta-reduce,
- regardless of the arity of f.
- /\a b. f @a @b --> f
-
-2. Type and dictionary abstraction. Regardless of whether 'f' is a value, it
+(EtaT) Type and dictionary abstraction. Regardless of whether 'f' is a value, it
is always sound to reduce /type lambdas/, thus:
- (/\a -> f a) --> f
+ (/\a -> f @a) --> f
Moreover, we always want to, because it makes RULEs apply more often:
- This RULE: `forall g. foldr (build (/\a -> g a))`
+ This RULE: `forall g. foldr (build (/\a -> g @a))`
should match `foldr (build (/\b -> ...something complex...))`
- and the simplest way to do so is eta-reduce `/\a -> g a` in the RULE to `g`.
+ and the simplest way to do so is eta-reduce `/\a -> g @a` in the RULE to `g`.
More debatably, we extend this to dictionary arguments too, because the type
checker can insert these eta-expanded versions, with both type and dictionary
@@ -2523,18 +2531,25 @@ case where `e` is trivial):
And here are a few more technical criteria for when it is *not* sound to
eta-reduce that are specific to Core and GHC:
-(J) We may not undersaturate join points.
+(EtaJ) We may not undersaturate join points.
See Note [Invariants on join points] in GHC.Core, and #20599.
-(B) We may not undersaturate functions with no binding.
+(EtaB) We may not undersaturate functions with no binding.
See Note [Eta expanding primops].
-(W) We may not undersaturate StrictWorkerIds.
+(EtaW) We may not undersaturate StrictWorkerIds.
See Note [CBV Function Ids: overview] in GHC.Types.Id.Info.
-Here is a list of historic accidents surrounding unsound eta-reduction:
-* Consider
+Here is a list of historic notes surrounding unsound eta-reduction:
+
+(EtaMult) We used to disable eta-reduction if performing it would change multiplicity.
+ For example:
+ (\x. K x) :: Int -> T but K :: Int %1 -> T
+ But that (a) inhibits beneficial eta-reduction (b) costs extra work to check, and
+ now we don't even try. See Note [Linting linearity] in GHC.Core.Lint, esp EXAMPLE 4
+
+(EtaBot) Consider
f = \x.f x
h y = case (case y of { True -> f `seq` True; False -> False }) of
True -> ...; False -> ...
@@ -2548,16 +2563,6 @@ Here is a list of historic accidents surrounding unsound eta-reduction:
Result: seg-fault because the boolean case actually gets a function value.
See #1947.
-* Never *reduce* arity. For example
- f = \xy. g x y
- Then if h has arity 1 we don't want to eta-reduce because then
- f's arity would decrease, and that is bad
- [SG in 2022: I don't understand this point. There is no `h`, perhaps that
- should have been `g`. Even then, this proposed eta-reduction is invalid by
- criterion (A), which might actually be the point this anecdote is trying to
- make. Perhaps the "no arity decrease" idea is also related to
- Note [Arity robustness]?]
-
Note [Do not eta reduce PAPs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I considered eta-reducing if the result is a PAP:
@@ -2598,11 +2603,12 @@ This should be eta-reduced to
So we need to accumulate a coercion, pushing it inward (past
variable arguments only) thus:
- f (x |> co_arg) |> co --> (f |> (sym co_arg -> co)) x
- f (x:t) |> co --> (f |> (t -> co)) x
- f @ a |> co --> (f |> (forall a.co)) @ a
- f @ (g:t1~t2) |> co --> (f |> (t1~t2 => co)) @ (g:t1~t2)
-These are the equations for ok_arg.
+(ECA1) \x. f (x |> co_arg) |> co --> (f |> (sym co_arg -> co))
+(ECA2) \x. f (x:t) |> co --> (f |> (t -> co))
+(ECA3) \x. f (g:t1~#t2) |> co --> (f |> (t1~#t2 => co))
+(ECA4) \x. f @ a |> co --> (f |> (forall a.co))
+
+These are implemented by the `go` equations in `tryEtaReduce`
Note [Eta reduction with casted function]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -2620,7 +2626,7 @@ eta-expansion may be turned off (by sm_eta_expand).
Note [Eta reduction based on evaluation context]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Note [Eta reduction soundness], criterion (S) allows us to eta-reduce
+Note [Eta reduction soundness], criterion (EtaS) allows us to eta-reduce
`g (\x y. e x y)` to `g e` when we know that `g` always calls its parameter with
at least 2 arguments. So how do we read that off `g`'s demand signature?
@@ -2713,13 +2719,13 @@ tryEtaReduce :: UnVarSet -> [Var] -> CoreExpr -> SubDemand -> Maybe CoreExpr
-- and Note [Eta reduction makes sense] when that is the case.
-- and Note [Eta reduction based on evaluation context] for the `eval_sd` arg
tryEtaReduce rec_ids bndrs body eval_sd
- = go (reverse bndrs) body (mkRepReflCo (exprType body))
+ = go (reverse bndrs) body MRefl
where
- incoming_arity = count isId bndrs -- See Note [Eta reduction makes sense], point (2)
+ incoming_arity = count isId bndrs -- See (EtaA) in Note [Eta reduction soundness]
go :: [Var] -- Binders, innermost first, types [a3,a2,a1]
-> CoreExpr -- Of type tr
- -> Coercion -- Of type tr ~ ts
+ -> MCoercion -- Of type tr ~ ts
-> Maybe CoreExpr -- Of type a1 -> a2 -> a3 -> ts
-- See Note [Eta reduction with casted arguments]
-- for why we have an accumulating coercion
@@ -2729,19 +2735,37 @@ tryEtaReduce rec_ids bndrs body eval_sd
-- See Note [Eta reduction with casted function]
go bs (Cast e co1) co2
- = go bs e (co1 `mkTransCo` co2)
+ = go bs e (co1 `mkTransMCoR` co2)
go bs (Tick t e) co
| tickishFloatable t
= fmap (Tick t) $ go bs e co
-- Float app ticks: \x -> Tick t (e x) ==> Tick t e
- go (b : bs) (App fun arg) co
- | Just (co', ticks) <- ok_arg b arg co (exprType fun)
- = fmap (flip (foldr mkTick) ticks) $ go bs fun co'
- -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e
+ -- Implements (ECA4)
+ go all_bs@(b : bs) all_e@(App fun (Type arg_ty)) mco
+ | Just tv <- getTyVar_maybe arg_ty
+ , b == tv
+ , Just (bndr, body_ty) <- splitForAllForAllTyBinder_maybe (exprType fun)
+ = go bs fun (mkEtaReduceForAllMCo bndr body_ty tv mco)
- go remaining_bndrs fun co
+ | otherwise
+ = go_finish all_bs all_e mco
+ -- Want to go to the finish case; see the call
+ -- to (all isTyVar remaining_bndrs) there
+
+ -- Implements (ECA1), (ECA2), (ECA3)
+ go (b : bs) (App fun val_arg) mco
+ | Just (v, arg_mco, arg_ticks) <- getTrivialHead_maybe val_arg
+ , b == v
+ , Just co' <- mkEtaReduceFunCo (exprType fun) arg_mco mco
+ = fmap (flip (foldr mkTick) arg_ticks) $
+ go bs fun co'
+ -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e
+
+ go bs fun co = go_finish bs fun co
+
+ go_finish remaining_bndrs fun co
| all isTyVar remaining_bndrs
-- If all the remaining_bnrs are tyvars, then the etad_exp
-- will be trivial, which is what we want.
@@ -2752,7 +2776,7 @@ tryEtaReduce rec_ids bndrs body eval_sd
, remaining_bndrs `ltLength` bndrs
-- Only reply Just if /something/ has happened
, ok_fun fun
- , let used_vars = exprFreeVars fun `unionVarSet` tyCoVarsOfCo co
+ , let used_vars = exprFreeVars fun `unionVarSet` tyCoVarsOfMCo co
reduced_bndrs = mkVarSet (dropList remaining_bndrs bndrs)
-- reduced_bndrs are the ones we are eta-reducing away
, used_vars `disjointVarSet` reduced_bndrs
@@ -2761,10 +2785,10 @@ tryEtaReduce rec_ids bndrs body eval_sd
-- See Note [Eta reduction makes sense], intro and point (1)
-- NB: don't compute used_vars from exprFreeVars (mkCast fun co)
-- because the latter may be ill formed if the guard fails (#21801)
- = Just (mkLams (reverse remaining_bndrs) (mkCast fun co))
+ = Just (mkLams (reverse remaining_bndrs) (mkCastMCo fun co))
- go _remaining_bndrs _fun _ = -- pprTrace "tER fail" (ppr _fun $$ ppr _remaining_bndrs) $
- Nothing
+ | otherwise
+ = Nothing
---------------
-- See Note [Eta reduction makes sense], point (1)
@@ -2777,18 +2801,18 @@ tryEtaReduce rec_ids bndrs body eval_sd
---------------
-- See Note [Eta reduction soundness], this is THE place to check soundness!
is_eta_reduction_sound fun
- | fun `elemUnVarSet` rec_ids -- Criterion (R)
+ | fun `elemUnVarSet` rec_ids -- Criterion (EtaR)
= False -- Don't eta-reduce in fun in its own recursive RHSs
- | cantEtaReduceFun fun -- Criteria (J), (W), (B)
+ | cantEtaReduceFun fun -- Criteria (EtaJ), (EtaW), (EtaB)
= False -- Function can't be eta reduced to arity 0
-- without violating invariants of Core and GHC
| otherwise
= -- Check that eta-reduction won't make the program stricter...
- fun_arity fun >= incoming_arity -- Criterion (A) and (E)
- || all_calls_with_arity incoming_arity -- Criterion (S)
- || all ok_lam bndrs -- Criterion (T)
+ fun_arity fun >= incoming_arity -- Criterion (EtaA) and (EtaE)
+ || all_calls_with_arity incoming_arity -- Criterion (EtaS)
+ || all ok_lam bndrs -- Criterion (EtaT)
all_calls_with_arity n = isStrict (fst $ peelManyCalls n eval_sd)
-- See Note [Eta reduction based on evaluation context]
@@ -2797,57 +2821,76 @@ tryEtaReduce rec_ids bndrs body eval_sd
fun_arity fun
| arity > 0 = arity
| isEvaldUnfolding (idUnfolding fun) = 1
- -- See Note [Eta reduction soundness], criterion (E)
+ -- See Note [Eta reduction soundness], criterion (EtaE)
| otherwise = 0
where
arity = idArity fun
---------------
ok_lam v = isTyVar v || isEvId v
- -- See Note [Eta reduction makes sense], point (2)
-
- ---------------
- ok_arg :: Var -- Of type bndr_t
- -> CoreExpr -- Of type arg_t
- -> Coercion -- Of kind (t1~t2)
- -> Type -- Type (arg_t -> t1) of the function
- -- to which the argument is supplied
- -> Maybe (Coercion -- Of type (arg_t -> t1 ~ bndr_t -> t2)
- -- (and similarly for tyvars, coercion args)
- , [CoreTickish])
- -- See Note [Eta reduction with casted arguments]
- ok_arg bndr (Type arg_ty) co fun_ty
- | Just tv <- getTyVar_maybe arg_ty
- , bndr == tv = case splitForAllForAllTyBinder_maybe fun_ty of
- Just (Bndr _ vis, _) -> Just (fco, [])
- where !fco = mkForAllCo tv vis coreTyLamForAllTyFlag MRefl co
- -- The lambda we are eta-reducing always has visibility
- -- 'coreTyLamForAllTyFlag' which may or may not match
- -- the visibility on the inner function (#24014)
- Nothing -> pprPanic "tryEtaReduce: type arg to non-forall type"
- (text "fun:" <+> ppr bndr
- $$ text "arg:" <+> ppr arg_ty
- $$ text "fun_ty:" <+> ppr fun_ty)
- ok_arg bndr (Var v) co fun_ty
- | bndr == v
- , let mult = idMult bndr
- , Just (_af, fun_mult, _, _) <- splitFunTy_maybe fun_ty
- , mult `eqType` fun_mult -- There is no change in multiplicity, otherwise we must abort
- = Just (mkFunResCo Representational bndr co, [])
- ok_arg bndr (Cast e co_arg) co fun_ty
- | (ticks, Var v) <- stripTicksTop tickishFloatable e
- , Just (_, fun_mult, _, _) <- splitFunTy_maybe fun_ty
- , bndr == v
- , fun_mult `eqType` idMult bndr
- = Just (mkFunCoNoFTF Representational (multToCo fun_mult) (mkSymCo co_arg) co, ticks)
- -- The simplifier combines multiple casts into one,
- -- so we can have a simple-minded pattern match here
- ok_arg bndr (Tick t arg) co fun_ty
- | tickishFloatable t, Just (co', ticks) <- ok_arg bndr arg co fun_ty
- = Just (co', t:ticks)
-
- ok_arg _ _ _ _ = Nothing
+ -- See Note [Eta reduction soundness], point (EtaT)
+
+
+-----------------
+getTrivialHead_maybe :: CoreExpr -> Maybe (Id, MCoercion, [CoreTickish])
+-- (getTrivialHead_maybe e) returns (Just (fn, co,ts))
+-- if `e` looks like (Tick ts (fn |> co)) and ts are floatable
+-- So co :: fn_ty ~ arg_ty
+
+getTrivialHead_maybe (Var v)
+ = Just (v, MRefl, [])
+
+getTrivialHead_maybe (Cast e co_outer)
+ = do { (v, mco_inner, ticks) <- getTrivialHead_maybe e
+ ; return (v, mco_inner `mkTransMCoL` co_outer, ticks) }
+
+getTrivialHead_maybe (Tick t arg)
+ | tickishFloatable t
+ = do { (v, co, ticks) <- getTrivialHead_maybe arg
+ ; return (v, co, t:ticks) }
+
+getTrivialHead_maybe _ = Nothing
+
+-----------------
+mkEtaReduceFunCo :: Type -> MCoercion -> MCoercion -> Maybe MCoercion
+mkEtaReduceFunCo _ MRefl MRefl
+ = Just MRefl -- Very common case
+mkEtaReduceFunCo fun_ty arg_mco res_mco
+ | Just (ftf, mult, arg_ty, res_ty) <- splitFunTy_maybe fun_ty
+ -- fun_ty = arg_ty -> res_ty
+ -- sym arg_mco : arg_ty ~ inner_arg_ty
+ -- res_mco : res_ty ~ outer_res_ty
+ , let arg_co = mCoToCo Representational arg_ty arg_mco
+ res_co = mCoToCo Representational res_ty res_mco
+ mult_co = multToCo mult
+ ftf' = chooseFunTyFlag (coercionLKind arg_co) (coercionRKind res_co)
+ = Just (MCo (mkFunCo2 Representational ftf ftf' mult_co (mkSymCo arg_co) res_co))
+ -- (arg_ty -> res_ty) ~ (inner_arg_ty -> outer_res_ty)
+ | otherwise
+ = Nothing
+-----------------
+mkEtaReduceForAllMCo :: ForAllTyBinder -> Type -> TyVar -> MCoercion -> MCoercion
+-- Very similar to mkEtaForAllMCo, but with
+-- the visibilities the other way around. Tiresome.
+-- mkEtaReduceForAllMCo (forall a[vis]. body_ty) b (co :: ty1 ~ ty2)
+-- (where `b` may be free in `ty1` and `ty2`)
+-- = ForAllCo b[vis]~[spec]. (co :: ty1 ~ ty2)
+-- where `coreTyLamForAllTyFlag` is [spec]
+mkEtaReduceForAllMCo (Bndr fun_tv vis) body_ty tv mco
+ = case mco of
+ MRefl | isCoreTyLamForAllTyFlag vis
+ -- The lambda we are eta-reducing always has visibility
+ -- 'coreTyLamForAllTyFlag' which may or may not match the
+ -- visibility on the inner function (#24014)
+ -> MRefl
+ | otherwise
+ -> MCo $ mkForAllCo fun_tv vis coreTyLamForAllTyFlag MRefl refl_co
+ MCo co -> MCo $ mkForAllCo tv vis coreTyLamForAllTyFlag MRefl co
+ -- Tricky: `fun_tv` scopes over `body_ty` and hence over `refl_co`
+ -- but: `tv` scopes over `mco` and hence over `co`
+ where
+ refl_co = mkRepReflCo body_ty
{- *********************************************************************
* *
=====================================
compiler/GHC/Core/Opt/OccurAnal.hs
=====================================
@@ -42,7 +42,6 @@ import GHC.Core.Utils ( exprIsTrivial, isDefaultAlt, isExpandableApp,
import GHC.Core.Opt.Arity ( joinRhsArity, isOneShotBndr )
import GHC.Core.Coercion
import GHC.Core.Type
-import GHC.Core.TyCo.FVs ( tyCoVarsOfMCo )
import GHC.Data.Maybe( orElse )
import GHC.Data.Graph.Directed ( SCC(..), Node(..)
@@ -2227,7 +2226,7 @@ lambda and casts, e.g.
* Why do we take care to account for intervening casts? Answer:
currently we don't do eta-expansion and cast-swizzling in a stable
- unfolding (see Historical-note [Eta-expansion in stable unfoldings]).
+ unfolding (see Note [Eta expansion in stable unfoldings and rules])
So we can get
f = \x. ((\y. ...x...y...) |> co)
Now, since the lambdas aren't together, the occurrence analyser will
=====================================
compiler/GHC/Core/Opt/Pipeline.hs
=====================================
@@ -352,8 +352,25 @@ runMaybe :: Maybe a -> (a -> CoreToDo) -> CoreToDo
runMaybe (Just x) f = f x
runMaybe Nothing _ = CoreDoNothing
-{- Note [Inline in InitialPhase]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [The InitialPhase of the Simplifier]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+The first run of the simplifier, historically called "gentle" simplification,
+has phase=InitialPhase, which does a number of things:
+
+* Usually sm_case_case is switched off in this phase; see
+ Note [Case-of-case and full laziness] and `initGentleSimplMode`
+
+* Inlining, however, is not switched off in InitialPhase.
+ See Note [Inline in InitialPhase]
+
+* Rules can run in InitialPhase
+ Note [RULEs enabled in InitialPhase]
+
+* Lint is a little aggressive about loop-breaker warnings in InitialPhase.
+ See `check_lbs` in `GHC.Core.Lint.perPassFlags`.
+
+Note [Inline in InitialPhase]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In GHC 8 and earlier we did not inline anything in the InitialPhase. But that is
confusing for users because when they say INLINE they expect the function to inline
right away.
=====================================
compiler/GHC/Core/Opt/Simplify/Env.hs
=====================================
@@ -355,12 +355,18 @@ This simplifier phase is stored in the sm_phase field of SimplMode, usin
the 'SimplPhase' constructor. This allows us to determine which rules/inlinings
are active.
-When we invoke the simplifier on the RHS of a rule, such as 'rhs' above, instead
-of setting the simplifier mode to a single phase, we use a phase range
-corresponding to the range of phases in which the rule is active, with the
-'SimplPhaseRange' constructor. This allows us to check whether other rules or
-inlinings are active throughout the whole activation of the rule.
-See Note [What is active in the RHS of a RULE or unfolding?] in GHC.Core.Opt.Simplify.Utils.
+Wrinkles
+
+(SP1) InitialPhase: see Note [The InitialPhase of the Simplifier]
+ in GHC.Core.Opt.Pipeline.
+
+(SP2) Phase ranges. When we invoke the simplifier on the RHS of a rule, such as
+ `rhs` above, instead of setting the simplifier mode to a single phase, we use a
+ phase /range/ corresponding to the range of phases in which the rule is active,
+ with the 'SimplPhaseRange' constructor. This allows us to check whether other
+ rules or inlinings are active throughout the whole activation of the rule. See
+ Note [What is active in the RHS of a RULE or unfolding?] in
+ GHC.Core.Opt.Simplify.Utils.
-}
instance Outputable SimplMode where
@@ -1234,6 +1240,8 @@ out_id so that its arity is visible in its RHS. Examples:
Example: `f = \x. f x`. See Note [Eta reduction in recursive RHSs] for how
we prevent that.
+c.f. (EtaA) in Note [Eta reduction soundness] in GHC.Core.Opt.Arity.
+
Note [Robust OccInfo]
~~~~~~~~~~~~~~~~~~~~~
It's important that we *do* retain the loop-breaker OccInfo, because
=====================================
compiler/GHC/Core/Opt/Simplify/Inline.hs
=====================================
@@ -126,11 +126,6 @@ activeUnfolding mode id
| otherwise
= isActive (sm_phase mode) (idInlineActivation id)
&& sm_inline mode
- -- `or` isStableUnfolding (realIdUnfolding id)
- -- Inline things when
- -- (a) they are active
- -- (b) sm_inline says so, except that for stable unfoldings
- -- (ie pragmas) we inline anyway
-- | Report the inlining of an identifier's RHS to the user, if requested.
traceInline :: Logger -> UnfoldingOpts -> Id -> String -> SDoc -> a -> a
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -3143,7 +3143,7 @@ There have been various earlier versions of this patch:
case_bndr_evald_next _ = False
This patch was part of fixing #7542. See also
- Note [Eta reduction soundness], criterion (E) in GHC.Core.Utils.)
+ Note [Eta reduction soundness], criterion (EtaE) in GHC.Core.Opt.Arity.)
Further notes about case elimination
@@ -4959,7 +4959,7 @@ eta-expand the stable unfolding to arity N too. Simple and consistent.
Wrinkles
-* See Historical-note [Eta-expansion in stable unfoldings] in
+* See Note [Eta expansion in stable unfoldings and rules]
GHC.Core.Opt.Simplify.Utils
* Don't eta-expand a trivial expr, else each pass will eta-reduce it,
=====================================
compiler/GHC/Core/Opt/Simplify/Utils.hs
=====================================
@@ -1319,43 +1319,6 @@ But this old note is no longer relevant because the specialiser has
improved: see Note [Account for casts in binding] in
GHC.Core.Opt.Specialise. So we seem to have a free choice.
-Note [Inlining in gentle mode]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Something is inlined if
- (i) the sm_inline flag is on, AND
- (ii) the thing has an INLINE pragma, AND
- (iii) the thing is inlinable in the earliest phase.
-
-Example of why (iii) is important:
- {-# INLINE [~1] g #-}
- g = ...
-
- {-# INLINE f #-}
- f x = g (g x)
-
-If we were to inline g into f's inlining, then an importing module would
-never be able to do
- f e --> g (g e) ---> RULE fires
-because the stable unfolding for f has had g inlined into it.
-
-On the other hand, it is bad not to do ANY inlining into an
-stable unfolding, because then recursive knots in instance declarations
-don't get unravelled.
-
-However, *sometimes* SimplGently must do no call-site inlining at all
-(hence sm_inline = False). Before full laziness we must be careful
-not to inline wrappers, because doing so inhibits floating
- e.g. ...(case f x of ...)...
- ==> ...(case (case x of I# x# -> fw x#) of ...)...
- ==> ...(case x of I# x# -> case fw x# of ...)...
-and now the redex (f x) isn't floatable any more.
-
-The no-inlining thing is also important for Template Haskell. You might be
-compiling in one-shot mode with -O2; but when TH compiles a splice before
-running it, we don't want to use -O2. Indeed, we don't want to inline
-anything, because the byte-code interpreter might get confused about
-unboxed tuples and suchlike.
-
Note [What is active in the RHS of a RULE or unfolding?]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have either a RULE or a stable unfolding with an explicit activation:
@@ -1448,7 +1411,7 @@ First, consider the following example
Now, if that's the ONLY occurrence of f, it might be inlined inside g,
and thence copied multiple times when g is inlined. HENCE we treat
any occurrence in a stable unfolding as a multiple occurrence, not a single
-one; see OccurAnal.addRuleUsage.
+one; see Note [Occurrences in stable unfoldings and RULES] in GHC.Core.Opt.OccurAnal.
Second, we must be careful when simplifying the RHS that we do not apply RULES
which are not active over the whole active range of the stable unfolding.
@@ -1477,17 +1440,6 @@ strictness wrapper get activation (ActiveAfter 0). So the strictness
wrepper fails the test and won't be inlined into f's stable unfolding. That
means f can inline, expose the specialised call to g, so the specialisation
rules can fire.
-
-A note about wrappers
-~~~~~~~~~~~~~~~~~~~~~
-It's also important not to inline a worker back into a wrapper.
-A wrapper looks like
- wraper = inline_me (\x -> ...worker... )
-Normally, the inline_me prevents the worker getting inlined into
-the wrapper (initially, the worker's only call site!). But,
-if the wrapper is sure to be called, the strictness analyser will
-mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
-continuation.
-}
getUnfoldingInRuleMatch :: SimplEnv -> InScopeEnv
@@ -2158,8 +2110,9 @@ tryEtaExpandRhs :: SimplEnv -> BindContext -> OutId -> OutExpr
tryEtaExpandRhs env bind_cxt bndr rhs
| seEtaExpand env -- If Eta-expansion is on
, wantEtaExpansion rhs -- and we'd like to eta-expand e
- , do_eta_expand -- and e's manifest arity is lower than
- -- what it could be
+ , do_eta_expand -- and arity analysis finds a greater arity
+ -- than (exprArity e); NB: not manifestArity
+ -- See Note [Do not eta-expand PAPs]
-- (never true for join points)
= -- Do eta-expansion.
assertPpr( not (isJoinBC bind_cxt) ) (ppr bndr) $
@@ -2178,7 +2131,8 @@ tryEtaExpandRhs env bind_cxt bndr rhs
(do_eta_expand, arity_type) = findRhsArity arity_opts is_rec bndr rhs
wantEtaExpansion :: CoreExpr -> Bool
--- Mostly True; but False of PAPs which will immediately eta-reduce again
+-- Mostly True; but False of trivial RHSs, and of PAPs at the top of the RHS
+-- (PAPs under value lambdas are dealt with by findRhsArity)
-- See Note [Which RHSs do we eta-expand?]
wantEtaExpansion (Cast e _) = wantEtaExpansion e
wantEtaExpansion (Tick _ e) = wantEtaExpansion e
@@ -2195,24 +2149,6 @@ We now eta expand at let-bindings, which is where the payoff comes.
The most significant thing is that we can do a simple arity analysis
(in GHC.Core.Opt.Arity.findRhsArity), which we can't do for free-floating lambdas
-One useful consequence of not eta-expanding lambdas is this example:
- genMap :: C a => ...
- {-# INLINE genMap #-}
- genMap f xs = ...
-
- myMap :: D a => ...
- {-# INLINE myMap #-}
- myMap = genMap
-
-Notice that 'genMap' should only inline if applied to two arguments.
-In the stable unfolding for myMap we'll have the unfolding
- (\d -> genMap Int (..d..))
-We do not want to eta-expand to
- (\d f xs -> genMap Int (..d..) f xs)
-because then 'genMap' will inline, and it really shouldn't: at least
-as far as the programmer is concerned, it's not applied to two
-arguments!
-
Note [Which RHSs do we eta-expand?]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't eta-expand:
@@ -2234,7 +2170,22 @@ seems like a Good idea.
Note [Do not eta-expand PAPs]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-We used to have old_arity = manifestArity rhs, which meant that we
+We do not eta-expand a RHS that is a partial application (PAP). This
+is achieved in two places:
+
+(DEP1) A PAP at the top of the RHS, such as
+ f = g d -- g has arity 2
+ is rejected by `wantEtaExpansion`.
+
+(DEP2) A PAP under value lambdas, such as
+ f = \x. g x -- g has arity 3
+ is not eta-expanded because `findRhsArity` asks for eta-expansion
+ only if the arity it finds is greater than (exprArity rhs), and
+ `exprArity` takes account of PAPs: here (exprArity rhs) = 3.
+ Using `manifestArity` (which is 1 here) instead would eta-expand
+ to f = \x y z. g x y z.
+
+Up to 2014 we used old_arity = manifestArity rhs, which meant that we
would eta-expand even PAPs. But this gives no particular advantage,
and can lead to a massive blow-up in code size, exhibited by #9020.
Suppose we have a PAP
@@ -2250,6 +2201,17 @@ coercions and whatnot that eventually disappear again. For T9020, GHC
allocated 6.6G before, and 0.8G afterwards; and residency dropped from
1.8G to 45M.
+#27212 tried switching (DEP2) back to manifestArity, with these results:
+
+* T13960: bytestring's
+ cstring1 = \(a::Addr#) @r. cstring2 @r a -- cstring2 has arity 4
+ was eta-expanded to (\a @r k br s. cstring2 @r a k br s). That bigger
+ unfolding is inlined at every string literal, adding 6 terms per
+ literal; compile-time allocation went up by 9%.
+
+* T13056: a derived-instance method (\ @a d. lvl @a), where `lvl` is
+ bottoming, was eta-expanded, and then needlessly worker/wrappered.
+
Moreover, if we eta expand
f = g d ==> f = \x. g d x
that might in turn make g inline (if it has an inline pragma), which
@@ -2261,6 +2223,24 @@ But note that this won't eta-expand, say
Does it matter not eta-expanding such functions? I'm not sure. Perhaps
strictness analysis will have less to bite on?
+One useful consequence of not eta-expanding PAPs is this example:
+ genMap :: C a => ...
+ {-# INLINE genMap #-}
+ genMap f xs = ...
+
+ myMap :: D a => ...
+ {-# INLINE myMap #-}
+ myMap = genMap
+
+Notice that 'genMap' should only inline if applied to two arguments.
+In the stable unfolding for myMap we'll have the unfolding
+ (\d -> genMap Int (..d..))
+We do not want to eta-expand to
+ (\d f xs -> genMap Int (..d..) f xs)
+because then 'genMap' will inline, and it really shouldn't: at least
+as far as the programmer is concerned, it's not applied to two
+arguments!
+
************************************************************************
* *
=====================================
compiler/GHC/Core/Opt/SpecConstr.hs
=====================================
@@ -684,7 +684,7 @@ But regardless, SpecConstr can and should! It's easy:
Wrinkles:
* This should all work perfectly fine for newtype classes. Mind you,
- currently newtype classes are inlined fairly agressively, but we
+ currently newtype classes are inlined fairly aggressively, but we
may change that. And it would take extra code to exclude them, as
well as being unnecessary.
=====================================
compiler/GHC/Core/Opt/Specialise.hs
=====================================
@@ -3345,7 +3345,7 @@ pair_fvs :: (Id, CoreExpr) -> VarSet
pair_fvs (bndr, rhs) = exprSomeFreeVars interesting rhs
`unionVarSet` bndrFreeVars bndr
-- bndrFreeVars: don't forget variables mentioned in
- -- the rules of the bndr. C.f. OccAnal.addRuleUsage
+ -- the rules or unfolding of the bndr.
-- Also tyvars mentioned in its type; they may not appear
-- in the RHS
-- type T a = Int
=====================================
compiler/GHC/Core/TyCo/Make.hs
=====================================
@@ -58,7 +58,7 @@ module GHC.Core.TyCo.Make (
, mkAxInstCo
, mkTransCo, mkTransMCo, mkTransMCoL, mkTransMCoR
, mkProofIrrelCo
- , coToMCo, kindCoToMKindCo
+ , coToMCo, kindCoToMKindCo, mCoToCo
, mkCoherenceLeftCo, mkCoherenceRightCo, mkCoherenceRightMCo
, toPhantomCo, mkPhantomCo
, isReflCo, isReflMCo, isReflKindCo, isReflKindMCo, isReflCo_maybe
@@ -860,7 +860,7 @@ mkHomoForAllCos vs orig_co
= foldr go orig_co vs
where
go :: ForAllTyBinder -> Coercion -> Coercion
- go (Bndr var vis) co = mk_forall_co var vis vis MRefl co
+ go (Bndr var vis) co = mkForAllCoNonRefl var vis vis MRefl co
mkHomoForAllCo :: TyVar -> Coercion -> Coercion
-- Specialised for a single TyVar,
@@ -869,7 +869,7 @@ mkHomoForAllCo tv orig_co
| Just (ty, r) <- isReflCo_maybe orig_co
= mkReflCo r (mkForAllTy (Bndr tv vis) ty)
| otherwise
- = mk_forall_co tv vis vis MRefl orig_co
+ = mkForAllCoNonRefl tv vis vis MRefl orig_co
where
vis = coreTyLamForAllTyFlag
@@ -892,15 +892,15 @@ mkForAllCo v visL visR kind_co co
| Just refl_co <- isReflForAllCo v visL visR kind_co co
= refl_co
| otherwise
- = mk_forall_co v visL visR kind_co co
+ = mkForAllCoNonRefl v visL visR kind_co co
--- | `mk_forall_co` just builds a ForAllCo.
+-- | `mkForAllCoNonRefl` just builds a ForAllCo.
-- With debug on, it checks invariants (e.g. he kind of the tycovar should
-- be the left-hand kind of the kind coercion).
-- Callers should have done any isReflCo short-cutting.
-mk_forall_co :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag
- -> KindMCoercion -> Coercion -> Coercion
-mk_forall_co tcv visL visR kind_co co
+mkForAllCoNonRefl :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag
+ -> KindMCoercion -> Coercion -> Coercion
+mkForAllCoNonRefl tcv visL visR kind_co co
= assertGoodForAllCo tcv visL visR kind_co co $
assertPpr (not (isReflCo co && isReflMCo kind_co && visL `eqForAllVis` visR)) (ppr co) $
ForAllCo { fco_tcv = tcv, fco_visL = visL, fco_visR = visR
@@ -1289,6 +1289,10 @@ coToMCo :: Coercion -> MCoercion
coToMCo co | isReflCo co = MRefl
| otherwise = MCo co
+mCoToCo :: Role -> Type -> MCoercion -> Coercion
+mCoToCo role ty MRefl = mkReflCo role ty
+mCoToCo _ _ (MCo co) = co
+
kindCoToMKindCo :: KindCoercion -> KindMCoercion
-- Convert a KindCoercion to a KindMCoercion,
-- coToMCo doesn't eliminate GRefl, but kindCoToMCo can
=====================================
compiler/GHC/Core/Type.hs
=====================================
@@ -160,7 +160,7 @@ module GHC.Core.Type (
-- * Type free variables
tyCoVarsOfType, tyCoVarsOfTypes, tyCoVarsOfTypeDSet,
- coVarsOfType, coVarsOfTypes,
+ tyCoVarsOfMCo, coVarsOfType, coVarsOfTypes,
anyFreeVarsOfType, anyFreeVarsOfTypes,
noFreeVarsOfType,
=====================================
compiler/GHC/Core/Utils.hs
=====================================
@@ -2392,7 +2392,7 @@ canCollectArgsThroughTick id t
= tickishFloatable t || cantEtaReduceFun id
-- | Can we eta-reduce the given function?
--- See Note [Eta reduction soundness], criteria (B), (J), and (W).
+-- See Note [Eta reduction soundness], criteria (EtaB), (EtaJ), and (EtaW).
cantEtaReduceFun :: Id -> Bool
cantEtaReduceFun fun
= hasNoBinding fun -- (B)
@@ -3295,17 +3295,16 @@ Now
the caller guarantees to pass an EPT argument (see Note [EPT enforcement] in
GHC.Core.Stg.EnforceEpt)
- * The code generator will discard that "extra eval" case, because $wfoo is
- CBV.
+ * The code generator will discard that "extra eval" case, because $wfoo is CBV.
See also Note [CBV Function Ids: overview].
-In tihs case the argument is known to be properly tagged at the call site so there is
+In this case the argument is known to be properly tagged at the call site so there is
no additional work for the caller and the worker can be more efficient since it can
assume the presence of a tag.
This is especially true for recursive functions like this:
- -- myPred expect it's argument properly tagged
+ -- myPred expects its argument properly tagged
-- The EnforceEPT pass has made it a CBV function
myPred !x = ...
@@ -3414,16 +3413,17 @@ This note deals with the second part.
There are multiple reasons why we might not want to insert a seq in the rhs to
strictify a functions argument:
-1) The argument doesn't exist at runtime.
- For zero width types (like Types) there is no benefit as we don't operate on them
- at runtime at all. This includes things like void#, coercions and state tokens.
+(WIS1) The argument doesn't exist at runtime: types are erased.
-2) The argument is a unlifted type.
- If the argument is a unlifted type the calling convention already is explicitly
+(WIS2) For zero width types there is no benefit as we don't operate on them at
+ runtime at all. This includes things like void#, coercions and state tokens.
+
+(WIS3) The argument is a unlifted type.
+ If the argument is an unlifted type the calling convention already is explicitly
cbv. This means inserting a seq on this argument wouldn't do anything as the seq
would be a no-op *and* it wouldn't affect the calling convention.
-3) The argument is absent.
+(WIS4) The argument is absent.
If the argument is absent in the body there is no advantage to it being passed as
cbv to the function. The function won't ever look at it so we don't save any work.
@@ -3445,7 +3445,7 @@ strictify a functions argument:
Note [Absent fillers] has an example of this. However this is so rare it's not worth
caring about here.
-5) Functions
+(WIS5) Functions
Functions are tricky (see Note [TagInfo of functions] in EnforceEpt).
But the gist of it even if we make a higher order function argument strict
we can't avoid the tag check when it's used later in the body.
@@ -3453,7 +3453,7 @@ strictify a functions argument:
Wrinkles:
-(WIS1) You might have thought that we can omit the eval if the argument is used
+(WIS6) You might have thought that we can omit the eval if the argument is used
strictly demanded in the body. But you'd be wrong. Consider this code:
data T = MkT ![Int]
f t = case t of MkT xs{Dmd=STR} -> reverse xs
@@ -3509,25 +3509,30 @@ Wrinkles:
wantCbvForId :: Var -> Bool
wantCbvForId v
-- Must be a runtime var.
- -- See Note [Which Ids should be strictified] point 1)
- | isId v
- , not $ isZeroBitTy ty
+ -- See (WIS1) in Note [Which Ids should be strictified]
+ | not (isRuntimeVar v) = False
+
+ -- Not zero-width value
+ -- See (WIS2) in Note [Which Ids should be strictified]
+ | isZeroBitTy ty = False
+
-- Unlifted things don't need special measures to be treated as cbv
- -- See Note [Which Ids should be strictified] point 2)
- , mightBeLiftedType ty
+ -- See (WIS3) in Note [Which Ids should be strictified]
+ | definitelyUnliftedType ty = False
+
+ -- If the var is absent, don't add a seq
+ -- See (WIS4) in Note [Which Ids should be strictified]
+ | isAbsDmd (idDemandInfo v) = False
+
-- Functions sometimes get a zero tag so we can't eliminate the tag check.
-- See Note [TagInfo of functions] in EnforceEpt.
- -- See Note [Which Ids should be strictified] point 5)
- , not $ isFunTy ty
- -- If the var is strict already a seq is redundant.
- -- See Note [Which Ids should be strictified] point 4)
- , not (isAbsDmd dmd)
- = True
- | otherwise
- = False
+ -- See (WIS5) in Note [Which Ids should be strictified]
+ | isFunTy ty = False
+
+ -- Finally! We should add a `seq`
+ | otherwise = True
where
ty = idType v
- dmd = idDemandInfo v
{- *********************************************************************
* *
=====================================
compiler/GHC/Driver/Config/Core/Opt/Simplify.hs
=====================================
@@ -77,6 +77,7 @@ initSimplMode dflags phase name = SimplMode
}
initGentleSimplMode :: DynFlags -> SimplMode
+-- See Note [The InitialPhase of the Simplifier] in GHC.Core.Opt.Pipeline
initGentleSimplMode dflags = (initSimplMode dflags InitialPhase "Gentle")
{ -- Don't do case-of-case transformations.
-- This makes full laziness work better
=====================================
compiler/Language/Haskell/Syntax/Binds/InlinePragma.hs
=====================================
@@ -124,11 +124,15 @@ Note [inl_inline and inl_act]
INLINABLE, OPAQUE, or nothing at all
* inl_act says in what phases the unfolding is active or inactive
- E.g If you write INLINE[1] then inl_act will be set to ActiveAfter 1
- If you write NOINLINE[1] then inl_act will be set to ActiveBefore 1
- If you write NOINLINE[~1] then inl_act will be set to ActiveAfter 1
- So note that inl_act does not say what pragma you wrote: it just
- expresses its consequences
+ E.g If you write then inl_act will be set to
+ INLINE AlwaysActive
+ INLINE[1] ActiveAfter 1
+ INLINE[~1] ActiveBefore 1
+ NOINLINE[1] ActiveAfter 1
+ NOINLINE[~1] ActiveBefore 1
+ NOINLINE NeverActive
+ So note that inl_act does not say what pragma you wrote:
+ it just expresses its consequences
* inl_act just says when the unfolding is active; it doesn't say what
to inline. If you say INLINE f, then f's inl_act will be AlwaysActive,
=====================================
docs/users_guide/debug-info.rst
=====================================
@@ -69,8 +69,9 @@ Here we used the ``-g`` option to inform GHC that it should add debugging
information in the produced binary. There are three levels of debugging
output: ``-g0`` (no debugging information, the default), ``-g1`` (sufficient for
basic backtraces), ``-g2`` (or just ``-g`` for short; emitting everything GHC knows).
-Note that this debugging information does not affect the optimizations performed
-by GHC.
+Note that this debugging information does not affect the optimizations
+that GHC attempts to perform; but it can affect how successful it is in
+performing them (see #21471, #27687).
.. tip::
Under Mac OS X debug information is kept apart from the executable. After
=====================================
docs/users_guide/using-optimisation.rst
=====================================
@@ -1817,7 +1817,7 @@ as such you shouldn't need to set any of them explicitly. A flag
:type: dynamic
:category:
- :default: 80
+ :default: 90
.. index::
single: inlining, controlling
=====================================
testsuite/tests/dmdanal/sigs/T21888a.stderr
=====================================
@@ -7,7 +7,7 @@ T21888a.wombat: <S!P(S)>b
==================== Cpr signatures ====================
-T21888a.f: 2
+T21888a.f:
T21888a.g: 1
T21888a.wombat: b
=====================================
testsuite/tests/printer/T18052a.stderr
=====================================
@@ -10,11 +10,11 @@ Dependent packages: [(normal, base-4.23.0.0)]
==================== Tidy Core ====================
Result size of Tidy Core
- = {terms: 24, types: 52, coercions: 0, joins: 0/0}
+ = {terms: 18, types: 46, coercions: 0, joins: 0/0}
--- RHS size: {terms: 7, types: 6, coercions: 0, joins: 0/0}
+-- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
T18052a.$b:||: :: forall {a} {b}. a -> b -> (a, b)
-T18052a.$b:||: = \ (@a) (@b) (x :: a) (y :: b) -> (x, y)
+T18052a.$b:||: = GHC.Internal.Tuple.(,)
-- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
(+++) :: forall {a}. [a] -> [a] -> [a]
=====================================
testsuite/tests/simplCore/should_compile/T27212.hs
=====================================
@@ -0,0 +1,17 @@
+module T27212 where
+
+import Unsafe.Coerce
+
+class Given a where given :: a
+newtype Gift a r = Gift (Given a => r)
+
+useIt :: Given Int => Int
+useIt = given + 1
+{-# NOINLINE useIt #-}
+
+foo :: [Int] -> [Int]
+foo xs = case unsafeEqualityProof @(Gift Int Int) @(Int -> Int) of
+ UnsafeRefl -> map (\y -> (Gift useIt :: Gift Int Int) y) xs
+ -- That (\y. glah y) can eta-reduce to `glah`
+ -- but doing doing so makes a FunCo coercion that crosses from
+ -- Type to constraint. Tricky.
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -631,3 +631,4 @@ test('T27936', normal, compile, [''])
test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
+test('T27212', normal, compile, ['-O'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/c4818edcb2fb2915086ada7c2ff26a…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/c4818edcb2fb2915086ada7c2ff26a…
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
1
0