[Git][ghc/ghc][wip/marge_bot_batch_merge_job] 4 commits: Late plugins
Marge Bot (@marge-bot)
gitlab at gitlab.haskell.org
Sun Dec 17 06:23:24 UTC 2023
Marge Bot pushed to branch wip/marge_bot_batch_merge_job at Glasgow Haskell Compiler / GHC
Commits:
874228a7 by Finley McIlwaine at 2023-12-17T01:23:15-05:00
Late plugins
- - - - -
19dbb579 by Finley McIlwaine at 2023-12-17T01:23:15-05:00
withTiming on LateCCs and late plugins
- - - - -
f037cf95 by Finley McIlwaine at 2023-12-17T01:23:15-05:00
add test for late plugins
- - - - -
00709bc8 by Finley McIlwaine at 2023-12-17T01:23:15-05:00
Document late plugins
- - - - -
9 changed files:
- compiler/GHC/Core/LateCC.hs
- compiler/GHC/Driver/Main.hs
- compiler/GHC/Driver/Plugins.hs
- docs/users_guide/9.10.1-notes.rst
- docs/users_guide/extending_ghc.rst
- testsuite/tests/plugins/Makefile
- testsuite/tests/plugins/all.T
- + testsuite/tests/plugins/late-plugin/LatePlugin.hs
- + testsuite/tests/plugins/test-late-plugin.hs
Changes:
=====================================
compiler/GHC/Core/LateCC.hs
=====================================
@@ -71,34 +71,32 @@ addLateCostCentresMG guts = do
let env :: Env
env = Env
{ thisModule = mg_module guts
- , ccState = newCostCentreState
, countEntries = gopt Opt_ProfCountEntries dflags
, collectCCs = False -- See Note [Collecting late cost centres]
}
- let guts' = guts { mg_binds = fst (addLateCostCentres env (mg_binds guts))
+ let guts' = guts { mg_binds = fstOf3 (addLateCostCentres env (mg_binds guts))
}
return guts'
-addLateCostCentresPgm :: DynFlags -> Logger -> Module -> CoreProgram -> IO (CoreProgram, S.Set CostCentre)
+addLateCostCentresPgm :: DynFlags -> Logger -> Module -> CoreProgram -> IO (CoreProgram, S.Set CostCentre, CostCentreState)
addLateCostCentresPgm dflags logger mod binds =
withTiming logger
(text "LateCC"<+>brackets (ppr mod))
- (\(a,b) -> a `seqList` (b `seq` ())) $ do
+ (\(a,b,c) -> a `seqList` (b `seq` (c `seq` ()))) $ do
let env = Env
{ thisModule = mod
- , ccState = newCostCentreState
, countEntries = gopt Opt_ProfCountEntries dflags
, collectCCs = True -- See Note [Collecting late cost centres]
}
- (binds', ccs) = addLateCostCentres env binds
+ (binds', ccs, cc_state) = addLateCostCentres env binds
when (dopt Opt_D_dump_late_cc dflags || dopt Opt_D_verbose_core2core dflags) $
putDumpFileMaybe logger Opt_D_dump_late_cc "LateCC" FormatCore (vcat (map ppr binds'))
- return (binds', ccs)
+ return (binds', ccs, cc_state)
-addLateCostCentres :: Env -> CoreProgram -> (CoreProgram,S.Set CostCentre)
+addLateCostCentres :: Env -> CoreProgram -> (CoreProgram, S.Set CostCentre, CostCentreState)
addLateCostCentres env binds =
let (binds', state) = runState (mapM (doBind env) binds) initLateCCState
- in (binds',lcs_ccs state)
+ in (binds', lcs_ccs state, lcs_state state)
doBind :: Env -> CoreBind -> M CoreBind
@@ -161,7 +159,6 @@ addCC !env cc = do
data Env = Env
{ thisModule :: !Module
, countEntries:: !Bool
- , ccState :: !CostCentreState
, collectCCs :: !Bool
}
=====================================
compiler/GHC/Driver/Main.hs
=====================================
@@ -297,6 +297,7 @@ import GHC.StgToCmm.Utils (IPEStats)
import GHC.Types.Unique.FM
import GHC.Types.Unique.DFM
import GHC.Cmm.Config (CmmConfig)
+import GHC.Types.CostCentre.State (newCostCentreState)
{- **********************************************************************
@@ -1781,40 +1782,70 @@ hscGenHardCode :: HscEnv -> CgGuts -> ModLocation -> FilePath
-> IO (FilePath, Maybe FilePath, [(ForeignSrcLang, FilePath)], Maybe StgCgInfos, Maybe CmmCgInfos )
-- ^ @Just f@ <=> _stub.c is f
hscGenHardCode hsc_env cgguts location output_filename = do
- let CgGuts{ -- This is the last use of the ModGuts in a compilation.
- -- From now on, we just use the bits we need.
- cg_module = this_mod,
+ let CgGuts{ cg_module = this_mod,
cg_binds = core_binds,
- cg_ccs = local_ccs,
- cg_tycons = tycons,
- cg_foreign = foreign_stubs0,
- cg_foreign_files = foreign_files,
- cg_dep_pkgs = dependencies,
- cg_hpc_info = hpc_info,
- cg_spt_entries = spt_entries
+ cg_ccs = local_ccs
} = cgguts
dflags = hsc_dflags hsc_env
logger = hsc_logger hsc_env
- hooks = hsc_hooks hsc_env
- tmpfs = hsc_tmpfs hsc_env
- llvm_config = hsc_llvm_config hsc_env
- profile = targetProfile dflags
- data_tycons = filter isDataTyCon tycons
- -- cg_tycons includes newtypes, for the benefit of External Core,
- -- but we don't generate any code for newtypes
+
-------------------
-- Insert late cost centres if enabled.
-- If `-fprof-late-inline` is enabled we can skip this, as it will have added
-- a superset of cost centres we would add here already.
- (late_cc_binds, late_local_ccs) <-
+ (late_cc_binds, late_local_ccs, cc_state) <-
if gopt Opt_ProfLateCcs dflags && not (gopt Opt_ProfLateInlineCcs dflags)
- then {-# SCC lateCC #-} do
- (binds,late_ccs) <- addLateCostCentresPgm dflags logger this_mod core_binds
- return ( binds, (S.toList late_ccs `mappend` local_ccs ))
+ then
+ withTiming
+ logger
+ (text "LateCCs"<+>brackets (ppr this_mod))
+ (const ())
+ $ {-# SCC lateCC #-} do
+ (binds, late_ccs, cc_state) <- addLateCostCentresPgm dflags logger this_mod core_binds
+ return ( binds, (S.toList late_ccs `mappend` local_ccs ), cc_state)
else
- return (core_binds, local_ccs)
+ return (core_binds, local_ccs, newCostCentreState)
+
+ -------------------
+ -- Run late plugins
+ -- This is the last use of the ModGuts in a compilation.
+ -- From now on, we just use the bits we need.
+ ( CgGuts
+ { cg_tycons = tycons,
+ cg_foreign = foreign_stubs0,
+ cg_foreign_files = foreign_files,
+ cg_dep_pkgs = dependencies,
+ cg_hpc_info = hpc_info,
+ cg_spt_entries = spt_entries,
+ cg_binds = late_binds,
+ cg_ccs = late_local_ccs'
+ }
+ , _
+ ) <-
+ {-# SCC latePlugins #-}
+ withTiming
+ logger
+ (text "LatePlugins"<+>brackets (ppr this_mod))
+ (const ()) $
+ withPlugins (hsc_plugins hsc_env)
+ (($ hsc_env) . latePlugin)
+ ( cgguts
+ { cg_binds = late_cc_binds
+ , cg_ccs = late_local_ccs
+ }
+ , cc_state
+ )
+
+ let
+ hooks = hsc_hooks hsc_env
+ tmpfs = hsc_tmpfs hsc_env
+ llvm_config = hsc_llvm_config hsc_env
+ profile = targetProfile dflags
+ data_tycons = filter isDataTyCon tycons
+ -- cg_tycons includes newtypes, for the benefit of External Core,
+ -- but we don't generate any code for newtypes
@@ -1827,7 +1858,7 @@ hscGenHardCode hsc_env cgguts location output_filename = do
(hsc_logger hsc_env)
cp_cfg
(initCorePrepPgmConfig (hsc_dflags hsc_env) (interactiveInScope $ hsc_IC hsc_env))
- this_mod location late_cc_binds data_tycons
+ this_mod location late_binds data_tycons
----------------- Convert to STG ------------------
(stg_binds_with_deps, denv, (caf_ccs, caf_cc_stacks), stg_cg_infos)
@@ -1845,7 +1876,7 @@ hscGenHardCode hsc_env cgguts location output_filename = do
let (stg_binds,_stg_deps) = unzip stg_binds_with_deps
let cost_centre_info =
- (late_local_ccs ++ caf_ccs, caf_cc_stacks)
+ (late_local_ccs' ++ caf_ccs, caf_cc_stacks)
platform = targetPlatform dflags
prof_init
| sccProfilingEnabled dflags = profilingInitCode platform this_mod cost_centre_info
=====================================
compiler/GHC/Driver/Plugins.hs
=====================================
@@ -58,6 +58,10 @@ module GHC.Driver.Plugins (
-- | hole fit plugins allow plugins to change the behavior of valid hole
-- fit suggestions
, HoleFitPluginR
+ -- ** Late plugins
+ -- | Late plugins can access and modify the core of a module after
+ -- optimizations have been applied and after interface creation.
+ , LatePlugin
-- * Internal
, PluginWithArgs(..), pluginsWithArgs, pluginRecompile'
@@ -89,8 +93,10 @@ import GHC.Core.Opt.Pipeline.Types ( CoreToDo )
import GHC.Hs
import GHC.Types.Error (Messages)
import GHC.Linker.Types
+import GHC.Types.CostCentre.State
import GHC.Types.Unique.DFM
+import GHC.Unit.Module.ModGuts (CgGuts)
import GHC.Utils.Fingerprint
import GHC.Utils.Outputable
import GHC.Utils.Panic
@@ -157,6 +163,13 @@ data Plugin = Plugin {
--
-- @since 8.10.1
+ , latePlugin :: LatePlugin
+ -- ^ A plugin that runs after interface creation and after late cost centre
+ -- insertion. Useful for transformations that should not impact interfaces
+ -- or optimization at all.
+ --
+ -- @since 9.10.1
+
, pluginRecompile :: [CommandLineOption] -> IO PluginRecompile
-- ^ Specify how the plugin should affect recompilation.
, parsedResultAction :: [CommandLineOption] -> ModSummary
@@ -260,6 +273,7 @@ type CorePlugin = [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
type TcPlugin = [CommandLineOption] -> Maybe GHC.Tc.Types.TcPlugin
type DefaultingPlugin = [CommandLineOption] -> Maybe GHC.Tc.Types.DefaultingPlugin
type HoleFitPlugin = [CommandLineOption] -> Maybe HoleFitPluginR
+type LatePlugin = HscEnv -> [CommandLineOption] -> (CgGuts, CostCentreState) -> IO (CgGuts, CostCentreState)
purePlugin, impurePlugin, flagRecompile :: [CommandLineOption] -> IO PluginRecompile
purePlugin _args = return NoForceRecompile
@@ -280,6 +294,7 @@ defaultPlugin = Plugin {
, defaultingPlugin = const Nothing
, holeFitPlugin = const Nothing
, driverPlugin = const return
+ , latePlugin = \_ -> const return
, pluginRecompile = impurePlugin
, renamedResultAction = \_ env grp -> return (env, grp)
, parsedResultAction = \_ _ -> return
=====================================
docs/users_guide/9.10.1-notes.rst
=====================================
@@ -126,6 +126,9 @@ Compiler
- The :ghc-flag:`-Wforall-identifier` flag is now deprecated and removed from :ghc-flag:`-Wdefault`,
as ``forall`` is no longer parsed as an identifier.
+- Late plugins have been added. These are plugins which can access and/or modify
+ the core of a module after optimization and after interface creation. See :ghc-ticket:`24254`.
+
GHCi
~~~~
=====================================
docs/users_guide/extending_ghc.rst
=====================================
@@ -510,6 +510,58 @@ in a module it compiles:
return bndr
printBind _ bndr = return bndr
+.. _late-plugins:
+
+Late Plugins
+^^^^^^^^^^^^
+
+If the ``CoreProgram`` of a module is modified in a normal core plugin, the
+modified bindings can end up in unfoldings the interface file for the module.
+This may be undesireable, as the plugin could make changes which affect inlining
+or optimization.
+
+Late plugins can be used to avoid introducing such changes into the interface
+file. Late plugins are a bit different from typical core plugins:
+
+1. They do not run in the ``CoreM`` monad. Instead, they are explicitly passed
+ the ``HscEnv`` and they run in ``IO``.
+2. They are given ``CgGuts`` instead of ``ModGuts``. ``CgGuts`` are a restricted
+ form of ``ModGuts`` intended for code generation. The ``CoreProgram`` held in
+ the ``CgGuts`` given to a late plugin will already be fully optimized.
+3. They must maintain a ``CostCentreState`` and track any cost centres they
+ introduce by adding them to the ``cg_ccs`` field of ``CgGuts``. This is
+ because the automatic collection of cost centres happens before the late
+ plugin stage. If a late plugin does not introduce any cost centres, it may
+ simply return the given cost centre state.
+
+Here is a very simply example of a late plugin that changes the value of a
+binding in a module. If it finds a non-recursive top-level binding named
+``testBinding`` with type ``Int``, it will change its value to the ``Int``
+expression ``111111``.
+
+::
+
+ plugin :: Plugin
+ plugin = defaultPlugin { latePlugin = lateP }
+
+ lateP :: LatePlugin
+ lateP _ _ (cg_guts, cc_state) = do
+ binds' <- editCoreBinding (cg_binds cg_guts)
+ return (cg_guts { cg_binds = binds' }, cc_state)
+
+ editCoreBinding :: CoreProgram -> IO CoreProgram
+ editCoreBinding pgm = pure . go
+ where
+ go :: [CoreBind] -> [CoreBind]
+ go (b@(NonRec v e) : bs)
+ | occNameString (getOccName v) == "testBinding" && exprType e `eqType` intTy =
+ NonRec v (mkUncheckedIntExpr 111111) : bs
+ go (b:bs) = b : go bs
+ go [] = []
+
+Since this is a late plugin, the changed binding value will not end up in the
+interface file.
+
.. _getting-annotations:
Using Annotations
=====================================
testsuite/tests/plugins/Makefile
=====================================
@@ -224,3 +224,13 @@ plugins-external:
cp shared-plugin/pkg.plugins01/dist/build/$(call DLL,HSsimple-plugin*) $(call DLL,HSsimple-plugin)
"$(TEST_HC)" $(TEST_HC_OPTS) $(ghcPluginWayFlags) --make -v0 -fplugin-library "$(PWD)/$(call DLL,HSsimple-plugin);simple-plugin-1234;Simple.Plugin;[\"Plugin\",\"loaded\",\"from\",\"a shared lib\"]" plugins-external.hs
./plugins-external
+
+# Runs a plugin that is both a core plugin and a late plugin, then makes sure
+# only the changes from the core plugin end up in the interface files.
+test-late-plugin:
+ "$(TEST_HC)" $(TEST_HC_OPTS) $(ghcPluginWayFlags) -O -package ghc $@.hs
+ SHOW_IFACE="$$($(TEST_HC) --show-iface $@.hi)" ; \
+ ContainsEarlyBinding=$$(echo $$SHOW_IFACE | grep -o 111111) ; \
+ ContainsLateBinding=$$(echo $$SHOW_IFACE | grep -o 222222) ; \
+ echo "$$ContainsLateBinding" ; \
+ [ "$$ContainsEarlyBinding" = "111111" ] && [ "$$ContainLateBinding" = "" ]
=====================================
testsuite/tests/plugins/all.T
=====================================
@@ -358,3 +358,8 @@ test('test-log-hooks-plugin',
pre_cmd('$MAKE -s --no-print-directory -C hooks-plugin package.test-log-hooks-plugin TOP={top}')],
compile_fail,
['-package-db hooks-plugin/pkg.test-log-hooks-plugin/local.package.conf -fplugin Hooks.LogPlugin -package hooks-plugin ' + config.plugin_way_flags])
+
+test('test-late-plugin',
+ [extra_files(['late-plugin/LatePlugin.hs']), ignore_stdout],
+ makefile_test,
+ [])
=====================================
testsuite/tests/plugins/late-plugin/LatePlugin.hs
=====================================
@@ -0,0 +1,50 @@
+module LatePlugin where
+
+import Data.Bool
+import GHC.Core
+import GHC.Core.TyCo.Compare
+import GHC.Driver.Monad
+import GHC.Plugins
+import GHC.Types.Avail
+import GHC.Types.Var
+import GHC.Types.Id
+import System.IO
+
+-- | Both a core plugin and a late plugin. The Core plugin edits the binding in
+-- the test file (testBinding) to be the integer "111111". The late plugin then
+-- edits the binding to be the integer "222222". Then we make sure the "222222"
+-- did not make it in the interface file and the "111111" did.
+plugin :: Plugin
+plugin =
+ defaultPlugin
+ { installCoreToDos = earlyP
+ , latePlugin = lateP
+ }
+
+earlyP :: CorePlugin
+earlyP _ todos = do
+ return
+ . (: todos)
+ $ CoreDoPluginPass "earlyP"
+ $ \mgs -> liftIO $ do
+ binds' <- editCoreBinding True (moduleName (mg_module mgs)) (mg_binds mgs)
+ return mgs { mg_binds = binds' }
+
+lateP :: LatePlugin
+lateP _ opts (cg_guts, cc_state) = do
+ binds' <- editCoreBinding False (moduleName (cg_module cg_guts)) (cg_binds cg_guts)
+ return (cg_guts { cg_binds = binds' }, cc_state)
+
+editCoreBinding :: Bool -> ModuleName -> CoreProgram -> IO CoreProgram
+editCoreBinding early modName pgm = do
+ putStrLn $
+ bool "late " "early " early ++ "plugin running on module " ++
+ moduleNameString modName
+ pure $ go pgm
+ where
+ go :: [CoreBind] -> [CoreBind]
+ go (b@(NonRec v e) : bs)
+ | occNameString (getOccName v) == "testBinding" && exprType e `eqType` intTy =
+ NonRec v (mkUncheckedIntExpr $ bool 222222 111111 early) : bs
+ go (b:bs) = b : go bs
+ go [] = []
=====================================
testsuite/tests/plugins/test-late-plugin.hs
=====================================
@@ -0,0 +1,15 @@
+{-# LANGUAGE MagicHash #-}
+{-# OPTIONS_GHC -fplugin=LatePlugin #-}
+
+module TestLatePlugin (testBinding) where
+
+import GHC.Exts
+
+-- This file is edited by a core plugin at the beginning of the core pipeline so
+-- that the value of testBinding becomes 111111. Then, a late plugin edits the
+-- binding to set testBinding to 222222. The test then checks that the early
+-- binding value is what makes it into the interface file, just to be sure that
+-- changes from late plugins do not end up in interface files.
+
+testBinding :: Int
+testBinding = -1
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/45928a5cabdd6e86414e112aa69646c94c65fe03...00709bc8dc9ef5dbcc2463d4e560ffb90e895f58
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/45928a5cabdd6e86414e112aa69646c94c65fe03...00709bc8dc9ef5dbcc2463d4e560ffb90e895f58
You're receiving this email because of your account on gitlab.haskell.org.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/ghc-commits/attachments/20231217/1d97d77f/attachment-0001.html>
More information about the ghc-commits
mailing list