Simon Peyton Jones pushed to branch wip/T28169 at Glasgow Haskell Compiler / GHC Commits: 1daa8f40 by Simon Peyton Jones at 2026-11-25T12:39:53+00:00 I think this is done Fixes #28183 too Needs a commit message - - - - - 21 changed files: - compiler/GHC/Builtin/WiredIn/Types.hs - compiler/GHC/Core/DataCon.hs - compiler/GHC/Core/FamInstEnv.hs - compiler/GHC/Core/Opt/DmdAnal.hs - compiler/GHC/Core/Opt/Simplify/Iteration.hs - compiler/GHC/Core/Opt/SpecConstr.hs - compiler/GHC/Core/Opt/WorkWrap/Utils.hs - compiler/GHC/Core/SimpleOpt.hs - compiler/GHC/Core/TyCon.hs - compiler/GHC/Core/Type.hs - compiler/GHC/Core/Utils.hs - compiler/GHC/Tc/Gen/HsType.hs - compiler/GHC/Tc/Gen/Pat.hs - compiler/GHC/Tc/TyCl.hs - compiler/GHC/Tc/TyCl/Build.hs - compiler/GHC/Tc/TyCl/Instance.hs - compiler/GHC/Tc/TyCl/Utils.hs - compiler/GHC/Types/Id/Make.hs - compiler/GHC/Utils/Misc.hs - + testsuite/tests/simplCore/should_compile/T28169.hs - testsuite/tests/simplCore/should_compile/all.T Changes: ===================================== compiler/GHC/Builtin/WiredIn/Types.hs ===================================== @@ -626,7 +626,7 @@ typeSymbolKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Symbol") pcTyCon :: Name -> Maybe (CType GhcTc) -> [TyVar] -> [DataCon] -> TyCon pcTyCon name cType tyvars cons = mkAlgTyCon name (mkTyConKind bndrs res_kind) bndrs 0 res_kind - (map (const Representational) tyvars) + (mapConst Representational tyvars) cType [] -- No stupid theta (mkDataTyConRhs cons) @@ -717,9 +717,10 @@ pcDataConWithFixity' declared_infix dc_name wrk_key rri -- we call pcDataConWithFixity' with static TyCons in the same module. -- See Note [Constructor tag allocation] and #14657 data_con = mkDataCon dc_name declared_infix prom_info - (map (const no_bang) arg_tys) - (map (const HsLazy) arg_tys) - (map (const NotMarkedStrict) arg_tys) + (mapConst no_bang arg_tys) + (mapConst HsLazy arg_tys) + (mapConst NotMarkedStrict theta ++ + mapConst NotMarkedStrict arg_tys) [] -- No labelled fields tyvars ex_tyvars conc_tyvars ===================================== compiler/GHC/Core/DataCon.hs ===================================== @@ -44,7 +44,7 @@ module GHC.Core.DataCon ( dataConIsInfix, dataConWorkId, dataConWrapId, dataConWrapId_maybe, dataConImplicitTyThings, - dataConRepStrictness, + dataConRepStrictness, dataConRepFullStrictness, dataConImplBangs, dataConBoxer, dataConRepIsLazy, @@ -524,9 +524,9 @@ data DataCon dcStricts :: [StrictnessMark], -- One mark for every field of the DataCon /worker/ - -- Lines up 1-1 with dataConRepArgTys + -- INVARIANT: length dcStricts = length dataConRepArgTys -- Relates only to user-specified strictness annotations, - -- not to liftedness or othewrise + -- not to liftedness or otherwise -- E.g. data T a = MkT {-# UNPACK #-} !(S a) Int# !a -- data S a = MkS a !a -- Then the worker for MkT has four fields, the first two arising from @@ -535,6 +535,12 @@ data DataCon -- See also Note [Strict fields in Core] in GHC.Core -- for the effect on the strictness signature + dcFullStricts :: [StrictnessMark], + -- Just like dcStricts, but preceded by one NotMarkedStrict + -- for each CoVar in dcExTyCoVars + -- INVARIANT: length dcFullStricts = dataConRepArity + -- See (EXCO1) Note [Existential coercion variables] + dcFields :: [FieldLabel], -- Field labels for this constructor, in the -- same order as the dcOrigArgTys; @@ -543,7 +549,7 @@ data DataCon dcIsLazy :: Bool, -- True if (a) all fields of the data con /worker/ are definitely lifted -- (b) no field has a `StrictnessMark` that forces evaluation - -- So if `dcIsLazy` is True then all fields of the worker are lazy thunks + -- So if `dcIsLazy` is True then all fields of the worker are lazy thunks -- The curried worker function that corresponds to the constructor: -- It doesn't have an unfolding; the code generator saturates these Ids @@ -593,18 +599,29 @@ we can in Core. Consider having: data T :: forall k. k -> k -> Constraint where MkT :: forall k (a::k) (b::k). - forall k' (c::k') (co::k'~k). - (b ~# (c|>co)) => T k a b + forall k' (c::k') (co::k'~#k). + (b ~# (c|>co)) => !a -> T k a b dcUnivTyVars = [k,a,b] dcExTyCoVars = [k',c,co] dcUserTyVarBinders = [k,a,k',c] dcEqSpec = [b ~# (c|>co)] dcOtherTheta = [] - dcOrigArgTys = [] + dcOrigArgTys = [a] dcRepTyCon = T + dcStricts = [MarkedStrict] + dcFullStricts = [NotMarkedStrict, MarkedStrict] -- (EXCO1) + +* `dataConKindEqSpec` returns [k'~k]. +* `dataConRepArgTys` returns [ b~#(c|>co), a ] + +(EXCO1) In a call of the data constructor worker we will see + MkT tk ta tb tk' tc (co1::tk'~#tk) (co2::tb~#(tc |> co1)) + dcFullStricts returns a [StrictnessMark] that lines up with all the + value arguments, /including/ co1 -Function call 'dataConKindEqSpec' returns [k'~k] + dcFullStricts = dcStricts almost always; they differ only in the + rare case that we have existential coercion variables Note [DataCon arities] ~~~~~~~~~~~~~~~~~~~~~~ @@ -864,7 +881,8 @@ type DataConEnv a = UniqFM DataCon a -- Keyed by DataCon -- In the AST, the @SourceText@ is hidden inside the extension point -- 'Language.Haskell.Syntax.Extension.XConDeclField'. data HsSrcBang - = HsSrcBang SourceText SrcUnpackedness SrcStrictness -- See Note [Pragma source text] in "GHC.Types.SourceText" + = HsSrcBang SourceText SrcUnpackedness SrcStrictness + -- See Note [Pragma source text] in "GHC.Types.SourceText" deriving Data.Data -- | Haskell Implementation Bang @@ -872,14 +890,14 @@ data HsSrcBang -- Bangs of data constructor arguments as generated by the compiler -- after consulting HsSrcBang, flags, etc. data HsImplBang - = HsLazy -- ^ Lazy field, or one with an unlifted type + = HsLazy -- ^ Lazy field, or one with an unlifted type + | HsStrict Bool -- ^ Strict but not unpacked field - -- True <=> we could have unpacked, but opted not to - -- because of -O0. - -- See Note [Detecting useless UNPACK pragmas] - | HsUnpack (Maybe Coercion) - -- ^ Strict and unpacked field - -- co :: arg-ty ~ product-ty HsBang + -- True <=> we could have unpacked, but opted not to because of -O0 + -- See Note [Detecting useless UNPACK pragmas] + + | HsUnpack (Maybe Coercion) -- ^ Strict and unpacked field + -- co :: arg-ty ~ product-ty HsBang deriving Data.Data @@ -961,9 +979,8 @@ Terminology: you the demand signature of the wrapper, if it exists. These demand signatures are set in GHC.Types.Id.Make.mkDataConWorkId, - computed from the single source of truth `dataConRepStrictness`, which is - generated from `dcStricts`. - Note that `dataConRepStrictness` lines up 1-1 with `idDmdSig (dataConWorkId dc)`. + computed from the single source of truth `dataConRepFullStrictness`. + So `dataConRepFullStrictness` lines up 1-1 with `idDmdSig (dataConWorkId dc)`. Note [Detecting useless UNPACK pragmas] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1129,7 +1146,7 @@ mkDataCon name declared_infix prom_info impl_bangs -- Must match orig_arg_tys 1-1 str_marks -- Must be empty or match dataConRepArgTys 1-1 fields - univ_tvs ex_tvs conc_tvs user_tvbs + univ_tvs ex_tcvs conc_tvs user_tvbs eq_spec theta orig_arg_tys orig_res_ty rep_info rep_tycon tag stupid_theta work_id rep @@ -1143,7 +1160,7 @@ mkDataCon name declared_infix prom_info = con where - is_vanilla = null ex_tvs && null eq_spec && null theta + is_vanilla = null ex_tcvs && null eq_spec && null theta is_lazy = not (any isMarkedStrict str_marks) && all (definitelyLiftedType . scaledThing) rep_arg_tys @@ -1154,7 +1171,7 @@ mkDataCon name declared_infix prom_info , dcVanilla = is_vanilla , dcUnivTyVars = univ_tvs - , dcExTyCoVars = ex_tvs + , dcExTyCoVars = ex_tcvs , dcConcreteTyVars = conc_tvs , dcUserTyVarBinders = user_tvbs , dcEqSpec = eq_spec @@ -1171,18 +1188,20 @@ mkDataCon name declared_infix prom_info , dcStricts = assertPpr (equalLength str_marks rep_arg_tys) (ppr name <+> ppr str_marks) str_marks + , dcFullStricts = replicate n_ex_co_vars NotMarkedStrict ++ str_marks , dcIsLazy = is_lazy , dcFields = fields , dcWorkId = work_id , dcSourceArity = length orig_arg_tys - , dcRepArity = length rep_arg_tys + count isCoVar ex_tvs + , dcRepArity = n_ex_co_vars + length rep_arg_tys , dcPromoted = promoted } -- The 'arg_stricts' passed to mkDataCon are simply those for the -- source-language arguments. We add extra ones for the -- dictionary arguments right here. - rep_arg_tys = dataConRepArgTys con + n_ex_co_vars = count isCoVar ex_tcvs + rep_arg_tys = dataConRepArgTys con rep_ty = case rep of -- If the DataCon has no wrapper, then the worker's type *is* the @@ -1190,7 +1209,7 @@ mkDataCon name declared_infix prom_info NoDataConRep -> dataConWrapperType con -- If the DataCon has a wrapper, then the worker's type is never seen -- by the user. The visibilities we pick do not matter here. - DCR{} -> mkInfForAllTys univ_tvs $ mkTyCoInvForAllTys ex_tvs $ + DCR{} -> mkInfForAllTys univ_tvs $ mkTyCoInvForAllTys ex_tcvs $ mkScaledFunctionTys rep_arg_tys $ mkTyConApp rep_tycon (mkTyVarTys univ_tvs) -- res_arg_tys is a mixture of TypeLike and ConstraintLike, @@ -1213,8 +1232,8 @@ mkDataCon name declared_infix prom_info prom_res_kind roles rep_info roles = map (\tv -> if isTyVar tv then Nominal else Phantom) - (univ_tvs ++ ex_tvs) - ++ map (const Representational) (theta ++ map scaledThing orig_arg_tys) + (univ_tvs ++ ex_tcvs) + ++ mapConst Representational (theta ++ map scaledThing orig_arg_tys) freshNames :: [Name] -> [Name] -- Make an infinite list of Names whose Uniques and OccNames @@ -1422,9 +1441,15 @@ isNullaryRepDataCon dc = dataConRepArity dc == 0 dataConRepStrictness :: DataCon -> [StrictnessMark] -- ^ Give the demands on the runtime arguments of a Core DataCon worker --- application. Maches 1-1 with `dataConRepArgTys` +-- application. Matches 1-1 with `dataConRepArgTys` dataConRepStrictness = dcStricts +dataConRepFullStrictness :: DataCon -> [StrictnessMark] +-- ^ Give the demands on the runtime arguments of a Core DataCon worker +-- application, /including/ any existential CoVar args +-- See (EXCO1) in Note [Existential coercion variables] +dataConRepFullStrictness = dcFullStricts + dataConRepIsLazy :: DataCon -> Bool dataConRepIsLazy = dcIsLazy @@ -1537,10 +1562,11 @@ dataConWrapperType (MkData { dcUserTyVarBinders = user_tvbs, res_ty -- | Finds the instantiated types of the arguments required to construct a --- 'DataCon' representation +-- data constructor worker application -- NB: these INCLUDE any dictionary args --- but EXCLUDE the data-declaration context, which is discarded --- It's all post-flattening etc; this is a representation type +-- but EXCLUDE the "stupid theta" data-declaration context, which is discarded +-- +-- Result list is 1-1 with dataConRepArgTys, and dataConRepStrictness dataConInstArgTys :: DataCon -- ^ A datacon with no existentials or equality constraints -- However, it can have a dcTheta (notably it can be a -- class dictionary, with superclasses) @@ -1635,9 +1661,10 @@ dataConOrigArgTys dc = dcOrigArgTys dc dataConOtherTheta :: DataCon -> ThetaType dataConOtherTheta dc = dcOtherTheta dc --- | Returns the arg types of the worker, including *all* non-dependent --- evidence, after any flattening has been done and without substituting for --- any type variables +-- | Returns the arg types of the worker, after any flattening has been done and +-- without substituting for any type variables +-- +-- Includes evidence, namely `dcEqSpec` and `dcOtherTheta` dataConRepArgTys :: DataCon -> [Scaled Type] dataConRepArgTys (MkData { dcRep = rep , dcEqSpec = eq_spec @@ -1656,8 +1683,10 @@ dataConRepArgTys (MkData { dcRep = rep -- I think it's because of the call in mkDataCon, which in turn feeds -- into dcRepArity, which in turn is used in mkDataConWorkId. -- c.f. #23022 - | otherwise -> assert (null eq_spec) $ - map unrestricted theta ++ orig_arg_tys + | otherwise -> assert (null eq_spec) $ + -- null eq_spec: all GADTs go via DCR + -- See `dataConUserTyVarsNeedWrapper` + map unrestricted theta ++ orig_arg_tys -- | The string @package:module.name@ identifying a constructor, which is attached -- to its info table and used by the GHCi debugger and the heap profiler ===================================== compiler/GHC/Core/FamInstEnv.hs ===================================== @@ -828,7 +828,7 @@ mkSingleCoAxiom role ax_name tvs eta_tvs cvs fam_tc lhs_tys rhs_ty -- Note [Storing compatibility] where branch = mkCoAxBranch tvs eta_tvs cvs lhs_tys rhs_ty - (map (const Nominal) tvs) + (mapConst Nominal tvs) (getSrcSpan ax_name) -- | Create a coercion constructor (axiom) suitable for the given ===================================== compiler/GHC/Core/Opt/DmdAnal.hs ===================================== @@ -1020,15 +1020,16 @@ dmdTransform :: AnalEnv -- ^ The analysis environment -- this function plus demand on its free variables -- See Note [DmdSig: demand signatures, and demand-sig arity] in "GHC.Types.Demand" dmdTransform env var sd - -- Data constructors + -- Data constructor workers | Just con <- isDataConWorkId_maybe var = -- pprTraceWith "dmdTransform:DataCon" (\ty -> ppr con $$ ppr sd $$ ppr ty) $ - dmdTransformDataConSig (dataConRepStrictness con) sd - -- See Note [DmdAnal for DataCon wrappers] + dmdTransformDataConSig (dataConRepFullStrictness con) sd + -- See Note [DmdAnal for DataCon wrappers] | Just rhs <- dataConWrapUnfolding_maybe var , WithDmdType dmd_ty _rhs' <- dmdAnal env sd rhs = dmd_ty + -- Dictionary component selectors -- Used to be controlled by a flag. -- See #18429 for some perf measurements. @@ -1036,10 +1037,12 @@ dmdTransform env var sd = -- pprTrace "dmdTransform:DictSel" (ppr var $$ ppr (idDmdSig var) $$ ppr sd) $ dmdTransformDictSelSig (idDmdSig var) sd -- Imported functions + | isGlobalId var , let res = dmdTransformSig (idDmdSig var) sd = -- pprTrace "dmdTransform:import" (vcat [ppr var, ppr (idDmdSig var), ppr sd, ppr res]) res + -- Top-level or local let-bound thing for which we use LetDown ('useLetUp'). -- In that case, we have a strictness signature to unleash in our AnalEnv. | Just (sig, top_lvl) <- lookupSigEnv env var ===================================== compiler/GHC/Core/Opt/Simplify/Iteration.hs ===================================== @@ -2257,18 +2257,21 @@ inline y, we must *not* replace x by x' in the inlined copy!! Note [Fast path for lazy data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -For applications of a /lazy/ data constructor worker, the full glory of -rebuildCall is a waste of effort; +For applications of a completely /lazy/ data constructor worker, the full +glory of rebuildCall is a waste of effort; * They never inline, obviously * They have no rewrite rules * Lazy constructors don't need the `StrictArg` treatment. So it's fine to zoom straight to `rebuild` which just rebuilds the -call in a very straightforward way. +call in a very straightforward way. But: -For a data constructor worker that is strict (see Note [Strict fields in Core]) -we take the slow path, so that we'll transform - K (case x of (a,b) -> a) --> case x of (a,b) -> K a -via the StrictArg case of rebuildCall +* For a data constructor worker that is strict (see Note [Strict fields in Core]) + we take the slow path, so that we'll transform + K (case x of (a,b) -> a) --> case x of (a,b) -> K a + via the StrictArg case of rebuildCall + +* If the data constructor has unlifted arguments, we must also take the + slow path (#28169). Same example as `K` above if its arg is Int# Some programs have a /lot/ of data constructors in the source program (compiler/perf/T9961 is an example), so this fast path can be very @@ -2278,8 +2281,9 @@ valuable. simplInId :: SimplEnv -> InId -> SimplCont -> SimplM (SimplFloats, OutExpr) simplInId env var cont | Just dc <- isDataConWorkId_maybe var - , dataConRepLazy dc -- See Note [Fast path for lazy data constructors] + , dataConRepIsLazy dc -- See Note [Fast path for lazy data constructors] = rebuild env (Var var) cont + | otherwise = assertPpr (not (isCoVar var)) (ppr var) $ case substId env var of @@ -3649,7 +3653,7 @@ adjustFieldsIdInfo _scrut case_bndr bndr_swap con vs | otherwise = go vs the_strs where - the_strs = dataConRepStrictness con + the_strs = dataConRepFullStrictness con go [] [] = [] go (v:vs') strs | isTyVar v = v : go vs' strs @@ -3659,7 +3663,7 @@ adjustFieldsIdInfo _scrut case_bndr bndr_swap con vs ppr vs $$ ppr_with_length (map strdisp the_strs) $$ ppr_with_length (dataConRepArgTys con) $$ - ppr_with_length (dataConRepStrictness con)) + ppr_with_length (dataConRepFullStrictness con)) where ppr_with_length list = ppr list <+> parens (text "length =" <+> ppr (length list)) @@ -4306,10 +4310,9 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in) | otherwise = do { let rhs_ty' = exprType alt_rhs_in - bangs - | DataAlt c <- con - = dataConRepStrictness c - | otherwise = [] + bangs = case con of + DataAlt dc -> dataConRepFullStrictness dc + _ -> [] abstracted_binders = abstract_binders alt_bndrs bangs ===================================== compiler/GHC/Core/Opt/SpecConstr.hs ===================================== @@ -2769,7 +2769,7 @@ argToPat1 env in_scope val_env _pat_ty arg arg_occ _arg_str = do { let (ty_args, rest_args) = splitAtList (dataConUnivTyVars dc) args con_str :: [StrictnessMark] -- con_str corresponds 1-1 with the /value/ arguments - con_str = dataConRepStrictness dc + con_str = dataConRepFullStrictness dc con_ty = applyTypeToArgs (dataConRepType dc) ty_args -- ; pprTraceM "bangs" (ppr (length rest_args == length con_str) $$ -- ppr dc $$ ===================================== compiler/GHC/Core/Opt/WorkWrap/Utils.hs ===================================== @@ -221,7 +221,7 @@ mkWwBodies opts fun_id ww_arity arg_vars res_ty demands res_cpr zapped_arg_vars = map zap_var arg_vars ; (subst, cloned_arg_vars) <- cloneBndrsM empty_subst zapped_arg_vars ; let res_ty' = substTyUnchecked subst res_ty - init_str_marks = map (const NotMarkedStrict) cloned_arg_vars + init_str_marks = mapConst NotMarkedStrict cloned_arg_vars ; (useful1, work_args_str, wrap_fn_str, fn_args) <- -- pprTrace "mkWWbodies" (ppr fun_id $$ ppr (arg_vars `zip` cloned_arg_vars) $$ ppr demands) $ @@ -1050,7 +1050,7 @@ unbox_one_arg opts arg_var -- Mark arguments coming out of strict fields so we can seq them in the worker -- See Note [Call-by-value for worker args] - all_str_marks = (map (const NotMarkedStrict) ex_tvs') ++ con_str_marks + all_str_marks = mapConst NotMarkedStrict ex_tvs' ++ con_str_marks ; (nested_useful, worker_args, wrap_fn, wrap_args) <- mkWWstr opts (ex_tvs' ++ arg_ids') all_str_marks ===================================== compiler/GHC/Core/SimpleOpt.hs ===================================== @@ -1727,9 +1727,9 @@ exprIsConApp_maybe ise@(ISE in_scope id_unf) expr -- why we insert them mkFieldSeqFloats in_scope dc args | dataConRepIsLazy dc = (in_scope, nilOL, args) -- Short cut in common case - | otherwise = (in_scope', floats', ty_args ++ val_args') + | otherwise = (in_scope', floats', tyco_args ++ val_args') where - (ty_args, val_args) = splitAtList (dataConUnivAndExTyCoVars dc) args + (tyco_args, val_args) = splitAtList (dataConUnivAndExTyCoVars dc) args (in_scope', floats', val_args') = foldr do_one (in_scope, nilOL, []) $ zipEqual str_marks val_args str_marks = dataConRepStrictness dc ===================================== compiler/GHC/Core/TyCon.hs ===================================== @@ -1513,9 +1513,10 @@ There are a number of wrinkles data C a = MkC !(a->a) so that in exprOkForSpeculation/exprOkToDiscard/exprOkForSpecEval, and in exprIsHNF/exprIsConLike, we evaluate the argument. This strictness flag - is set in `GHC.Tc.TyCl.buildClass + is set in `GHC.Tc.TyCl.Build.buildClass`; see `bangs` and `bang_opts`. + (#28183 shows why this matters.) -(UMC4) To avoid regressions, in Core we want to remember that +(UCM4) To avoid regressions, in Core we want to remember that (MkUC x) is really just x (op d) is really just d We account for this in several places: @@ -3067,8 +3068,8 @@ isUnaryClassTyCon tc@(TyCon { tyConDetails = details }) isTerminatingTyCon :: TyCon -> Bool -- ^ True <=> a value of type (T t1..tn), where `T` is this TyCon, cannot be bottom. --- The only TyCons that satisfy `isTerminatingTyCon` are non-unary class TyCons. --- See (UCM3) in Note [Unary class magic], and +-- The only TyCons that satisfy `isTerminatingTyCon` are /non-unary/ class TyCons. +-- See (UCM3a) in Note [Unary class magic], and -- Note [NON-BOTTOM-DICTS invariant] in GHC.Core. -- An AbstractTyCon returns False: it comes from an hs-boot file, and the real -- declaration may turn out to be a unary class. See (NBD2) in that Note. ===================================== compiler/GHC/Core/Type.hs ===================================== @@ -1781,7 +1781,7 @@ fun_kind_arg_flags = go emptySubst where argf | isVisibleFunArg af = Required | otherwise = Inferred - go _ _ arg_tys = map (const Required) arg_tys + go _ _ arg_tys = mapConst Required arg_tys -- something is ill-kinded. But this can happen -- when printing errors. Assume everything is Required. ===================================== compiler/GHC/Core/Utils.hs ===================================== @@ -2271,13 +2271,12 @@ app_ok fun_ok primop_ok fun val_args | otherwise = case idDetails fun of DFunId terminating -> terminating - -- DFuns terminate, unless the dict is implemented - -- by a no-op in which case they may not - -- See (UCM3) in Note [Unary class magic] in GHC.Core.TyCon + -- DFuns terminate, except for unary classes + -- See (UCM3a) in Note [Unary class magic] in GHC.Core.TyCon DataConWorkId dc - | dataConRepLazy dc -> True -- Args are all thunks - | otherwise -> fields_ok (dataConRepStrictness dc) + | dataConRepIsLazy dc -> True -- Args are all thunks + | otherwise -> fields_ok (dataConRepFullStrictness dc) ClassOpId _ is_terminating_result | is_terminating_result -- See Note [exprOkForSpeculation and type classes] @@ -2696,45 +2695,54 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e -- check_app: See Note [exprIsHNF for function applications] -- for the specification and examples + -- We check arity (and CONLIKEness) first because it's cheaper + -- and we reject quickly on saturated apps. + check_app :: Id -> [CoreArg] -> Bool check_app id val_args = case compare (idArity id) (length val_args) of EQ -> check_saturated id val_args -- Saturated application GT -> check_args id val_args -- Partial application LT -> False -- Over-saturated + check_saturated :: Id -> [CoreArg] -> Bool check_saturated id val_args | Just dc <- isDataConWorkId_maybe id - = -- Saturated data constructors; must account for the strictness flags - all3Prefix check_field val_args (val_arg_tys id) (dataConStrictness dc) + , let strs = dataConRepFullStrictness dc + arg_tys = get_val_arg_tys id + = -- Saturated data constructors; use `check_field` + -- to ensure we account for the strictness flags + assertPpr (equalLength val_args arg_tys && equalLength val_args strs) + (ppr dc $$ ppr val_args $$ ppr arg_tys $$ ppr strs) $ + all3Prefix check_field val_args arg_tys strs + | is_con id -- Saturated CONLIKE: check the arguments = check_args id val_args + | otherwise -- Saturated function, not a constructor => not HNF = False -- check_args: check that any unlifted args are hnf-like - check_args id val_args = assert (sameLength val_args arg_tys) $ - all2Prefix check_arg val_args arg_tys + -- NB: there may be fewer val_args than arg_tys (e.g. (map f)) + check_args :: Id -> [CoreArg] -> Bool + check_args id val_args = all2Prefix check_arg val_args arg_tys where - arg_tys = val_arg_tys id + arg_tys = get_val_arg_tys id - check_arg a_ty a - | mightBeUnliftedType a_ty = is_hnf_like a - | otherwise = True - -- Check unliftedness; for example f (x /# 12#) where f has arity two, - -- and the first argument is unboxed. This is not a value! - -- But f 34# is a value, so check args for HNFs. - -- NB: We check arity (and CONLIKEness) first because it's cheaper - -- and we reject quickly on saturated apps. + -- check_arg: check unliftedness; for example f (x /# 12#) where f + -- has arity two, and the first argument is unboxed. This is not a value! + -- But f 34# is a value, so check unlifted args for HNFs. + check_arg arg arg_ty + | mightBeUnliftedType arg_ty = is_hnf_like arg + | otherwise = True -- check_field: used for a data constructor worker: - -- check unlifted val_args and strict fields + -- check unlifted val_args /and/ strict fields -- See (SFC1) of Note [Strict fields in Core] - check_field a a_ty str - | mightBeUnliftedType a_ty = is_hnf_like a - | isMarkedStrict str = is_hnf_like a - | otherwise = True + check_field arg arg_ty str + | isMarkedStrict str = is_hnf_like arg + | otherwise = check_arg arg arg_ty - val_arg_tys id = splitUninstantiatedValArgTys (idType id) + get_val_arg_tys id = splitUninstantiatedValArgTys (idType id) -- val_arg_tys = map exprType val_args, but much less costly. -- The obvious definition regresses T16577 by 30% so we don't do it. @@ -2893,7 +2901,7 @@ dataConInstPat fss uniqs mult con inst_tys ex_tvs = dataConExTyCoVars con arg_tys = dataConRepArgTys con arg_strs = dataConRepStrictness con -- 1-1 with arg_tys - n_ex = length ex_tvs + n_ex = length ex_tvs -- split the Uniques and FastStrings (ex_uniqs, id_uniqs) = splitAt n_ex uniqs ===================================== compiler/GHC/Tc/Gen/HsType.hs ===================================== @@ -1369,7 +1369,7 @@ tc_hs_tuple_ty rn_ty mode HsBoxedOrConstraintTuple hs_tys exp_kind checkExpectedKind hs_ty ty kind arg_kind | ((L loc hs_ty),ty,kind) <- zip3 hs_tys tys kinds ] - ; finish_tuple rn_ty tup_sort tys' (map (const arg_kind) tys') exp_kind } + ; finish_tuple rn_ty tup_sort tys' (mapConst arg_kind tys') exp_kind } tc_hs_tuple_ty rn_ty mode HsUnboxedTuple tys exp_kind = tc_tuple rn_ty mode UnboxedTuple tys exp_kind ===================================== compiler/GHC/Tc/Gen/Pat.hs ===================================== @@ -655,7 +655,7 @@ tc_pat scaled_exp_pat_ty@(Scaled w_pat exp_pat_ty) penv ps_pat thing_inside = OrPat _ pats -> do -- See Note [Implementation of OrPatterns], Typechecker (1) { let pats_list = NE.toList pats - pat_exp_tys = map (const scaled_exp_pat_ty) pats_list + pat_exp_tys = mapConst scaled_exp_pat_ty pats_list ; (pats_list', (res, pat_ct)) <- tc_lpats pat_exp_tys penv pats_list (captureConstraints thing_inside) ; let pats' = NE.fromList pats_list' -- tc_lpats preserves non-emptiness ; emitConstraints pat_ct ===================================== compiler/GHC/Tc/TyCl.hs ===================================== @@ -3713,7 +3713,7 @@ tcTyFamInstEqn fam_tc mb_clsinfo -- (tcFamInstEqnGuts zonks to Type) ; let ax = mkCoAxBranch qtvs [] [] pats rhs_ty - (map (const Nominal) qtvs) + (mapConst Nominal qtvs) (locA loc) vi = VI { vi_loc = locA loc , vi_qtvs = qtvs ===================================== compiler/GHC/Tc/TyCl/Build.hs ===================================== @@ -291,9 +291,9 @@ type MethInfo -- A temporary intermediate, to communicate buildClass :: Name -- Name of the class/tycon (they have the same Name) -> Kind - -> [TyConBinder] -- Of the tycon + -> [TyConBinder] -- Of the tycon -> [Role] - -> [FunDep TyVar] -- Functional dependencies + -> [FunDep TyVar] -- Functional dependencies -> KnotTied ThetaType -- Superclasess -> [ClassATItem] -- Associated types -> [KnotTied MethInfo] -- Methods @@ -330,10 +330,15 @@ buildClass tycon_name kind binders roles fds sc_theta at_items sig_stuff mindef rec_tycon = classTyCon rec_clas univ_bndrs = tyVarSpecToBinders $ tyConInvisTVBinders binders univ_tvs = binderVars univ_bndrs - bang_opts = FixedBangOpts (map (const HsLazy) args) + + -- Unary classes behave as if we added a bang + -- See (UCM3b) in Note [Unary class magic] + bang_opts :: DataConBangOpts + bang_opts | unary_class = FixedBangOpts [HsStrict False] + | otherwise = FixedBangOpts (mapConst HsLazy args) bangs :: [HsSrcBang] - bangs | unary_class = [yes_bang] -- See (UCM3b) in Note [Unary class magic] - | otherwise = map (const no_bang) args + bangs | unary_class = [yes_bang] + | otherwise = mapConst no_bang args ; rep_nm <- newTyConRepName datacon_name ; dict_con <- buildDataCon (panic "buildClass: FamInstEnvs") @@ -356,8 +361,7 @@ buildClass tycon_name kind binders roles fds sc_theta at_items sig_stuff mindef ; let rhs | unary_class = UnaryClassTyCon dict_con | isCTupleTyConName tycon_name - = TupleTyCon { data_con = dict_con - , tup_sort = ConstraintTuple } + = TupleTyCon { data_con = dict_con, tup_sort = ConstraintTuple } | otherwise = mkDataTyConRhs [dict_con] ===================================== compiler/GHC/Tc/TyCl/Instance.hs ===================================== @@ -837,7 +837,7 @@ tcDataFamInstDecl mb_clsinfo tv_skol_env rep_tc = mkAlgTyCon rep_tc_name user_kind ty_binders (length extra_tcbs) res_kind - (map (const Nominal) ty_binders) + (mapConst Nominal ty_binders) (fmap (typeCheckCType . unLoc) cType) stupid_theta tc_rhs parent gadt_syntax ===================================== compiler/GHC/Tc/TyCl/Utils.hs ===================================== @@ -471,7 +471,7 @@ initialRoleEnv hsc_src annots = extendNameEnvList emptyNameEnv . initialRoleEnv1 :: HscSource -> RoleAnnotEnv -> TyCon -> (Name, [Role]) initialRoleEnv1 hsc_src annots_env tc - | isFamilyTyCon tc = (name, map (const Nominal) bndrs) + | isFamilyTyCon tc = (name, mapConst Nominal bndrs) | isAlgTyCon tc = (name, default_roles) | isTypeSynonymTyCon tc = (name, default_roles) | otherwise = pprPanic "initialRoleEnv1" (ppr tc) ===================================== compiler/GHC/Types/Id/Make.hs ===================================== @@ -541,7 +541,6 @@ mkDataConWorkId wkr_name data_con univ_tvs = dataConUnivTyVars data_con ex_tcvs = dataConExTyCoVars data_con arg_tys = dataConRepArgTys data_con -- Should be same as dataConOrigArgTys - str_marks = dataConRepStrictness data_con ----------- Workers for data types -------------- alg_wkr_info = noCafIdInfo @@ -555,10 +554,17 @@ mkDataConWorkId wkr_name data_con `setLFInfo` wkr_lf_info wkr_inline_prag = alwaysConLikePragma - wkr_arity = dataConRepArity data_con - wkr_sig = mkClosedDmdSig wkr_dmds topDiv - wkr_dmds = map mk_dmd str_marks + -- Strictness signature has arity = wkr_arity + -- i.e. including any existential CoVars + -- See (EXCO1) in Note [Existential coercion variables] + wkr_arity = dataConRepArity data_con + str_marks = dataConRepFullStrictness data_con + wkr_dmds = map mk_dmd str_marks + wkr_sig = assertPpr (str_marks `lengthIs` wkr_arity && + splitUninstantiatedValArgTys wkr_ty `lengthIs` wkr_arity) + (ppr data_con $$ ppr str_marks $$ ppr wkr_ty) $ + mkClosedDmdSig wkr_dmds topDiv mk_dmd MarkedStrict = evalDmd mk_dmd NotMarkedStrict = topDmd @@ -824,7 +830,7 @@ mkDataConRep platform dc_bang_opts fam_envs wrap_name data_con wrap_ty = dataConWrapperType data_con ev_tys = eqSpecPreds eq_spec ++ theta all_arg_tys = map unrestricted ev_tys ++ orig_arg_tys - ev_ibangs = map (const HsLazy) ev_tys + ev_ibangs = mapConst HsLazy ev_tys orig_bangs = dataConSrcBangs data_con wrap_arg_tys @@ -852,14 +858,14 @@ mkDataConRep platform dc_bang_opts fam_envs wrap_name data_con arg_ibangs | new_tycon - = map (const HsLazy) orig_arg_tys -- See Note [HsImplBangs for newtypes] - -- orig_arg_tys should be a singleton, but - -- if a user declared a wrong newtype we - -- detect this later (see test T2334A) + = mapConst HsLazy orig_arg_tys -- See Note [HsImplBangs for newtypes] + -- orig_arg_tys should be a singleton, but + -- if a user declared a wrong newtype we + -- detect this later (see test T2334A) | otherwise = case dc_bang_opts of SrcBangOpts bang_opts -> zipWith (dataConSrcToImplBang platform bang_opts fam_envs) - orig_arg_tys orig_bangs + orig_arg_tys orig_bangs FixedBangOpts bangs -> bangs (rep_tys_w_strs, wrappers) @@ -999,11 +1005,11 @@ For further reading, see: Note [Bangs on imported data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -We pass Maybe [HsImplBang] to mkDataConRep to make use of HsImplBangs +We pass `DataConBangOpts` to `mkDataConRep` to make use of `HsImplBangs` from imported modules. -- Nothing <=> use HsSrcBangs -- Just bangs <=> use HsImplBangs +- SrcBangOpts opts <=> use HsSrcBangs +- FixedBangOpts impl_bangs <=> use impl_bangs For imported types we can't work it all out from the HsSrcBangs, because we want to be very sure to follow what the original module @@ -1011,8 +1017,8 @@ because we want to be very sure to follow what the original module flags were enabled when it was compiled. So we record the decisions in the interface file. -The HsImplBangs passed are in 1-1 correspondence with the -dataConOrigArgTys of the DataCon. +The `HsImplBangs` passed are in 1-1 correspondence with the +`dataConOrigArgTys` of the DataCon. Note [Data con wrappers and unlifted types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ===================================== compiler/GHC/Utils/Misc.hs ===================================== @@ -18,7 +18,7 @@ module GHC.Utils.Misc ( unzipWith, - mapFst, mapSnd, chkAppend, + mapFst, mapSnd, mapConst, chkAppend, mapAndUnzip, mapAndUnzip3, mapAndUnzip4, filterOut, partitionWith, partitionWithM, @@ -329,6 +329,10 @@ mapSnd :: Functor f => (b->c) -> f(a,b) -> f(a,c) mapFst = fmap . first mapSnd = fmap . second +mapConst :: a -> [b] -> [a] +-- (mapConst k [a,b,c]) returns [k,k,k] +mapConst k xs = [ k | _ <- xs ] + zipWithAndUnzip :: (a -> b -> (c,d)) -> [a] -> [b] -> ([c],[d]) zipWithAndUnzip f (a:as) (b:bs) = let (r1, r2) = f a b ===================================== testsuite/tests/simplCore/should_compile/T28169.hs ===================================== @@ -0,0 +1,8 @@ +{-# LANGUAGE MagicHash #-} + +module T28169 where +import GHC.Exts + +f :: Int# -> (Int,Int) +f x = let y = I# (let z = x +# 1# in z *# z) + in (y + y, y * y) ===================================== testsuite/tests/simplCore/should_compile/all.T ===================================== @@ -631,3 +631,6 @@ test('T27936', normal, compile, ['']) test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques']) test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques']) test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques']) + +# T28169: test that there are no calls to boxed arithmetic,e.g. GHC.Internal.Num.$fNumInt_$c+ +test('T28169', grep_errmsg(r'\$c'), compile, ['-O -ddump-simpl -dsuppress-uniques']) View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/1daa8f406690ca7747424c88053185ca... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/1daa8f406690ca7747424c88053185ca... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Simon Peyton Jones (@simonpj)