
[Git][ghc/ghc][wip/haanss/depdir] And the export list for TH.Syntax should obviously include addDependentDirectory now. Duh.
by Hassan Al-Awwadi (@hassan.awwadi) 05 Jul '25
by Hassan Al-Awwadi (@hassan.awwadi) 05 Jul '25
05 Jul '25
Hassan Al-Awwadi pushed to branch wip/haanss/depdir at Glasgow Haskell Compiler / GHC
Commits:
fc8e3b58 by Hassan Al-Awwadi at 2025-07-05T23:14:43+02:00
And the export list for TH.Syntax should obviously include addDependentDirectory now. Duh.
- - - - -
1 changed file:
- libraries/template-haskell/Language/Haskell/TH/Syntax.hs
Changes:
=====================================
libraries/template-haskell/Language/Haskell/TH/Syntax.hs
=====================================
@@ -32,6 +32,7 @@ module Language.Haskell.TH.Syntax (
ModName (..),
addCorePlugin,
addDependentFile,
+ addDependentDirectory,
addForeignFile,
addForeignFilePath,
addForeignSource,
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/fc8e3b5898ae04729f63973e6cbb0bd…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/fc8e3b5898ae04729f63973e6cbb0bd…
You're receiving this email because of your account on gitlab.haskell.org.
1
0

[Git][ghc/ghc][wip/haanss/depdir] the TH interface has been extended so the interface test should be updated
by Hassan Al-Awwadi (@hassan.awwadi) 05 Jul '25
by Hassan Al-Awwadi (@hassan.awwadi) 05 Jul '25
05 Jul '25
Hassan Al-Awwadi pushed to branch wip/haanss/depdir at Glasgow Haskell Compiler / GHC
Commits:
668322d8 by Hassan Al-Awwadi at 2025-07-05T23:13:26+02:00
the TH interface has been extended so the interface test should be updated
- - - - -
1 changed file:
- testsuite/tests/interface-stability/template-haskell-exports.stdout
Changes:
=====================================
testsuite/tests/interface-stability/template-haskell-exports.stdout
=====================================
@@ -1727,7 +1727,7 @@ module Language.Haskell.TH.Syntax where
qExtsEnabled :: m [Extension]
qPutDoc :: DocLoc -> GHC.Internal.Base.String -> m ()
qGetDoc :: DocLoc -> m (GHC.Internal.Maybe.Maybe GHC.Internal.Base.String)
- {-# MINIMAL qNewName, qReport, qRecover, qLookupName, qReify, qReifyFixity, qReifyType, qReifyInstances, qReifyRoles, qReifyAnnotations, qReifyModule, qReifyConStrictness, qLocation, qGetPackageRoot, qAddDependentFile, qAddTempFile, qAddTopDecls, qAddForeignFilePath, qAddModFinalizer, qAddCorePlugin, qGetQ, qPutQ, qIsExtEnabled, qExtsEnabled, qPutDoc, qGetDoc #-}
+ {-# MINIMAL qNewName, qReport, qRecover, qLookupName, qReify, qReifyFixity, qReifyType, qReifyInstances, qReifyRoles, qReifyAnnotations, qReifyModule, qReifyConStrictness, qLocation, qGetPackageRoot, qAddDependentFile, qAddDependentDirectory, qAddTempFile, qAddTopDecls, qAddForeignFilePath, qAddModFinalizer, qAddCorePlugin, qGetQ, qPutQ, qIsExtEnabled, qExtsEnabled, qPutDoc, qGetDoc #-}
type Quote :: (* -> *) -> Constraint
class GHC.Internal.Base.Monad m => Quote m where
newName :: GHC.Internal.Base.String -> m Name
@@ -1781,6 +1781,7 @@ module Language.Haskell.TH.Syntax where
type VarStrictType = VarBangType
addCorePlugin :: GHC.Internal.Base.String -> Q ()
addDependentFile :: GHC.Internal.IO.FilePath -> Q ()
+ addDependentDirectory :: GHC.Internal.IO.FilePath -> Q ()
addForeignFile :: ForeignSrcLang -> GHC.Internal.Base.String -> Q ()
addForeignFilePath :: ForeignSrcLang -> GHC.Internal.IO.FilePath -> Q ()
addForeignSource :: ForeignSrcLang -> GHC.Internal.Base.String -> Q ()
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/668322d8ec1d3cda35fcb5e9bcfb445…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/668322d8ec1d3cda35fcb5e9bcfb445…
You're receiving this email because of your account on gitlab.haskell.org.
1
0

[Git][ghc/ghc][wip/T23162-spj] This completes moving dict fundeps to the main loop
by Simon Peyton Jones (@simonpj) 05 Jul '25
by Simon Peyton Jones (@simonpj) 05 Jul '25
05 Jul '25
Simon Peyton Jones pushed to branch wip/T23162-spj at Glasgow Haskell Compiler / GHC
Commits:
0c5da224 by Simon Peyton Jones at 2025-07-05T17:45:38+01:00
This completes moving dict fundeps to the main loop
- - - - -
4 changed files:
- compiler/GHC/Tc/Solver/Dict.hs
- compiler/GHC/Tc/Solver/Equality.hs
- compiler/GHC/Tc/Solver/Monad.hs
- compiler/GHC/Tc/Solver/Solve.hs
Changes:
=====================================
compiler/GHC/Tc/Solver/Dict.hs
=====================================
@@ -10,7 +10,7 @@ module GHC.Tc.Solver.Dict (
solveCallStack, -- For GHC.Tc.Solver
-- * Functional dependencies
- generateTopFunDeps
+ doTopFunDepImprovement, doLocalFunDepImprovement
) where
import GHC.Prelude
@@ -95,7 +95,7 @@ solveDict dict_ct@(DictCt { di_ev = ev, di_cls = cls, di_tys = tys })
-- Try fundeps /after/ tryInstances:
-- see (DFL2) in Note [Do fundeps last]
- ; doLocalFunDepImprovement dict_ct
+-- ; doLocalFunDepImprovement dict_ct
-- doLocalFunDepImprovement does StartAgain if there
-- are any fundeps: see (DFL1) in Note [Do fundeps last]
@@ -1434,7 +1434,7 @@ But in general it's a bit painful to figure out the necessary coercion,
so we just take the first approach. Here is a better example. Consider:
class C a b c | a -> b
And:
- [G] d1 : C T Int Char
+ [G] d1 : C T Int Char
[W] d2 : C T beta Int
In this case, it's *not even possible* to solve the wanted immediately.
So we should simply output the functional dependency and add this guy
@@ -1630,16 +1630,23 @@ as the fundeps.
#7875 is a case in point.
-}
-generateTopFunDeps :: InstEnvs -> Cts -> [FunDepEqn (CtLoc, RewriterSet)]
+doTopFunDepImprovement :: Bag DictCt -> TcS (Cts, Bool)
+-- (doFunDeps inst_envs cts)
+-- * Generate the fundeps from interacting the
+-- top-level `inst_envs` with the constraints `cts`
+-- * Do the unifications and return any unsolved constraints
-- See Note [Fundeps with instances, and equality orientation]
-generateTopFunDeps inst_evs cts
- = foldMap do_top cts -- "RAE" `unionBags` interactions
+doTopFunDepImprovement cts
+ = do { inst_envs <- getInstEnvs
+ ; do_dict_fundeps (do_one inst_envs) cts }
where
- do_top :: Ct -> [FunDepEqn (CtLoc, RewriterSet)]
- do_top (CDictCan (DictCt { di_ev = ev, di_cls = cls, di_tys = xis }))
- = assert (not (isGiven ev)) $
- improveFromInstEnv inst_evs mk_ct_loc cls xis
+ do_one :: InstEnvs -> DictCt -> TcS (Cts, Bool)
+ do_one inst_envs (DictCt { di_ev = ev, di_cls = cls, di_tys = xis })
+ = unifyFunDepWanteds ev eqns
where
+ eqns :: [FunDepEqn (CtLoc, RewriterSet)]
+ eqns = improveFromInstEnv inst_envs mk_ct_loc cls xis
+
dict_pred = mkClassPred cls xis
dict_loc = ctEvLoc ev
dict_origin = ctLocOrigin dict_loc
@@ -1655,93 +1662,57 @@ generateTopFunDeps inst_evs cts
new_orig = FunDepOrigin2 dict_pred dict_origin
inst_pred inst_loc
- do_top _other = []
-
-
-doLocalFunDepImprovement :: DictCt -> SolverStage ()
--- Add wanted constraints from type-class functional dependencies.
-doLocalFunDepImprovement dict_ct@(DictCt { di_ev = work_ev, di_cls = cls })
- = Stage $
- do { inerts <- getInertCans
- ; imp <- foldlM add_fds False (findDictsByClass (inert_dicts inerts) cls)
- ; if imp then startAgainWith (CDictCan dict_ct)
- else continueWith () }
+doLocalFunDepImprovement :: Bag DictCt -> TcS (Cts,Bool)
+-- Add wanted constraints from type-class functional dependencies
+-- against Givens
+doLocalFunDepImprovement cts
+ = do { inerts <- getInertCans -- The inert_dicts are all Givens
+ ; do_dict_fundeps (do_one (inert_dicts inerts)) cts }
where
- work_pred = ctEvPred work_ev
- work_loc = ctEvLoc work_ev
-
- add_fds :: Bool -> DictCt -> TcS Bool
- add_fds so_far (DictCt { di_ev = inert_ev })
- | isGiven work_ev && isGiven inert_ev
- -- Do not create FDs from Given/Given interactions: See Note [No Given/Given fundeps]
- = return so_far
- | otherwise
- = do { traceTcS "doLocalFunDepImprovement" (vcat
- [ ppr work_ev
- , pprCtLoc work_loc, ppr (isGivenLoc work_loc)
- , pprCtLoc inert_loc, ppr (isGivenLoc inert_loc)
- , pprCtLoc derived_loc, ppr (isGivenLoc derived_loc) ])
-
- ; (new_eqs, unifs)
- <- unifyFunDepWanteds work_ev $
- improveFromAnother (derived_loc, inert_rewriters)
- inert_pred work_pred
-
- -- Emit the deferred constraints
- -- See Note [Work-list ordering] in GHC.Tc.Solved.Equality
- --
- -- All the constraints in `cts` share the same rewriter set so,
- -- rather than looking at it one by one, we pass it to
- -- extendWorkListChildEqs; just a small optimisation.
- ; unless (isEmptyBag cts) $
- updWorkListTcS (extendWorkListChildEqs ev new_eqs)
-
- ; return (so_far || unifs)
- }
+ do_one givens (DictCt { di_cls = cls, di_ev = wanted_ev })
+ = do_dict_fundeps do_one_given (findDictsByClass givens cls)
where
- inert_pred = ctEvPred inert_ev
- inert_loc = ctEvLoc inert_ev
- inert_rewriters = ctEvRewriters inert_ev
- derived_loc = work_loc { ctl_depth = ctl_depth work_loc `maxSubGoalDepth`
- ctl_depth inert_loc
- , ctl_origin = FunDepOrigin1 work_pred
- (ctLocOrigin work_loc)
- (ctLocSpan work_loc)
- inert_pred
- (ctLocOrigin inert_loc)
- (ctLocSpan inert_loc) }
-
-doTopFunDepImprovement :: DictCt -> SolverStage ()
--- Try to functional-dependency improvement between the constraint
--- and the top-level instance declarations
--- See Note [Fundeps with instances, and equality orientation]
--- See also Note [Weird fundeps]
-doTopFunDepImprovement dict_ct@(DictCt { di_ev = ev, di_cls = cls, di_tys = xis })
- | isGiven ev -- No improvement for Givens
- = Stage $ continueWith ()
- | otherwise
- = Stage $
- do { traceTcS "try_fundeps" (ppr dict_ct)
- ; instEnvs <- getInstEnvs
- ; let fundep_eqns = improveFromInstEnv instEnvs mk_ct_loc cls xis
- ; imp <- emitFunDepWanteds ev fundep_eqns
- ; if imp then startAgainWith (CDictCan dict_ct)
- else continueWith () }
+ wanted_pred = ctEvPred wanted_ev
+ wanted_loc = ctEvLoc wanted_ev
+
+ do_one_given :: DictCt -> TcS (Cts,Bool)
+ do_one_given (DictCt { di_ev = given_ev })
+ = do { traceTcS "doLocalFunDepImprovement" $
+ vcat [ ppr wanted_ev
+ , pprCtLoc wanted_loc, ppr (isGivenLoc wanted_loc)
+ , pprCtLoc given_loc, ppr (isGivenLoc given_loc)
+ , pprCtLoc deriv_loc, ppr (isGivenLoc deriv_loc) ]
+
+ ; unifyFunDepWanteds wanted_ev $
+ improveFromAnother (deriv_loc, given_rewriters)
+ given_pred wanted_pred }
+ where
+ given_pred = ctEvPred given_ev
+ given_loc = ctEvLoc given_ev
+ given_rewriters = ctEvRewriters given_ev
+ deriv_loc = wanted_loc { ctl_depth = deriv_depth
+ , ctl_origin = deriv_origin }
+ deriv_depth = ctl_depth wanted_loc `maxSubGoalDepth`
+ ctl_depth given_loc
+ deriv_origin = FunDepOrigin1 wanted_pred
+ (ctLocOrigin wanted_loc)
+ (ctLocSpan wanted_loc)
+ given_pred
+ (ctLocOrigin given_loc)
+ (ctLocSpan given_loc)
+
+do_dict_fundeps :: (DictCt -> TcS (Cts,Bool)) -> Bag DictCt -> TcS (Cts,Bool)
+do_dict_fundeps do_dict_fundep cts
+ = foldr do_one (return (emptyBag, False)) cts
where
- dict_pred = mkClassPred cls xis
- dict_loc = ctEvLoc ev
- dict_origin = ctLocOrigin dict_loc
- dict_rewriters = ctEvRewriters ev
-
- mk_ct_loc :: ClsInst -- The instance decl
- -> (CtLoc, RewriterSet)
- mk_ct_loc ispec
- = ( dict_loc { ctl_origin = FunDepOrigin2 dict_pred dict_origin
- inst_pred inst_loc }
- , dict_rewriters )
- where
- inst_pred = mkClassPred cls (is_tys ispec)
- inst_loc = getSrcSpan (is_dfun ispec)
+ do_one :: DictCt -> TcS (Cts,Bool) -> TcS (Cts,Bool)
+ do_one dict_ct do_rest
+ = -- assert (not (isGiven (dictCtEvidence dict_ct)) $
+ do { (cts1, unifs1) <- do_dict_fundep dict_ct
+ ; if isEmptyBag cts1 && not unifs1
+ then do_rest -- Common case
+ else do { (cts2, unifs2) <- do_rest
+ ; return (cts1 `unionBags` cts2, unifs1 || unifs2) } }
{- *********************************************************************
=====================================
compiler/GHC/Tc/Solver/Equality.hs
=====================================
@@ -118,7 +118,7 @@ solveEquality ev eq_rel ty1 ty2
; solveIrred irred_ct } ;
Right eq_ct -> do { tryInertEqs eq_ct
- ; tryFunDeps eq_rel eq_ct
+ ; tryFunDeps eq_ct
; tryQCsEqCt eq_ct
; simpleStage (updInertEqs eq_ct)
; stopWithStage (eqCtEvidence eq_ct) "Kept inert EqCt" } } }
@@ -3044,8 +3044,8 @@ equality with the template on the left. Delicate, but it works.
-}
--------------------
-tryFunDeps :: EqRel -> EqCt -> SolverStage ()
-tryFunDeps eq_rel work_item@(EqCt { eq_lhs = lhs, eq_ev = ev })
+tryFunDeps :: EqCt -> SolverStage ()
+tryFunDeps work_item@(EqCt { eq_lhs = lhs, eq_ev = ev, eq_eq_rel = eq_rel })
| NomEq <- eq_rel
, TyFamLHS tc args <- lhs
= Stage $
@@ -3264,7 +3264,7 @@ improveWantedLocalFunEqs funeqs_for_tc fam_tc args work_ev rhs
= do { traceTcS "interactFunEq improvements: " $
vcat [ text "Eqns:" <+> ppr improvement_eqns
, text "Candidates:" <+> ppr funeqs_for_tc ]
- ; emitFunDepWanteds work_ev improvement_eqns }
+ ; unifyAndEmitFunDepWanteds work_ev improvement_eqns }
where
work_loc = ctEvLoc work_ev
work_pred = ctEvPred work_ev
=====================================
compiler/GHC/Tc/Solver/Monad.hs
=====================================
@@ -105,7 +105,7 @@ module GHC.Tc.Solver.Monad (
-- Unification
wrapUnifierX, wrapUnifierTcS, unifyFunDeps, uPairsTcM, unifyForAllBody,
- unifyFunDepWanteds,
+ unifyFunDepWanteds, unifyAndEmitFunDepWanteds,
-- MetaTyVars
newFlexiTcSTy, instFlexiX,
@@ -2243,6 +2243,23 @@ solverDepthError loc ty
************************************************************************
-}
+unifyAndEmitFunDepWanteds :: CtEvidence -- The work item
+ -> [FunDepEqn (CtLoc, RewriterSet)]
+ -> TcS Bool -- True <=> some unification happened
+unifyAndEmitFunDepWanteds ev fd_eqns
+ = do { (new_eqs, unifs) <- unifyFunDepWanteds ev fd_eqns
+
+ ; -- Emit the deferred constraints
+ -- See Note [Work-list ordering] in GHC.Tc.Solved.Equality
+ --
+ -- All the constraints in `cts` share the same rewriter set so,
+ -- rather than looking at it one by one, we pass it to
+ -- extendWorkListChildEqs; just a small optimisation.
+ ; unless (isEmptyBag new_eqs) $
+ updWorkListTcS (extendWorkListChildEqs ev new_eqs)
+
+ ; return unifs }
+
unifyFunDepWanteds :: CtEvidence -- The work item
-> [FunDepEqn (CtLoc, RewriterSet)]
-> TcS (Cts, Bool) -- True <=> some unification happened
=====================================
compiler/GHC/Tc/Solver/Solve.hs
=====================================
@@ -26,7 +26,6 @@ import GHC.Tc.Types
import GHC.Tc.Types.Origin
import GHC.Tc.Types.Constraint
import GHC.Tc.Types.CtLoc( mkGivenLoc )
-import GHC.Tc.Instance.FunDeps ( FunDepEqn(..) )
import GHC.Tc.Solver.InertSet
import GHC.Tc.Solver.Monad
import GHC.Tc.Utils.Monad as TcM
@@ -47,7 +46,6 @@ import GHC.Types.Unique.Set( nonDetStrictFoldUniqSet )
import GHC.Data.Bag
import GHC.Data.Maybe
-import GHC.Data.Pair
import GHC.Utils.Outputable
import GHC.Utils.Panic
@@ -207,14 +205,21 @@ maybe_simplify_again n limit unif_happened wc@(WC { wc_simple = simples })
| otherwise
= return Nothing
+ dicts :: Bag DictCt
+ dicts = mapMaybeBag is_dict simples
+ where
+ is_dict (CDictCan d) = Just d
+ is_dict _ = Nothing
+
try_fundeps :: TcS (Maybe NextAction)
try_fundeps
- = do { inst_envs <- getInstEnvs
- ; let fundep_eqns = generateTopFunDeps inst_envs simples
- ; (new_eqs, unif_happened) <- unifyFunDepWanteds fundep_eqns
- ; if null new_eqs && not unif_happened
+ = do { (new_eqs1, unifs1) <- doTopFunDepImprovement dicts
+ ; (new_eqs2, unifs2) <- doLocalFunDepImprovement dicts
+ ; let new_eqs = new_eqs1 `unionBags` new_eqs2
+ unifs = unifs1 || unifs2
+ ; if null new_eqs && not unifs
then return Nothing
- else return (Just (NA_TryAgain (wc `addSimples` new_eqs) unif_happened)) }
+ else return (Just (NA_TryAgain (wc `addSimples` new_eqs) unifs)) }
{- Note [Superclass iteration]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/0c5da2245dd48e9f3dacefebeac4a14…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/0c5da2245dd48e9f3dacefebeac4a14…
You're receiving this email because of your account on gitlab.haskell.org.
1
0

[Git][ghc/ghc][wip/haanss/depdir] 2 commits: got letter wrong
by Hassan Al-Awwadi (@hassan.awwadi) 05 Jul '25
by Hassan Al-Awwadi (@hassan.awwadi) 05 Jul '25
05 Jul '25
Hassan Al-Awwadi pushed to branch wip/haanss/depdir at Glasgow Haskell Compiler / GHC
Commits:
582bc274 by Hassan Al-Awwadi at 2025-07-05T13:53:03+02:00
got letter wrong
- - - - -
5a6525bb by Hassan Al-Awwadi at 2025-07-05T14:11:54+02:00
more missing cases for UsageDirectory added and some clean up
- - - - -
7 changed files:
- compiler/GHC/HsToCore/Usage.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/Iface/Recomp/Types.hs
- compiler/GHC/Unit/Module/Deps.hs
- 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
Changes:
=====================================
compiler/GHC/HsToCore/Usage.hs
=====================================
@@ -31,7 +31,6 @@ import GHC.Unit.External
import GHC.Unit.Module.Imported
import GHC.Unit.Module.ModIface
import GHC.Unit.Module.Deps
-import GHC.Unit.Finder(getDirHash)
import GHC.Data.Maybe
import GHC.Data.FastString
@@ -49,8 +48,6 @@ import GHC.Types.Unique.DFM
import GHC.Driver.Plugins
import qualified GHC.Unit.Home.Graph as HUG
-import qualified System.Directory as SD
-
{- Note [Module self-dependency]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC.Rename.Names.calculateAvails asserts the invariant that a module must not occur in
=====================================
compiler/GHC/Iface/Recomp.hs
=====================================
@@ -816,6 +816,7 @@ checkModUsage fc UsageFile{ usg_file_path = file,
handler = if debugIsOn
then \e -> pprTrace "UsageFile" (text (show e)) $ return recomp
else \_ -> return recomp -- if we can't find the file, just recompile, don't fail
+
checkModUsage fc UsageDirectory{ usg_dir_path = dir,
usg_dir_hash = old_hash,
usg_dir_label = mlabel } =
@@ -829,7 +830,7 @@ checkModUsage fc UsageDirectory{ usg_dir_path = dir,
reason = DirChanged $ unpackFS dir
recomp = needsRecompileBecause $ fromMaybe reason $ fmap CustomReason mlabel
handler = if debugIsOn
- then \e -> pprTrace "UsageDir" (text (show e)) $ return recomp
+ then \e -> pprTrace "UsageDirectory" (text (show e)) $ return recomp
else \_ -> return recomp -- if we can't find the dir, just recompile, don't fail
-- | We are importing a module whose exports have changed.
=====================================
compiler/GHC/Iface/Recomp/Types.hs
=====================================
@@ -140,6 +140,10 @@ pprUsage usage@UsageFile{}
= hsep [text "addDependentFile",
doubleQuotes (ftext (usg_file_path usage)),
ppr (usg_file_hash usage)]
+pprUsage usage@UsageDirectory{}
+ = hsep [text "AddDependentDirectory",
+ doubleQuotes (ftext (usg_dir_path usage)),
+ ppr (usg_dir_hash usage)]
pprUsage usage@UsageMergedRequirement{}
= hsep [text "merged", ppr (usg_mod usage), ppr (usg_mod_hash usage)]
pprUsage usage@UsageHomeModuleInterface{}
=====================================
compiler/GHC/Unit/Module/Deps.hs
=====================================
@@ -490,7 +490,7 @@ instance Binary Usage where
dp <- get bh
hash <- get bh
label <- get bh
- return UsageDirectory { usg_dir_path = fp, usg_dir_hash = hash, usg_dir_label = label }
+ return UsageDirectory { usg_dir_path = dp, usg_dir_hash = hash, usg_dir_label = label }
i -> error ("Binary.get(Usage): " ++ show i)
=====================================
testsuite/tests/interface-stability/base-exports.stdout
=====================================
@@ -7087,7 +7087,6 @@ module GHC.Fingerprint where
fingerprintFingerprints :: [Fingerprint] -> Fingerprint
fingerprintString :: GHC.Internal.Base.String -> Fingerprint
getFileHash :: GHC.Internal.IO.FilePath -> GHC.Internal.Types.IO Fingerprint
- getDirHash :: GHC.Internal.IO.FilePath -> GHC.Internal.Types.IO Fingerprint
module GHC.Fingerprint.Type where
-- Safety: Safe
=====================================
testsuite/tests/interface-stability/base-exports.stdout-javascript-unknown-ghcjs
=====================================
@@ -7059,7 +7059,6 @@ module GHC.Fingerprint where
fingerprintFingerprints :: [Fingerprint] -> Fingerprint
fingerprintString :: GHC.Internal.Base.String -> Fingerprint
getFileHash :: GHC.Internal.IO.FilePath -> GHC.Internal.Types.IO Fingerprint
- getDirHash :: GHC.Internal.IO.FilePath -> GHC.Internal.Types.IO Fingerprint
module GHC.Fingerprint.Type where
-- Safety: Safe
=====================================
testsuite/tests/interface-stability/base-exports.stdout-mingw32
=====================================
@@ -7230,7 +7230,6 @@ module GHC.Fingerprint where
fingerprintFingerprints :: [Fingerprint] -> Fingerprint
fingerprintString :: GHC.Internal.Base.String -> Fingerprint
getFileHash :: GHC.Internal.IO.FilePath -> GHC.Internal.Types.IO Fingerprint
- getDirHash :: GHC.Internal.IO.FilePath -> GHC.Internal.Types.IO Fingerprint
module GHC.Fingerprint.Type where
-- Safety: Safe
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/e4016a66aa751eeb863b6a01680647…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/e4016a66aa751eeb863b6a01680647…
You're receiving this email because of your account on gitlab.haskell.org.
1
0

[Git][ghc/ghc][wip/haanss/depdir] Added cases for UsageDirectory in the functions rnf, put_ and get
by Hassan Al-Awwadi (@hassan.awwadi) 05 Jul '25
by Hassan Al-Awwadi (@hassan.awwadi) 05 Jul '25
05 Jul '25
Hassan Al-Awwadi pushed to branch wip/haanss/depdir at Glasgow Haskell Compiler / GHC
Commits:
e4016a66 by Hassan Al-Awwadi at 2025-07-05T13:25:30+02:00
Added cases for UsageDirectory in the functions rnf, put_ and get
- - - - -
2 changed files:
- compiler/GHC/Unit/Finder.hs
- compiler/GHC/Unit/Module/Deps.hs
Changes:
=====================================
compiler/GHC/Unit/Finder.hs
=====================================
@@ -151,7 +151,7 @@ initFinderCache = do
hash <- getDirHash key
atomicModifyIORef' dir_cache $ \c -> (M.insert key hash c, ())
return hash
- Just fp -> return fp
+ Just fp -> return fp
return FinderCache{..}
-- | This function computes a shallow hash of a directory, so really just what files and directories are directly inside it.
=====================================
compiler/GHC/Unit/Module/Deps.hs
=====================================
@@ -412,6 +412,7 @@ instance NFData Usage where
rnf (UsagePackageModule mod hash safe) = rnf mod `seq` rnf hash `seq` rnf safe `seq` ()
rnf (UsageHomeModule mod uid hash entities exports safe) = rnf mod `seq` rnf uid `seq` rnf hash `seq` rnf entities `seq` rnf exports `seq` rnf safe `seq` ()
rnf (UsageFile file hash label) = rnf file `seq` rnf hash `seq` rnf label `seq` ()
+ rnf (UsageDirectory dir hash label) = rnf dir `seq` rnf hash `seq` rnf label `seq` ()
rnf (UsageMergedRequirement mod hash) = rnf mod `seq` rnf hash `seq` ()
rnf (UsageHomeModuleInterface mod uid hash) = rnf mod `seq` rnf uid `seq` rnf hash `seq` ()
@@ -448,6 +449,12 @@ instance Binary Usage where
put_ bh (usg_unit_id usg)
put_ bh (usg_iface_hash usg)
+ put_ bh usg@UsageDirectory{} = do
+ putByte bh 5
+ put_ bh (usg_dir_path usg)
+ put_ bh (usg_dir_hash usg)
+ put_ bh (usg_dir_label usg)
+
get bh = do
h <- getByte bh
case h of
@@ -479,6 +486,12 @@ instance Binary Usage where
uid <- get bh
hash <- get bh
return UsageHomeModuleInterface { usg_mod_name = mod, usg_unit_id = uid, usg_iface_hash = hash }
+ 5 -> do
+ dp <- get bh
+ hash <- get bh
+ label <- get bh
+ return UsageDirectory { usg_dir_path = fp, usg_dir_hash = hash, usg_dir_label = label }
+
i -> error ("Binary.get(Usage): " ++ show i)
-- | Records the imports that we depend on from a home module,
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/e4016a66aa751eeb863b6a01680647e…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/e4016a66aa751eeb863b6a01680647e…
You're receiving this email because of your account on gitlab.haskell.org.
1
0

[Git][ghc/ghc][wip/haanss/depdir] this commit takes the previously defined getDirHash and moves it from...
by Hassan Al-Awwadi (@hassan.awwadi) 05 Jul '25
by Hassan Al-Awwadi (@hassan.awwadi) 05 Jul '25
05 Jul '25
Hassan Al-Awwadi pushed to branch wip/haanss/depdir at Glasgow Haskell Compiler / GHC
Commits:
0163c08f by Hassan Al-Awwadi at 2025-07-05T11:26:13+02:00
this commit takes the previously defined getDirHash and moves it from Fingerprints module to being locally defined within GHC.Unit.Finder (which is lower in the module tree that GHC.HsToCore.Usage).
This way we avoid altering GHC.Internals or base, which is maybe for the best, but one could argue it really does belong inside Fingerprint...
- - - - -
9 changed files:
- compiler/GHC/HsToCore/Usage.hs
- compiler/GHC/Iface/Recomp.hs
- compiler/GHC/Unit/Finder.hs
- compiler/GHC/Unit/Module/Deps.hs
- compiler/GHC/Utils/Fingerprint.hs
- libraries/base/src/GHC/Fingerprint.hs
- libraries/ghc-internal/src/GHC/Internal/Fingerprint.hs
- libraries/ghc-internal/src/GHC/Internal/TH/Syntax.hs
- testsuite/tests/interface-stability/base-exports.stdout-ws-32
Changes:
=====================================
compiler/GHC/HsToCore/Usage.hs
=====================================
@@ -2,7 +2,7 @@ module GHC.HsToCore.Usage (
-- * Dependency/fingerprinting code (used by GHC.Iface.Make)
mkUsageInfo, mkUsedNames,
- UsageConfig(..),
+ UsageConfig(..)
) where
import GHC.Prelude
@@ -31,6 +31,7 @@ import GHC.Unit.External
import GHC.Unit.Module.Imported
import GHC.Unit.Module.ModIface
import GHC.Unit.Module.Deps
+import GHC.Unit.Finder(getDirHash)
import GHC.Data.Maybe
import GHC.Data.FastString
@@ -48,6 +49,8 @@ import GHC.Types.Unique.DFM
import GHC.Driver.Plugins
import qualified GHC.Unit.Home.Graph as HUG
+import qualified System.Directory as SD
+
{- Note [Module self-dependency]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GHC.Rename.Names.calculateAvails asserts the invariant that a module must not occur in
=====================================
compiler/GHC/Iface/Recomp.hs
=====================================
@@ -231,6 +231,7 @@ instance Outputable RecompReason where
ModuleRemoved (_st, _uid, m) -> ppr m <+> text "removed"
ModuleAdded (_st, _uid, m) -> ppr m <+> text "added"
FileChanged fp -> text fp <+> text "changed"
+ DirChanged dp -> text dp <+> text "changed"
CustomReason s -> text s
FlagsChanged -> text "Flags changed"
LinkFlagsChanged -> text "Flags changed"
=====================================
compiler/GHC/Unit/Finder.hs
=====================================
@@ -31,6 +31,9 @@ module GHC.Unit.Finder (
findObjectLinkableMaybe,
findObjectLinkable,
+
+ -- important that GHC.HsToCore.Usage uses the same hashing method for usage dirs as is done here.
+ getDirHash,
) where
import GHC.Prelude
@@ -69,6 +72,7 @@ import GHC.Driver.Env
import GHC.Driver.Config.Finder
import qualified Data.Set as Set
import Data.List.NonEmpty ( NonEmpty (..) )
+import qualified System.Directory as SD
import qualified System.OsPath as OsPath
import qualified Data.List.NonEmpty as NE
@@ -147,10 +151,20 @@ initFinderCache = do
hash <- getDirHash key
atomicModifyIORef' dir_cache $ \c -> (M.insert key hash c, ())
return hash
- Just fp -> return fp
-
+ Just fp -> return fp
return FinderCache{..}
+-- | This function computes a shallow hash of a directory, so really just what files and directories are directly inside it.
+-- It does not look at the contents of the files, or the contents of the directories it contains.
+getDirHash :: FilePath -> IO Fingerprint
+getDirHash dir = do
+ contents <- SD.listDirectory dir
+ -- The documentation of Fingerprints describes this as an easy naive implementation
+ -- I wonder if we should do something more sophisticated here?
+ let hashes = fingerprintString <$> contents
+ let hash = fingerprintFingerprints hashes
+ return hash
+
-- -----------------------------------------------------------------------------
-- The three external entry points
=====================================
compiler/GHC/Unit/Module/Deps.hs
=====================================
@@ -368,9 +368,9 @@ data Usage
-- ^ An optional string which is used in recompilation messages if
-- dir in question has changed.
- -- Note: We this is a very shallow check, just what the contents of
- -- the directory are, aka what files and directories are within it,
- -- if those files/directories have their own contents changed...
+ -- Note: We do a very shallow check indeed, just what the contents of
+ -- the directory are, aka what files and directories are within it.
+ -- If those files/directories have their own contents changed...
-- We won't spot it here, better recursive add them to your usage
-- seperately.
}
=====================================
compiler/GHC/Utils/Fingerprint.hs
=====================================
@@ -21,7 +21,6 @@ module GHC.Utils.Fingerprint (
fingerprintString,
fingerprintStrings,
getFileHash,
- getDirHash,
) where
import GHC.Prelude.Basic
=====================================
libraries/base/src/GHC/Fingerprint.hs
=====================================
@@ -5,8 +5,7 @@ module GHC.Fingerprint (
fingerprintData,
fingerprintString,
fingerprintFingerprints,
- getFileHash,
- getDirHash,
+ getFileHash,
) where
import GHC.Internal.Fingerprint
=====================================
libraries/ghc-internal/src/GHC/Internal/Fingerprint.hs
=====================================
@@ -17,7 +17,6 @@ module GHC.Internal.Fingerprint (
fingerprintString,
fingerprintFingerprints,
getFileHash,
- getDirHash
) where
import GHC.Internal.IO
@@ -107,16 +106,6 @@ getFileHash path = withBinaryFile path ReadMode $ \h ->
in loop
--- | Computes the hash of a given file.
--- This function computes a shallow hash of a directory, so really just what files and directories are directly inside it.
--- It does not look at the contents of the files, or the contents of the directories it contains.
-getDirHash :: FilePath -> IO Fingerprint
-getDirHash dir = do
- contens <- listDirectory dir
- let hashes = fingerprintString <$> contents
- let hash = fingerprintFingerprints hashes
- return hash
-
data MD5Context
foreign import ccall unsafe "__hsbase_MD5Init"
=====================================
libraries/ghc-internal/src/GHC/Internal/TH/Syntax.hs
=====================================
@@ -836,7 +836,7 @@ getPackageRoot = Q qGetPackageRoot
--
-- * ghc -M does not know about these dependencies - it does not execute TH.
--
--- * The dependency is shallow, just a hash of its direct contents
+-- * The dependency is shallow, just a hash of its direct contents
addDependentDirectory :: FilePath -> Q ()
addDependentDirectory dp = Q (qAddDependentDirectory dp)
=====================================
testsuite/tests/interface-stability/base-exports.stdout-ws-32
=====================================
@@ -7087,7 +7087,6 @@ module GHC.Fingerprint where
fingerprintFingerprints :: [Fingerprint] -> Fingerprint
fingerprintString :: GHC.Internal.Base.String -> Fingerprint
getFileHash :: GHC.Internal.IO.FilePath -> GHC.Internal.Types.IO Fingerprint
- getDirHash :: GHC.Internal.IO.FilePath -> GHC.Internal.Types.IO Fingerprint
module GHC.Fingerprint.Type where
-- Safety: Safe
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/0163c08f28fd8cfed1623a7de91c369…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/0163c08f28fd8cfed1623a7de91c369…
You're receiving this email because of your account on gitlab.haskell.org.
1
0

05 Jul '25
Hassan Al-Awwadi pushed new branch wip/haanss/depdir at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/haanss/depdir
You're receiving this email because of your account on gitlab.haskell.org.
1
0

[Git][ghc/ghc][wip/andreask/spec_tyfams] 3 commits: Specialise: Improve specialisation by refactoring interestingDict
by Simon Peyton Jones (@simonpj) 04 Jul '25
by Simon Peyton Jones (@simonpj) 04 Jul '25
04 Jul '25
Simon Peyton Jones pushed to branch wip/andreask/spec_tyfams at Glasgow Haskell Compiler / GHC
Commits:
47feb375 by Andreas Klebinger at 2025-07-04T22:47:13+01:00
Specialise: Improve specialisation by refactoring interestingDict
This MR addresses #26051, which concerns missed type-class specialisation.
The main payload of the MR is to completely refactor the key function
`interestingDict` in GHC.Core.Opt.Specialise
The main change is that we now also look at the structure of the
dictionary we consider specializing on, rather than only the type.
See the big `Note [Interesting dictionary arguments]`
- - - - -
bdbbedae by Simon Peyton Jones at 2025-07-04T22:47:58+01:00
Treat tuple dictionaries uniformly; don't unbox them
See `Note [Do not unbox class dictionaries]` in DmdAnal.hs,
sep (DNB1).
This MR reverses the plan in #23398, which suggested a special case to
unbox tuple dictionaries in worker/wrapper. But:
- This was the cause of a pile of complexity in the specialiser (#26158)
- Even with that complexity, specialision was still bad, very bad
See https://gitlab.haskell.org/ghc/ghc/-/issues/19747#note_626297
And it's entirely unnecessary! Specialision works fine without
unboxing tuple dictionaries.
- - - - -
ae8740b3 by Andreas Klebinger at 2025-07-04T22:58:58+01:00
Remove complex special case from the type-class specialiser
There was a pretty tricky special case in Specialise which is no
longer necessary.
* Historical Note [Floating dictionaries out of cases]
* #26158
* #19747 https://gitlab.haskell.org/ghc/ghc/-/issues/19747#note_626297
This MR removes it. Hooray.
- - - - -
16 changed files:
- compiler/GHC/Core/Opt/DmdAnal.hs
- compiler/GHC/Core/Opt/Specialise.hs
- compiler/GHC/Core/Predicate.hs
- compiler/GHC/Tc/Solver.hs
- compiler/GHC/Tc/Solver/Dict.hs
- compiler/GHC/Tc/Solver/InertSet.hs
- compiler/GHC/Tc/Solver/Monad.hs
- compiler/GHC/Tc/Utils/TcType.hs
- + testsuite/tests/perf/should_run/SpecTyFamRun.hs
- + testsuite/tests/perf/should_run/SpecTyFamRun.stdout
- + testsuite/tests/perf/should_run/SpecTyFam_Import.hs
- testsuite/tests/perf/should_run/all.T
- + testsuite/tests/simplCore/should_compile/T26051.hs
- + testsuite/tests/simplCore/should_compile/T26051.stderr
- + testsuite/tests/simplCore/should_compile/T26051_Import.hs
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core/Opt/DmdAnal.hs
=====================================
@@ -23,7 +23,7 @@ import GHC.Core.DataCon
import GHC.Core.Utils
import GHC.Core.TyCon
import GHC.Core.Type
-import GHC.Core.Predicate( isEqualityClass, isCTupleClass )
+import GHC.Core.Predicate( isEqualityClass {- , isCTupleClass -} )
import GHC.Core.FVs ( rulesRhsFreeIds, bndrRuleAndUnfoldingIds )
import GHC.Core.Coercion ( Coercion )
import GHC.Core.TyCo.FVs ( coVarsOfCos )
@@ -2194,7 +2194,7 @@ doNotUnbox :: Type -> Bool
doNotUnbox arg_ty
= case tyConAppTyCon_maybe arg_ty of
Just tc | Just cls <- tyConClass_maybe tc
- -> not (isEqualityClass cls || isCTupleClass cls)
+ -> not (isEqualityClass cls)
-- See (DNB2) and (DNB1) in Note [Do not unbox class dictionaries]
_ -> False
@@ -2232,22 +2232,32 @@ TL;DR we /never/ unbox class dictionaries. Unboxing the dictionary, and passing
a raft of higher-order functions isn't a huge win anyway -- you really want to
specialise the function.
-Wrinkle (DNB1): we /do/ want to unbox tuple dictionaries (#23398)
- f :: (% Eq a, Show a %) => blah
- with -fdicts-strict it is great to unbox to
- $wf :: Eq a => Show a => blah
- (where I have written out the currying explicitly). Now we can specialise
- $wf on the Eq or Show dictionary. Nothing is lost.
-
- And something is gained. It is possible that `f` will look like this:
- f = /\a. \d:(% Eq a, Show a %). ... f @a (% sel1 d, sel2 d %)...
- where there is a recurive call to `f`, or to another function that takes the
- same tuple dictionary, but where the tuple is built from the components of
- `d`. The Simplier does not fix this. But if we unpacked the dictionary
- we'd get
- $wf = /\a. \(d1:Eq a) (d2:Show a). let d = (% d1, d2 %)
- in ...f @a (% sel1 d, sel2 d %)
- and all the tuple building and taking apart will disappear.
+Wrinkle (DNB1): we /do not/ to unbox tuple dictionaries either. We used to
+ have a special case to unbox tuple dictionaries (#23398), but it ultimately
+ turned out to be a very bad idea (see !19747#note_626297). In summary:
+
+ - If w/w unboxes tuple dictionaries we get things like
+ case d of CTuple2 d1 d2 -> blah
+ rather than
+ let { d1 = sc_sel1 d; d2 = sc_sel2 d } in blah
+ The latter works much better with the specialiser: when `d` is instantiated
+ to some useful dictionary the `sc_sel1 d` selection can fire.
+
+ - The attempt to deal with unpacking dictionaries with `case` led to
+ significant extra complexity in the type-class specialiser (#26158) that is
+ rendered unnecessary if we only take do superclass selection with superclass
+ selectors, never with `case` expressions.
+
+ Even with that extra complexity, specialisation was /still/ sometimes worse,
+ and sometimes /tremendously/ worse (a factor of 70x); see #19747.
+
+ - Suppose f :: forall a. (% Eq a, Show a %) => blah
+ The specialiser is perfectly capable of specialising a call like
+ f @Int (% dEqInt, dShowInt %)
+ so the tuple doesn't get in the way.
+
+ - It's simpler and more uniform. There is nothing special about constraint
+ tuples; anyone can write class (C1 a, C2 a) => D a where {}
Wrinkle (DNB2): we /do/ want to unbox equality dictionaries,
for (~), (~~), and Coercible (#23398). Their payload is a single unboxed
=====================================
compiler/GHC/Core/Opt/Specialise.hs
=====================================
@@ -1,3 +1,5 @@
+{-# LANGUAGE MultiWayIf #-}
+
{-
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
@@ -14,9 +16,9 @@ import GHC.Driver.Config.Diagnostic
import GHC.Driver.Config.Core.Rules ( initRuleOpts )
import GHC.Core.Type hiding( substTy, substCo, extendTvSubst, zapSubst )
-import GHC.Core.Multiplicity
-import GHC.Core.SimpleOpt( defaultSimpleOpts, simpleOptExprWith )
+import GHC.Core.SimpleOpt( defaultSimpleOpts, simpleOptExprWith, exprIsConApp_maybe )
import GHC.Core.Predicate
+import GHC.Core.Class( classMethods )
import GHC.Core.Coercion( Coercion )
import GHC.Core.Opt.Monad
import qualified GHC.Core.Subst as Core
@@ -26,12 +28,12 @@ import GHC.Core.Make ( mkLitRubbish )
import GHC.Core.Unify ( tcMatchTy )
import GHC.Core.Rules
import GHC.Core.Utils ( exprIsTrivial, exprIsTopLevelBindable
- , mkCast, exprType
+ , mkCast, exprType, exprIsHNF
, stripTicksTop, mkInScopeSetBndrs )
import GHC.Core.FVs
import GHC.Core.TyCo.FVs ( tyCoVarsOfTypeList )
import GHC.Core.Opt.Arity( collectBindersPushingCo )
--- import GHC.Core.Ppr( pprIds )
+import GHC.Core.Ppr( pprIds )
import GHC.Builtin.Types ( unboxedUnitTy )
@@ -64,8 +66,12 @@ import GHC.Unit.Module.ModGuts
import GHC.Core.Unfold
import Data.List( partition )
-import Data.List.NonEmpty ( NonEmpty (..) )
+-- import Data.List.NonEmpty ( NonEmpty (..) )
import GHC.Core.Subst (substTickish)
+import GHC.Core.TyCon (tyConClass_maybe)
+import GHC.Core.DataCon (dataConTyCon)
+
+import Control.Monad
{-
************************************************************************
@@ -1277,67 +1283,10 @@ specCase :: SpecEnv
, OutId
, [OutAlt]
, UsageDetails)
-specCase env scrut' case_bndr [Alt con args rhs]
- | -- See Note [Floating dictionaries out of cases]
- interestingDict scrut' (idType case_bndr)
- , not (isDeadBinder case_bndr && null sc_args')
- = do { case_bndr_flt :| sc_args_flt <- mapM clone_me (case_bndr' :| sc_args')
-
- ; let case_bndr_flt' = case_bndr_flt `addDictUnfolding` scrut'
- scrut_bind = mkDB (NonRec case_bndr_flt scrut')
-
- sc_args_flt' = zipWith addDictUnfolding sc_args_flt sc_rhss
- sc_rhss = [ Case (Var case_bndr_flt') case_bndr' (idType sc_arg')
- [Alt con args' (Var sc_arg')]
- | sc_arg' <- sc_args' ]
- cb_set = unitVarSet case_bndr_flt'
- sc_binds = [ DB { db_bind = NonRec sc_arg_flt sc_rhs, db_fvs = cb_set }
- | (sc_arg_flt, sc_rhs) <- sc_args_flt' `zip` sc_rhss ]
-
- flt_binds = scrut_bind : sc_binds
-
- -- Extend the substitution for RHS to map the *original* binders
- -- to their floated versions.
- mb_sc_flts :: [Maybe DictId]
- mb_sc_flts = map (lookupVarEnv clone_env) args'
- clone_env = zipVarEnv sc_args' sc_args_flt'
-
- subst_prs = (case_bndr, Var case_bndr_flt)
- : [ (arg, Var sc_flt)
- | (arg, Just sc_flt) <- args `zip` mb_sc_flts ]
- subst' = se_subst env_rhs
- `Core.extendSubstInScopeList` (case_bndr_flt' : sc_args_flt')
- `Core.extendIdSubstList` subst_prs
- env_rhs' = env_rhs { se_subst = subst' }
-
- ; (rhs', rhs_uds) <- specExpr env_rhs' rhs
- ; let (free_uds, dumped_dbs) = dumpUDs (case_bndr':args') rhs_uds
- all_uds = flt_binds `consDictBinds` free_uds
- alt' = Alt con args' (wrapDictBindsE dumped_dbs rhs')
--- ; pprTrace "specCase" (ppr case_bndr $$ ppr scrut_bind) $
- ; return (Var case_bndr_flt, case_bndr', [alt'], all_uds) }
- where
- (env_rhs, (case_bndr':|args')) = substBndrs env (case_bndr:|args)
- sc_args' = filter is_flt_sc_arg args'
-
- clone_me bndr = do { uniq <- getUniqueM
- ; return (mkUserLocalOrCoVar occ uniq wght ty loc) }
- where
- name = idName bndr
- wght = idMult bndr
- ty = idType bndr
- occ = nameOccName name
- loc = getSrcSpan name
-
- arg_set = mkVarSet args'
- is_flt_sc_arg var = isId var
- && not (isDeadBinder var)
- && isDictTy var_ty
- && tyCoVarsOfType var_ty `disjointVarSet` arg_set
- where
- var_ty = idType var
-
-
+-- We used to have a complex special case for
+-- case d of { CTuple2 d1 d2 -> blah }
+-- but we no longer do so.
+-- See Historical Note [Floating dictionaries out of cases]
specCase env scrut case_bndr alts
= do { (alts', uds_alts) <- mapAndCombineSM spec_alt alts
; return (scrut, case_bndr', alts', uds_alts) }
@@ -1346,14 +1295,11 @@ specCase env scrut case_bndr alts
spec_alt (Alt con args rhs)
= do { (rhs', uds) <- specExpr env_rhs rhs
; let (free_uds, dumped_dbs) = dumpUDs (case_bndr' : args') uds
--- ; unless (isNilOL dumped_dbs) $
--- pprTrace "specAlt" (vcat
--- [text "case_bndr', args" <+> (ppr case_bndr' $$ ppr args)
--- ,text "dumped" <+> ppr dumped_dbs ]) return ()
; return (Alt con args' (wrapDictBindsE dumped_dbs rhs'), free_uds) }
where
(env_rhs, args') = substBndrs env_alt args
+
{- Note [Fire rules in the specialiser]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (#21851)
@@ -1414,36 +1360,39 @@ Note [tryRules: plan (BEFORE)] in the Simplifier (partly) redundant. That is,
if we run rules in the specialiser, does it matter if we make rules "win" over
inlining in the Simplifier? Yes, it does! See the discussion in #21851.
-Note [Floating dictionaries out of cases]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Consider
+Historical Note [Floating dictionaries out of cases]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Function `specCase` used to give special treatment to a case-expression
+that scrutinised a dictionary, like this:
g = \d. case d of { MkD sc ... -> ...(f sc)... }
-Naively we can't float d2's binding out of the case expression,
-because 'sc' is bound by the case, and that in turn means we can't
-specialise f, which seems a pity.
-
-So we invert the case, by floating out a binding
-for 'sc_flt' thus:
- sc_flt = case d of { MkD sc ... -> sc }
-Now we can float the call instance for 'f'. Indeed this is just
-what'll happen if 'sc' was originally bound with a let binding,
-but case is more efficient, and necessary with equalities. So it's
-good to work with both.
-
-You might think that this won't make any difference, because the
-call instance will only get nuked by the \d. BUT if 'g' itself is
-specialised, then transitively we should be able to specialise f.
-
-In general, given
- case e of cb { MkD sc ... -> ...(f sc)... }
-we transform to
- let cb_flt = e
- sc_flt = case cb_flt of { MkD sc ... -> sc }
- in
- case cb_flt of bg { MkD sc ... -> ....(f sc_flt)... }
-
-The "_flt" things are the floated binds; we use the current substitution
-to substitute sc -> sc_flt in the RHS
+But actually
+
+* We never explicitly case-analyse a dictionary; rather the class-op
+ rules select superclasses from it. NB: in the past worker/wrapper
+ unboxed tuple dictionaries, but no longer; see (DNB1) in
+ Note [Do not unbox class dictionaries] in GHC.Core.Opt.DmdAnal.
+ Now it really is the case that only the class-op and superclass
+ selectors take dictionaries apart.
+
+* Calling `interestingDict` on every scrutinee is hardly sensible;
+ generally `interestingDict` is called only on Constraint-kinded things.
+
+* It was giving a Lint scope error in !14272
+
+So now there is no special case. This Note just records the change
+in case we ever want to reinstate it. The original note was
+added in
+
+ commit c107a00ccf1e641a2d008939cf477c71caa028d5
+ Author: Simon Peyton Jones <simonpj(a)microsoft.com>
+ Date: Thu Aug 12 13:11:33 2010 +0000
+
+ Improve the Specialiser, fixing Trac #4203
+
+The ticket to remove the code is #26158.
+
+End of Historical Note
+
************************************************************************
* *
@@ -1644,9 +1593,9 @@ specCalls spec_imp env existing_rules calls_for_me fn rhs
-- switch off specialisation for inline functions
= -- pprTrace "specCalls: some" (vcat
- -- [ text "function" <+> ppr fn
- -- , text "calls:" <+> ppr calls_for_me
- -- , text "subst" <+> ppr (se_subst env) ]) $
+ -- [ text "function" <+> ppr fn
+ -- , text "calls:" <+> ppr calls_for_me
+ -- , text "subst" <+> ppr (se_subst env) ]) $
foldlM spec_call ([], [], emptyUDs) calls_for_me
| otherwise -- No calls or RHS doesn't fit our preconceptions
@@ -1694,21 +1643,21 @@ specCalls spec_imp env existing_rules calls_for_me fn rhs
, rule_bndrs, rule_lhs_args
, spec_bndrs1, dx_binds, spec_args) <- specHeader env rhs_bndrs all_call_args
--- ; pprTrace "spec_call" (vcat
--- [ text "fun: " <+> ppr fn
--- , text "call info: " <+> ppr _ci
--- , text "useful: " <+> ppr useful
--- , text "rule_bndrs:" <+> ppr rule_bndrs
--- , text "lhs_args: " <+> ppr rule_lhs_args
--- , text "spec_bndrs1:" <+> ppr spec_bndrs1
--- , text "leftover_bndrs:" <+> pprIds leftover_bndrs
--- , text "spec_args: " <+> ppr spec_args
--- , text "dx_binds: " <+> ppr dx_binds
--- , text "rhs_bndrs" <+> ppr rhs_bndrs
--- , text "rhs_body" <+> ppr rhs_body
--- , text "rhs_env2: " <+> ppr (se_subst rhs_env2)
--- , ppr dx_binds ]) $
--- return ()
+ ; when False $ pprTrace "spec_call" (vcat
+ [ text "fun: " <+> ppr fn
+ , text "call info: " <+> ppr _ci
+ , text "useful: " <+> ppr useful
+ , text "rule_bndrs:" <+> ppr rule_bndrs
+ , text "lhs_args: " <+> ppr rule_lhs_args
+ , text "spec_bndrs1:" <+> ppr spec_bndrs1
+ , text "leftover_bndrs:" <+> pprIds leftover_bndrs
+ , text "spec_args: " <+> ppr spec_args
+ , text "dx_binds: " <+> ppr dx_binds
+ , text "rhs_bndrs" <+> ppr rhs_bndrs
+ , text "rhs_body" <+> ppr rhs_body
+ , text "rhs_env2: " <+> ppr (se_subst rhs_env2)
+ , ppr dx_binds ]) $
+ return ()
; let all_rules = rules_acc ++ existing_rules
-- all_rules: we look both in the rules_acc (generated by this invocation
@@ -3102,30 +3051,14 @@ mkCallUDs' env f args
-- For "invisibleFunArg", which are the type-class dictionaries,
-- we decide on a case by case basis if we want to specialise
-- on this argument; if so, SpecDict, if not UnspecArg
- mk_spec_arg arg (Anon pred af)
+ mk_spec_arg arg (Anon _pred af)
| isInvisibleFunArg af
- , interestingDict arg (scaledThing pred)
+ , interestingDict env arg
-- See Note [Interesting dictionary arguments]
= SpecDict arg
| otherwise = UnspecArg
-{-
-Note [Ticks on applications]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Ticks such as source location annotations can sometimes make their way
-onto applications (see e.g. #21697). So if we see something like
-
- App (Tick _ f) e
-
-we need to descend below the tick to find what the real function being
-applied is.
-
-The resulting RULE also has to be able to match this annotated use
-site, so we only look through ticks that RULE matching looks through
-(see Note [Tick annotations in RULE matching] in GHC.Core.Rules).
--}
-
wantCallsFor :: SpecEnv -> Id -> Bool
-- See Note [wantCallsFor]
wantCallsFor _env f
@@ -3145,8 +3078,60 @@ wantCallsFor _env f
WorkerLikeId {} -> True
RepPolyId {} -> True
-{- Note [wantCallsFor]
-~~~~~~~~~~~~~~~~~~~~~~
+interestingDict :: SpecEnv -> CoreExpr -> Bool
+-- This is a subtle and important function
+-- See Note [Interesting dictionary arguments]
+interestingDict env (Var v) -- See (ID3) and (ID5)
+ | Just rhs <- maybeUnfoldingTemplate (idUnfolding v)
+ -- Might fail for loop breaker dicts but that seems fine.
+ = interestingDict env rhs
+
+interestingDict env arg -- Main Plan: use exprIsConApp_maybe
+ | Cast inner_arg _ <- arg -- See (ID5)
+ = if | isConstraintKind $ typeKind $ exprType inner_arg
+ -- If coercions were always homo-kinded, we'd know
+ -- that this would be the only case
+ -> interestingDict env inner_arg
+
+ -- Check for an implicit parameter at the top
+ | Just (cls,_) <- getClassPredTys_maybe arg_ty
+ , isIPClass cls -- See (ID4)
+ -> False
+
+ -- Otherwise we are unwrapping a unary type class
+ | otherwise
+ -> exprIsHNF arg -- See (ID7)
+
+ | Just (_, _, data_con, _tys, args) <- exprIsConApp_maybe in_scope_env arg
+ , Just cls <- tyConClass_maybe (dataConTyCon data_con)
+ , not_ip_like -- See (ID4)
+ = if null (classMethods cls) -- See (ID6)
+ then any (interestingDict env) args
+ else True
+
+ | otherwise
+ = not (exprIsTrivial arg) && not_ip_like -- See (ID8)
+ where
+ arg_ty = exprType arg
+ not_ip_like = not (couldBeIPLike arg_ty)
+ in_scope_env = ISE (substInScopeSet $ se_subst env) realIdUnfolding
+
+{- Note [Ticks on applications]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Ticks such as source location annotations can sometimes make their way
+onto applications (see e.g. #21697). So if we see something like
+
+ App (Tick _ f) e
+
+we need to descend below the tick to find what the real function being
+applied is.
+
+The resulting RULE also has to be able to match this annotated use
+site, so we only look through ticks that RULE matching looks through
+(see Note [Tick annotations in RULE matching] in GHC.Core.Rules).
+
+Note [wantCallsFor]
+~~~~~~~~~~~~~~~~~~~
`wantCallsFor env f` says whether the Specialiser should collect calls for
function `f`; other thing being equal, the fewer calls we collect the better. It
is False for things we can't specialise:
@@ -3172,44 +3157,91 @@ collect usage info for imported overloaded functions.
Note [Interesting dictionary arguments]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-In `mkCallUDs` we only use `SpecDict` for dictionaries of which
-`interestingDict` holds. Otherwise we use `UnspecArg`. Two reasons:
-
-* Consider this
- \a.\d:Eq a. let f = ... in ...(f d)...
- There really is not much point in specialising f wrt the dictionary d,
- because the code for the specialised f is not improved at all, because
- d is lambda-bound. We simply get junk specialisations.
-
-* Consider this (#25703):
- f :: (Eq a, Show b) => a -> b -> INt
- goo :: forall x. (Eq x) => x -> blah
- goo @x (d:Eq x) (arg:x) = ...(f @x @Int d $fShowInt)...
- If we built a `ci_key` with a (SpecDict d) for `d`, we would end up
- discarding the call at the `\d`. But if we use `UnspecArg` for that
- uninteresting `d`, we'll get a `ci_key` of
- f @x @Int UnspecArg (SpecDict $fShowInt)
- and /that/ can float out to f's definition and specialise nicely.
- Hooray. (NB: the call can float only if `-fpolymorphic-specialisation`
- is on; otherwise it'll be trapped by the `\@x -> ...`.)(
-
-What is "interesting"? (See `interestingDict`.) Just that it has *some*
-structure. But what about variables? We look in the variable's /unfolding/.
-And that means that we must be careful to ensure that dictionaries /have/
-unfoldings,
-
-* cloneBndrSM discards non-Stable unfoldings
-* specBind updates the unfolding after specialisation
- See Note [Update unfolding after specialisation]
-* bindAuxiliaryDict adds an unfolding for an aux dict
- see Note [Specialisation modulo dictionary selectors]
-* specCase adds unfoldings for the new bindings it creates
-
-We accidentally lost accurate tracking of local variables for a long
-time, because cloned variables didn't have unfoldings. But makes a
-massive difference in a few cases, eg #5113. For nofib as a
-whole it's only a small win: 2.2% improvement in allocation for ansi,
-1.2% for bspt, but mostly 0.0! Average 0.1% increase in binary size.
+Consider this
+ \a.\d:Eq a. let f = ... in ...(f d)...
+There really is not much point in specialising f wrt the dictionary d,
+because the code for the specialised f is not improved at all, because
+d is lambda-bound. We simply get junk specialisations.
+
+What is "interesting"? Our Main Plan is to use `exprIsConApp_maybe` to see
+if the argument is a dictionary constructor applied to some arguments, in which
+case we can clearly specialise. But there are wrinkles:
+
+(ID1) Note that we look at the argument /term/, not its /type/. Suppose the
+ argument is
+ (% d1, d2 %) |> co
+ where co :: (% Eq [a], Show [a] %) ~ F Int a, and `F` is a type family.
+ Then its type (F Int a) looks very un-informative, but the term is super
+ helpful. See #19747 (where missing this point caused a 70x slow down)
+ and #7785.
+
+(ID2) Note that the Main Plan works fine for an argument that is a DFun call,
+ e.g. $fOrdList $dOrdInt
+ because `exprIsConApp_maybe` cleverly deals with DFunId applications. Good!
+
+(ID3) For variables, we look in the variable's /unfolding/. And that means
+ that we must be careful to ensure that dictionaries /have/ unfoldings:
+ * cloneBndrSM discards non-Stable unfoldings
+ * specBind updates the unfolding after specialisation
+ See Note [Update unfolding after specialisation]
+ * bindAuxiliaryDict adds an unfolding for an aux dict
+ see Note [Specialisation modulo dictionary selectors]
+ * specCase adds unfoldings for the new bindings it creates
+
+ We accidentally lost accurate tracking of local variables for a long
+ time, because cloned variables didn't have unfoldings. But makes a
+ massive difference in a few cases, eg #5113. For nofib as a
+ whole it's only a small win: 2.2% improvement in allocation for ansi,
+ 1.2% for bspt, but mostly 0.0! Average 0.1% increase in binary size.
+
+(ID4) We must be very careful not to specialise on a "dictionary" that is, or contains
+ an implicit parameter, because implicit parameters are emphatically not singleton
+ types. See #25999:
+ useImplicit :: (?i :: Int) => Int
+ useImplicit = ?i + 1
+
+ foo = let ?i = 1 in (useImplicit, let ?i = 2 in useImplicit)
+ Both calls to `useImplicit` are at type `?i::Int`, but they pass different values.
+ We must not specialise on implicit parameters! Hence the call to `couldBeIPLike`.
+
+(ID5) Suppose the argument is (e |> co). Can we rely on `exprIsConApp_maybe` to deal
+ with the coercion. No! That only works if (co :: C t1 ~ C t2) with the same type
+ constructor at the top of both sides. But see the example in (ID1), where that
+ is not true. For thes same reason, we can't rely on `exprIsConApp_maybe` to look
+ through unfoldings (because there might be a cast inside), hence dealing with
+ expandable unfoldings in `interestingDict` directly.
+
+(ID6) The Main Plan says that it's worth specialising if the argument is an application
+ of a dictionary contructor. But what if the dictionary has no methods? Then we
+ gain nothing by specialising, unless the /superclasses/ are interesting. A case
+ in point is constraint tuples (% d1, .., dn %); a constraint N-tuple is a class
+ with N superclasses and no methods.
+
+(ID7) A unary (single-method) class is currently represented by (meth |> co). We
+ will unwrap the cast (see (ID5)) and then want to reply "yes" if the method
+ has any struture. We rather arbitrarily use `exprIsHNF` for this. (We plan a
+ new story for unary classes, see #23109, and this special case will become
+ irrelevant.)
+
+(ID8) Sadly, if `exprIsConApp_maybe` says Nothing, we still want to treat a
+ non-trivial argument as interesting. In T19695 we have this:
+ askParams :: Monad m => blah
+ mhelper :: MonadIO m => blah
+ mhelper (d:MonadIO m) = ...(askParams @m ($p1 d))....
+ where `$p1` is the superclass selector for `MonadIO`. Now, if `mhelper` is
+ specialised at `Handler` we'll get this call in the specialised `$smhelper`:
+ askParams @Handler ($p1 $fMonadIOHandler)
+ and we /definitely/ want to specialise that, even though the argument isn't
+ visibly a dictionary application. In fact the specialiser fires the superclass
+ selector rule (see Note [Fire rules in the specialiser]), so we get
+ askParams @Handler ($cp1MonadIO $fMonadIOIO)
+ but it /still/ doesn't look like a dictionary application.
+
+ Conclusion: we optimistically assume that any non-trivial argument is worth
+ specialising on.
+
+ So why do the `exprIsConApp_maybe` and `Cast` stuff? Because we want to look
+ under type-family casts (ID1) and constraint tuples (ID6).
Note [Update unfolding after specialisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -3237,6 +3269,7 @@ Consider (#21848)
Now `f` turns into:
f @a @b (dd :: D a) (ds :: Show b) a b
+
= let dc :: D a = %p1 dd -- Superclass selection
in meth @a dc ....
meth @a dc ....
@@ -3252,27 +3285,6 @@ in the NonRec case of specBind. (This is too exotic to trouble with
the Rec case.)
-}
-interestingDict :: CoreExpr -> Type -> Bool
--- A dictionary argument is interesting if it has *some* structure,
--- see Note [Interesting dictionary arguments]
--- NB: "dictionary" arguments include constraints of all sorts,
--- including equality constraints; hence the Coercion case
--- To make this work, we need to ensure that dictionaries have
--- unfoldings in them.
-interestingDict arg arg_ty
- | not (typeDeterminesValue arg_ty) = False -- See Note [Type determines value]
- | otherwise = go arg
- where
- go (Var v) = hasSomeUnfolding (idUnfolding v)
- || isDataConWorkId v
- go (Type _) = False
- go (Coercion _) = False
- go (App fn (Type _)) = go fn
- go (App fn (Coercion _)) = go fn
- go (Tick _ a) = go a
- go (Cast e _) = go e
- go _ = True
-
thenUDs :: UsageDetails -> UsageDetails -> UsageDetails
thenUDs (MkUD {ud_binds = db1, ud_calls = calls1})
(MkUD {ud_binds = db2, ud_calls = calls2})
=====================================
compiler/GHC/Core/Predicate.hs
=====================================
@@ -24,7 +24,7 @@ module GHC.Core.Predicate (
classMethodTy, classMethodInstTy,
-- Implicit parameters
- isIPLikePred, mentionsIP, isIPTyCon, isIPClass,
+ couldBeIPLike, mightMentionIP, isIPTyCon, isIPClass,
isCallStackTy, isCallStackPred, isCallStackPredTy,
isExceptionContextPred, isExceptionContextTy,
isIPPred_maybe,
@@ -126,9 +126,12 @@ isDictTy ty = isClassPred pred
where
(_, pred) = splitInvisPiTys ty
+-- | Is the type *guaranteed* to determine the value?
+--
+-- Might say No even if the type does determine the value. (See the Note)
typeDeterminesValue :: Type -> Bool
-- See Note [Type determines value]
-typeDeterminesValue ty = isDictTy ty && not (isIPLikePred ty)
+typeDeterminesValue ty = isDictTy ty && not (couldBeIPLike ty)
getClassPredTys :: HasDebugCallStack => PredType -> (Class, [Type])
getClassPredTys ty = case getClassPredTys_maybe ty of
@@ -171,6 +174,10 @@ So we treat implicit params just like ordinary arguments for the
purposes of specialisation. Note that we still want to specialise
functions with implicit params if they have *other* dicts which are
class params; see #17930.
+
+It's also not always possible to infer that a type determines the value
+if type families are in play. See #19747 for one such example.
+
-}
-- --------------------- Equality predicates ---------------------------------
@@ -421,44 +428,44 @@ isCallStackTy ty
| otherwise
= False
--- --------------------- isIPLike and mentionsIP --------------------------
+-- --------------------- couldBeIPLike and mightMentionIP --------------------------
-- See Note [Local implicit parameters]
-isIPLikePred :: Type -> Bool
+couldBeIPLike :: Type -> Bool
-- Is `pred`, or any of its superclasses, an implicit parameter?
-- See Note [Local implicit parameters]
-isIPLikePred pred =
- mentions_ip_pred initIPRecTc (const True) (const True) pred
-
-mentionsIP :: (Type -> Bool) -- ^ predicate on the string
- -> (Type -> Bool) -- ^ predicate on the type
- -> Class
- -> [Type] -> Bool
--- ^ @'mentionsIP' str_cond ty_cond cls tys@ returns @True@ if:
+couldBeIPLike pred
+ = might_mention_ip1 initIPRecTc (const True) (const True) pred
+
+mightMentionIP :: (Type -> Bool) -- ^ predicate on the string
+ -> (Type -> Bool) -- ^ predicate on the type
+ -> Class
+ -> [Type] -> Bool
+-- ^ @'mightMentionIP' str_cond ty_cond cls tys@ returns @True@ if:
--
-- - @cls tys@ is of the form @IP str ty@, where @str_cond str@ and @ty_cond ty@
-- are both @True@,
-- - or any superclass of @cls tys@ has this property.
--
-- See Note [Local implicit parameters]
-mentionsIP = mentions_ip initIPRecTc
+mightMentionIP = might_mention_ip initIPRecTc
-mentions_ip :: RecTcChecker -> (Type -> Bool) -> (Type -> Bool) -> Class -> [Type] -> Bool
-mentions_ip rec_clss str_cond ty_cond cls tys
+might_mention_ip :: RecTcChecker -> (Type -> Bool) -> (Type -> Bool) -> Class -> [Type] -> Bool
+might_mention_ip rec_clss str_cond ty_cond cls tys
| Just (str_ty, ty) <- isIPPred_maybe cls tys
= str_cond str_ty && ty_cond ty
| otherwise
- = or [ mentions_ip_pred rec_clss str_cond ty_cond (classMethodInstTy sc_sel_id tys)
+ = or [ might_mention_ip1 rec_clss str_cond ty_cond (classMethodInstTy sc_sel_id tys)
| sc_sel_id <- classSCSelIds cls ]
-mentions_ip_pred :: RecTcChecker -> (Type -> Bool) -> (Type -> Bool) -> Type -> Bool
-mentions_ip_pred rec_clss str_cond ty_cond ty
+might_mention_ip1 :: RecTcChecker -> (Type -> Bool) -> (Type -> Bool) -> Type -> Bool
+might_mention_ip1 rec_clss str_cond ty_cond ty
| Just (cls, tys) <- getClassPredTys_maybe ty
, let tc = classTyCon cls
, Just rec_clss' <- if isTupleTyCon tc then Just rec_clss
else checkRecTc rec_clss tc
- = mentions_ip rec_clss' str_cond ty_cond cls tys
+ = might_mention_ip rec_clss' str_cond ty_cond cls tys
| otherwise
= False -- Includes things like (D []) where D is
-- a Constraint-ranged family; #7785
@@ -471,7 +478,7 @@ initIPRecTc = setRecTcMaxBound 1 initRecTc
See also wrinkle (SIP1) in Note [Shadowing of implicit parameters] in
GHC.Tc.Solver.Dict.
-The function isIPLikePred tells if this predicate, or any of its
+The function couldBeIPLike tells if this predicate, or any of its
superclasses, is an implicit parameter.
Why are implicit parameters special? Unlike normal classes, we can
@@ -479,7 +486,7 @@ have local instances for implicit parameters, in the form of
let ?x = True in ...
So in various places we must be careful not to assume that any value
of the right type will do; we must carefully look for the innermost binding.
-So isIPLikePred checks whether this is an implicit parameter, or has
+So couldBeIPLike checks whether this is an implicit parameter, or has
a superclass that is an implicit parameter.
Several wrinkles
@@ -520,16 +527,16 @@ Small worries (Sept 20):
think nothing does.
* I'm a little concerned about type variables; such a variable might
be instantiated to an implicit parameter. I don't think this
- matters in the cases for which isIPLikePred is used, and it's pretty
+ matters in the cases for which couldBeIPLike is used, and it's pretty
obscure anyway.
* The superclass hunt stops when it encounters the same class again,
but in principle we could have the same class, differently instantiated,
and the second time it could have an implicit parameter
I'm going to treat these as problems for another day. They are all exotic.
-Note [Using typesAreApart when calling mentionsIP]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-We call 'mentionsIP' in two situations:
+Note [Using typesAreApart when calling mightMentionIP]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+We call 'mightMentionIP' in two situations:
(1) to check that a predicate does not contain any implicit parameters
IP str ty, for a fixed literal str and any type ty,
=====================================
compiler/GHC/Tc/Solver.hs
=====================================
@@ -1914,7 +1914,7 @@ growThetaTyVars theta tcvs
| otherwise = transCloVarSet mk_next seed_tcvs
where
seed_tcvs = tcvs `unionVarSet` tyCoVarsOfTypes ips
- (ips, non_ips) = partition isIPLikePred theta
+ (ips, non_ips) = partition couldBeIPLike theta
-- See Note [Inheriting implicit parameters]
mk_next :: VarSet -> VarSet -- Maps current set to newly-grown ones
=====================================
compiler/GHC/Tc/Solver/Dict.hs
=====================================
@@ -749,7 +749,7 @@ shortCutSolver dflags ev_w ev_i
-- programs should typecheck regardless of whether we take this step or
-- not. See Note [Shortcut solving]
- , not (isIPLikePred (ctEvPred ev_w)) -- Not for implicit parameters (#18627)
+ , not (couldBeIPLike (ctEvPred ev_w)) -- Not for implicit parameters (#18627)
, not (xopt LangExt.IncoherentInstances dflags)
-- If IncoherentInstances is on then we cannot rely on coherence of proofs
=====================================
compiler/GHC/Tc/Solver/InertSet.hs
=====================================
@@ -2040,10 +2040,10 @@ solveOneFromTheOther ct_i ct_w
is_wsc_orig_w = isWantedSuperclassOrigin orig_w
different_level_strategy -- Both Given
- | isIPLikePred pred = if lvl_w `strictlyDeeperThan` lvl_i then KeepWork else KeepInert
- | otherwise = if lvl_w `strictlyDeeperThan` lvl_i then KeepInert else KeepWork
+ | couldBeIPLike pred = if lvl_w `strictlyDeeperThan` lvl_i then KeepWork else KeepInert
+ | otherwise = if lvl_w `strictlyDeeperThan` lvl_i then KeepInert else KeepWork
-- See Note [Replacement vs keeping] part (1)
- -- For the isIPLikePred case see Note [Shadowing of implicit parameters]
+ -- For the couldBeIPLike case see Note [Shadowing of implicit parameters]
-- in GHC.Tc.Solver.Dict
same_level_strategy -- Both Given
=====================================
compiler/GHC/Tc/Solver/Monad.hs
=====================================
@@ -401,8 +401,8 @@ updInertDicts dict_ct@(DictCt { di_cls = cls, di_ev = ev, di_tys = tys })
-- an implicit parameter (?str :: ty) for the given 'str' and any type 'ty'?
does_not_mention_ip_for :: Type -> DictCt -> Bool
does_not_mention_ip_for str_ty (DictCt { di_cls = cls, di_tys = tys })
- = not $ mentionsIP (not . typesAreApart str_ty) (const True) cls tys
- -- See Note [Using typesAreApart when calling mentionsIP]
+ = not $ mightMentionIP (not . typesAreApart str_ty) (const True) cls tys
+ -- See Note [Using typesAreApart when calling mightMentionIP]
-- in GHC.Core.Predicate
updInertIrreds :: IrredCt -> TcS ()
@@ -534,7 +534,7 @@ updSolvedDicts what dict_ct@(DictCt { di_cls = cls, di_tys = tys, di_ev = ev })
= do { is_callstack <- is_tyConTy isCallStackTy callStackTyConName
; is_exceptionCtx <- is_tyConTy isExceptionContextTy exceptionContextTyConName
; let contains_callstack_or_exceptionCtx =
- mentionsIP
+ mightMentionIP
(const True)
-- NB: the name of the call-stack IP is irrelevant
-- e.g (?foo :: CallStack) counts!
@@ -552,9 +552,9 @@ updSolvedDicts what dict_ct@(DictCt { di_cls = cls, di_tys = tys, di_ev = ev })
-- Return a predicate that decides whether a type is CallStack
-- or ExceptionContext, accounting for e.g. type family reduction, as
- -- per Note [Using typesAreApart when calling mentionsIP].
+ -- per Note [Using typesAreApart when calling mightMentionIP].
--
- -- See Note [Using isCallStackTy in mentionsIP].
+ -- See Note [Using isCallStackTy in mightMentionIP].
is_tyConTy :: (Type -> Bool) -> Name -> TcS (Type -> Bool)
is_tyConTy is_eq tc_name
= do { (mb_tc, _) <- wrapTcS $ TcM.tryTc $ TcM.tcLookupTyCon tc_name
@@ -582,14 +582,14 @@ in a different context!
See also Note [Shadowing of implicit parameters], which deals with a similar
problem with Given implicit parameter constraints.
-Note [Using isCallStackTy in mentionsIP]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Note [Using isCallStackTy in mightMentionIP]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To implement Note [Don't add HasCallStack constraints to the solved set],
we need to check whether a constraint contains a HasCallStack or HasExceptionContext
constraint. We do this using the 'mentionsIP' function, but as per
-Note [Using typesAreApart when calling mentionsIP] we don't want to simply do:
+Note [Using typesAreApart when calling mightMentionIP] we don't want to simply do:
- mentionsIP
+ mightMentionIP
(const True) -- (ignore the implicit parameter string)
(isCallStackTy <||> isExceptionContextTy)
=====================================
compiler/GHC/Tc/Utils/TcType.hs
=====================================
@@ -155,7 +155,7 @@ module GHC.Tc.Utils.TcType (
mkTyConTy, mkTyVarTy, mkTyVarTys,
mkTyCoVarTy, mkTyCoVarTys,
- isClassPred, isEqPred, isIPLikePred, isEqClassPred,
+ isClassPred, isEqPred, couldBeIPLike, isEqClassPred,
isEqualityClass, mkClassPred,
tcSplitQuantPredTy, tcSplitDFunTy, tcSplitDFunHead, tcSplitMethodTy,
isRuntimeRepVar, isFixedRuntimeRepKind,
@@ -1819,7 +1819,7 @@ pickCapturedPreds
pickCapturedPreds qtvs theta
= filter captured theta
where
- captured pred = isIPLikePred pred || (tyCoVarsOfType pred `intersectsVarSet` qtvs)
+ captured pred = couldBeIPLike pred || (tyCoVarsOfType pred `intersectsVarSet` qtvs)
-- Superclasses
=====================================
testsuite/tests/perf/should_run/SpecTyFamRun.hs
=====================================
@@ -0,0 +1,15 @@
+{-# OPTIONS_GHC -fspecialise-aggressively #-}
+{-# OPTIONS_GHC -fno-spec-constr #-}
+module Main(main) where
+
+import SpecTyFam_Import (specMe, MaybeShowNum)
+import GHC.Exts
+
+-- We want to see a specialization of `specMe` which doesn't take a dictionary at runtime.
+
+{-# NOINLINE foo #-}
+foo :: Int -> (String,Int)
+-- We want specMe to be specialized, but not inlined
+foo x = specMe True x
+
+main = print $ sum $ map (snd . foo) [1..1000 :: Int]
=====================================
testsuite/tests/perf/should_run/SpecTyFamRun.stdout
=====================================
@@ -0,0 +1 @@
+500500
=====================================
testsuite/tests/perf/should_run/SpecTyFam_Import.hs
=====================================
@@ -0,0 +1,13 @@
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE BangPatterns #-}
+
+module SpecTyFam_Import (specMe, MaybeShowNum) where
+
+import Data.Kind
+
+type family MaybeShowNum a n :: Constraint where
+ MaybeShowNum a n = (Show a, Num n)
+
+{-# INLINABLE specMe #-}
+specMe :: (Integral n, MaybeShowNum a n) => a -> n -> (String,n)
+specMe s !n = (show s, n+1 `div` 2)
=====================================
testsuite/tests/perf/should_run/all.T
=====================================
@@ -423,3 +423,12 @@ test('ByteCodeAsm',
],
compile_and_run,
['-package ghc'])
+
+# Check that $s$wspecMe doesn't have any dictionary args after specialization in addition to perf stats
+# See also #19747
+test('SpecTyFamRun', [ grep_errmsg(r'foo')
+ , extra_files(['SpecTyFam_Import.hs'])
+ , only_ways(['optasm'])
+ , collect_stats('bytes allocated', 5)],
+ multimod_compile_and_run,
+ ['SpecTyFamRun', '-O2'])
=====================================
testsuite/tests/simplCore/should_compile/T26051.hs
=====================================
@@ -0,0 +1,15 @@
+{-# OPTIONS_GHC -fspecialise-aggressively #-}
+{-# OPTIONS_GHC -fno-spec-constr #-}
+
+module T26051(main, foo) where
+
+import T26051_Import (specMe, MaybeShowNum)
+import GHC.Exts
+
+-- We want to see a specialization of `specMe` which doesn't take a dictionary at runtime.
+
+{-# OPAQUE foo #-}
+foo :: Int -> (String,Int)
+foo x = specMe True x
+
+main = print $ sum $ map (snd . foo) [1..1000 :: Int]
=====================================
testsuite/tests/simplCore/should_compile/T26051.stderr
=====================================
@@ -0,0 +1,78 @@
+[1 of 2] Compiling T26051_Import ( T26051_Import.hs, T26051_Import.o )
+
+==================== Specialise ====================
+Result size of Specialise = {terms: 31, types: 39, coercions: 8, joins: 0/1}
+
+-- RHS size: {terms: 30, types: 27, coercions: 8, joins: 0/1}
+specMe [InlPrag=INLINABLE] :: forall n a. (Integral n, MaybeShowNum a n) => a -> n -> (String, n)
+[LclIdX,
+ Arity=4,
+ Unf=Unf{Src=StableUser, TopLvl=True, Value=True, ConLike=True, WorkFree=True, Expandable=True, Guidance=IF_ARGS [30 0 0 20] 260 10
+ Tmpl= \ (@n) (@a) ($dIntegral [Occ=Once1] :: Integral n) (irred :: MaybeShowNum a n) (eta [Occ=Once1] :: a) (eta [Occ=Once1] :: n) ->
+ let {
+ $dNum :: Num n
+ [LclId, Unf=Unf{Src=<vanilla>, TopLvl=False, Value=False, ConLike=False, WorkFree=False, Expandable=True, Guidance=IF_ARGS [] 20 0}]
+ $dNum = GHC.Internal.Classes.$p1CTuple2 @(Show a) @(Num n) (irred `cast` (Sub (T26051_Import.D:R:MaybeShowNum[0] <a>_N <n>_N) :: MaybeShowNum a n ~R# (Show a, Num n))) } in
+ case eta of n [Occ=Once1] { __DEFAULT -> (show @a (GHC.Internal.Classes.$p0CTuple2 @(Show a) @(Num n) (irred `cast` (Sub (T26051_Import.D:R:MaybeShowNum[0] <a>_N <n>_N) :: MaybeShowNum a n ~R# (Show a, Num n)))) eta, + @n $dNum n (div @n $dIntegral (fromInteger @n $dNum (GHC.Internal.Bignum.Integer.IS 1#)) (fromInteger @n $dNum (GHC.Internal.Bignum.Integer.IS 2#)))) }}]
+specMe
+ = \ (@n) (@a) ($dIntegral :: Integral n) (irred :: MaybeShowNum a n) (eta :: a) (eta :: n) ->
+ let {
+ $dNum :: Num n
+ [LclId, Unf=Unf{Src=<vanilla>, TopLvl=False, Value=False, ConLike=False, WorkFree=False, Expandable=True, Guidance=IF_ARGS [] 20 0}]
+ $dNum = GHC.Internal.Classes.$p1CTuple2 @(Show a) @(Num n) (irred `cast` (Sub (T26051_Import.D:R:MaybeShowNum[0] <a>_N <n>_N) :: MaybeShowNum a n ~R# (Show a, Num n))) } in
+ case eta of n { __DEFAULT -> (show @a (GHC.Internal.Classes.$p0CTuple2 @(Show a) @(Num n) (irred `cast` (Sub (T26051_Import.D:R:MaybeShowNum[0] <a>_N <n>_N) :: MaybeShowNum a n ~R# (Show a, Num n)))) eta, + @n $dNum n (div @n $dIntegral (fromInteger @n $dNum (GHC.Internal.Bignum.Integer.IS 1#)) (fromInteger @n $dNum (GHC.Internal.Bignum.Integer.IS 2#)))) }
+
+
+
+[2 of 2] Compiling T26051 ( T26051.hs, T26051.o )
+
+==================== Specialise ====================
+Result size of Specialise = {terms: 84, types: 86, coercions: 13, joins: 0/1}
+
+Rec {
+-- RHS size: {terms: 3, types: 4, coercions: 0, joins: 0/0}
+$dCTuple2 :: (Show Bool, Num Int)
+[LclId, Unf=Unf{Src=<vanilla>, TopLvl=False, Value=True, ConLike=True, WorkFree=True, Expandable=True, Guidance=IF_ARGS [] 10 10}]
+$dCTuple2 = (GHC.Internal.Show.$fShowBool, GHC.Internal.Num.$fNumInt)
+
+-- RHS size: {terms: 19, types: 9, coercions: 0, joins: 0/1}
+$s$wspecMe [InlPrag=INLINABLE[2]] :: Bool -> Int -> (# String, Int #)
+[LclId, Arity=2]
+$s$wspecMe
+ = \ (eta [Occ=Once1] :: Bool) (eta1 [Occ=Once1] :: Int) ->
+ let {
+ $dNum :: Num Int
+ [LclId, Unf=Unf{Src=<vanilla>, TopLvl=False, Value=True, ConLike=True, WorkFree=True, Expandable=True, Guidance=ALWAYS_IF(arity=0,unsat_ok=True,boring_ok=True)}]
+ $dNum = GHC.Internal.Num.$fNumInt } in
+ case eta1 of n1 [Occ=Once1] { __DEFAULT -> (# GHC.Internal.Show.$fShowBool_$cshow eta, GHC.Internal.Num.$fNumInt_$c+ n1 (GHC.Internal.Real.$fIntegralInt_$cdiv (GHC.Internal.Num.$fNumInt_$cfromInteger (GHC.Internal.Bignum.Integer.IS 1#)) (GHC.Internal.Num.$fNumInt_$cfromInteger (GHC.Internal.Bignum.Integer.IS 2#))) #) }
+
+-- RHS size: {terms: 12, types: 13, coercions: 5, joins: 0/0}
+$sspecMe [InlPrag=INLINABLE[2]] :: Bool -> Int -> (String, Int)
+[LclId,
+ Arity=2,
+ Unf=Unf{Src=StableSystem, TopLvl=True, Value=True, ConLike=True, WorkFree=True, Expandable=True, Guidance=ALWAYS_IF(arity=2,unsat_ok=True,boring_ok=False)
+ Tmpl= \ (eta [Occ=Once1] :: Bool) (eta1 [Occ=Once1] :: Int) -> case T26051_Import.$wspecMe @Int @Bool GHC.Internal.Real.$fIntegralInt ($dCTuple2 `cast` (Sub (Sym (T26051_Import.D:R:MaybeShowNum[0] <Bool>_N <Int>_N)) :: (Show Bool, Num Int) ~R# MaybeShowNum Bool Int)) eta eta1 of { (# ww [Occ=Once1], ww1 [Occ=Once1] #) -> (ww, ww1) }}]
+$sspecMe = \ (eta [Occ=Once1] :: Bool) (eta1 [Occ=Once1] :: Int) -> case T26051_Import.$wspecMe @Int @Bool GHC.Internal.Real.$fIntegralInt ($dCTuple2 `cast` (Sub (Sym (T26051_Import.D:R:MaybeShowNum[0] <Bool>_N <Int>_N)) :: (Show Bool, Num Int) ~R# MaybeShowNum Bool Int)) eta eta1 of { (# ww [Occ=Once1], ww1 [Occ=Once1] #) -> (ww, ww1) }
+end Rec }
+
+-- RHS size: {terms: 6, types: 3, coercions: 5, joins: 0/0}
+foo [InlPrag=OPAQUE] :: Int -> (String, Int)
+[LclIdX, Arity=1, Unf=Unf{Src=<vanilla>, TopLvl=False, Value=True, ConLike=True, WorkFree=True, Expandable=True, Guidance=IF_ARGS [0] 50 0}]
+foo = \ (x :: Int) -> specMe @Int @Bool GHC.Internal.Real.$fIntegralInt ($dCTuple2 `cast` (Sub (Sym (T26051_Import.D:R:MaybeShowNum[0] <Bool>_N <Int>_N)) :: (Show Bool, Num Int) ~R# MaybeShowNum Bool Int)) GHC.Internal.Types.True x
+
+-- RHS size: {terms: 37, types: 26, coercions: 0, joins: 0/0}
+main :: State# RealWorld -> (# State# RealWorld, () #)
+[LclId, Arity=1, Unf=Unf{Src=<vanilla>, TopLvl=False, Value=True, ConLike=True, WorkFree=True, Expandable=True, Guidance=IF_ARGS [0] 301 0}]
+main = \ (eta [OS=OneShot] :: State# RealWorld) -> GHC.Internal.IO.Handle.Text.hPutStr2 GHC.Internal.IO.StdHandles.stdout (case GHC.Internal.Enum.eftIntFB @(Int -> Int) (GHC.Internal.Base.mapFB @Int @(Int -> Int) @Int (\ (ds :: Int) (ds1 [OS=OneShot] :: Int -> Int) (v [OS=OneShot] :: Int) -> case v of { I# ipv -> ds1 (case ds of { I# y -> GHC.Internal.Types.I# (+# ipv y) }) }) (\ (x :: Int) -> case foo x of { (_ [Occ=Dead], y) -> y })) (breakpoint @Int) 1# 1000# (GHC.Internal.Types.I# 0#) of { I# n -> GHC.Internal.Show.itos n (GHC.Internal.Types.[] @Char) }) GHC.Internal.Types.True eta
+
+-- RHS size: {terms: 1, types: 0, coercions: 3, joins: 0/0}
+main :: IO ()
+[LclIdX, Arity=1, Unf=Unf{Src=<vanilla>, TopLvl=False, Value=True, ConLike=True, WorkFree=True, Expandable=True, Guidance=ALWAYS_IF(arity=0,unsat_ok=True,boring_ok=True)}]
+main = main `cast` (Sym (GHC.Internal.Types.N:IO <()>_R) :: (State# RealWorld -> (# State# RealWorld, () #)) ~R# IO ())
+
+
+------ Local rules for imported ids --------
+"SPEC/T26051 $wspecMe @Int @Bool" [2] forall ($dIntegral :: Integral Int) (irred :: MaybeShowNum Bool Int). T26051_Import.$wspecMe @Int @Bool $dIntegral irred = $s$wspecMe
+"SPEC/T26051 specMe @Int @Bool" [2] forall ($dIntegral :: Integral Int) (irred :: MaybeShowNum Bool Int). specMe @Int @Bool $dIntegral irred = $sspecMe
+
+
=====================================
testsuite/tests/simplCore/should_compile/T26051_Import.hs
=====================================
@@ -0,0 +1,14 @@
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE ImplicitParams #-}
+
+module T26051_Import (specMe, MaybeShowNum) where
+
+import Data.Kind
+
+type family MaybeShowNum a n :: Constraint where
+ MaybeShowNum a n = (Show a, Num n)
+
+{-# INLINABLE specMe #-}
+specMe :: (Integral n, MaybeShowNum a n) => a -> n -> (String,n)
+specMe s !n = (show s, n+1 `div` 2)
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -548,3 +548,9 @@ test('T25965', normal, compile, ['-O'])
test('T25703', [grep_errmsg(r'SPEC')], compile, ['-O -fpolymorphic-specialisation -ddump-rule-firings'])
test('T25703a', [grep_errmsg(r'SPEC')], compile, ['-O -fpolymorphic-specialisation -ddump-rule-firings'])
+# Check that $s$wspecMe doesn't have any dictionary args after specialization in addition to perf stats
+test('T26051', [ grep_errmsg(r'\$wspecMe')
+ , extra_files(['T26051_Import.hs'])
+ , only_ways(['optasm'])],
+ multimod_compile,
+ ['T26051', '-O2 -ddump-spec -dsuppress-uniques -dno-typeable-binds -dppr-cols=1000'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/3db11f250db73518752615c5a0439f…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/3db11f250db73518752615c5a0439f…
You're receiving this email because of your account on gitlab.haskell.org.
1
0

04 Jul '25
Cheng Shao pushed to branch wip/symbolizer at Glasgow Haskell Compiler / GHC
Commits:
237b7508 by Cheng Shao at 2025-07-04T21:04:36+00:00
rts: remove libbfd logic
- - - - -
9 changed files:
- configure.ac
- hadrian/cfg/system.config.in
- hadrian/src/Oracles/Flag.hs
- hadrian/src/Settings/Packages.hs
- − m4/fp_bfd_support.m4
- rts/Printer.c
- rts/configure.ac
- rts/include/rts/Config.h
- rts/rts.cabal
Changes:
=====================================
configure.ac
=====================================
@@ -868,9 +868,6 @@ AC_SUBST([UseLibm])
TargetHasLibm=$UseLibm
AC_SUBST(TargetHasLibm)
-FP_BFD_FLAG
-AC_SUBST([UseLibbfd])
-
dnl ################################################################
dnl Check for libraries
dnl ################################################################
=====================================
hadrian/cfg/system.config.in
=====================================
@@ -120,7 +120,6 @@ use-lib-numa = @UseLibNuma@
use-lib-m = @UseLibm@
use-lib-rt = @UseLibrt@
use-lib-dl = @UseLibdl@
-use-lib-bfd = @UseLibbfd@
use-lib-pthread = @UseLibpthread@
need-libatomic = @NeedLibatomic@
=====================================
hadrian/src/Oracles/Flag.hs
=====================================
@@ -37,7 +37,6 @@ data Flag = CrossCompiling
| UseLibm
| UseLibrt
| UseLibdl
- | UseLibbfd
| UseLibpthread
| NeedLibatomic
| UseGhcToolchain
@@ -61,7 +60,6 @@ flag f = do
UseLibm -> "use-lib-m"
UseLibrt -> "use-lib-rt"
UseLibdl -> "use-lib-dl"
- UseLibbfd -> "use-lib-bfd"
UseLibpthread -> "use-lib-pthread"
NeedLibatomic -> "need-libatomic"
UseGhcToolchain -> "use-ghc-toolchain"
=====================================
hadrian/src/Settings/Packages.hs
=====================================
@@ -440,7 +440,6 @@ rtsPackageArgs = package rts ? do
, useSystemFfi `cabalFlag` "use-system-libffi"
, useLibffiForAdjustors `cabalFlag` "libffi-adjustors"
, flag UseLibpthread `cabalFlag` "need-pthread"
- , flag UseLibbfd `cabalFlag` "libbfd"
, flag NeedLibatomic `cabalFlag` "need-atomic"
, flag UseLibdw `cabalFlag` "libdw"
, flag UseLibnuma `cabalFlag` "libnuma"
=====================================
m4/fp_bfd_support.m4 deleted
=====================================
@@ -1,59 +0,0 @@
-# FP_BFD_SUPPORT()
-# ----------------------
-# Whether to use libbfd for debugging RTS
-#
-# Sets:
-# UseLibbfd: [YES|NO]
-AC_DEFUN([FP_BFD_FLAG], [
- UseLibbfd=NO
- AC_ARG_ENABLE(bfd-debug,
- [AS_HELP_STRING([--enable-bfd-debug],
- [Enable symbol resolution for -debug rts ('+RTS -Di') via binutils' libbfd [default=no]])],
- [UseLibbfd=YES],
- [UseLibbfd=NO])
-])
-
-# FP_WHEN_ENABLED_BFD
-# ----------------------
-# Checks for libraries in the default way, which will define various
-# `HAVE_*` macros.
-AC_DEFUN([FP_WHEN_ENABLED_BFD], [
- # don't pollute general LIBS environment
- save_LIBS="$LIBS"
- AC_CHECK_HEADERS([bfd.h])
- dnl ** check whether this machine has BFD and libiberty installed (used for debugging)
- dnl the order of these tests matters: bfd needs libiberty
- AC_CHECK_LIB(iberty, xmalloc)
- dnl 'bfd_init' is a rare non-macro in libbfd
- AC_CHECK_LIB(bfd, bfd_init)
-
- AC_LINK_IFELSE(
- [AC_LANG_PROGRAM(
- [[#include <bfd.h>]],
- [[
- /* mimic our rts/Printer.c */
- bfd* abfd;
- const char * name;
- char **matching;
-
- name = "some.executable";
- bfd_init();
- abfd = bfd_openr(name, "default");
- bfd_check_format_matches (abfd, bfd_object, &matching);
- {
- long storage_needed;
- storage_needed = bfd_get_symtab_upper_bound (abfd);
- }
- {
- asymbol **symbol_table;
- long number_of_symbols;
- symbol_info info;
-
- number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
- bfd_get_symbol_info(abfd,symbol_table[0],&info);
- }
- ]])],
- [], dnl bfd seems to work
- [AC_MSG_ERROR([can't use 'bfd' library])])
- LIBS="$save_LIBS"
-])
=====================================
rts/Printer.c
=====================================
@@ -872,110 +872,11 @@ const char *lookupGHCName( void *addr )
* Symbol table loading
* ------------------------------------------------------------------------*/
-/* Causing linking trouble on Win32 plats, so I'm
- disabling this for now.
-*/
-#if defined(USING_LIBBFD)
-# define PACKAGE 1
-# define PACKAGE_VERSION 1
-/* Those PACKAGE_* defines are workarounds for bfd:
- * https://sourceware.org/bugzilla/show_bug.cgi?id=14243
- * ghc's build system filter PACKAGE_* values out specifically to avoid clashes
- * with user's autoconf-based Cabal packages.
- * It's a shame <bfd.h> checks for unrelated fields instead of actually used
- * macros.
- */
-# include <bfd.h>
-
-/* Fairly ad-hoc piece of code that seems to filter out a lot of
- * rubbish like the obj-splitting symbols
- */
-
-static bool isReal( flagword flags STG_UNUSED, const char *name )
-{
-#if 0
- /* ToDo: make this work on BFD */
- int tp = type & N_TYPE;
- if (tp == N_TEXT || tp == N_DATA) {
- return (name[0] == '_' && name[1] != '_');
- } else {
- return false;
- }
-#else
- if (*name == '\0' ||
- (name[0] == 'g' && name[1] == 'c' && name[2] == 'c') ||
- (name[0] == 'c' && name[1] == 'c' && name[2] == '.')) {
- return false;
- }
- return true;
-#endif
-}
-
-extern void DEBUG_LoadSymbols( const char *name )
-{
- bfd* abfd;
- char **matching;
-
- bfd_init();
- abfd = bfd_openr(name, "default");
- if (abfd == NULL) {
- barf("can't open executable %s to get symbol table", name);
- }
- if (!bfd_check_format_matches (abfd, bfd_object, &matching)) {
- barf("mismatch");
- }
-
- {
- long storage_needed;
- asymbol **symbol_table;
- long number_of_symbols;
- long num_real_syms = 0;
- long i;
-
- storage_needed = bfd_get_symtab_upper_bound (abfd);
-
- if (storage_needed < 0) {
- barf("can't read symbol table");
- }
- symbol_table = (asymbol **) stgMallocBytes(storage_needed,"DEBUG_LoadSymbols");
-
- number_of_symbols = bfd_canonicalize_symtab (abfd, symbol_table);
-
- if (number_of_symbols < 0) {
- barf("can't canonicalise symbol table");
- }
-
- if (add_to_fname_table == NULL)
- add_to_fname_table = allocHashTable();
-
- for( i = 0; i != number_of_symbols; ++i ) {
- symbol_info info;
- bfd_get_symbol_info(abfd,symbol_table[i],&info);
- if (isReal(info.type, info.name)) {
- insertHashTable(add_to_fname_table,
- info.value, (void*)info.name);
- num_real_syms += 1;
- }
- }
-
- IF_DEBUG(interpreter,
- debugBelch("Loaded %ld symbols. Of which %ld are real symbols\n",
- number_of_symbols, num_real_syms)
- );
-
- stgFree(symbol_table);
- }
-}
-
-#else /* USING_LIBBFD */
-
extern void DEBUG_LoadSymbols( const char *name STG_UNUSED )
{
/* nothing, yet */
}
-#endif /* USING_LIBBFD */
-
void findPtr(P_ p, int); /* keep gcc -Wall happy */
int searched = 0;
=====================================
rts/configure.ac
=====================================
@@ -171,8 +171,6 @@ AS_IF(
[test "$CABAL_FLAG_libm" = 1],
[AC_DEFINE([HAVE_LIBM], [1], [Define to 1 if you need to link with libm])])
-AS_IF([test "$CABAL_FLAG_libbfd" = 1], [FP_WHEN_ENABLED_BFD])
-
dnl ################################################################
dnl Check for libraries
dnl ################################################################
=====================================
rts/include/rts/Config.h
=====================================
@@ -19,13 +19,6 @@
#error TICKY_TICKY is incompatible with THREADED_RTS
#endif
-/*
- * Whether the runtime system will use libbfd for debugging purposes.
- */
-#if defined(DEBUG) && defined(HAVE_BFD_H) && defined(HAVE_LIBBFD) && !defined(_WIN32)
-#define USING_LIBBFD 1
-#endif
-
/*
* We previously only offer the eventlog in a subset of RTS ways; we now
* enable it unconditionally to simplify packaging. See #18948.
@@ -101,4 +94,3 @@ code.
#else
#define CACHELINE_SIZE 64
#endif
-
=====================================
rts/rts.cabal
=====================================
@@ -46,9 +46,6 @@ flag libffi-adjustors
flag need-pthread
default: False
manual: True
-flag libbfd
- default: False
- manual: True
flag need-atomic
default: False
manual: True
@@ -250,9 +247,6 @@ library
if flag(need-atomic)
-- for sub-word-sized atomic operations (#19119)
extra-libraries: atomic
- if flag(libbfd)
- -- for debugging
- extra-libraries: bfd iberty
if flag(libdw)
-- for backtraces
extra-libraries: elf dw
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/237b750831434016450e320ff6e2462…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/237b750831434016450e320ff6e2462…
You're receiving this email because of your account on gitlab.haskell.org.
1
0
Cheng Shao pushed new branch wip/symbolizer at Glasgow Haskell Compiler / GHC
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/tree/wip/symbolizer
You're receiving this email because of your account on gitlab.haskell.org.
1
0