Simon Peyton Jones pushed to branch wip/T28169 at Glasgow Haskell Compiler / GHC

Commits:

23 changed files:

Changes:

  • compiler/GHC/Builtin/WiredIn/Types.hs
    ... ... @@ -626,7 +626,7 @@ typeSymbolKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Symbol")
    626 626
     pcTyCon :: Name -> Maybe (CType GhcTc) -> [TyVar] -> [DataCon] -> TyCon
    
    627 627
     pcTyCon name cType tyvars cons
    
    628 628
       = mkAlgTyCon name (mkTyConKind bndrs res_kind) bndrs 0 res_kind
    
    629
    -                (map (const Representational) tyvars)
    
    629
    +                (mapConst Representational tyvars)
    
    630 630
                     cType
    
    631 631
                     []              -- No stupid theta
    
    632 632
                     (mkDataTyConRhs cons)
    
    ... ... @@ -717,9 +717,10 @@ pcDataConWithFixity' declared_infix dc_name wrk_key rri
    717 717
         -- we call pcDataConWithFixity' with static TyCons in the same module.
    
    718 718
         -- See Note [Constructor tag allocation] and #14657
    
    719 719
         data_con = mkDataCon dc_name declared_infix prom_info
    
    720
    -                (map (const no_bang) arg_tys)
    
    721
    -                (map (const HsLazy) arg_tys)
    
    722
    -                (map (const NotMarkedStrict) arg_tys)
    
    720
    +                (mapConst no_bang arg_tys)
    
    721
    +                (mapConst HsLazy arg_tys)
    
    722
    +                (mapConst NotMarkedStrict theta ++
    
    723
    +                 mapConst NotMarkedStrict arg_tys)
    
    723 724
                     []      -- No labelled fields
    
    724 725
                     tyvars ex_tyvars
    
    725 726
                     conc_tyvars
    

  • compiler/GHC/Core/DataCon.hs
    ... ... @@ -44,14 +44,15 @@ module GHC.Core.DataCon (
    44 44
             dataConIsInfix,
    
    45 45
             dataConWorkId, dataConWrapId, dataConWrapId_maybe,
    
    46 46
             dataConImplicitTyThings,
    
    47
    -        dataConRepStrictness,
    
    47
    +        dataConRepStrictness, dataConRepArgCbvInfos,
    
    48
    +        ArgCbvInfo(..), argCbvInfoStrictnessMark,
    
    48 49
             dataConImplBangs, dataConBoxer,
    
    50
    +        dataConRepIsLazy,
    
    49 51
     
    
    50 52
             splitDataProductType_maybe,
    
    51 53
     
    
    52 54
             -- ** Predicates on DataCons
    
    53 55
             isNullarySrcDataCon, isNullaryRepDataCon,
    
    54
    -        isLazyDataConRep,
    
    55 56
             isTupleDataCon, isBoxedTupleDataCon, isUnboxedTupleDataCon,
    
    56 57
             isUnboxedSumDataCon, isCovertGadtDataCon, isUnaryClassDataCon,
    
    57 58
             isVanillaDataCon, isNewDataCon, isTypeDataCon, isBoxingDataCon,
    
    ... ... @@ -523,17 +524,37 @@ data DataCon
    523 524
                     -- See Note [Bangs on data constructor arguments]
    
    524 525
     
    
    525 526
             dcStricts :: [StrictnessMark],
    
    526
    -                -- One mark for every field of the DataCon worker;
    
    527
    -                -- if it's empty, then all fields are lazy,
    
    528
    -                -- otherwise 1-1 with dataConRepArgTys.
    
    527
    +                -- One mark for every field of the DataCon /worker/
    
    528
    +                -- INVARIANT: length dcStricts = length dataConRepArgTys
    
    529
    +                -- Relates only to user-specified strictness annotations,
    
    530
    +                --   not to liftedness or otherwise
    
    531
    +                -- E.g. data T a = MkT {-# UNPACK #-} !(S a) Int# !a
    
    532
    +                --      data S a = MkS a !a
    
    533
    +                -- Then the worker for MkT has four fields, the first two arising from
    
    534
    +                --   unpacking S.  The corresponding strictness marks are [-,!,-,!]; again
    
    535
    +                --   the first two come from MkS
    
    529 536
                     -- See also Note [Strict fields in Core] in GHC.Core
    
    530
    -                -- for the effect on the strictness signature
    
    537
    +                --    for the effect on the strictness signature
    
    538
    +
    
    539
    +        dcArgCbvInfos :: [ArgCbvInfo],
    
    540
    +                -- One entry for each /value/ argument of the worker,
    
    541
    +                --   /including/ each CoVar in dcExTyCoVars
    
    542
    +                -- Unlike dcStricts, takes account of liftedness
    
    543
    +                -- INVARIANT: length dcArgCbvInfos = dataConRepArity
    
    544
    +                -- See (EXCO1) Note [Existential coercion variables]
    
    545
    +                -- and Note [ArgCbvInfo]
    
    531 546
     
    
    532 547
             dcFields  :: [FieldLabel],
    
    533 548
                     -- Field labels for this constructor, in the
    
    534 549
                     -- same order as the dcOrigArgTys;
    
    535 550
                     -- length = 0 (if not a record) or dataConSourceArity.
    
    536 551
     
    
    552
    +        dcIsLazy :: Bool,
    
    553
    +                -- True <=> all of dcArgCbvInfos are ArgCbn; that is
    
    554
    +                --   (a) all fields of the data con /worker/ are definitely lifted
    
    555
    +                --   (b) no field has a `StrictnessMark` that forces evaluation
    
    556
    +                -- So if `dcIsLazy` is True then all fields of the worker are lazy thunks
    
    557
    +
    
    537 558
             -- The curried worker function that corresponds to the constructor:
    
    538 559
             -- It doesn't have an unfolding; the code generator saturates these Ids
    
    539 560
             -- and allocates a real constructor when it finds one.
    
    ... ... @@ -582,18 +603,30 @@ we can in Core. Consider having:
    582 603
     
    
    583 604
       data T :: forall k. k -> k -> Constraint where
    
    584 605
         MkT :: forall k (a::k) (b::k).
    
    585
    -           forall k' (c::k') (co::k'~k).
    
    586
    -           (b ~# (c|>co)) => T k a b
    
    606
    +           forall k' (c::k') (co::k'~#k).
    
    607
    +           (b ~# (c|>co)) => !a -> T k a b
    
    587 608
     
    
    588 609
       dcUnivTyVars       = [k,a,b]
    
    589 610
       dcExTyCoVars       = [k',c,co]
    
    590 611
       dcUserTyVarBinders = [k,a,k',c]
    
    591 612
       dcEqSpec           = [b ~# (c|>co)]
    
    592 613
       dcOtherTheta       = []
    
    593
    -  dcOrigArgTys       = []
    
    614
    +  dcOrigArgTys       = [a]
    
    594 615
       dcRepTyCon         = T
    
    616
    +  dcStricts          = [NotMarkedStrict, MarkedStrict]
    
    617
    +  dcArgCbvInfos      = [ArgCbv, ArgCbv, ArgCbv]  -- (EXCO1)
    
    618
    +
    
    619
    +* `dataConKindEqSpec` returns [k'~k].
    
    620
    +* `dataConRepArgTys`  returns [ b~#(c|>co), a ]
    
    621
    +
    
    622
    +(EXCO1) In a call of the data constructor worker we will see
    
    623
    +            MkT tk ta tb tk' tc (co1::tk'~#tk) (co2::tb~#(tc |> co1))
    
    624
    +   dcArgCbvInfos returns a [ArgCbvInfo] that lines up with all the
    
    625
    +   value arguments, /including/ co1.  (Coercion arguments are unlifted,
    
    626
    +   hence ArgCbv; see Note [ArgCbvInfo].)
    
    595 627
     
    
    596
    -Function call 'dataConKindEqSpec' returns [k'~k]
    
    628
    +   dcArgCbvInfos lines up with dcStricts almost always; they differ in length
    
    629
    +   only in the rare case that we have existential coercion variables
    
    597 630
     
    
    598 631
     Note [DataCon arities]
    
    599 632
     ~~~~~~~~~~~~~~~~~~~~~~
    
    ... ... @@ -830,7 +863,7 @@ data DataConRep
    830 863
     
    
    831 864
             , dcr_boxer   :: DataConBoxer
    
    832 865
     
    
    833
    -        , dcr_arg_tys :: [Scaled Type]    -- Final, representation argument types,
    
    866
    +        , dcr_arg_tys :: [Scaled Type]    -- Final, representation /value/ argument types,
    
    834 867
                                               -- after unboxing and flattening,
    
    835 868
                                               -- and *including* all evidence args
    
    836 869
     
    
    ... ... @@ -853,7 +886,8 @@ type DataConEnv a = UniqFM DataCon a -- Keyed by DataCon
    853 886
     -- In the AST, the @SourceText@ is hidden inside the extension point
    
    854 887
     -- 'Language.Haskell.Syntax.Extension.XConDeclField'.
    
    855 888
     data HsSrcBang
    
    856
    -  = HsSrcBang SourceText SrcUnpackedness SrcStrictness -- See Note [Pragma source text] in "GHC.Types.SourceText"
    
    889
    +  = HsSrcBang SourceText SrcUnpackedness SrcStrictness
    
    890
    +              -- See Note [Pragma source text] in "GHC.Types.SourceText"
    
    857 891
       deriving Data.Data
    
    858 892
     
    
    859 893
     -- | Haskell Implementation Bang
    
    ... ... @@ -861,14 +895,14 @@ data HsSrcBang
    861 895
     -- Bangs of data constructor arguments as generated by the compiler
    
    862 896
     -- after consulting HsSrcBang, flags, etc.
    
    863 897
     data HsImplBang
    
    864
    -  = HsLazy    -- ^ Lazy field, or one with an unlifted type
    
    898
    +  = HsLazy        -- ^ Lazy field, or one with an unlifted type
    
    899
    +
    
    865 900
       | HsStrict Bool -- ^ Strict but not unpacked field
    
    866
    -                  -- True <=> we could have unpacked, but opted not to
    
    867
    -                  -- because of -O0.
    
    868
    -                  -- See Note [Detecting useless UNPACK pragmas]
    
    869
    -  | HsUnpack (Maybe Coercion)
    
    870
    -    -- ^ Strict and unpacked field
    
    871
    -    -- co :: arg-ty ~ product-ty HsBang
    
    901
    +      -- True <=> we could have unpacked, but opted not to because of -O0
    
    902
    +      --          See Note [Detecting useless UNPACK pragmas]
    
    903
    +
    
    904
    +  | HsUnpack (Maybe Coercion)  -- ^ Strict and unpacked field
    
    905
    +                               -- co :: arg-ty ~ product-ty HsBang
    
    872 906
       deriving Data.Data
    
    873 907
     
    
    874 908
     
    
    ... ... @@ -879,6 +913,51 @@ data HsImplBang
    879 913
     data StrictnessMark = MarkedStrict | NotMarkedStrict
    
    880 914
         deriving Eq
    
    881 915
     
    
    916
    +-- | How a data constructor worker treats one of its value arguments
    
    917
    +-- See Note [ArgCbvInfo]
    
    918
    +data ArgCbvInfo
    
    919
    +  = ArgCbn      -- ^ Call-by-need: definitely lifted, and no bang:
    
    920
    +                --   the worker does not evaluate the argument
    
    921
    +  | ArgCbv      -- ^ Call-by-value: definitely unlifted, or has a bang
    
    922
    +                --   (MarkedStrict): the argument is certainly evaluated
    
    923
    +  | ArgRepPoly  -- ^ No bang, but representation-polymorphic,
    
    924
    +                --   so we don't know whether it is lifted or not
    
    925
    +  deriving Eq
    
    926
    +
    
    927
    +argCbvInfoStrictnessMark :: ArgCbvInfo -> StrictnessMark
    
    928
    +-- Conservative: ArgRepPoly might be lifted, so NotMarkedStrict
    
    929
    +argCbvInfoStrictnessMark ArgCbv     = MarkedStrict
    
    930
    +argCbvInfoStrictnessMark ArgCbn     = NotMarkedStrict
    
    931
    +argCbvInfoStrictnessMark ArgRepPoly = NotMarkedStrict
    
    932
    +
    
    933
    +{- Note [ArgCbvInfo]
    
    934
    +~~~~~~~~~~~~~~~~~~~~
    
    935
    +`dcArgCbvInfos :: [ArgCbvInfo]` tells, for each value argument of a data
    
    936
    +constructor worker, whether that argument is certainly evaluated
    
    937
    +(ArgCbv), certainly not evaluated (ArgCbn), or we don't know
    
    938
    +(ArgRepPoly, e.g. the fields of an unboxed tuple (#,#), whose types
    
    939
    +are representation-polymorphic until instantiated).
    
    940
    +
    
    941
    +An argument is evaluated if it has an unlifted type, or if it is a strict
    
    942
    +field (see Note [Strict fields in Core] in GHC.Core).  For many purposes
    
    943
    +these are the same thing, so we combine them here; e.g. both
    
    944
    +    K (case x of (a,b) -> a)      where K has a strict field
    
    945
    +    I# (case x of (a,b) -> a#)
    
    946
    +should become (case x of (a,b) -> K a) in the Simplifier (#28169).
    
    947
    +
    
    948
    +Consumers must decide what to do with ArgRepPoly, and the right choice
    
    949
    +depends on the consumer, in opposite directions:
    
    950
    +
    
    951
    +* `GHC.Core.Opt.Simplify.Utils.dataConArgInfo` treats ArgRepPoly as /lazy/.
    
    952
    +  There "strict" licenses the StrictArg transformation, which is only an
    
    953
    +  optimisation; claiming laziness is always safe.
    
    954
    +
    
    955
    +* `exprIsHNF` (check_field) and `exprOkForSpeculation` (field_ok) in
    
    956
    +  GHC.Core.Utils treat ArgRepPoly as /possibly strict/.  There, wrongly
    
    957
    +  claiming laziness would wrongly say that (K e) is a value even if `e`
    
    958
    +  is an unlifted expression that might diverge.
    
    959
    +-}
    
    960
    +
    
    882 961
     -- | An 'EqSpec' is a tyvar/type pair representing an equality made in
    
    883 962
     -- rejigging a GADT constructor
    
    884 963
     data EqSpec = EqSpec TyVar Type
    
    ... ... @@ -950,9 +1029,8 @@ Terminology:
    950 1029
       you the demand signature of the wrapper, if it exists.
    
    951 1030
     
    
    952 1031
       These demand signatures are set in GHC.Types.Id.Make.mkDataConWorkId,
    
    953
    -  computed from the single source of truth `dataConRepStrictness`, which is
    
    954
    -  generated from `dcStricts`.
    
    955
    -  Note that `dataConRepStrictness` lines up 1-1 with `idDmdSig (dataConWorkId dc)`.
    
    1032
    +  computed from the single source of truth `dataConRepArgCbvInfos`.
    
    1033
    +  So `dataConRepArgCbvInfos` lines up 1-1 with `idDmdSig (dataConWorkId dc)`.
    
    956 1034
     
    
    957 1035
     Note [Detecting useless UNPACK pragmas]
    
    958 1036
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    ... ... @@ -1032,6 +1110,11 @@ instance Outputable StrictnessMark where
    1032 1110
         ppr MarkedStrict    = text "!"
    
    1033 1111
         ppr NotMarkedStrict = empty
    
    1034 1112
     
    
    1113
    +instance Outputable ArgCbvInfo where
    
    1114
    +    ppr ArgCbn     = text "cbn"
    
    1115
    +    ppr ArgCbv     = text "cbv"
    
    1116
    +    ppr ArgRepPoly = text "rep-poly"
    
    1117
    +
    
    1035 1118
     instance Binary StrictnessMark where
    
    1036 1119
         put_ bh NotMarkedStrict = putByte bh 0
    
    1037 1120
         put_ bh MarkedStrict    = putByte bh 1
    
    ... ... @@ -1118,7 +1201,7 @@ mkDataCon name declared_infix prom_info
    1118 1201
               impl_bangs   -- Must match orig_arg_tys 1-1
    
    1119 1202
               str_marks    -- Must be empty or match dataConRepArgTys 1-1
    
    1120 1203
               fields
    
    1121
    -          univ_tvs ex_tvs conc_tvs user_tvbs
    
    1204
    +          univ_tvs ex_tcvs conc_tvs user_tvbs
    
    1122 1205
               eq_spec theta
    
    1123 1206
               orig_arg_tys orig_res_ty rep_info rep_tycon tag
    
    1124 1207
               stupid_theta work_id rep
    
    ... ... @@ -1132,44 +1215,62 @@ mkDataCon name declared_infix prom_info
    1132 1215
     
    
    1133 1216
       = con
    
    1134 1217
       where
    
    1135
    -    is_vanilla = null ex_tvs && null eq_spec && null theta
    
    1136
    -    str_marks' | not $ any isMarkedStrict str_marks = []
    
    1137
    -               | otherwise                          = str_marks
    
    1138
    -
    
    1139
    -    con = MkData {dcName = name, dcUnique = nameUnique name,
    
    1140
    -                  dcVanilla = is_vanilla, dcInfix = declared_infix,
    
    1141
    -                  dcUnivTyVars = univ_tvs,
    
    1142
    -                  dcExTyCoVars = ex_tvs,
    
    1143
    -                  dcConcreteTyVars = conc_tvs,
    
    1144
    -                  dcUserTyVarBinders = user_tvbs,
    
    1145
    -                  dcEqSpec = eq_spec,
    
    1146
    -                  dcOtherTheta = theta,
    
    1147
    -                  dcStupidTheta = stupid_theta,
    
    1148
    -                  dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
    
    1149
    -                  dcRepTyCon = rep_tycon,
    
    1150
    -                  dcSrcBangs = arg_stricts, dcImplBangs = impl_bangs,
    
    1151
    -                  dcStricts = str_marks',
    
    1152
    -                  dcFields = fields, dcTag = tag, dcRepType = rep_ty,
    
    1153
    -                  dcWorkId = work_id,
    
    1154
    -                  dcRep = rep,
    
    1155
    -                  dcSourceArity = length orig_arg_tys,
    
    1156
    -                  dcRepArity = length rep_arg_tys + count isCoVar ex_tvs,
    
    1157
    -                  dcPromoted = promoted }
    
    1218
    +    is_vanilla = null ex_tcvs && null eq_spec && null theta
    
    1219
    +    full_arg_info = replicate n_ex_co_vars ArgCbv  -- Coercions are unlifted
    
    1220
    +                    ++ zipWith mk_arg_info str_marks rep_arg_tys
    
    1221
    +    mk_arg_info str (Scaled _ ty)
    
    1222
    +      | isMarkedStrict str        = ArgCbv
    
    1223
    +      | definitelyLiftedType ty   = ArgCbn
    
    1224
    +      | definitelyUnliftedType ty = ArgCbv
    
    1225
    +      | otherwise                 = ArgRepPoly
    
    1226
    +    is_lazy = all (== ArgCbn) full_arg_info
    
    1227
    +
    
    1228
    +    con = MkData { dcName    = name
    
    1229
    +                 , dcUnique  = nameUnique name
    
    1230
    +                 , dcInfix   = declared_infix
    
    1231
    +                 , dcTag     = tag
    
    1232
    +                 , dcVanilla = is_vanilla
    
    1233
    +
    
    1234
    +                 , dcUnivTyVars       = univ_tvs
    
    1235
    +                 , dcExTyCoVars       = ex_tcvs
    
    1236
    +                 , dcConcreteTyVars   = conc_tvs
    
    1237
    +                 , dcUserTyVarBinders = user_tvbs
    
    1238
    +                 , dcEqSpec           = eq_spec
    
    1239
    +                 , dcOtherTheta       = theta
    
    1240
    +                 , dcStupidTheta      = stupid_theta
    
    1241
    +                 , dcOrigArgTys       = orig_arg_tys
    
    1242
    +                 , dcOrigResTy        = orig_res_ty
    
    1243
    +
    
    1244
    +                 , dcRep         = rep
    
    1245
    +                 , dcRepType     = rep_ty
    
    1246
    +                 , dcRepTyCon    = rep_tycon
    
    1247
    +                 , dcSrcBangs    = arg_stricts
    
    1248
    +                 , dcImplBangs   = impl_bangs
    
    1249
    +                 , dcStricts     = assertPpr (equalLength str_marks rep_arg_tys)
    
    1250
    +                                             (ppr name <+> ppr str_marks)
    
    1251
    +                                   str_marks
    
    1252
    +                 , dcArgCbvInfos = full_arg_info
    
    1253
    +                 , dcIsLazy      = is_lazy
    
    1254
    +                 , dcFields      = fields
    
    1255
    +                 , dcWorkId      = work_id
    
    1256
    +                 , dcSourceArity = length orig_arg_tys
    
    1257
    +                 , dcRepArity    = n_ex_co_vars + length rep_arg_tys
    
    1258
    +                 , dcPromoted    = promoted }
    
    1158 1259
     
    
    1159 1260
             -- The 'arg_stricts' passed to mkDataCon are simply those for the
    
    1160 1261
             -- source-language arguments.  We add extra ones for the
    
    1161 1262
             -- dictionary arguments right here.
    
    1162 1263
     
    
    1163
    -    rep_arg_tys = dataConRepArgTys con
    
    1264
    +    n_ex_co_vars = count isCoVar ex_tcvs
    
    1265
    +    rep_arg_tys  = dataConRepArgTys con
    
    1164 1266
     
    
    1165
    -    rep_ty =
    
    1166
    -      case rep of
    
    1267
    +    rep_ty = case rep of
    
    1167 1268
             -- If the DataCon has no wrapper, then the worker's type *is* the
    
    1168 1269
             -- user-facing type, so we can simply use dataConWrapperType.
    
    1169 1270
             NoDataConRep -> dataConWrapperType con
    
    1170 1271
             -- If the DataCon has a wrapper, then the worker's type is never seen
    
    1171 1272
             -- by the user. The visibilities we pick do not matter here.
    
    1172
    -        DCR{} -> mkInfForAllTys univ_tvs $ mkTyCoInvForAllTys ex_tvs $
    
    1273
    +        DCR{} -> mkInfForAllTys univ_tvs $ mkTyCoInvForAllTys ex_tcvs $
    
    1173 1274
                      mkScaledFunctionTys rep_arg_tys $
    
    1174 1275
                      mkTyConApp rep_tycon (mkTyVarTys univ_tvs)
    
    1175 1276
                      -- res_arg_tys is a mixture of TypeLike and ConstraintLike,
    
    ... ... @@ -1192,8 +1293,8 @@ mkDataCon name declared_infix prom_info
    1192 1293
                                              prom_res_kind roles rep_info
    
    1193 1294
     
    
    1194 1295
         roles = map (\tv -> if isTyVar tv then Nominal else Phantom)
    
    1195
    -                (univ_tvs ++ ex_tvs)
    
    1196
    -            ++ map (const Representational) (theta ++ map scaledThing orig_arg_tys)
    
    1296
    +                (univ_tvs ++ ex_tcvs)
    
    1297
    +            ++ mapConst Representational (theta ++ map scaledThing orig_arg_tys)
    
    1197 1298
     
    
    1198 1299
     freshNames :: [Name] -> [Name]
    
    1199 1300
     -- Make an infinite list of Names whose Uniques and OccNames
    
    ... ... @@ -1399,20 +1500,19 @@ isNullarySrcDataCon dc = dataConSourceArity dc == 0
    1399 1500
     isNullaryRepDataCon :: DataCon -> Bool
    
    1400 1501
     isNullaryRepDataCon dc = dataConRepArity dc == 0
    
    1401 1502
     
    
    1402
    -isLazyDataConRep :: DataCon -> Bool
    
    1403
    --- ^ True <==> All fields are lazy
    
    1404
    -isLazyDataConRep dc = null (dcStricts dc)
    
    1405
    -
    
    1406 1503
     dataConRepStrictness :: DataCon -> [StrictnessMark]
    
    1407 1504
     -- ^ Give the demands on the runtime arguments of a Core DataCon worker
    
    1408
    --- application.
    
    1409
    --- The length of the list matches `dataConRepArgTys` (e.g., the number
    
    1410
    --- of runtime arguments).
    
    1411
    -dataConRepStrictness dc
    
    1412
    -  | isLazyDataConRep dc
    
    1413
    -  = replicate (dataConRepArity dc) NotMarkedStrict
    
    1414
    -  | otherwise
    
    1505
    +-- application. Matches 1-1 with `dataConRepArgTys`
    
    1506
    +dataConRepStrictness = dcStricts
    
    1507
    +
    
    1508
    +dataConRepArgCbvInfos :: DataCon -> [ArgCbvInfo]
    
    1509
    +-- ^ Describes each value argument of a Core DataCon worker
    
    1510
    +-- application, /including/ any existential CoVar args
    
    1511
    +-- See Note [ArgCbvInfo] and (EXCO1) in Note [Existential coercion variables]
    
    1512
    +dataConRepArgCbvInfos = dcArgCbvInfos
    
    1513
    +
    
    1514
    +dataConRepIsLazy :: DataCon -> Bool
    
    1515
    +dataConRepIsLazy = dcIsLazy
    
    1415 1516
     
    
    1416 1517
     dataConImplBangs :: DataCon -> [HsImplBang]
    
    1417 1518
     -- The implementation decisions about the strictness/unpack of each
    
    ... ... @@ -1523,10 +1623,11 @@ dataConWrapperType (MkData { dcUserTyVarBinders = user_tvbs,
    1523 1623
         res_ty
    
    1524 1624
     
    
    1525 1625
     -- | Finds the instantiated types of the arguments required to construct a
    
    1526
    --- 'DataCon' representation
    
    1626
    +--   data constructor worker application
    
    1527 1627
     -- NB: these INCLUDE any dictionary args
    
    1528
    ---     but EXCLUDE the data-declaration context, which is discarded
    
    1529
    --- It's all post-flattening etc; this is a representation type
    
    1628
    +--     but EXCLUDE the "stupid theta" data-declaration context, which is discarded
    
    1629
    +--
    
    1630
    +-- Result list is 1-1 with dataConRepArgTys, and dataConRepStrictness
    
    1530 1631
     dataConInstArgTys :: DataCon    -- ^ A datacon with no existentials or equality constraints
    
    1531 1632
                                     -- However, it can have a dcTheta (notably it can be a
    
    1532 1633
                                     -- class dictionary, with superclasses)
    
    ... ... @@ -1621,9 +1722,10 @@ dataConOrigArgTys dc = dcOrigArgTys dc
    1621 1722
     dataConOtherTheta :: DataCon -> ThetaType
    
    1622 1723
     dataConOtherTheta dc = dcOtherTheta dc
    
    1623 1724
     
    
    1624
    --- | Returns the arg types of the worker, including *all* non-dependent
    
    1625
    --- evidence, after any flattening has been done and without substituting for
    
    1626
    --- any type variables
    
    1725
    +-- | Returns the arg types of the worker, after any flattening has been done and
    
    1726
    +-- without substituting for any type variables
    
    1727
    +--
    
    1728
    +-- Includes evidence, namely `dcEqSpec` and `dcOtherTheta`
    
    1627 1729
     dataConRepArgTys :: DataCon -> [Scaled Type]
    
    1628 1730
     dataConRepArgTys (MkData { dcRep        = rep
    
    1629 1731
                              , dcEqSpec     = eq_spec
    
    ... ... @@ -1642,8 +1744,10 @@ dataConRepArgTys (MkData { dcRep = rep
    1642 1744
               -- I think it's because of the call in mkDataCon, which in turn feeds
    
    1643 1745
               -- into dcRepArity, which in turn is used in mkDataConWorkId.
    
    1644 1746
               -- c.f. #23022
    
    1645
    -        | otherwise          -> assert (null eq_spec) $
    
    1646
    -                                map unrestricted theta ++ orig_arg_tys
    
    1747
    +        | otherwise -> assert (null eq_spec) $
    
    1748
    +                       -- null eq_spec: all GADTs go via DCR
    
    1749
    +                       -- See `dataConUserTyVarsNeedWrapper`
    
    1750
    +                       map unrestricted theta ++ orig_arg_tys
    
    1647 1751
     
    
    1648 1752
     -- | The string @package:module.name@ identifying a constructor, which is attached
    
    1649 1753
     -- 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
    828 828
                                    --      Note [Storing compatibility]
    
    829 829
       where
    
    830 830
         branch = mkCoAxBranch tvs eta_tvs cvs lhs_tys rhs_ty
    
    831
    -                          (map (const Nominal) tvs)
    
    831
    +                          (mapConst Nominal tvs)
    
    832 832
                               (getSrcSpan ax_name)
    
    833 833
     
    
    834 834
     -- | Create a coercion constructor (axiom) suitable for the given
    

  • compiler/GHC/Core/Opt/DmdAnal.hs
    ... ... @@ -1020,15 +1020,16 @@ dmdTransform :: AnalEnv -- ^ The analysis environment
    1020 1020
                               -- this function plus demand on its free variables
    
    1021 1021
     -- See Note [DmdSig: demand signatures, and demand-sig arity] in "GHC.Types.Demand"
    
    1022 1022
     dmdTransform env var sd
    
    1023
    -  -- Data constructors
    
    1023
    +  -- Data constructor workers
    
    1024 1024
       | Just con <- isDataConWorkId_maybe var
    
    1025 1025
       = -- pprTraceWith "dmdTransform:DataCon" (\ty -> ppr con $$ ppr sd $$ ppr ty) $
    
    1026
    -    dmdTransformDataConSig (dataConRepStrictness con) sd
    
    1027
    -  -- See Note [DmdAnal for DataCon wrappers]
    
    1026
    +    dmdTransformDataConSig (dataConRepArgCbvInfos con) sd
    
    1028 1027
     
    
    1028
    +  -- See Note [DmdAnal for DataCon wrappers]
    
    1029 1029
       | Just rhs <- dataConWrapUnfolding_maybe var
    
    1030 1030
       , WithDmdType dmd_ty _rhs' <- dmdAnal env sd rhs
    
    1031 1031
       = dmd_ty
    
    1032
    +
    
    1032 1033
       -- Dictionary component selectors
    
    1033 1034
       -- Used to be controlled by a flag.
    
    1034 1035
       -- See #18429 for some perf measurements.
    
    ... ... @@ -1036,10 +1037,12 @@ dmdTransform env var sd
    1036 1037
       = -- pprTrace "dmdTransform:DictSel" (ppr var $$ ppr (idDmdSig var) $$ ppr sd) $
    
    1037 1038
         dmdTransformDictSelSig (idDmdSig var) sd
    
    1038 1039
       -- Imported functions
    
    1040
    +
    
    1039 1041
       | isGlobalId var
    
    1040 1042
       , let res = dmdTransformSig (idDmdSig var) sd
    
    1041 1043
       = -- pprTrace "dmdTransform:import" (vcat [ppr var, ppr (idDmdSig var), ppr sd, ppr res])
    
    1042 1044
         res
    
    1045
    +
    
    1043 1046
       -- Top-level or local let-bound thing for which we use LetDown ('useLetUp').
    
    1044 1047
       -- In that case, we have a strictness signature to unleash in our AnalEnv.
    
    1045 1048
       | Just (sig, top_lvl) <- lookupSigEnv env var
    

  • compiler/GHC/Core/Opt/Simplify/Iteration.hs
    ... ... @@ -64,6 +64,7 @@ import GHC.Builtin.KnownKeys( runRWKey, seqHashKey )
    64 64
     import GHC.Builtin.WiredIn.Ids( seqId )
    
    65 65
     
    
    66 66
     import qualified GHC.Data.List.Infinite as Inf
    
    67
    +import GHC.Data.List.Infinite ( Infinite(..) )
    
    67 68
     import GHC.Data.Maybe   ( isNothing, orElse, mapMaybe )
    
    68 69
     import GHC.Data.FastString
    
    69 70
     import GHC.Unit.Module ( moduleName )
    
    ... ... @@ -75,7 +76,6 @@ import GHC.Utils.Logger
    75 76
     import GHC.Utils.Misc
    
    76 77
     
    
    77 78
     import Control.Monad
    
    78
    -import Data.List.NonEmpty (NonEmpty (..))
    
    79 79
     
    
    80 80
     {-
    
    81 81
     The guts of the simplifier is in this module, but the driver loop for
    
    ... ... @@ -1639,7 +1639,7 @@ rebuild_go env expr cont
    1639 1639
     
    
    1640 1640
           ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
    
    1641 1641
                      , sc_cont = cont, sc_hole_ty = fun_ty }
    
    1642
    -        -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
    
    1642
    +        -> do { arg' <- simplArg env fun_ty arg_se arg arg_mco
    
    1643 1643
                   ; rebuild_go env (App expr arg') cont }
    
    1644 1644
     
    
    1645 1645
     completeBindX :: SimplEnv
    
    ... ... @@ -1841,27 +1841,21 @@ pushCast env co cont
    1841 1841
         go_mco (MCo co) opt cont = go co opt cont
    
    1842 1842
     
    
    1843 1843
     simplArg :: SimplEnvIS              -- ^ Used only for its InScopeSet
    
    1844
    -         -> Maybe ArgInfo           -- ^ Just <=> This arg `ai` occurs in an app
    
    1845
    -                                    --   `f a1 ... an` where we have ArgInfo on
    
    1846
    -                                    --   how `f` uses `ai`, affecting the Stop
    
    1847
    -                                    --   continuation passed to 'simplExprC'
    
    1848 1844
              -> OutType                 -- ^ Type of the function applied to this arg
    
    1849 1845
              -> StaticEnv -> CoreExpr   -- ^ Expression with its static envt
    
    1850 1846
              -> MOutCoercion            -- Wrap this around the result
    
    1851 1847
              -> SimplM OutExpr
    
    1852
    -simplArg _ _ _ (Simplified {}) arg mco
    
    1848
    +-- Simplify an argument in a boring context
    
    1849
    +-- c.f. the lazy-argument case of `rebuildCall`, which does the same,
    
    1850
    +--      but with a more informative Stop continuation
    
    1851
    +simplArg _ _ (Simplified {}) arg mco
    
    1853 1852
       = -- See Note [Avoid repeated simplification]
    
    1854 1853
         case mco of
    
    1855 1854
            MRefl  -> return arg       -- Vastly common case
    
    1856 1855
            MCo co -> return (mkCast arg co)
    
    1857
    -simplArg env mb_arg_info fun_ty (UnSimplified arg_se) arg mco
    
    1858
    -  = do { let arg_env' = arg_se `setInScopeFromE` env
    
    1859
    -             arg_ty   = funArgTy fun_ty
    
    1860
    -             stop     = case mb_arg_info of
    
    1861
    -                           Nothing -> mkBoringStop arg_ty
    
    1862
    -                           Just ai -> mkLazyArgStop arg_ty ai
    
    1863
    -             cont     = addCastMCo mco stop
    
    1864
    -       ; simplExprC arg_env' arg cont }
    
    1856
    +simplArg env fun_ty (UnSimplified arg_se) arg mco
    
    1857
    +  = simplExprC (arg_se `setInScopeFromE` env) arg $
    
    1858
    +    addCastMCo mco (mkBoringStop (funArgTy fun_ty))
    
    1865 1859
     
    
    1866 1860
     {-
    
    1867 1861
     ************************************************************************
    
    ... ... @@ -1920,7 +1914,7 @@ simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_env = arg_se
    1920 1914
                  -- in this round of the Simplifier
    
    1921 1915
                  -> simplNonRecE env from_what bndr (arg, arg_env) body cont
    
    1922 1916
     
    
    1923
    -           _ -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
    
    1917
    +           _ -> do { arg' <- simplArg env fun_ty arg_se arg arg_mco
    
    1924 1918
                        ; completeBindX env from_what bndr arg' body cont }
    
    1925 1919
            }
    
    1926 1920
       where
    
    ... ... @@ -2255,31 +2249,49 @@ zap the SubstEnv. This is VITAL. Consider
    2255 2249
     We'll clone the inner \x, adding x->x' in the id_subst Then when we
    
    2256 2250
     inline y, we must *not* replace x by x' in the inlined copy!!
    
    2257 2251
     
    
    2258
    -Note [Fast path for lazy data constructors]
    
    2259
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2260
    -For applications of a /lazy/ data constructor worker, the full glory of
    
    2261
    -rebuildCall is a waste of effort;
    
    2252
    +Note [Simplifying data constructor applications]
    
    2253
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2254
    +For applications of a data constructor worker, much of the work done for
    
    2255
    +an ordinary function application is a waste of effort:
    
    2256
    +* Workers are global, so there is no need to look in the substitution
    
    2262 2257
     * They never inline, obviously
    
    2263 2258
     * They have no rewrite rules
    
    2264
    -* Lazy constructors don't need the `StrictArg` treatment.
    
    2265
    -So it's fine to zoom straight to `rebuild` which just rebuilds the
    
    2266
    -call in a very straightforward way.
    
    2267
    -
    
    2268
    -For a data constructor worker that is strict (see Note [Strict fields in Core])
    
    2269
    -we take the slow path, so that we'll transform
    
    2270
    -  K (case x of (a,b) -> a)  -->   case x of (a,b) -> K a
    
    2271
    -via the StrictArg case of rebuildCall
    
    2272
    -
    
    2273
    -Some programs have a /lot/ of data constructors in the source program
    
    2274
    -(compiler/perf/T9961 is an example), so this fast path can be very
    
    2275
    -valuable.
    
    2259
    +* We know their argument strictness without looking at their type
    
    2260
    +So `simplInId` takes a short cut:
    
    2261
    +
    
    2262
    +(SDC1) If the constructor is completely lazy (`dataConRepIsLazy`: all
    
    2263
    +  arguments are lifted and none has a bang), there is nothing for
    
    2264
    +  `rebuildCall` to do, so we zoom straight to `rebuild`, which just
    
    2265
    +  rebuilds the call in a very straightforward way.
    
    2266
    +
    
    2267
    +  This is not just a nicety: `rebuildCall` costs noticeably more per
    
    2268
    +  argument than `rebuild` (ArgInfo, ArgSpecs, argInfoExpr, closures), and
    
    2269
    +  some programs have a /lot/ of data constructors (compiler/perf/T9961 is
    
    2270
    +  an example).  Sending lazy constructors through `rebuildCall` made T9961
    
    2271
    +  allocate about 3% more, even with the specialised DataConArgInfo of (SDC2).
    
    2272
    +
    
    2273
    +(SDC2) Otherwise we go straight to `rebuildCall`, skipping `simplOutId`,
    
    2274
    +  with a `DataConArgInfo` built by `dataConArgInfo`.  `DataConArgInfo` is a
    
    2275
    +  specialised form of `ArgInfo`, with far fewer fields: a worker has no
    
    2276
    +  rules, no unfolding discounts, never diverges, and its argument strictness
    
    2277
    +  is given by `dataConRepArgCbvInfos`.  `rebuildCall` has a separate, much
    
    2278
    +  simpler, equation for it.
    
    2279
    +
    
    2280
    +  We want `rebuildCall`, rather than `rebuild`, for its StrictArg treatment
    
    2281
    +  of arguments that are evaluated: strict fields (see Note [Strict fields
    
    2282
    +  in Core]), and unlifted arguments (#28169).  E.g. we want
    
    2283
    +      K (case x of (a,b) -> a)    -->   case x of (a,b) -> K a
    
    2284
    +      I# (case x of (a,b) -> a#)  -->   case x of (a,b) -> I# a#
    
    2285
    +  See Note [ArgCbvInfo] in GHC.Core.DataCon.
    
    2276 2286
     -}
    
    2277 2287
     
    
    2278 2288
     simplInId :: SimplEnv -> InId -> SimplCont -> SimplM (SimplFloats, OutExpr)
    
    2279 2289
     simplInId env var cont
    
    2280
    -  | Just dc <- isDataConWorkId_maybe var
    
    2281
    -  , isLazyDataConRep dc                    -- See Note [Fast path for lazy data constructors]
    
    2282
    -  = rebuild env (Var var) cont
    
    2290
    +  | Just dc <- isDataConWorkId_maybe var  -- See Note [Simplifying data constructor applications]
    
    2291
    +  = if dataConRepIsLazy dc
    
    2292
    +    then rebuild env (Var var) cont                              -- (SDC1)
    
    2293
    +    else rebuildCall (zapSubstEnv env) (dataConArgInfo dc) cont  -- (SDC2)
    
    2294
    +
    
    2283 2295
       | otherwise
    
    2284 2296
       = assertPpr (not (isCoVar var)) (ppr var) $
    
    2285 2297
         case substId env var of
    
    ... ... @@ -2439,54 +2451,123 @@ rebuildCall :: SimplEnvIS -> ArgInfo -> SimplCont
    2439 2451
     -- it is usually empty, and regardless should be ignored.
    
    2440 2452
     -- Only the in-scope set matters, plus the seMode flags
    
    2441 2453
     
    
    2442
    --- Check the invariant
    
    2443
    -rebuildCall env arg_info _cont
    
    2444
    -  | assertPpr (checkSimplEnvIS env) (pprBadSimplEnvIS env $$ ppr arg_info) False
    
    2445
    -  = pprPanic "rebuildCall" empty
    
    2446
    -
    
    2447
    ----------- Bottoming applications --------------
    
    2448
    -rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_dmds = [] }) cont
    
    2449
    -  -- When we run out of demands, it means that the call is definitely bottom.
    
    2450
    -  -- See (TC2) in Note [Trimming the continuation for bottoming functions]
    
    2451
    -  = rebuild env (argInfoExpr fun rev_args) (mkBottomCont cont)
    
    2452
    -
    
    2453
    ----------- Simplify type applications --------------
    
    2454
    -rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = cont })
    
    2455
    -  = rebuildCall env (addTyArgTo info arg_ty hole_ty) cont
    
    2456
    -
    
    2457
    ----------- Simplify value arguments --------------------
    
    2458
    -rebuildCall env fun_info
    
    2459
    -            (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
    
    2460
    -                        , sc_hole_ty = fun_ty, sc_cont = cont })
    
    2461
    -  | UnSimplified arg_env <- arg_se
    
    2462
    -  , isStrictArgInfo fun_info  -- Strict arguments
    
    2463
    -  , seCaseCase env            -- But only when case-of-case is on.
    
    2464
    -                              -- See Note [Case-of-case and full laziness]
    
    2465
    -  = simplExprF (arg_env `setInScopeFromE` env) arg $
    
    2466
    -    addCastMCo arg_mco $
    
    2467
    -    StrictArg { sc_fun = fun_info, sc_fun_ty = fun_ty
    
    2468
    -              , sc_dup = NoDup
    
    2469
    -              , sc_cont = cont }
    
    2470
    -                -- Note [Shadowing in the Simplifier]
    
    2471
    -
    
    2472
    -  | otherwise      -- Lazy, or already simplified arguments
    
    2473
    -  -- DO NOT float anything outside, hence simplExprC
    
    2474
    -  -- There is no benefit (unlike in a let-binding), and we'd
    
    2475
    -  -- have to be very careful about bogus strictness through
    
    2476
    -  -- floating a demanded let.
    
    2477
    -  = do  { arg' <- simplArg env (Just fun_info) fun_ty arg_se arg arg_mco
    
    2478
    -        ; rebuildCall env (addValArgTo fun_info  arg' fun_ty) cont }
    
    2479
    -
    
    2480
    ----------- No further useful info, revert to generic rebuild ------------
    
    2481
    -rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_arg_specs, ai_rules = rules }) cont
    
    2482
    -  | null rules
    
    2483
    -  = rebuild env (argInfoExpr fun rev_arg_specs) cont
    
    2484
    -  | otherwise  -- Try rules again: Plan (AFTER) in Note [When to apply rewrite rules]
    
    2485
    -  = do { let arg_specs = reverse rev_arg_specs
    
    2486
    -       ; mb_match <- tryRules env rules fun (map argSpecArg arg_specs)
    
    2487
    -       ; case mb_match of
    
    2488
    -           Just rule_match -> fireRuleAFTER env rule_match arg_specs cont
    
    2489
    -           Nothing         -> rebuild env (argInfoExpr fun rev_arg_specs) cont }
    
    2454
    +-- NB: rebuildCall takes the ArgInfo apart once, and then loops with `go`,
    
    2455
    +-- passing only the pieces that change from one argument to the next.
    
    2456
    +-- We only re-package an ArgInfo when we need one, for a StrictArg
    
    2457
    +-- continuation.  This saves allocating a fresh ArgInfo record for every
    
    2458
    +-- argument, which is measurable (e.g. compiler/perf/T9961).
    
    2459
    +-- Similarly `go` loops over the [Demand] in the RemainingArgDmds; the
    
    2460
    +-- Divergence (which says what happens when they run out) does not change.
    
    2461
    +---------- Data constructor workers ------------
    
    2462
    +-- A specialised, much simpler, version of the general case below
    
    2463
    +-- See (SDC2) in Note [Simplifying data constructor applications]
    
    2464
    +rebuildCall env (DataConArgInfo { ai_dc_app = app0, ai_dc_args = dc_args0 })
    
    2465
    +            cont0
    
    2466
    +  = assertPpr (checkSimplEnvIS env) (pprBadSimplEnvIS env) $
    
    2467
    +    go app0 dc_args0 cont0
    
    2468
    +  where
    
    2469
    +    -- `app` is the data constructor applied to the arguments so far
    
    2470
    +    go :: OutExpr -> [ArgCbvInfo] -> SimplCont -> SimplM (SimplFloats, OutExpr)
    
    2471
    +    go app dc_args (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
    
    2472
    +      = go (App app (Type arg_ty)) dc_args cont
    
    2473
    +
    
    2474
    +    go app (dc_arg : dc_args)
    
    2475
    +       (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
    
    2476
    +                   , sc_hole_ty = fun_ty, sc_cont = cont })
    
    2477
    +      | ArgCbv <- dc_arg          -- Strict (or unlifted) field; ArgRepPoly is lazy
    
    2478
    +                                  -- See Note [ArgCbvInfo] in GHC.Core.DataCon
    
    2479
    +      , UnSimplified arg_env <- arg_se
    
    2480
    +      , seCaseCase env            -- Only when case-of-case is on.
    
    2481
    +                                  -- See Note [Case-of-case and full laziness]
    
    2482
    +      = simplExprF (arg_env `setInScopeFromE` env) arg $
    
    2483
    +        addCastMCo arg_mco $
    
    2484
    +        StrictArg { sc_fun = DataConArgInfo { ai_dc_app = app
    
    2485
    +                                            , ai_dc_args = dc_arg : dc_args }
    
    2486
    +                  , sc_fun_ty = fun_ty
    
    2487
    +                  , sc_dup = NoDup
    
    2488
    +                  , sc_cont = cont }
    
    2489
    +
    
    2490
    +      | otherwise
    
    2491
    +      = do  { arg' <- simplArg env fun_ty arg_se arg arg_mco
    
    2492
    +            ; go (App app arg') dc_args cont }
    
    2493
    +
    
    2494
    +    go app _ cont   -- No rules for data constructors
    
    2495
    +      = rebuild env app cont
    
    2496
    +
    
    2497
    +---------- The general case ------------
    
    2498
    +rebuildCall env info@(ArgInfo { ai_fun_id = fun, ai_args = rev_args0, ai_rules = rules
    
    2499
    +                              , ai_encl = encl, ai_discs = discs0
    
    2500
    +                              , ai_dmds = dmd_ty0@(DmdType { dt_env = dmd_env0
    
    2501
    +                                                           , dt_args = dmds0 }) })
    
    2502
    +            cont0
    
    2503
    +  = assertPpr (checkSimplEnvIS env) (pprBadSimplEnvIS env $$ ppr info) $
    
    2504
    +    go rev_args0 dmds0 discs0 cont0
    
    2505
    +  where
    
    2506
    +    go :: [ArgSpec] -> [Demand] -> Infinite Int -> SimplCont
    
    2507
    +       -> SimplM (SimplFloats, OutExpr)
    
    2508
    +
    
    2509
    +    ---------- Bottoming applications --------------
    
    2510
    +    go rev_args [] _ cont
    
    2511
    +      | isDeadEndDiv (de_div dmd_env0)  -- c.f. splitArgDmd
    
    2512
    +      -- When we run out of demands, it means that the call is definitely bottom.
    
    2513
    +      -- See (TC2) in Note [Trimming the continuation for bottoming functions]
    
    2514
    +      = rebuild env (argInfoExpr fun rev_args) (mkBottomCont cont)
    
    2515
    +
    
    2516
    +    ---------- Simplify type applications --------------
    
    2517
    +    go rev_args dmds discs (ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = cont })
    
    2518
    +      = go (TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty } : rev_args) dmds discs cont
    
    2519
    +
    
    2520
    +    ---------- Simplify value arguments --------------------
    
    2521
    +    go rev_args dmds discs@(Inf _ discs')
    
    2522
    +       (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
    
    2523
    +                   , sc_hole_ty = fun_ty, sc_cont = cont })
    
    2524
    +      | UnSimplified arg_env <- arg_se
    
    2525
    +      , seCaseCase env            -- Only when case-of-case is on.
    
    2526
    +                                  -- See Note [Case-of-case and full laziness]
    
    2527
    +      , isStrUsedDmd dmd          -- Strict arguments; c.f. isStrictArgInfo
    
    2528
    +                                  -- NB: mkArgInfo makes unlifted args strict
    
    2529
    +      = simplExprF (arg_env `setInScopeFromE` env) arg $
    
    2530
    +        addCastMCo arg_mco $
    
    2531
    +        StrictArg { sc_fun = info { ai_args = rev_args, ai_discs = discs
    
    2532
    +                                  , ai_dmds = dmd_ty0 { dt_args = dmds } }
    
    2533
    +                  , sc_fun_ty = fun_ty
    
    2534
    +                  , sc_dup = NoDup
    
    2535
    +                  , sc_cont = cont }
    
    2536
    +                    -- Note [Shadowing in the Simplifier]
    
    2537
    +
    
    2538
    +      | otherwise      -- Lazy, or already simplified arguments
    
    2539
    +      -- DO NOT float anything outside, hence simplExprC
    
    2540
    +      -- There is no benefit (unlike in a let-binding), and we'd
    
    2541
    +      -- have to be very careful about bogus strictness through
    
    2542
    +      -- floating a demanded let.
    
    2543
    +      = do  { arg' <- case arg_se of
    
    2544
    +                 Simplified {}  -- See Note [Avoid repeated simplification]
    
    2545
    +                   -> return (mkCastMCo arg arg_mco)
    
    2546
    +                 UnSimplified arg_env
    
    2547
    +                   -> simplExprC (arg_env `setInScopeFromE` env) arg $
    
    2548
    +                      addCastMCo arg_mco $
    
    2549
    +                      Stop (funArgTy fun_ty) (lazyArgCallCtxt encl discs)
    
    2550
    +                           (subDemandIfEvaluated dmd)   -- c.f. mkLazyArgStop
    
    2551
    +            ; go (ValArg { as_arg = arg', as_hole_ty = fun_ty, as_dmd = dmd } : rev_args)
    
    2552
    +                 dmds' discs' cont }
    
    2553
    +      where
    
    2554
    +        !(dmd, dmds') = case dmds of
    
    2555
    +                          dmd : dmds' -> (dmd, dmds')
    
    2556
    +                          []          -> (topDmd, [])
    
    2557
    +                             -- Not bottoming (see first equation of `go`),
    
    2558
    +                             -- so the default demand is topDmd
    
    2559
    +                          -- Bang: avoid allocating thunks for dmd and dmds'
    
    2560
    +
    
    2561
    +    ---------- No further useful info, revert to generic rebuild ------------
    
    2562
    +    go rev_arg_specs _ _ cont
    
    2563
    +      | null rules
    
    2564
    +      = rebuild env (argInfoExpr fun rev_arg_specs) cont
    
    2565
    +      | otherwise  -- Try rules again: Plan (AFTER) in Note [When to apply rewrite rules]
    
    2566
    +      = do { let arg_specs = reverse rev_arg_specs
    
    2567
    +           ; mb_match <- tryRules env rules fun (map argSpecArg arg_specs)
    
    2568
    +           ; case mb_match of
    
    2569
    +               Just rule_match -> fireRuleAFTER env rule_match arg_specs cont
    
    2570
    +               Nothing         -> rebuild env (argInfoExpr fun rev_arg_specs) cont }
    
    2490 2571
     
    
    2491 2572
     -----------------------------------
    
    2492 2573
     tryInlining :: SimplEnv -> Logger -> OutId -> SimplCont -> SimplM (Maybe OutExpr)
    
    ... ... @@ -3649,7 +3730,7 @@ adjustFieldsIdInfo _scrut case_bndr bndr_swap con vs
    3649 3730
       | otherwise
    
    3650 3731
       = go vs the_strs
    
    3651 3732
       where
    
    3652
    -    the_strs = dataConRepStrictness con
    
    3733
    +    the_strs = map argCbvInfoStrictnessMark (dataConRepArgCbvInfos con)
    
    3653 3734
     
    
    3654 3735
         go [] [] = []
    
    3655 3736
         go (v:vs') strs | isTyVar v = v : go vs' strs
    
    ... ... @@ -3659,7 +3740,7 @@ adjustFieldsIdInfo _scrut case_bndr bndr_swap con vs
    3659 3740
                    ppr vs  $$
    
    3660 3741
                    ppr_with_length (map strdisp the_strs) $$
    
    3661 3742
                    ppr_with_length (dataConRepArgTys con) $$
    
    3662
    -               ppr_with_length (dataConRepStrictness con))
    
    3743
    +               ppr_with_length (dataConRepArgCbvInfos con))
    
    3663 3744
           where
    
    3664 3745
             ppr_with_length list
    
    3665 3746
               = ppr list <+> parens (text "length =" <+> ppr (length list))
    
    ... ... @@ -4053,20 +4134,22 @@ This trimming can also be done with other continuations:
    4053 4134
     
    
    4054 4135
     We implement the trimming in three parts:
    
    4055 4136
     
    
    4056
    -(TC1) In `mkArgInfo`, for a bottoming function, we make a list of `RemainingArgDmds`
    
    4057
    -  with a finite list of elements (in the example above, just one).
    
    4137
    +(TC1) In `mkArgInfo`, for a bottoming function, we use its `DmdType` as the
    
    4138
    +  `RemainingArgDmds`. It has a finite list of argument demands (in the example
    
    4139
    +  above, just one), and a divergence that `isDeadEndDiv`.
    
    4058 4140
     
    
    4059
    -  For comparison, note that, for non-bottoming functions, the `RemainingArgDmds`
    
    4060
    -  always finishes with an infinite list of `topDmd`.
    
    4141
    +  For comparison, note that, for non-bottoming functions, the divergence is
    
    4142
    +  not `isDeadEndDiv`, so `splitArgDmd` yields `topDmd` once the argument
    
    4143
    +  demands run out.
    
    4061 4144
     
    
    4062
    -(TC2) In `rebuildCall`, when we run out of `RemainingArgDmds` we discard the
    
    4145
    +(TC2) In `rebuildCall`, when `splitArgDmd` returns Nothing we discard the
    
    4063 4146
       remaining continuation.
    
    4064 4147
     
    
    4065 4148
       After discarding the continuation, the types might not match, in which case
    
    4066 4149
       we leave behind a (case <hole> of {}) wrapper.  See the call to `mkBottomCont`.
    
    4067 4150
     
    
    4068 4151
     (TC3) In `mkDupableContWithDmds`, we similarly discard the continuation when
    
    4069
    -  we run out of `RemainingArgDmds`.
    
    4152
    +  `splitArgDmd` returns Nothing.
    
    4070 4153
     -}
    
    4071 4154
     
    
    4072 4155
     --------------------
    
    ... ... @@ -4098,7 +4181,7 @@ mkDupableCont :: SimplEnvIS
    4098 4181
                                            --   extra let/join-floats and in-scope variables
    
    4099 4182
                             , SimplCont)   -- dup_cont: duplicable continuation
    
    4100 4183
     mkDupableCont env cont
    
    4101
    -  = mkDupableContWithDmds (zapSubstEnv env) (repeat topDmd) cont
    
    4184
    +  = mkDupableContWithDmds (zapSubstEnv env) nopDmdType cont
    
    4102 4185
     
    
    4103 4186
     mkDupableContWithDmds
    
    4104 4187
        :: SimplEnvIS -> RemainingArgDmds
    
    ... ... @@ -4116,7 +4199,7 @@ mkDupableContWithDmds env remaining_dmds cont
    4116 4199
       --                 => simply trim the continuation
    
    4117 4200
       -- c.f. the null-demands case in `rebuildCall`
    
    4118 4201
       -- See (TC3) in Note [Trimming the continuation for bottoming functions]
    
    4119
    -  | null remaining_dmds
    
    4202
    +  | Nothing <- splitArgDmd remaining_dmds
    
    4120 4203
       = return (emptyFloats env, mkBottomCont cont)
    
    4121 4204
     
    
    4122 4205
     mkDupableContWithDmds _ _ (Stop {}) = panic "mkDupableCont"     -- Handled by previous eqn
    
    ... ... @@ -4158,18 +4241,24 @@ mkDupableContWithDmds env _
    4158 4241
         (StrictArg { sc_fun = fun, sc_cont = cont
    
    4159 4242
                    , sc_fun_ty = fun_ty })
    
    4160 4243
       -- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
    
    4161
    -  | isNothing (isDataConId_maybe (ai_fun fun))
    
    4244
    +  | ArgInfo { ai_fun_id = fun_id, ai_dmds = fun_dmds, ai_args = args } <- fun
    
    4245
    +       -- Not a DataConArgInfo: these always use Plan B, which is just as well,
    
    4246
    +       -- because a DataConArgInfo does not record its arguments separately
    
    4247
    +  , isNothing (isDataConId_maybe fun_id)
    
    4162 4248
              -- isDataConId: see point (DJ4) of Note [Duplicating join points]
    
    4249
    +         -- NB: fun_id is never a data constructor /worker/ (they use
    
    4250
    +         --     DataConArgInfo), but it can be a data constructor /wrapper/
    
    4163 4251
       , thumbsUpPlanA cont
    
    4164 4252
       = -- Use Plan A of Note [Duplicating StrictArg]
    
    4165
    ---    pprTrace "Using plan A" (ppr (ai_fun fun) $$ text "args" <+> ppr (ai_args fun) $$ text "cont" <+> ppr cont) $
    
    4166
    -    do { let _ :| dmds = expectNonEmpty (ai_dmds fun)   -- See Invariant of StrictArg;
    
    4167
    -                                                        -- ai_dmds is never empty
    
    4253
    +--    pprTrace "Using plan A" (ppr (ai_fun_id fun) $$ text "args" <+> ppr (ai_args fun) $$ text "cont" <+> ppr cont) $
    
    4254
    +    do { let dmds = case splitArgDmd fun_dmds of
    
    4255
    +                       Just (_, dmds) -> dmds
    
    4256
    +                       Nothing -> pprPanic "mkDupableContWithDmds" (ppr fun)
    
    4257
    +                          -- See Invariant of StrictArg
    
    4168 4258
            ; (floats1, cont')  <- mkDupableContWithDmds env dmds cont
    
    4169 4259
                                   -- Use the demands from the function to add the right
    
    4170 4260
                                   -- demand info on any bindings we make for further args
    
    4171
    -       ; (floats_s, args') <- mapAndUnzipM (makeTrivialArg env)
    
    4172
    -                                           (ai_args fun)
    
    4261
    +       ; (floats_s, args') <- mapAndUnzipM (makeTrivialArg env) args
    
    4173 4262
            ; return ( foldl' addLetFloats floats1 floats_s
    
    4174 4263
                     , StrictArg { sc_fun = fun { ai_args = args' }
    
    4175 4264
                                 , sc_cont = cont'
    
    ... ... @@ -4210,13 +4299,14 @@ mkDupableContWithDmds env dmds
    4210 4299
             --              let a = ...arg...
    
    4211 4300
             --              in [...hole...] a
    
    4212 4301
             -- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
    
    4213
    -    do  { let dmd:|cont_dmds =
    
    4214
    -                -- We took care to handle an empty demand list at the start,
    
    4215
    -                -- ensuring this call to 'expectNonEmpty' does not panic (#27261).
    
    4216
    -                expectNonEmpty dmds
    
    4302
    +    do  { let (dmd, cont_dmds) = case splitArgDmd dmds of
    
    4303
    +                Just prs -> prs
    
    4304
    +                Nothing  -> pprPanic "mkDupableContWithDmds:ApplyToVal" (ppr cont)
    
    4305
    +                -- We took care to handle bottoming demands at the start,
    
    4306
    +                -- ensuring this does not panic (#27261).
    
    4217 4307
             ; (floats1, cont') <- mkDupableContWithDmds env cont_dmds cont
    
    4218 4308
             ; let env' = env `setInScopeFromF` floats1
    
    4219
    -        ; arg' <- simplArg env' Nothing hole_ty se arg arg_mco
    
    4309
    +        ; arg' <- simplArg env' hole_ty se arg arg_mco
    
    4220 4310
             ; (let_floats2, triv_arg) <- makeTrivial env' NotTopLevel dmd (fsLit "karg") arg'
    
    4221 4311
             ; let all_floats = floats1 `addLetFloats` let_floats2
    
    4222 4312
             ; return ( all_floats
    
    ... ... @@ -4281,10 +4371,10 @@ mkDupableStrictBind env arg_bndr join_rhs res_ty
    4281 4371
                             , sc_cont = mkBoringStop res_ty } )
    
    4282 4372
       | otherwise
    
    4283 4373
       = do { join_bndr <- newJoinId [arg_bndr] res_ty
    
    4284
    -       ; let arg_info = ArgInfo { ai_fun   = join_bndr
    
    4285
    -                                , ai_rules = [], ai_args  = []
    
    4286
    -                                , ai_encl  = False, ai_dmds  = repeat topDmd
    
    4287
    -                                , ai_discs = Inf.repeat 0 }
    
    4374
    +       ; let arg_info = ArgInfo { ai_fun_id = join_bndr
    
    4375
    +                                , ai_rules  = [], ai_args = []
    
    4376
    +                                , ai_encl   = False, ai_dmds = nopDmdType
    
    4377
    +                                , ai_discs  = Inf.repeat 0 }
    
    4288 4378
            ; return ( addJoinFloats (emptyFloats env) $
    
    4289 4379
                       unitJoinFloat                   $
    
    4290 4380
                       NonRec join_bndr                $
    
    ... ... @@ -4306,10 +4396,9 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
    4306 4396
       | otherwise
    
    4307 4397
       = do  { let rhs_ty'  = exprType alt_rhs_in
    
    4308 4398
     
    
    4309
    -              bangs
    
    4310
    -                | DataAlt c <- con
    
    4311
    -                = dataConRepStrictness c
    
    4312
    -                | otherwise = []
    
    4399
    +              bangs = case con of
    
    4400
    +                          DataAlt dc -> map argCbvInfoStrictnessMark (dataConRepArgCbvInfos dc)
    
    4401
    +                          _          -> []
    
    4313 4402
     
    
    4314 4403
                   abstracted_binders = abstract_binders alt_bndrs bangs
    
    4315 4404
     
    

  • compiler/GHC/Core/Opt/Simplify/Utils.hs
    ... ... @@ -31,11 +31,11 @@ module GHC.Core.Opt.Simplify.Utils (
    31 31
             interestingCallContext,
    
    32 32
     
    
    33 33
             -- ArgInfo
    
    34
    -        ArgInfo(..), ArgSpec(..), RemainingArgDmds, mkArgInfo,
    
    34
    +        ArgInfo(..), ArgSpec(..), RemainingArgDmds, mkArgInfo, dataConArgInfo,
    
    35 35
             addValArgTo, addTyArgTo,
    
    36 36
             argInfoExpr, argSpecArg,
    
    37 37
             pushOutArgs, pushArgSpecs,
    
    38
    -        isStrictArgInfo, lazyArgContext,
    
    38
    +        isStrictArgInfo, lazyArgContext, lazyArgCallCtxt,
    
    39 39
     
    
    40 40
             abstractFloats,
    
    41 41
     
    
    ... ... @@ -44,7 +44,6 @@ module GHC.Core.Opt.Simplify.Utils (
    44 44
         ) where
    
    45 45
     
    
    46 46
     import GHC.Prelude hiding (head, init, last, tail)
    
    47
    -import qualified GHC.Prelude as Partial (head)
    
    48 47
     
    
    49 48
     import GHC.Core
    
    50 49
     import GHC.Types.Literal ( isLitRubbish )
    
    ... ... @@ -64,7 +63,8 @@ import GHC.Core.Unfold.Make
    64 63
     import GHC.Core.Opt.Simplify.Monad
    
    65 64
     import GHC.Core.Type     hiding( substTy )
    
    66 65
     import GHC.Core.Coercion hiding( substCo )
    
    67
    -import GHC.Core.DataCon ( dataConWorkId, isNullaryRepDataCon )
    
    66
    +import GHC.Core.DataCon ( DataCon, ArgCbvInfo(..), dataConWorkId, isNullaryRepDataCon
    
    67
    +                         , dataConRepArgCbvInfos )
    
    68 68
     import GHC.Core.Multiplicity
    
    69 69
     import GHC.Core.Opt.ConstantFold
    
    70 70
     
    
    ... ... @@ -150,7 +150,7 @@ Key points:
    150 150
     data SimplCont
    
    151 151
       = Stop                -- ^ Stop[e] = e
    
    152 152
             OutType         -- ^ Type of the <hole>
    
    153
    -        CallCtxt        -- ^ Tells if there is something interesting about
    
    153
    +        !CallCtxt       -- ^ Tells if there is something interesting about
    
    154 154
                             --          the syntactic context, and hence the inliner
    
    155 155
                             --          should be a bit keener (see interestingCallContext)
    
    156 156
                             -- Specifically:
    
    ... ... @@ -158,7 +158,7 @@ data SimplCont
    158 158
                             --     Inlining the call might allow the rule to fire
    
    159 159
                             -- Never ValAppCxt (use ApplyToVal instead)
    
    160 160
                             -- or CaseCtxt (use Select instead)
    
    161
    -        SubDemand       -- ^ The evaluation context of e. Tells how e is evaluated.
    
    161
    +        !SubDemand      -- ^ The evaluation context of e. Tells how e is evaluated.
    
    162 162
                             -- This fuels eta-expansion or eta-reduction without looking
    
    163 163
                             -- at lambda bodies, for example.
    
    164 164
                             --
    
    ... ... @@ -212,7 +212,7 @@ data SimplCont
    212 212
           , sc_fun  :: ArgInfo     -- Specifies f, e1..en, whether f has rules, etc
    
    213 213
                                    --     plus demands and discount flags for *this* arg
    
    214 214
                                    --          and further args
    
    215
    -                               --     Invariant: ai_dmds and ai_discs are never empty
    
    215
    +                               --     Invariant: (splitArgDmd ai_dmds) is never Nothing
    
    216 216
           , sc_fun_ty :: OutType   -- Type of the function (f e1 .. en),
    
    217 217
                                    -- presumably (arg_ty -> res_ty)
    
    218 218
                                    -- where res_ty is expected by sc_cont
    
    ... ... @@ -317,7 +317,10 @@ instance Outputable SimplCont where
    317 317
       ppr (StrictBind { sc_bndr = b, sc_cont = cont })
    
    318 318
         = (text "StrictBind" <+> ppr b) $$ ppr cont
    
    319 319
       ppr (StrictArg { sc_fun = ai, sc_cont = cont })
    
    320
    -    = (text "StrictArg" <+> ppr (ai_fun ai)) $$ ppr cont
    
    320
    +    = (text "StrictArg" <+> pp_fun ai) $$ ppr cont
    
    321
    +    where
    
    322
    +      pp_fun (ArgInfo { ai_fun_id = fun })        = ppr fun
    
    323
    +      pp_fun (DataConArgInfo { ai_dc_app = app }) = ppr app
    
    321 324
       ppr (Select { sc_env = env, sc_bndr = bndr, sc_alts = alts, sc_cont = cont })
    
    322 325
         = (text "Select" <> braces (ppr env) <+> ppr bndr) $$
    
    323 326
           whenPprDebug (nest 2 $ ppr alts) $$ ppr cont
    
    ... ... @@ -352,9 +355,9 @@ doesn't matter because we'll never compute them all.
    352 355
     
    
    353 356
     data ArgInfo
    
    354 357
       = ArgInfo {
    
    355
    -        ai_fun   :: OutId,      -- ^ The function
    
    356
    -        ai_args  :: [ArgSpec],  -- ^ ...applied to these args (which are in *reverse* order)
    
    357
    -                                -- NB: all these argumennts are already simplified
    
    358
    +        ai_fun_id :: OutId,       -- ^ The function
    
    359
    +        ai_args   :: [ArgSpec],   -- ^ ...applied to these args (which are in *reverse* order)
    
    360
    +                                  -- NB: all these argumennts are already simplified
    
    358 361
     
    
    359 362
             ai_rules :: [CoreRule], -- ^ Rules for this function
    
    360 363
             ai_encl  :: Bool,
    
    ... ... @@ -365,6 +368,7 @@ data ArgInfo
    365 368
     
    
    366 369
             ai_dmds :: RemainingArgDmds,
    
    367 370
               -- ^ Demands on remaining value arguments (beyond 'ai_args')
    
    371
    +          --   Take it apart with 'splitArgDmd'
    
    368 372
     
    
    369 373
             ai_discs :: Infinite Int
    
    370 374
               -- ^ Discounts for remaining value arguments (beyond 'ai_args')
    
    ... ... @@ -372,12 +376,32 @@ data ArgInfo
    372 376
               -- A non-zero value means: be keener to inline
    
    373 377
         }
    
    374 378
     
    
    379
    +  -- | A specialised ArgInfo for a data constructor /worker/;
    
    380
    +  -- see Note [Simplifying data constructor applications]
    
    381
    +  -- in GHC.Core.Opt.Simplify.Iteration.
    
    382
    +  -- A worker has no rules, no unfolding discounts, never diverges, and
    
    383
    +  -- its argument strictness is fixed; so we need many fewer fields.
    
    384
    +  | DataConArgInfo {
    
    385
    +        ai_dc_app  :: OutExpr,     -- ^ The data constructor worker, applied to
    
    386
    +                                   --   the (simplified) arguments so far
    
    387
    +                                   -- NB: we never need to duplicate a StrictArg
    
    388
    +                                   --   whose sc_fun is a DataConArgInfo, so we do
    
    389
    +                                   --   not need the args separately; see point
    
    390
    +                                   --   (DJ4) of Note [Duplicating join points]
    
    391
    +        ai_dc_args :: [ArgCbvInfo]  -- ^ Info about the remaining value arguments
    
    392
    +                                   --   See Note [ArgCbvInfo] in GHC.Core.DataCon
    
    393
    +    }
    
    394
    +
    
    375 395
     -- | 'RemainingArgDmds' gives the demands on any remaining value arguments.
    
    376 396
     --
    
    377
    --- It is usually infinite (with 'topDmd's in the tail), but if it is finite it
    
    378
    --- guarantees that the function diverges after being applied to that number
    
    379
    --- of arguments.
    
    380
    -type RemainingArgDmds = [Demand]
    
    397
    +-- Take it apart with 'splitArgDmd'.  When its 'dt_args' run out, the
    
    398
    +-- Divergence in its 'dt_env' says what happens next:
    
    399
    +--   * if 'isDeadEndDiv', the function diverges after being applied to that
    
    400
    +--     number of arguments; 'splitArgDmd' returns Nothing.
    
    401
    +--   * otherwise all further arguments have demand 'topDmd'
    
    402
    +-- See Note [Trimming the continuation for bottoming functions]
    
    403
    +-- in GHC.Core.Opt.Simplify.Iteration
    
    404
    +type RemainingArgDmds = DmdType
    
    381 405
     
    
    382 406
     data ArgSpec
    
    383 407
       -- | A value argument
    
    ... ... @@ -389,20 +413,31 @@ data ArgSpec
    389 413
               , as_hole_ty :: OutType }   -- ^ Type of the function (presumably @t1 -> t2@ for 'ValArg' or @forall a. blah@ for 'TyArg')
    
    390 414
     
    
    391 415
     instance Outputable ArgInfo where
    
    392
    -  ppr (ArgInfo { ai_fun = fun, ai_args = args, ai_dmds = dmds, ai_rules = rules })
    
    416
    +  ppr (ArgInfo { ai_fun_id = fun, ai_args = args, ai_dmds = dmds, ai_rules = rules })
    
    393 417
         = text "ArgInfo" <+> braces
    
    394 418
              (sep [ text "fun =" <+> ppr fun
    
    395
    -              , text "dmds(first 10) =" <+> ppr (take 10 dmds)
    
    419
    +              , text "dmds =" <+> ppr dmds
    
    396 420
                   , text "args =" <+> ppr args
    
    397 421
                   , text "rewrite =" <+> ppr rules ])
    
    422
    +  ppr (DataConArgInfo { ai_dc_app = app, ai_dc_args = dc_args })
    
    423
    +    = text "DataConArgInfo" <+> braces
    
    424
    +         (sep [ text "app =" <+> ppr app
    
    425
    +              , text "dc_args =" <+> ppr dc_args ])
    
    398 426
     
    
    399 427
     instance Outputable ArgSpec where
    
    400 428
       ppr (ValArg { as_arg = arg })  = text "ValArg" <+> ppr arg
    
    401 429
       ppr (TyArg { as_arg_ty = ty }) = text "TyArg" <+> ppr ty
    
    402 430
     
    
    403 431
     addValArgTo :: ArgInfo ->  OutExpr -> OutType -> ArgInfo
    
    432
    +addValArgTo ai@(DataConArgInfo { ai_dc_app = app, ai_dc_args = dc_args }) arg _hole_ty
    
    433
    +  | _ : dc_args' <- dc_args
    
    434
    +  = DataConArgInfo { ai_dc_app = App app arg, ai_dc_args = dc_args' }
    
    435
    +  | otherwise
    
    436
    +  = pprPanic "addValArgTo:DataConArgInfo" (ppr ai $$ ppr arg)
    
    437
    +
    
    404 438
     addValArgTo ai arg hole_ty
    
    405
    -  | ArgInfo { ai_dmds = dmd:dmds, ai_discs = Inf _ discs } <- ai
    
    439
    +  | ArgInfo { ai_dmds = dmds0, ai_discs = Inf _ discs } <- ai
    
    440
    +  , Just (dmd, dmds) <- splitArgDmd dmds0
    
    406 441
           -- Pop the top demand and and discounts off
    
    407 442
       , let arg_spec = ValArg { as_arg = arg, as_hole_ty = hole_ty, as_dmd = dmd }
    
    408 443
       = ai { ai_args    = arg_spec : ai_args ai
    
    ... ... @@ -413,15 +448,40 @@ addValArgTo ai arg hole_ty
    413 448
         -- There should always be enough demands and discounts
    
    414 449
     
    
    415 450
     addTyArgTo :: ArgInfo -> OutType -> OutType -> ArgInfo
    
    416
    -addTyArgTo ai arg_ty hole_ty = ai { ai_args    = arg_spec : ai_args ai }
    
    417
    -  where
    
    418
    -    arg_spec = TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty }
    
    451
    +addTyArgTo ai@(DataConArgInfo { ai_dc_app = app }) arg_ty _hole_ty
    
    452
    +  = ai { ai_dc_app = App app (Type arg_ty) }
    
    453
    +addTyArgTo ai arg_ty hole_ty
    
    454
    +  = ai { ai_args   = TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty } : ai_args ai }
    
    455
    +
    
    456
    +argCbvInfoDmd :: ArgCbvInfo -> Demand
    
    457
    +-- The demand that a data constructor worker places on an argument
    
    458
    +-- Treat ArgRepPoly as lazy; see Note [ArgCbvInfo] in GHC.Core.DataCon
    
    459
    +-- c.f. GHC.Types.Id.Make.mkDataConWorkId, which makes the same choice
    
    460
    +argCbvInfoDmd ArgCbv     = evalDmd
    
    461
    +argCbvInfoDmd ArgCbn     = topDmd
    
    462
    +argCbvInfoDmd ArgRepPoly = topDmd
    
    419 463
     
    
    420 464
     isStrictArgInfo :: ArgInfo -> Bool
    
    421 465
     -- True if the function is strict in the next argument
    
    466
    +isStrictArgInfo (DataConArgInfo { ai_dc_args = dc_args })
    
    467
    +  = case dc_args of { ArgCbv : _ -> True; _ -> False }
    
    422 468
     isStrictArgInfo (ArgInfo { ai_dmds = dmds })
    
    423
    -  | dmd:_ <- dmds = isStrUsedDmd dmd
    
    424
    -  | otherwise     = False
    
    469
    +  | Just (dmd,_) <- splitArgDmd dmds = isStrUsedDmd dmd
    
    470
    +  | otherwise                        = False
    
    471
    +
    
    472
    +argInfoNextDmd :: ArgInfo -> Demand
    
    473
    +-- The demand on the next argument; the call should not be bottoming
    
    474
    +argInfoNextDmd ai@(DataConArgInfo { ai_dc_args = dc_args })
    
    475
    +  | dc_arg : _ <- dc_args            = argCbvInfoDmd dc_arg
    
    476
    +  | otherwise                        = pprPanic "argInfoNextDmd" (ppr ai)
    
    477
    +argInfoNextDmd ai@(ArgInfo { ai_dmds = dmds })
    
    478
    +  | Just (dmd,_) <- splitArgDmd dmds = dmd
    
    479
    +  | otherwise                        = pprPanic "argInfoNextDmd" (ppr ai)
    
    480
    +
    
    481
    +argInfoHasRules :: ArgInfo -> Bool
    
    482
    +-- True <=> this function, or an enclosing one, has rules; see ai_encl
    
    483
    +argInfoHasRules (DataConArgInfo {})           = False
    
    484
    +argInfoHasRules (ArgInfo { ai_encl = encl }) = encl
    
    425 485
     
    
    426 486
     pushOutArgs :: Type -> [OutExpr] -> SimplCont -> SimplCont
    
    427 487
     pushOutArgs _fun_ty [] cont
    
    ... ... @@ -478,7 +538,7 @@ mkRhsStop ty is_rec bndr_dmd = Stop ty (RhsCtxt is_rec) (subDemandIfEvaluated bn
    478 538
     mkLazyArgStop :: OutType -> ArgInfo -> SimplCont
    
    479 539
     mkLazyArgStop ty fun_info = Stop ty (lazyArgContext fun_info) arg_sd
    
    480 540
       where
    
    481
    -    arg_sd = subDemandIfEvaluated (Partial.head (ai_dmds fun_info))
    
    541
    +    arg_sd = subDemandIfEvaluated (argInfoNextDmd fun_info)
    
    482 542
     
    
    483 543
     -------------------
    
    484 544
     contIsRhs :: SimplCont -> Maybe RecFlag
    
    ... ... @@ -669,7 +729,7 @@ contEvalContext bndrs cont = go cont
    669 729
                                                   , text "cont:"  <+> ppr cont ])
    
    670 730
                                           topSubDmd
    
    671 731
     
    
    672
    -    go (StrictArg{sc_fun=fun_info}) = subDemandIfEvaluated (Partial.head (ai_dmds fun_info))
    
    732
    +    go (StrictArg{sc_fun=fun_info}) = subDemandIfEvaluated (argInfoNextDmd fun_info)
    
    673 733
         go (StrictBind{sc_bndr=bndr})   = subDemandIfEvaluated (idDemandInfo bndr)
    
    674 734
         go (Select{})                   = topSubDmd
    
    675 735
         -- Perhaps reconstruct the demand on the scrutinee by looking at field
    
    ... ... @@ -705,21 +765,29 @@ mkBottomCont cont = go cont
    705 765
                stop_cont = contStop k
    
    706 766
     
    
    707 767
     -------------------
    
    768
    +dataConArgInfo :: DataCon -> ArgInfo
    
    769
    +-- Like mkArgInfo, but specialised for a data constructor worker
    
    770
    +-- See Note [Simplifying data constructor applications]
    
    771
    +--     in GHC.Core.Opt.Simplify.Iteration
    
    772
    +dataConArgInfo dc
    
    773
    +  = DataConArgInfo { ai_dc_app  = Var (dataConWorkId dc)
    
    774
    +                   , ai_dc_args = dataConRepArgCbvInfos dc }
    
    775
    +
    
    708 776
     mkArgInfo :: SimplEnv -> Id -> [CoreRule] -> SimplCont -> ArgInfo
    
    709 777
     mkArgInfo env fun rules_for_fun cont
    
    710 778
       | n_val_args < idArity fun            -- Note [Unsaturated functions]
    
    711
    -  = ArgInfo { ai_fun = fun, ai_args = []
    
    779
    +  = ArgInfo { ai_fun_id = fun, ai_args = []
    
    712 780
                 , ai_rules = rules_for_fun
    
    713 781
                 , ai_encl = False
    
    714
    -            , ai_dmds = vanilla_dmds
    
    782
    +            , ai_dmds = nopDmdType
    
    715 783
                 , ai_discs = vanilla_discounts }
    
    716 784
       | otherwise
    
    717
    -  = ArgInfo { ai_fun   = fun
    
    718
    -            , ai_args  = []
    
    719
    -            , ai_rules = rules_for_fun
    
    720
    -            , ai_encl  = fun_has_rules || contHasRules cont
    
    721
    -            , ai_dmds  = add_type_strictness (idType fun) arg_dmds
    
    722
    -            , ai_discs = arg_discounts }
    
    785
    +  = ArgInfo { ai_fun_id = fun
    
    786
    +            , ai_args   = []
    
    787
    +            , ai_rules  = rules_for_fun
    
    788
    +            , ai_encl   = fun_has_rules || contHasRules cont
    
    789
    +            , ai_dmds   = add_type_strictness (idType fun) arg_dmd_ty
    
    790
    +            , ai_discs  = arg_discounts }
    
    723 791
       where
    
    724 792
         n_val_args  = countValArgs cont
    
    725 793
     
    
    ... ... @@ -732,30 +800,19 @@ mkArgInfo env fun rules_for_fun cont
    732 800
                                   -> discounts Inf.++ vanilla_discounts
    
    733 801
                             _     -> vanilla_discounts
    
    734 802
     
    
    735
    -    vanilla_dmds :: RemainingArgDmds
    
    736
    -    vanilla_dmds  = repeat topDmd
    
    737
    -
    
    738
    -    arg_dmds :: RemainingArgDmds
    
    739
    -    arg_dmds
    
    803
    +    arg_dmd_ty :: RemainingArgDmds
    
    804
    +    arg_dmd_ty
    
    740 805
           | not (seInline env)
    
    741
    -      = vanilla_dmds -- See Note [Do not expose strictness if sm_inline=False]
    
    742
    -      | otherwise
    
    743
    -      = -- add_type_str fun_ty $
    
    744
    -        case splitDmdSig (idDmdSig fun) of
    
    745
    -          (demands, result_info)
    
    746
    -               | not (demands `lengthExceeds` n_val_args)
    
    747
    -               -> remaining_dmds     -- Enough args, use the strictness given.
    
    748
    -               | otherwise
    
    749
    -               -> warnPprTrace True "More demands than arity" (ppr fun <+> ppr (idArity fun)
    
    806
    +      = nopDmdType -- See Note [Do not expose strictness if sm_inline=False]
    
    807
    +      | DmdSig dmd_ty@(DmdType { dt_args = demands }) <- idDmdSig fun
    
    808
    +      = if not (demands `lengthExceeds` n_val_args)
    
    809
    +        then dmd_ty   -- Enough args, use the strictness given.
    
    810
    +                      -- If the divergence isDeadEndDiv, the result is bottom
    
    811
    +                      -- after (length demands) args; see (TC1) in
    
    812
    +                      -- Note [Trimming the continuation for bottoming functions]
    
    813
    +        else warnPprTrace True "More demands than arity" (ppr fun <+> ppr (idArity fun)
    
    750 814
                                     <+> ppr n_val_args <+> ppr demands) $
    
    751
    -                  vanilla_dmds      -- Not enough args, or no strictness
    
    752
    -
    
    753
    -                where
    
    754
    -                  remaining_dmds :: RemainingArgDmds
    
    755
    -                  -- isDeadEndDiv: if remaining_dmds is finite, result is bottom
    
    756
    -                  -- See (TC1) in Note [Trimming the continuation for bottoming functions]
    
    757
    -                  remaining_dmds | isDeadEndDiv result_info = demands
    
    758
    -                                 | otherwise                = demands ++ vanilla_dmds
    
    815
    +             nopDmdType      -- Not enough args, or no strictness
    
    759 816
     
    
    760 817
         add_type_strictness :: Type -> RemainingArgDmds -> RemainingArgDmds
    
    761 818
         -- If the function arg /types/ are strict, record that in the RemainingArgDmds
    
    ... ... @@ -764,27 +821,35 @@ mkArgInfo env fun rules_for_fun cont
    764 821
         -- add_type_strictness is done repeatedly (for each call);
    
    765 822
         --   might be better once-for-all in the function
    
    766 823
         -- But beware primops/datacons with no strictness
    
    767
    -
    
    768
    -    add_type_strictness fun_ty dmds
    
    769
    -      | null dmds = []
    
    770
    -
    
    771
    -      | Just (_, fun_ty') <- splitForAllTyCoVar_maybe fun_ty
    
    772
    -      = add_type_strictness fun_ty' dmds     -- Look through foralls
    
    773
    -
    
    774
    -      | Just (_, _, arg_ty, fun_ty') <- splitFunTy_maybe fun_ty        -- Add strict-type info
    
    775
    -      , dmd : rest_dmds <- dmds
    
    776
    -      , let dmd'
    
    777
    -             | definitelyUnliftedType arg_ty
    
    778
    -             = strictifyDmd dmd
    
    779
    -             | otherwise
    
    780
    -             -- Something that's not definitely unlifted.
    
    781
    -             -- If the type is representation-polymorphic, we can't know whether
    
    782
    -             -- it's strict.
    
    783
    -             = dmd
    
    784
    -      = dmd' : add_type_strictness fun_ty' rest_dmds
    
    785
    -
    
    786
    -      | otherwise
    
    787
    -      = dmds
    
    824
    +    add_type_strictness fun_ty dmd_ty@(DmdType { dt_env = dmd_env, dt_args = dmds0 })
    
    825
    +      = dmd_ty { dt_args = go fun_ty dmds0 }
    
    826
    +      where
    
    827
    +        -- NB: when the dt_args run out we must carry on (with the default
    
    828
    +        -- demand, topDmd) as long as there are more argument types, unless
    
    829
    +        -- the call is bottoming.  c.f. splitArgDmd
    
    830
    +        is_bottoming = isDeadEndDiv (de_div dmd_env)
    
    831
    +        next_dmd (dmd : dmds)        = Just (dmd, dmds)
    
    832
    +        next_dmd [] | is_bottoming   = Nothing
    
    833
    +                    | otherwise      = Just (topDmd, [])
    
    834
    +
    
    835
    +        go fun_ty dmds
    
    836
    +          | Just (_, fun_ty') <- splitForAllTyCoVar_maybe fun_ty
    
    837
    +          = go fun_ty' dmds     -- Look through foralls
    
    838
    +
    
    839
    +          | Just (_, _, arg_ty, fun_ty') <- splitFunTy_maybe fun_ty        -- Add strict-type info
    
    840
    +          , Just (dmd, rest_dmds) <- next_dmd dmds
    
    841
    +          , let dmd'
    
    842
    +                 | definitelyUnliftedType arg_ty
    
    843
    +                 = strictifyDmd dmd
    
    844
    +                 | otherwise
    
    845
    +                 -- Something that's not definitely unlifted.
    
    846
    +                 -- If the type is representation-polymorphic, we can't know whether
    
    847
    +                 -- it's strict.
    
    848
    +                 = dmd
    
    849
    +          = dmd' : go fun_ty' rest_dmds
    
    850
    +
    
    851
    +          | otherwise
    
    852
    +          = dmds
    
    788 853
     
    
    789 854
     {- Note [Unsaturated functions]
    
    790 855
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    ... ... @@ -964,12 +1029,19 @@ the incentive to disappear when we inline `f`!
    964 1029
     
    
    965 1030
     lazyArgContext :: ArgInfo -> CallCtxt
    
    966 1031
     -- Use this for lazy arguments
    
    1032
    +lazyArgContext (DataConArgInfo {}) = BoringCtxt
    
    967 1033
     lazyArgContext (ArgInfo { ai_encl = encl_rules, ai_discs = discs })
    
    1034
    +  = lazyArgCallCtxt encl_rules discs
    
    1035
    +
    
    1036
    +lazyArgCallCtxt :: Bool -> Infinite Int -> CallCtxt
    
    1037
    +-- Same as lazyArgContext, but taking the relevant pieces of the ArgInfo
    
    1038
    +lazyArgCallCtxt encl_rules discs
    
    968 1039
       | encl_rules                    = RuleArgCtxt
    
    969 1040
       | Inf disc _ <- discs, disc > 0 = DiscArgCtxt  -- Be keener here
    
    970 1041
       | otherwise                     = BoringCtxt   -- Nothing interesting
    
    971 1042
     
    
    972 1043
     strictArgContext :: ArgInfo -> CallCtxt
    
    1044
    +strictArgContext (DataConArgInfo {}) = RhsCtxt NonRecursive  -- See comments below
    
    973 1045
     strictArgContext (ArgInfo { ai_encl = encl_rules, ai_discs = discs })
    
    974 1046
     -- Use this for strict arguments
    
    975 1047
       | encl_rules                    = RuleArgCtxt
    
    ... ... @@ -1050,7 +1122,7 @@ contHasRules cont
    1050 1122
         go (ApplyToVal { sc_cont = cont }) = go cont
    
    1051 1123
         go (ApplyToTy  { sc_cont = cont }) = go cont
    
    1052 1124
         go (CastIt { sc_cont = cont })     = go cont
    
    1053
    -    go (StrictArg { sc_fun = fun })    = ai_encl fun
    
    1125
    +    go (StrictArg { sc_fun = fun })    = argInfoHasRules fun
    
    1054 1126
         go (Stop _ RuleArgCtxt _)          = True
    
    1055 1127
         go (TickIt _ c)                    = go c
    
    1056 1128
         go (Select {})                     = False
    

  • compiler/GHC/Core/Opt/SpecConstr.hs
    ... ... @@ -2605,7 +2605,7 @@ callToPat env bndr_occs call@(Call fn args con_env)
    2605 2605
       = do  { let in_scope = substInScopeSet (sc_subst env)
    
    2606 2606
     
    
    2607 2607
             ; arg_triples <- argsToPats env in_scope con_env (idType fn) args bndr_occs
    
    2608
    -                                    (repeat NotMarkedStrict)
    
    2608
    +                                    (repeat ArgCbn)
    
    2609 2609
                        -- This trims the args to be no longer than
    
    2610 2610
                        -- the lambdas in the function definition (bndr_occs)
    
    2611 2611
     
    
    ... ... @@ -2666,7 +2666,7 @@ argsToPats :: ScEnv
    2666 2666
                -> Type                -- ^ type of the head (function or data constructor)
    
    2667 2667
                -> [CoreArg]           -- ^ arguments of the head
    
    2668 2668
                -> [ArgOcc]            -- ^ occurrence info, one per argument; the result is trimmed to this length
    
    2669
    -           -> [StrictnessMark]    -- ^ strictness info, one per value argument
    
    2669
    +           -> [ArgCbvInfo]        -- ^ strictness info, one per value argument
    
    2670 2670
                -> UniqSM [(Bool, CoreArg, [Id])]
    
    2671 2671
     argsToPats env in_scope val_env = go
    
    2672 2672
       where
    
    ... ... @@ -2674,7 +2674,7 @@ argsToPats env in_scope val_env = go
    2674 2674
         go _ _ [] _ = return []
    
    2675 2675
         go fun_ty (arg : args) (occ : occs) strs
    
    2676 2676
           = do { (pat, strs') <- case arg of
    
    2677
    -               Type {} -> do { pat <- argToPat env in_scope val_env arg_ty arg occ NotMarkedStrict
    
    2677
    +               Type {} -> do { pat <- argToPat env in_scope val_env arg_ty arg occ ArgCbn
    
    2678 2678
                                  ; return (pat, strs) }
    
    2679 2679
                    _ | str : strs' <- strs
    
    2680 2680
                            -> do { pat <- argToPat env in_scope val_env arg_ty arg occ str
    
    ... ... @@ -2699,7 +2699,7 @@ argToPat :: ScEnv
    2699 2699
              -> Type                        -- ^ type for this argument
    
    2700 2700
              -> CoreArg                     -- ^ A call arg (or component thereof)
    
    2701 2701
              -> ArgOcc                      -- ^ occurrence info for the argument
    
    2702
    -         -> StrictnessMark              -- ^ Tells us if this argument is a strict field of a data constructor
    
    2702
    +         -> ArgCbvInfo                  -- ^ Tells us if this argument is a strict field of a data constructor
    
    2703 2703
                                             -- See Note [SpecConstr and strict fields]
    
    2704 2704
              -> UniqSM (Bool, CoreArg, [Id])
    
    2705 2705
     
    
    ... ... @@ -2726,7 +2726,7 @@ argToPat1 :: ScEnv
    2726 2726
       -> Type
    
    2727 2727
       -> Expr CoreBndr
    
    2728 2728
       -> ArgOcc
    
    2729
    -  -> StrictnessMark
    
    2729
    +  -> ArgCbvInfo
    
    2730 2730
       -> UniqSM (Bool, Expr CoreBndr, [Id])
    
    2731 2731
     argToPat1 _env _in_scope _val_env _pat_ty arg@(Type {}) _arg_occ _arg_str
    
    2732 2732
       = return (False, arg, [])
    
    ... ... @@ -2767,9 +2767,9 @@ argToPat1 env in_scope val_env _pat_ty arg arg_occ _arg_str
    2767 2767
       , not (ignoreDataCon env dc)        -- See Note [NoSpecConstr]
    
    2768 2768
       , Just arg_occs <- mb_scrut dc
    
    2769 2769
       = do { let (ty_args, rest_args) = splitAtList (dataConUnivTyVars dc) args
    
    2770
    -             con_str :: [StrictnessMark]
    
    2770
    +             con_str :: [ArgCbvInfo]
    
    2771 2771
                  -- con_str corresponds 1-1 with the /value/ arguments
    
    2772
    -             con_str = dataConRepStrictness dc
    
    2772
    +             con_str = dataConRepArgCbvInfos dc
    
    2773 2773
                  con_ty  = applyTypeToArgs (dataConRepType dc) ty_args
    
    2774 2774
           --  ; pprTraceM "bangs" (ppr (length rest_args == length con_str) $$
    
    2775 2775
           --       ppr dc $$
    
    ... ... @@ -2808,7 +2808,7 @@ argToPat1 env in_scope val_env _pat_ty (Var v) arg_occ arg_str
    2808 2808
            -- box that we can eliminate in the caller
    
    2809 2809
       , not (ignoreType env (varType v))
    
    2810 2810
       -- See Note [SpecConstr and strict fields]
    
    2811
    -  = return (True, Var v, if isMarkedStrict arg_str then [v] else mempty)
    
    2811
    +  = return (True, Var v, if arg_str == ArgCbv then [v] else mempty)
    
    2812 2812
       where
    
    2813 2813
         is_value
    
    2814 2814
             | isLocalId v = v `elemInScopeSet` in_scope
    
    ... ... @@ -2860,11 +2860,13 @@ argToPat1 _env _in_scope _val_env pat_ty _arg _arg_occ arg_str
    2860 2860
       = wildCardPat pat_ty arg_str
    
    2861 2861
     
    
    2862 2862
     -- | wildCardPats are always boring
    
    2863
    -wildCardPat :: Type -> StrictnessMark -> UniqSM (Bool, CoreArg, [Id])
    
    2863
    +wildCardPat :: Type -> ArgCbvInfo -> UniqSM (Bool, CoreArg, [Id])
    
    2864 2864
     wildCardPat ty str
    
    2865 2865
       = do { id <- mkSysLocalOrCoVarM (fsLit "sc") ManyTy ty
    
    2866 2866
            -- ; pprTraceM "wildCardPat" (ppr id' <+> ppr (idUnfolding id'))
    
    2867
    -       ; return (False, varToCoreExpr id, if isMarkedStrict str then [id] else []) }
    
    2867
    +       ; return (False, varToCoreExpr id, if str == ArgCbv then [id] else []) }
    
    2868
    +       -- NB: unlifted (ArgCbv) args will be filtered out by
    
    2869
    +       -- wantCbvForId in mkSeqs; see Note [SpecConstr and strict fields]
    
    2868 2870
     
    
    2869 2871
     isValue :: ValueEnv -> CoreExpr -> Maybe Value
    
    2870 2872
     isValue _env (Lit lit)
    

  • compiler/GHC/Core/Opt/WorkWrap/Utils.hs
    ... ... @@ -221,7 +221,7 @@ mkWwBodies opts fun_id ww_arity arg_vars res_ty demands res_cpr
    221 221
                   zapped_arg_vars = map zap_var arg_vars
    
    222 222
             ; (subst, cloned_arg_vars) <- cloneBndrsM empty_subst zapped_arg_vars
    
    223 223
             ; let res_ty' = substTyUnchecked subst res_ty
    
    224
    -              init_str_marks = map (const NotMarkedStrict) cloned_arg_vars
    
    224
    +              init_str_marks = mapConst NotMarkedStrict cloned_arg_vars
    
    225 225
     
    
    226 226
             ; (useful1, work_args_str, wrap_fn_str, fn_args)
    
    227 227
                  <- -- pprTrace "mkWWbodies" (ppr fun_id $$ ppr (arg_vars `zip` cloned_arg_vars) $$ ppr demands) $
    
    ... ... @@ -1050,7 +1050,7 @@ unbox_one_arg opts arg_var
    1050 1050
     
    
    1051 1051
                  -- Mark arguments coming out of strict fields so we can seq them in the worker
    
    1052 1052
                  -- See Note [Call-by-value for worker args]
    
    1053
    -             all_str_marks = (map (const NotMarkedStrict) ex_tvs') ++ con_str_marks
    
    1053
    +             all_str_marks = mapConst NotMarkedStrict ex_tvs' ++ con_str_marks
    
    1054 1054
     
    
    1055 1055
            ; (nested_useful, worker_args, wrap_fn, wrap_args)
    
    1056 1056
                  <- mkWWstr opts (ex_tvs' ++ arg_ids') all_str_marks
    

  • compiler/GHC/Core/SimpleOpt.hs
    ... ... @@ -1726,12 +1726,10 @@ exprIsConApp_maybe ise@(ISE in_scope id_unf) expr
    1726 1726
         -- See Note [Strict fields in Core] for what a field seq is and (SFC2) for
    
    1727 1727
         -- why we insert them
    
    1728 1728
         mkFieldSeqFloats in_scope dc args
    
    1729
    -      | isLazyDataConRep dc
    
    1730
    -      = (in_scope, nilOL, args)
    
    1731
    -      | otherwise
    
    1732
    -      = (in_scope', floats', ty_args ++ val_args')
    
    1729
    +      | dataConRepIsLazy dc = (in_scope, nilOL, args)  -- Short cut in common case
    
    1730
    +      | otherwise           = (in_scope', floats', tyco_args ++ val_args')
    
    1733 1731
           where
    
    1734
    -        (ty_args, val_args) = splitAtList (dataConUnivAndExTyCoVars dc) args
    
    1732
    +        (tyco_args, val_args) = splitAtList (dataConUnivAndExTyCoVars dc) args
    
    1735 1733
             (in_scope', floats', val_args') = foldr do_one (in_scope, nilOL, []) $
    
    1736 1734
                                               zipEqual str_marks val_args
    
    1737 1735
             str_marks = dataConRepStrictness dc
    

  • compiler/GHC/Core/TyCon.hs
    ... ... @@ -1504,16 +1504,27 @@ There are a number of wrinkles
    1504 1504
     (UCM2) The TyCon for a unary class is /not/ identified as a newtype.
    
    1505 1505
        Rather, it has its own AlgTyConRhs, namely `UnaryClassTyCon`
    
    1506 1506
     
    
    1507
    -(UCM3) Unlike non-unary classes, a value of type (C ty), where `C` is a unary
    
    1507
    +(UCM3a) Unlike non-unary classes, a value of type (C ty), where `C` is a unary
    
    1508 1508
        class, might be bottom, because it is represented by the method type alone.
    
    1509 1509
        See GHC.Core.Type.isTerminatingType, and Note [NON-BOTTOM-DICTS invariant]
    
    1510 1510
        in GHC.Core
    
    1511 1511
     
    
    1512
    -   Similarly in exprOkForSpeculation/exprOkToDiscard/exprOkForSpecEval,
    
    1513
    -   in GHC.Core.Utils.  In the utility funcion `app_ok` we need a special
    
    1514
    -   case for the DFunIds; they generally terminate, but not for unary classes.
    
    1515
    -
    
    1516
    -(UMC4) To avoid regressions, in Core we want to remember that
    
    1512
    +(UCM3b) Following (UCM3a), (MkC e) is a value, or ok-for-speculation, only if
    
    1513
    +   `e` is.  So `GHC.Core.Utils.exprIsHNF`, `exprIsConLike`, and `app_ok`
    
    1514
    +   (used by exprOkForSpeculation/exprOkToDiscard/exprOkForSpecEval) have a
    
    1515
    +   special case for unary-class data constructors.  (#28183 shows why this
    
    1516
    +   matters.)
    
    1517
    +
    
    1518
    +   We do /not/ achieve this by giving the data constructor a strict field
    
    1519
    +         data C a = MkC !(a->a)
    
    1520
    +   That would be semantically fine, but it leaks into DmdAnal, the StrictArg
    
    1521
    +   treatment in the Simplifier, and the field seqs of (SFC2) in Note [Strict
    
    1522
    +   fields in Core]; for example (op dict x) would become
    
    1523
    +         case $cop of m { __DEFAULT -> m x }
    
    1524
    +   which bloats code (T5321FD got 10% worse).  Those field seqs are pointless
    
    1525
    +   for unary classes anyway, because of (UCM13).
    
    1526
    +
    
    1527
    +(UCM4) To avoid regressions, in Core we want to remember that
    
    1517 1528
                  (MkUC x) is really just  x
    
    1518 1529
                  (op d)   is really just  d
    
    1519 1530
         We account for this in several places:
    
    ... ... @@ -3065,8 +3076,8 @@ isUnaryClassTyCon tc@(TyCon { tyConDetails = details })
    3065 3076
     
    
    3066 3077
     isTerminatingTyCon :: TyCon -> Bool
    
    3067 3078
     -- ^ True <=> a value of type (T t1..tn), where `T` is this TyCon, cannot be bottom.
    
    3068
    --- The only TyCons that satisfy `isTerminatingTyCon` are non-unary class TyCons.
    
    3069
    --- See (UCM3) in Note [Unary class magic], and
    
    3079
    +-- The only TyCons that satisfy `isTerminatingTyCon` are /non-unary/ class TyCons.
    
    3080
    +-- See (UCM3a) in Note [Unary class magic], and
    
    3070 3081
     -- Note [NON-BOTTOM-DICTS invariant] in GHC.Core.
    
    3071 3082
     -- An AbstractTyCon returns False: it comes from an hs-boot file, and the real
    
    3072 3083
     -- 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
    1781 1781
           where
    
    1782 1782
             argf | isVisibleFunArg af = Required
    
    1783 1783
                  | otherwise          = Inferred
    
    1784
    -    go _ _ arg_tys = map (const Required) arg_tys
    
    1784
    +    go _ _ arg_tys = mapConst Required arg_tys
    
    1785 1785
                             -- something is ill-kinded. But this can happen
    
    1786 1786
                             -- when printing errors. Assume everything is Required.
    
    1787 1787
     
    

  • compiler/GHC/Core/Utils.hs
    ... ... @@ -2271,15 +2271,14 @@ app_ok fun_ok primop_ok fun val_args
    2271 2271
       | otherwise
    
    2272 2272
       = case idDetails fun of
    
    2273 2273
           DFunId terminating -> terminating
    
    2274
    -         -- DFuns terminate, unless the dict is implemented
    
    2275
    -         -- by a no-op in which case they may not
    
    2276
    -         -- See (UCM3) in Note [Unary class magic] in GHC.Core.TyCon
    
    2274
    +         -- DFuns terminate, except for unary classes
    
    2275
    +         -- See (UCM3a) in Note [Unary class magic] in GHC.Core.TyCon
    
    2277 2276
     
    
    2278 2277
           DataConWorkId dc
    
    2279
    -        | isLazyDataConRep dc
    
    2280
    -        -> args_ok
    
    2281
    -        | otherwise
    
    2282
    -        -> fields_ok (dataConRepStrictness dc)
    
    2278
    +        | isUnaryClassDataCon dc -> all ok_for_spec val_args
    
    2279
    +              -- (MkC e) is just e; see (UCM3b) in Note [Unary class magic]
    
    2280
    +        | dataConRepIsLazy dc    -> True  -- Args are all thunks
    
    2281
    +        | otherwise              -> fields_ok (dataConRepArgCbvInfos dc)
    
    2283 2282
     
    
    2284 2283
           ClassOpId _ is_terminating_result
    
    2285 2284
             | is_terminating_result -- See Note [exprOkForSpeculation and type classes]
    
    ... ... @@ -2344,13 +2343,16 @@ app_ok fun_ok primop_ok fun val_args
    2344 2343
         -- Used for strict DataCon worker arguments
    
    2345 2344
         -- See (SFC1) of Note [Strict fields in Core]
    
    2346 2345
         -- See Note [exprOkForSpeculation] (a,b)
    
    2347
    -    fields_ok str_marks = all3Prefix field_ok val_arg_tys str_marks val_args
    
    2348
    -    field_ok :: Type -> StrictnessMark -> CoreExpr -> Bool
    
    2349
    -    field_ok arg_ty str arg
    
    2350
    -       = ok_for_spec arg || (definitely_lifted arg_ty arg && str==NotMarkedStrict)
    
    2346
    +    fields_ok arg_infos = all3Prefix field_ok val_arg_tys arg_infos val_args
    
    2347
    +    field_ok :: Type -> ArgCbvInfo -> CoreExpr -> Bool
    
    2348
    +    -- Conservative: treat ArgRepPoly as possibly strict; see Note [ArgCbvInfo]
    
    2349
    +    field_ok _      ArgCbn     _   = True
    
    2350
    +    field_ok _      ArgCbv     arg = ok_for_spec arg
    
    2351
    +    field_ok arg_ty ArgRepPoly arg = arg_ok arg_ty arg
    
    2351 2352
            -- The (ok_for_spec arg) test works for /both/ for unlifted types, /and/
    
    2352 2353
            -- for lifted but strict fields. E.g. K (I# 3) is ok-for-spec,
    
    2353 2354
            -- even if K is strict
    
    2355
    +       -- For ArgRepPoly, arg_ok looks at the type of the argument itself
    
    2354 2356
     
    
    2355 2357
         -- We want to see if the argument type is definitely lifted.
    
    2356 2358
         -- But consider
    
    ... ... @@ -2650,9 +2652,9 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
    2650 2652
         is_hnf_like e
    
    2651 2653
       where
    
    2652 2654
         is_hnf_like (Var v) -- NB: There are no value args at this point
    
    2653
    -      =  id_app_is_value v [] -- Catches nullary constructors,
    
    2654
    -                              --      so that [] and () are values, for example
    
    2655
    -                              -- and (e.g.) primops that don't have unfoldings
    
    2655
    +      =  check_app v [] -- Catches nullary constructors,
    
    2656
    +                        --      so that [] and () are values, for example
    
    2657
    +                        -- and (e.g.) primops that don't have unfoldings
    
    2656 2658
           || is_con_unf (idUnfolding v)
    
    2657 2659
             -- Check the thing's unfolding; it might be bound to a value
    
    2658 2660
             --   or to a guaranteed-evaluated variable (isEvaldUnfolding)
    
    ... ... @@ -2687,67 +2689,75 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
    2687 2689
           = is_hnf_like rhs
    
    2688 2690
         is_hnf_like _                = False
    
    2689 2691
     
    
    2690
    -    -- Collect arguments through Casts and Ticks and call id_app_is_value
    
    2692
    +    -- Collect arguments through Casts and Ticks and call check_app
    
    2691 2693
         app_is_value :: CoreExpr -> [CoreArg] -> Bool
    
    2692
    -    app_is_value (Var f)    as = id_app_is_value f as
    
    2694
    +    app_is_value (Var f)    as = check_app f as
    
    2693 2695
         app_is_value (Tick _ f) as = app_is_value f as
    
    2694 2696
         app_is_value (Cast f _) as = app_is_value f as
    
    2695 2697
         app_is_value (App f a)  as | isValArg a = app_is_value f (a:as)
    
    2696 2698
                                    | otherwise  = app_is_value f as
    
    2697 2699
         app_is_value _          _  = False
    
    2698 2700
     
    
    2699
    -    id_app_is_value id val_args
    
    2700
    -      | Just dc <- isDataConWorkId_maybe id
    
    2701
    -      , isUnaryClassDataCon  dc
    
    2702
    -      = all is_hnf_like val_args  -- Look through unary class data cons
    
    2703
    -      | otherwise
    
    2704
    -      -- See Note [exprIsHNF for function applications]
    
    2705
    -      --   for the specification and examples
    
    2701
    +    -- check_app: See Note [exprIsHNF for function applications]
    
    2702
    +    --            for the specification and examples
    
    2703
    +    -- We check arity (and CONLIKEness) first because it's cheaper
    
    2704
    +    --     and we reject quickly on saturated apps.
    
    2705
    +    check_app :: Id -> [CoreArg] -> Bool
    
    2706
    +    check_app id val_args
    
    2706 2707
           = case compare (idArity id) (length val_args) of
    
    2707
    -          EQ | is_con id ->      -- Saturated app of a DataCon/CONLIKE Id
    
    2708
    -            case mb_str_marks id of
    
    2709
    -              Just str_marks ->  -- with strict fields; see (SFC1) of Note [Strict fields in Core]
    
    2710
    -                assert (val_args `equalLength` str_marks) $
    
    2711
    -                fields_hnf str_marks
    
    2712
    -              Nothing ->         -- without strict fields: like PAP
    
    2713
    -                args_hnf         -- NB: CONLIKEs are lazy!
    
    2714
    -
    
    2715
    -          GT ->                  -- PAP: Check unlifted val_args
    
    2716
    -            args_hnf
    
    2708
    +          EQ -> check_saturated id val_args  -- Saturated application
    
    2709
    +          GT -> check_args      id val_args  -- Partial application
    
    2710
    +          LT -> False                        -- Over-saturated
    
    2717 2711
     
    
    2718
    -          _  -> False
    
    2712
    +    check_saturated :: Id -> [CoreArg] -> Bool
    
    2713
    +    check_saturated id val_args
    
    2714
    +      | Just dc <- isDataConWorkId_maybe id
    
    2715
    +      , isUnaryClassDataCon dc   -- (MkC e) is just e
    
    2716
    +      = all is_hnf_like val_args -- See (UCM3b) in Note [Unary class magic]
    
    2719 2717
     
    
    2718
    +      | Just dc <- isDataConWorkId_maybe id
    
    2719
    +      , let arg_infos = dataConRepArgCbvInfos dc
    
    2720
    +      = -- Saturated data constructors; use `check_field`
    
    2721
    +        -- to ensure we account for strict and unlifted fields
    
    2722
    +        assertPpr (equalLength val_args arg_infos)
    
    2723
    +                  (ppr dc $$ ppr val_args $$ ppr arg_infos) $
    
    2724
    +        all2Prefix check_field val_args arg_infos
    
    2725
    +
    
    2726
    +      | is_con id  -- Saturated CONLIKE: check the arguments
    
    2727
    +      = check_args id val_args
    
    2728
    +
    
    2729
    +      | otherwise  -- Saturated function, not a constructor => not HNF
    
    2730
    +      = False
    
    2731
    +
    
    2732
    +    -- check_args: check that any unlifted args are hnf-like
    
    2733
    +    -- NB: there may be fewer val_args than arg_tys (e.g. (map f))
    
    2734
    +    check_args :: Id -> [CoreArg] -> Bool
    
    2735
    +    check_args id val_args = all2Prefix check_arg val_args arg_tys
    
    2720 2736
           where
    
    2721
    -        -- Saturated, Strict DataCon: Check unlifted val_args and strict fields
    
    2722
    -        fields_hnf str_marks = all3Prefix check_field val_arg_tys str_marks val_args
    
    2723
    -
    
    2724
    -        -- PAP: Check unlifted val_args
    
    2725
    -        args_hnf             = all2Prefix check_arg   val_arg_tys           val_args
    
    2726
    -
    
    2727
    -        val_arg_tys = splitUninstantiatedValArgTys (idType id)
    
    2728
    -          -- val_arg_tys = map exprType val_args, but much less costly.
    
    2729
    -          -- The obvious definition regresses T16577 by 30% so we don't do it.
    
    2730
    -
    
    2731
    -        check_arg a_ty a
    
    2732
    -          | mightBeUnliftedType a_ty = is_hnf_like a
    
    2733
    -          | otherwise                = True
    
    2734
    -         -- Check unliftedness; for example f (x /# 12#) where f has arity two,
    
    2735
    -         -- and the first argument is unboxed. This is not a value!
    
    2736
    -         -- But  f 34#  is a value, so check args for HNFs.
    
    2737
    -         -- NB: We check arity (and CONLIKEness) first because it's cheaper
    
    2738
    -         --     and we reject quickly on saturated apps.
    
    2739
    -        check_field a_ty str a
    
    2740
    -          | mightBeUnliftedType a_ty = is_hnf_like a
    
    2741
    -          | isMarkedStrict str       = is_hnf_like a
    
    2742
    -          | otherwise                = True
    
    2743
    -          -- isMarkedStrict: Respect Note [Strict fields in Core]
    
    2744
    -
    
    2745
    -        mb_str_marks id
    
    2746
    -          | Just dc <- isDataConWorkId_maybe id
    
    2747
    -          , not (isLazyDataConRep dc)
    
    2748
    -          = Just (dataConRepStrictness dc)
    
    2749
    -          | otherwise
    
    2750
    -          = Nothing
    
    2737
    +        arg_tys = get_val_arg_tys id
    
    2738
    +
    
    2739
    +    -- check_arg: check unliftedness; for example f (x /# 12#) where f
    
    2740
    +    -- has arity two, and the first argument is unboxed. This is not a value!
    
    2741
    +    -- But  f 34#  is a value, so check unlifted args for HNFs.
    
    2742
    +    check_arg arg arg_ty
    
    2743
    +      | mightBeUnliftedType arg_ty = is_hnf_like arg
    
    2744
    +      | otherwise                  = True
    
    2745
    +
    
    2746
    +    -- check_field: used for a data constructor worker:
    
    2747
    +    --     check unlifted val_args /and/ strict fields
    
    2748
    +    -- See (SFC1) of Note [Strict fields in Core]
    
    2749
    +    -- Conservative: treat ArgRepPoly as possibly strict; see Note [ArgCbvInfo]
    
    2750
    +    -- (check_arg would do the same, because the uninstantiated type of a
    
    2751
    +    --  rep-poly field might be unlifted.)
    
    2752
    +    check_field :: CoreArg -> ArgCbvInfo -> Bool
    
    2753
    +    check_field _   ArgCbn     = True
    
    2754
    +    check_field arg ArgCbv     = is_hnf_like arg
    
    2755
    +    check_field arg ArgRepPoly = is_hnf_like arg
    
    2756
    +
    
    2757
    +    get_val_arg_tys id = splitUninstantiatedValArgTys (idType id)
    
    2758
    +       -- val_arg_tys = map exprType val_args, but much less costly.
    
    2759
    +       -- The obvious definition regresses T16577 by 30% so we don't do it.
    
    2760
    +
    
    2751 2761
     
    
    2752 2762
     {-
    
    2753 2763
     Note [exprIsHNF Tick]
    
    ... ... @@ -2903,7 +2913,7 @@ dataConInstPat fss uniqs mult con inst_tys
    2903 2913
         ex_tvs   = dataConExTyCoVars con
    
    2904 2914
         arg_tys  = dataConRepArgTys con
    
    2905 2915
         arg_strs = dataConRepStrictness con  -- 1-1 with arg_tys
    
    2906
    -    n_ex = length ex_tvs
    
    2916
    +    n_ex     = length ex_tvs
    
    2907 2917
     
    
    2908 2918
           -- split the Uniques and FastStrings
    
    2909 2919
         (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
    1369 1369
                                 checkExpectedKind hs_ty ty kind arg_kind
    
    1370 1370
                               | ((L loc hs_ty),ty,kind) <- zip3 hs_tys tys kinds ]
    
    1371 1371
     
    
    1372
    -       ; finish_tuple rn_ty tup_sort tys' (map (const arg_kind) tys') exp_kind }
    
    1372
    +       ; finish_tuple rn_ty tup_sort tys' (mapConst arg_kind tys') exp_kind }
    
    1373 1373
     tc_hs_tuple_ty rn_ty mode HsUnboxedTuple tys exp_kind =
    
    1374 1374
         tc_tuple rn_ty mode UnboxedTuple tys exp_kind
    
    1375 1375
     
    

  • 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 =
    655 655
     
    
    656 656
         OrPat _ pats -> do -- See Note [Implementation of OrPatterns], Typechecker (1)
    
    657 657
           { let pats_list   = NE.toList pats
    
    658
    -            pat_exp_tys = map (const scaled_exp_pat_ty) pats_list
    
    658
    +            pat_exp_tys = mapConst scaled_exp_pat_ty pats_list
    
    659 659
           ; (pats_list', (res, pat_ct)) <- tc_lpats pat_exp_tys penv pats_list (captureConstraints thing_inside)
    
    660 660
           ; let pats' = NE.fromList pats_list' -- tc_lpats preserves non-emptiness
    
    661 661
           ; emitConstraints pat_ct
    

  • compiler/GHC/Tc/TyCl.hs
    ... ... @@ -3713,7 +3713,7 @@ tcTyFamInstEqn fam_tc mb_clsinfo
    3713 3713
            -- (tcFamInstEqnGuts zonks to Type)
    
    3714 3714
     
    
    3715 3715
            ; let ax = mkCoAxBranch qtvs [] [] pats rhs_ty
    
    3716
    -                    (map (const Nominal) qtvs)
    
    3716
    +                    (mapConst Nominal qtvs)
    
    3717 3717
                         (locA loc)
    
    3718 3718
                  vi = VI { vi_loc          = locA loc
    
    3719 3719
                          , vi_qtvs         = qtvs
    

  • compiler/GHC/Tc/TyCl/Build.hs
    ... ... @@ -291,9 +291,9 @@ type MethInfo -- A temporary intermediate, to communicate
    291 291
     
    
    292 292
     buildClass :: Name  -- Name of the class/tycon (they have the same Name)
    
    293 293
                -> Kind
    
    294
    -           -> [TyConBinder]                -- Of the tycon
    
    294
    +           -> [TyConBinder]          -- Of the tycon
    
    295 295
                -> [Role]
    
    296
    -           -> [FunDep TyVar]               -- Functional dependencies
    
    296
    +           -> [FunDep TyVar]         -- Functional dependencies
    
    297 297
                -> KnotTied ThetaType     -- Superclasess
    
    298 298
                -> [ClassATItem]          -- Associated types
    
    299 299
                -> [KnotTied MethInfo]    -- Methods
    
    ... ... @@ -330,7 +330,9 @@ buildClass tycon_name kind binders roles fds sc_theta at_items sig_stuff mindef
    330 330
                   rec_tycon  = classTyCon rec_clas
    
    331 331
                   univ_bndrs = tyVarSpecToBinders $ tyConInvisTVBinders binders
    
    332 332
                   univ_tvs   = binderVars univ_bndrs
    
    333
    -              bang_opts  = FixedBangOpts (map (const HsLazy) args)
    
    333
    +              bang_opts  = FixedBangOpts (mapConst HsLazy args)
    
    334
    +                -- NB: even for unary classes the field is lazy;
    
    335
    +                -- see (UCM3b) in Note [Unary class magic]
    
    334 336
     
    
    335 337
             ; rep_nm   <- newTyConRepName datacon_name
    
    336 338
             ; dict_con <- buildDataCon (panic "buildClass: FamInstEnvs")
    
    ... ... @@ -338,7 +340,7 @@ buildClass tycon_name kind binders roles fds sc_theta at_items sig_stuff mindef
    338 340
                                        datacon_name
    
    339 341
                                        False        -- Not declared infix
    
    340 342
                                        rep_nm
    
    341
    -                                   (map (const no_bang) args)
    
    343
    +                                   (mapConst no_bang args)
    
    342 344
                                        [{- No fields -}]
    
    343 345
                                        univ_tvs
    
    344 346
                                        [{- no existentials -}]
    
    ... ... @@ -353,8 +355,7 @@ buildClass tycon_name kind binders roles fds sc_theta at_items sig_stuff mindef
    353 355
             ; let rhs | unary_class
    
    354 356
                       = UnaryClassTyCon dict_con
    
    355 357
                       | isCTupleTyConName tycon_name
    
    356
    -                  = TupleTyCon { data_con = dict_con
    
    357
    -                               , tup_sort = ConstraintTuple }
    
    358
    +                  = TupleTyCon { data_con = dict_con, tup_sort = ConstraintTuple }
    
    358 359
                       | otherwise
    
    359 360
                       = mkDataTyConRhs [dict_con]
    
    360 361
     
    

  • compiler/GHC/Tc/TyCl/Instance.hs
    ... ... @@ -837,7 +837,7 @@ tcDataFamInstDecl mb_clsinfo tv_skol_env
    837 837
                         rep_tc   = mkAlgTyCon rep_tc_name user_kind
    
    838 838
                                               ty_binders (length extra_tcbs)
    
    839 839
                                               res_kind
    
    840
    -                                          (map (const Nominal) ty_binders)
    
    840
    +                                          (mapConst Nominal ty_binders)
    
    841 841
                                               (fmap (typeCheckCType . unLoc) cType) stupid_theta
    
    842 842
                                               tc_rhs parent
    
    843 843
                                               gadt_syntax
    

  • compiler/GHC/Tc/TyCl/Utils.hs
    ... ... @@ -471,7 +471,7 @@ initialRoleEnv hsc_src annots = extendNameEnvList emptyNameEnv .
    471 471
     
    
    472 472
     initialRoleEnv1 :: HscSource -> RoleAnnotEnv -> TyCon -> (Name, [Role])
    
    473 473
     initialRoleEnv1 hsc_src annots_env tc
    
    474
    -  | isFamilyTyCon tc      = (name, map (const Nominal) bndrs)
    
    474
    +  | isFamilyTyCon tc      = (name, mapConst Nominal bndrs)
    
    475 475
       | isAlgTyCon tc         = (name, default_roles)
    
    476 476
       | isTypeSynonymTyCon tc = (name, default_roles)
    
    477 477
       | otherwise             = pprPanic "initialRoleEnv1" (ppr tc)
    

  • compiler/GHC/Types/Demand.hs
    ... ... @@ -59,7 +59,7 @@ module GHC.Types.Demand (
    59 59
         nopDmdType, botDmdType,
    
    60 60
         lubDmdType, maxDmdType, plusDmdType, multDmdType, discardArgDmds,
    
    61 61
         -- ** Other operations
    
    62
    -    peelFV, findIdDemand, addDemand, splitDmdTy, deferAfterPreciseException,
    
    62
    +    peelFV, findIdDemand, addDemand, splitDmdTy, splitArgDmd, deferAfterPreciseException,
    
    63 63
     
    
    64 64
         -- * Demand signatures
    
    65 65
         DmdSig(..), mkDmdSigForArity, mkClosedDmdSig, mkVanillaDmdSig,
    
    ... ... @@ -92,7 +92,7 @@ import GHC.Types.Basic
    92 92
     import GHC.Data.Maybe   ( orElse )
    
    93 93
     
    
    94 94
     import GHC.Core.Type    ( Type, isTerminatingType )
    
    95
    -import GHC.Core.DataCon ( splitDataProductType_maybe, StrictnessMark, isMarkedStrict )
    
    95
    +import GHC.Core.DataCon ( splitDataProductType_maybe, ArgCbvInfo(..) )
    
    96 96
     import GHC.Core.Multiplicity    ( scaledThing )
    
    97 97
     
    
    98 98
     import GHC.Utils.Binary
    
    ... ... @@ -1996,6 +1996,24 @@ splitDmdTy :: DmdType -> (Demand, DmdType)
    1996 1996
     splitDmdTy ty@DmdType{dt_args=dmd:args} = (dmd, ty{dt_args=args})
    
    1997 1997
     splitDmdTy ty@DmdType{dt_env=env}       = (defaultArgDmd (de_div env), ty)
    
    1998 1998
     
    
    1999
    +splitArgDmd :: DmdType -> Maybe (Demand, DmdType)
    
    2000
    +-- ^ Split off the demand on the next argument of a function with this DmdType
    
    2001
    +--   * Nothing       <=> the call is definitely bottom; that is, we have run
    
    2002
    +--                       out of argument demands, and the divergence isDeadEndDiv
    
    2003
    +--   * Just (d, ty') <=> d is the demand on the next argument
    
    2004
    +-- Contrast `splitDmdTy`, which returns the default argument demand when
    
    2005
    +-- we run out, rather than Nothing.
    
    2006
    +-- Used in the Simplifier; see Note [Trimming the continuation for bottoming functions]
    
    2007
    +-- in GHC.Core.Opt.Simplify.Iteration
    
    2008
    +{-# INLINE splitArgDmd #-}
    
    2009
    +splitArgDmd ty@(DmdType { dt_args = dmd : dmds })
    
    2010
    +  = Just (dmd, ty { dt_args = dmds })
    
    2011
    +splitArgDmd ty@(DmdType { dt_env = env })
    
    2012
    +  | isDeadEndDiv div = Nothing
    
    2013
    +  | otherwise        = Just (defaultArgDmd div, ty)
    
    2014
    +  where
    
    2015
    +    div = de_div env
    
    2016
    +
    
    1999 2017
     multDmdType :: Card -> DmdType -> DmdType
    
    2000 2018
     multDmdType C_11 dmd_ty = dmd_ty -- a vital optimisation for T25196
    
    2001 2019
     multDmdType n    (DmdType fv args)
    
    ... ... @@ -2487,17 +2505,19 @@ dmdTransformSig (DmdSig dmd_ty@(DmdType _ arg_ds)) sd
    2487 2505
     
    
    2488 2506
     -- | A special 'DmdTransformer' for data constructors that feeds product
    
    2489 2507
     -- demands into the constructor arguments.
    
    2490
    -dmdTransformDataConSig :: [StrictnessMark] -> DmdTransformer
    
    2508
    +dmdTransformDataConSig :: [ArgCbvInfo] -> DmdTransformer
    
    2491 2509
     -- See Note [Demand transformer for data constructors]
    
    2492
    -dmdTransformDataConSig str_marks sd = case viewProd arity body_sd of
    
    2510
    +dmdTransformDataConSig arg_infos sd = case viewProd arity body_sd of
    
    2493 2511
       Just (_, dmds) -> mk_body_ty n dmds
    
    2494 2512
       Nothing        -> nopDmdType
    
    2495 2513
       where
    
    2496
    -    arity = length str_marks
    
    2514
    +    arity = length arg_infos
    
    2497 2515
         (n, body_sd) = peelManyCalls arity sd
    
    2498
    -    mk_body_ty n dmds = DmdType nopDmdEnv (zipWith (bump n) str_marks dmds)
    
    2499
    -    bump n str dmd | isMarkedStrict str = multDmd n (plusDmd str_field_dmd dmd)
    
    2500
    -                   | otherwise          = multDmd n dmd
    
    2516
    +    mk_body_ty n dmds = DmdType nopDmdEnv (zipWith (bump n) arg_infos dmds)
    
    2517
    +    -- ArgRepPoly: treat as lazy, which is the conservative choice here
    
    2518
    +    -- See Note [ArgCbvInfo] in GHC.Core.DataCon
    
    2519
    +    bump n ArgCbv dmd = multDmd n (plusDmd str_field_dmd dmd)
    
    2520
    +    bump n _         dmd = multDmd n dmd
    
    2501 2521
         str_field_dmd = seqDmd -- See the bit about strict fields
    
    2502 2522
                                -- in Note [Demand transformer for data constructors]
    
    2503 2523
     
    

  • compiler/GHC/Types/Id/Make.hs
    ... ... @@ -541,7 +541,6 @@ mkDataConWorkId wkr_name data_con
    541 541
         univ_tvs  = dataConUnivTyVars data_con
    
    542 542
         ex_tcvs   = dataConExTyCoVars data_con
    
    543 543
         arg_tys   = dataConRepArgTys  data_con  -- Should be same as dataConOrigArgTys
    
    544
    -    str_marks = dataConRepStrictness data_con
    
    545 544
     
    
    546 545
         ----------- Workers for data types --------------
    
    547 546
         alg_wkr_info = noCafIdInfo
    
    ... ... @@ -555,12 +554,22 @@ mkDataConWorkId wkr_name data_con
    555 554
                        `setLFInfo`             wkr_lf_info
    
    556 555
     
    
    557 556
         wkr_inline_prag = alwaysConLikePragma
    
    558
    -    wkr_arity = dataConRepArity data_con
    
    559 557
     
    
    560
    -    wkr_sig = mkClosedDmdSig wkr_dmds topDiv
    
    561
    -    wkr_dmds = map mk_dmd str_marks
    
    562
    -    mk_dmd MarkedStrict    = evalDmd
    
    563
    -    mk_dmd NotMarkedStrict = topDmd
    
    558
    +    -- Strictness signature has arity = wkr_arity
    
    559
    +    -- i.e. including any existential CoVars
    
    560
    +    -- See (EXCO1) in Note [Existential coercion variables]
    
    561
    +    wkr_arity = dataConRepArity data_con
    
    562
    +    arg_infos = dataConRepArgCbvInfos data_con
    
    563
    +    wkr_dmds  = map mk_dmd arg_infos
    
    564
    +    wkr_sig   = assertPpr (arg_infos `lengthIs` wkr_arity &&
    
    565
    +                           splitUninstantiatedValArgTys wkr_ty `lengthIs` wkr_arity)
    
    566
    +                    (ppr data_con $$ ppr arg_infos $$ ppr wkr_ty) $
    
    567
    +                mkClosedDmdSig wkr_dmds topDiv
    
    568
    +    -- NB: GHC.Core.Opt.Simplify.Utils.dataConArgInfo uses this signature,
    
    569
    +    -- and relies on ArgRepPoly being treated as lazy; see Note [ArgCbvInfo]
    
    570
    +    mk_dmd ArgCbv     = evalDmd
    
    571
    +    mk_dmd ArgCbn     = topDmd
    
    572
    +    mk_dmd ArgRepPoly = topDmd
    
    564 573
     
    
    565 574
         -- See Note [LFInfo of DataCon workers and wrappers]
    
    566 575
         wkr_lf_info
    
    ... ... @@ -824,7 +833,7 @@ mkDataConRep platform dc_bang_opts fam_envs wrap_name data_con
    824 833
         wrap_ty      = dataConWrapperType data_con
    
    825 834
         ev_tys       = eqSpecPreds eq_spec ++ theta
    
    826 835
         all_arg_tys  = map unrestricted ev_tys ++ orig_arg_tys
    
    827
    -    ev_ibangs    = map (const HsLazy) ev_tys
    
    836
    +    ev_ibangs    = mapConst HsLazy ev_tys
    
    828 837
         orig_bangs   = dataConSrcBangs data_con
    
    829 838
     
    
    830 839
         wrap_arg_tys
    
    ... ... @@ -852,14 +861,14 @@ mkDataConRep platform dc_bang_opts fam_envs wrap_name data_con
    852 861
     
    
    853 862
         arg_ibangs
    
    854 863
           | new_tycon
    
    855
    -      = map (const HsLazy) orig_arg_tys -- See Note [HsImplBangs for newtypes]
    
    856
    -                                        -- orig_arg_tys should be a singleton, but
    
    857
    -                                        -- if a user declared a wrong newtype we
    
    858
    -                                        -- detect this later (see test T2334A)
    
    864
    +      = mapConst HsLazy orig_arg_tys -- See Note [HsImplBangs for newtypes]
    
    865
    +                                     -- orig_arg_tys should be a singleton, but
    
    866
    +                                     -- if a user declared a wrong newtype we
    
    867
    +                                     -- detect this later (see test T2334A)
    
    859 868
           | otherwise
    
    860 869
           = case dc_bang_opts of
    
    861 870
               SrcBangOpts bang_opts -> zipWith (dataConSrcToImplBang platform bang_opts fam_envs)
    
    862
    -                                    orig_arg_tys orig_bangs
    
    871
    +                                           orig_arg_tys orig_bangs
    
    863 872
               FixedBangOpts bangs   -> bangs
    
    864 873
     
    
    865 874
         (rep_tys_w_strs, wrappers)
    
    ... ... @@ -999,11 +1008,11 @@ For further reading, see:
    999 1008
     
    
    1000 1009
     Note [Bangs on imported data constructors]
    
    1001 1010
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    1002
    -We pass Maybe [HsImplBang] to mkDataConRep to make use of HsImplBangs
    
    1011
    +We pass `DataConBangOpts` to `mkDataConRep` to make use of `HsImplBangs`
    
    1003 1012
     from imported modules.
    
    1004 1013
     
    
    1005
    -- Nothing <=> use HsSrcBangs
    
    1006
    -- Just bangs <=> use HsImplBangs
    
    1014
    +- SrcBangOpts opts         <=> use HsSrcBangs
    
    1015
    +- FixedBangOpts impl_bangs <=> use impl_bangs
    
    1007 1016
     
    
    1008 1017
     For imported types we can't work it all out from the HsSrcBangs,
    
    1009 1018
     because we want to be very sure to follow what the original module
    
    ... ... @@ -1011,8 +1020,8 @@ because we want to be very sure to follow what the original module
    1011 1020
     flags were enabled when it was compiled. So we record the decisions in
    
    1012 1021
     the interface file.
    
    1013 1022
     
    
    1014
    -The HsImplBangs passed are in 1-1 correspondence with the
    
    1015
    -dataConOrigArgTys of the DataCon.
    
    1023
    +The `HsImplBangs` passed are in 1-1 correspondence with the
    
    1024
    +`dataConOrigArgTys` of the DataCon.
    
    1016 1025
     
    
    1017 1026
     Note [Data con wrappers and unlifted types]
    
    1018 1027
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    

  • compiler/GHC/Utils/Misc.hs
    ... ... @@ -18,7 +18,7 @@ module GHC.Utils.Misc (
    18 18
     
    
    19 19
             unzipWith,
    
    20 20
     
    
    21
    -        mapFst, mapSnd, chkAppend,
    
    21
    +        mapFst, mapSnd, mapConst, chkAppend,
    
    22 22
             mapAndUnzip, mapAndUnzip3, mapAndUnzip4,
    
    23 23
             filterOut, partitionWith, partitionWithM,
    
    24 24
     
    
    ... ... @@ -329,6 +329,10 @@ mapSnd :: Functor f => (b->c) -> f(a,b) -> f(a,c)
    329 329
     mapFst = fmap . first
    
    330 330
     mapSnd = fmap . second
    
    331 331
     
    
    332
    +mapConst :: a -> [b] -> [a]
    
    333
    +-- (mapConst k [a,b,c]) returns [k,k,k]
    
    334
    +mapConst k xs = [ k | _ <- xs ]
    
    335
    +
    
    332 336
     zipWithAndUnzip :: (a -> b -> (c,d)) -> [a] -> [b] -> ([c],[d])
    
    333 337
     zipWithAndUnzip f (a:as) (b:bs)
    
    334 338
       = let (r1,  r2)  = f a b
    

  • testsuite/tests/simplCore/should_compile/T28169.hs
    1
    +{-# LANGUAGE MagicHash #-}
    
    2
    +
    
    3
    +module T28169 where
    
    4
    +import GHC.Exts
    
    5
    +
    
    6
    +f :: Int# -> (Int,Int)
    
    7
    +f x = let y = I# (let z = x +# 1# in z *# z)
    
    8
    +      in (y + y, y * y)

  • testsuite/tests/simplCore/should_compile/all.T
    ... ... @@ -631,3 +631,6 @@ test('T27936', normal, compile, [''])
    631 631
     test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
    
    632 632
     test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
    
    633 633
     test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
    
    634
    +
    
    635
    +# T28169: test that there are no calls to boxed arithmetic,e.g. GHC.Internal.Num.$fNumInt_$c+
    
    636
    +test('T28169', grep_errmsg(r'\$c'), compile, ['-O -ddump-simpl -dsuppress-uniques'])