Simon Peyton Jones pushed to branch wip/case-bndr-unf at Glasgow Haskell Compiler / GHC

Commits:

10 changed files:

Changes:

  • compiler/GHC/Core/Opt/CprAnal.hs
    ... ... @@ -173,6 +173,25 @@ So currently we have
    173 173
     1. Strictness
    
    174 174
     2. CPR
    
    175 175
     3. worker/wrapper (for strictness and CPR)
    
    176
    +
    
    177
    +Wrinkles
    
    178
    +
    
    179
    +(CPR1) We have a flag `-fcpr-anal`, which sets `Opt_CprAnal`, enabled in -O1 and
    
    180
    +  -O1.  Strangely, it does /not/ switch off CPR analysis!  Rather, it just
    
    181
    +  switches off the worker/wrapper exploitation of CPR analysis, in `mkWWcpr_entry`.
    
    182
    +  The analysis itself runes whenever `-fstrictness` is on.
    
    183
    +
    
    184
    +  This is peculiar and, I suspect accidental.  It would make more sense to switch
    
    185
    +  off the analysis itself with `-fno-cpr-anal`.
    
    186
    +
    
    187
    +  It goes back to at least
    
    188
    +       commit ecb1752ffa12dfa71053f640e6cce64d15e47e8f
    
    189
    +       Author: Christiaan Baaij <christiaan.baaij@gmail.com>
    
    190
    +       Date:   Wed Aug 5 14:22:14 2015 +0200
    
    191
    +
    
    192
    +           Make -fcpr-off a dynamic flag
    
    193
    +
    
    194
    +  This note is just a breadcrumb to inform the next person who trips over this.
    
    176 195
     -}
    
    177 196
     
    
    178 197
     --
    
    ... ... @@ -343,7 +362,7 @@ cprTransform env id args
    343 362
       -- Any local binding, except for data structure bindings
    
    344 363
       -- See Note [Efficient Top sigs in SigEnv]
    
    345 364
       | Just sig <- lookupSigEnv env id
    
    346
    -  = applyCprTy (getCprSig sig) (length args)
    
    365
    +  = applyCprTy (cprSigType sig) (length args)
    
    347 366
       -- See Note [CPR for data structures]
    
    348 367
       | Just rhs <- cprDataStructureUnfolding_maybe id
    
    349 368
       = fst $ cprAnal env rhs
    
    ... ... @@ -362,7 +381,7 @@ cprTransform env id args
    362 381
       = cprTransformDataConWork env con args
    
    363 382
       -- Imported function
    
    364 383
       | otherwise
    
    365
    -  = applyCprTy (getCprSig (idCprSig id)) (length args)
    
    384
    +  = applyCprTy (cprSigType (idCprSig id)) (length args)
    
    366 385
     
    
    367 386
     -- | Precise, hand-written CPR transformers for select Ids
    
    368 387
     cprTransformBespoke :: Id -> [(CprType, CoreArg)] -> Maybe CprType
    
    ... ... @@ -870,27 +889,42 @@ Does f have the CPR property? Well, no.
    870 889
     However, if the strictness analyser has figured out (in a previous
    
    871 890
     iteration) that it's strict, then we DON'T need to forget the CPR info.
    
    872 891
     Instead we can retain the CPR info and do the thunk-splitting transform
    
    873
    -(see WorkWrap.splitThunk).
    
    892
    +(see Note [Thunk splitting] esp (B) CPR-led thunk splitting).
    
    874 893
     
    
    875 894
     This made a big difference to PrelBase.modInt, which had something like
    
    876 895
             modInt = \ x -> let r = ... -> I# v in
    
    877 896
                             ...body strict in r...
    
    878
    -r's RHS isn't a value yet; but modInt returns r in various branches, so
    
    879
    -if r doesn't have the CPR property then neither does modInt
    
    897
    +r's RHS isn't a value yet; but `modInt` returns `r` in various branches, so
    
    898
    +if `r` doesn't have the CPR property then neither does `modInt`
    
    899
    +
    
    880 900
     Another case I found in practice (in Complex.magnitude), looks like this:
    
    881
    -                let k = if ... then I# a else I# b
    
    882
    -                in ... body strict in k ....
    
    901
    +        let k* = if ... then I# a else I# b
    
    902
    +        in ... body strict in k ....
    
    883 903
     (For this example, it doesn't matter whether k is returned as part of
    
    884 904
     the overall result; but it does matter that k's RHS has the CPR property.)
    
    905
    +
    
    885 906
     Left to itself, the simplifier will make a join point thus:
    
    886
    -                let $j k = ...body strict in k...
    
    887
    -                if ... then $j (I# a) else $j (I# b)
    
    907
    +        let $j k = ...body strict in k...
    
    908
    +        if ... then $j (I# a) else $j (I# b)
    
    909
    +
    
    888 910
     With thunk-splitting, we get instead
    
    889
    -                let $j x = let k = I#x in ...body strict in k...
    
    890
    -                in if ... then $j a else $j b
    
    911
    +        let k* = case (if ... then I# a else I# b) of I# z -> I# z
    
    912
    +        in ... body strict in k ....
    
    913
    +Now the simplifier should pull out the `case` to give
    
    914
    +        case (if ... then I# a else I# b) of I# z ->
    
    915
    +        let k = I# z in ... body strict in k ...
    
    916
    +Now case-of-if will give
    
    917
    +        let $j z = let k = I# z in ...body strict in k... in
    
    918
    +        if ... then $j a else $j b
    
    891 919
     This is much better; there's a good chance the I# won't get allocated.
    
    920
    +TL'DR: During CPR analysis we want to give `k` the CPR property in `body`.
    
    921
    +
    
    922
    +What if the type involved has more than one constructor?  E.g.
    
    923
    +        let k* = if ... then Just a else Just b
    
    924
    +        in ... body strict in k ....
    
    925
    +That is good too: see (TS5) in Note [Thunk splitting]
    
    892 926
     
    
    893
    -But what about botCpr? Consider
    
    927
    +Finally, what about botCpr? Consider
    
    894 928
         lvl = error "boom"
    
    895 929
         fac -1 = lvl
    
    896 930
         fac 0 = 1
    

  • compiler/GHC/Core/Opt/Simplify/Iteration.hs
    ... ... @@ -51,7 +51,6 @@ import GHC.Types.Literal ( litIsLifted ) --, mkLitInt ) -- temporarily comment
    51 51
     import GHC.Types.SourceText
    
    52 52
     import GHC.Types.Id
    
    53 53
     import GHC.Types.Id.Info
    
    54
    -import GHC.Types.Cpr( isTopCprSig )
    
    55 54
     import GHC.Types.InlinePragma
    
    56 55
     import GHC.Types.Name   ( mkSystemVarName, isExternalName, getOccFS )
    
    57 56
     import GHC.Types.Demand
    
    ... ... @@ -1830,7 +1829,7 @@ simplNonRecE :: HasDebugCallStack
    1830 1829
     
    
    1831 1830
     simplNonRecE env from_what bndr (rhs, rhs_se) body cont
    
    1832 1831
       | assertPpr (isId bndr && not (isJoinId bndr)) (ppr bndr) True
    
    1833
    -  , useStrictBind env from_what bndr
    
    1832
    +  , useStrictBind env from_what bndr rhs
    
    1834 1833
       = -- Evaluate RHS strictly
    
    1835 1834
         simplExprF (rhs_se `setInScopeFromE` env) rhs
    
    1836 1835
                    (StrictBind { sc_bndr = bndr, sc_body = body, sc_from = from_what
    
    ... ... @@ -1865,11 +1864,10 @@ simplRecE env pairs body cont
    1865 1864
             ; return (floats1 `addFloats` floats2, expr') }
    
    1866 1865
     
    
    1867 1866
     
    
    1868
    -useStrictBind :: SimplEnv -> FromWhat -> InId -> Bool
    
    1867
    +useStrictBind :: SimplEnv -> FromWhat -> InId -> InExpr -> Bool
    
    1869 1868
     -- Can we use a StrictBind continuation for this let-binding?
    
    1870
    --- If so, return a binder that is suitable to become a lambda binder,
    
    1871
    --- i.e. one satisfying `lamBndrInfoOK`; see (SB3) in Note [StrictBind]
    
    1872
    -useStrictBind env from_what bndr
    
    1869
    +-- See (SB3) in Note [StrictBind]
    
    1870
    +useStrictBind env from_what bndr rhs
    
    1873 1871
       -- If we are coming from a beta-reduction (FromBeta) we must
    
    1874 1872
       -- establish the let-can-float invariant, so we must go via StrictBind
    
    1875 1873
       -- If not, the invariant holds already, and it's optional.
    
    ... ... @@ -1880,6 +1878,11 @@ useStrictBind env from_what bndr
    1880 1878
       | not (isStrUsedDmd dmd_info)
    
    1881 1879
       = False
    
    1882 1880
     
    
    1881
    +  -- Not if the RHS is ok-for-spec; no benefit. In particular if the RHS is a
    
    1882
    +  -- value lambda, we return False: only thunks use StrictBind
    
    1883
    +  | exprOkForSpeculation rhs
    
    1884
    +  = False
    
    1885
    +
    
    1883 1886
       -- Not if case-of-case is off
    
    1884 1887
       -- See (SB1) in Note [StrictBind]
    
    1885 1888
       | not (seCaseCase env)
    
    ... ... @@ -1889,13 +1892,8 @@ useStrictBind env from_what bndr
    1889 1892
       = True
    
    1890 1893
     
    
    1891 1894
       -- Not for things with RULES or INLINE or NOINLINE
    
    1892
    -  -- or with a strictnes or CPR signature -- all things we might lose
    
    1893 1895
       -- See (SB3) in Note [StrictBind]
    
    1894
    -  | isStableUnfolding (unfoldingInfo info)
    
    1895
    -    || not (isEmptyRuleInfo (ruleInfo info))
    
    1896
    -    || not (isAlwaysActive (inlinePragmaActivation (inlinePragInfo info)))
    
    1897
    -    || not (isNopSig (dmdSigInfo info))
    
    1898
    -    || not (isTopCprSig (cprSigInfo info))
    
    1896
    +  | hasRulesOrInline info
    
    1899 1897
       = False
    
    1900 1898
     
    
    1901 1899
       | otherwise
    
    ... ... @@ -4243,9 +4241,8 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
    4243 4241
                      , alt') }
    
    4244 4242
                     -- See Note [Duplicated env]
    
    4245 4243
     
    
    4246
    -{-
    
    4247
    -Note [Do not add unfoldings to join points at birth]
    
    4248
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    4244
    +{- Note [Do not add unfoldings to join points at birth]
    
    4245
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    4249 4246
     Consider this (#15360)
    
    4250 4247
     
    
    4251 4248
        case (case (case (case ...))) of
    
    ... ... @@ -4316,7 +4313,7 @@ The simplifier will find
    4316 4313
         (Var v) with continuation
    
    4317 4314
                 Select (pn -> rn) (
    
    4318 4315
                 Select [I# a -> I# a] (
    
    4319
    -            StrictBind body Stop
    
    4316
    +            StrictBind body Stop))
    
    4320 4317
     
    
    4321 4318
     So we'll call mkDupableCont on
    
    4322 4319
        Select [I# a -> I# a] (StrictBind body Stop)
    
    ... ... @@ -4455,7 +4452,7 @@ hack and bit us in multiple small and not-so-small ways
    4455 4452
     
    
    4456 4453
     Consider this
    
    4457 4454
        case (case .. ) of c {
    
    4458
    -     I# c# -> ....c....
    
    4455
    +     I# c# -> ....c.... }
    
    4459 4456
     
    
    4460 4457
     If we make a join point with c but not c# we get
    
    4461 4458
       $j = \c -> ....c....
    
    ... ... @@ -4655,30 +4652,56 @@ We simplify `rhs` with a StrictBind continuation that continues with
    4655 4652
        invariants] in GHC.Core.  But a let-binder `x` usually has IdInfo that a
    
    4656 4653
        lambda binder may not have (an unfolding, arity, a demand signature...).
    
    4657 4654
     
    
    4658
    -   So `useStrictBind_maybe` zaps that info, keeping only the occurrence info
    
    4659
    -   and the demand info.  If it happens to stay as a let-binding arity info will
    
    4660
    -   be re-derived, so nothing is lost.
    
    4655
    +   So when we duplicate StrictBind, in `mkDupableContWithDmds`, we use
    
    4656
    +   `mkLamBndrFromLetBndr` to zap that info, keeping only the occurrence
    
    4657
    +   info and the demand info.
    
    4661 4658
     
    
    4662
    -   The exceptions are RULES, a stable unfolding, and a non-default inlining
    
    4663
    -   activation: these cannot be re-derived, and we have nowhere convenient to
    
    4664
    -   put them if `x` becomes a lambda binder. For example:
    
    4659
    +   However, if the let-binder has
    
    4660
    +    * RULES
    
    4661
    +    * a stable unfolding
    
    4662
    +    * a non-default inlining activation
    
    4663
    +   we'd permanently lose these things if we lambda-bind it.  For example:
    
    4665 4664
            let {-# NOINLINE x #-}
    
    4666 4665
                x! = case y of { ... }
    
    4667 4666
            in blah
    
    4668
    -   If we make a join point  j x = blah, we have nowhere convenient
    
    4669
    -   to put that NOINLINE.  Ditto INLINE or RULES.  So in these cases we
    
    4670
    -   simply don't use StrictBind.  It's very unusual, so no harm done.
    
    4671
    -   But it does happen; one example is this, in the Applicative (ST s)
    
    4672
    -   instance in GHC.Internal.Control.Monad.St.Lazy.Imp
    
    4667
    +   If we make a join point j x = blah, we have nowhere convenient to put that
    
    4668
    +   NOINLINE.  Ditto INLINE or RULES.  It's unusual. But it happens; one example
    
    4669
    +   is the Applicative (ST s) instance in GHC.Internal.Control.Monad.St.Lazy.Imp
    
    4673 4670
              {-# NOINLINE res1 #-}
    
    4674 4671
              !res1 = unST fm s
    
    4675 4672
     
    
    4676
    -   TL;DR: the sc_bndr::Id field in StrictBind always satisfies `lamBndrInfoOK`.
    
    4677
    -   This means that in the above example { x! = case y of ... } we won't
    
    4678
    -   float the `case y` out. And perhaps that's fine because of the NOINLNE.
    
    4679
    -   We could imagine instead imposing these conditions only when we /duplicate/
    
    4680
    -   the StrictBind, rather than when we /create/ it, but that would require a
    
    4681
    -   bigger refactor.
    
    4673
    +   So in these cases we simply don't use StrictBind -- see `useStrictBind`.  We
    
    4674
    +   could imagine instead imposing these conditions only when we /duplicate/ the
    
    4675
    +   StrictBind, rather than when we /create/ it, but that would require a bigger
    
    4676
    +   refactor.  See (SB5) for why we don't worry if the binder has strictness or
    
    4677
    +   CPR information.
    
    4678
    +
    
    4679
    +(SB4) Shortcoming: not using StrictBind has a cost.  If we have
    
    4680
    +        {-# NOINLINE x #-}
    
    4681
    +        x! = case y of (a,b) -> a
    
    4682
    +   then isnce x is used strictly, we'd usually float that `case y` outwards -- but
    
    4683
    +   we do so precisely by using StrictBind.  But since the NOINLINE stops us using
    
    4684
    +   StrictBind we won't float out the case.
    
    4685
    +
    
    4686
    +   Fixing this would require `mkDupableCont` to return a non-duplicable tail of
    
    4687
    +   the continuation (declining to duplicate a StrictBind with a NOINLINE, say).
    
    4688
    +   But that's a lot of plumbing for a very narrow case. Who writes INLINE or NOINLINE
    
    4689
    +   or RULES for a thunk?  So we just accept the shortcoming.
    
    4690
    +
    
    4691
    +(SB5) What if a thunk has a strictness signature, or CPR information? We
    
    4692
    +   could make `useStrictBind` say False in these cases too, but that turns
    
    4693
    +   out to be a net loss: keeping a thunk is worse than losing the strictness
    
    4694
    +   information. Example, where f1,f2 are both strict:
    
    4695
    +         let f* {- Str=<S> -} = case x of { True -> f1; False -> f2 }
    
    4696
    +         in  body
    
    4697
    +   Keeping it as-is would use CBV for calls of `f` in `body`.  But
    
    4698
    +   allowing StrictBind would give us
    
    4699
    +         join j f* = body
    
    4700
    +         in case x of { True -> j f1; False -> j f2 }
    
    4701
    +   which avoids the thunk. It's a trade-off.
    
    4702
    +
    
    4703
    +   For CPR info, see Note [Thunk splitting] in GHC.Core.Opt.WorkWrap,
    
    4704
    +   especially (B) CPR-led thunk splitting.
    
    4682 4705
     
    
    4683 4706
     Note [Join point abstraction]  Historical note
    
    4684 4707
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    

  • compiler/GHC/Core/Opt/WorkWrap.hs
    ... ... @@ -598,13 +598,20 @@ tryWW ww_opts is_rec fn_id rhs
    598 598
       = splitFun ww_opts new_fn_id rhs
    
    599 599
     
    
    600 600
       -- See Note [Thunk splitting]
    
    601
    -  | isNonRec is_rec, is_thunk
    
    602
    -  = splitThunk ww_opts is_rec new_fn_id rhs
    
    601
    +  | isNonRec is_rec     -- See (TS4)
    
    602
    +  , is_thunk  -- All join points go via splitFun
    
    603
    +  , not (hasRulesOrInline (fn_info))  -- See (TS9)
    
    604
    +  = do { -- Try strictness then CPR; see (TS5)
    
    605
    +         rhs' <- splitThunkStr ww_opts new_fn_id rhs `orElseM`
    
    606
    +                 splitThunkCpr ww_opts new_fn_id rhs `orElseM`
    
    607
    +                 return rhs
    
    608
    +       ; return [ (new_fn_id, rhs') ] }
    
    603 609
     
    
    604 610
       | otherwise
    
    605 611
       = return [ (new_fn_id, rhs) ]
    
    606 612
     
    
    607 613
       where
    
    614
    +    is_join        = isJoinId fn_id
    
    608 615
         fn_info        = idInfo fn_id
    
    609 616
         (wrap_dmds, _) = splitDmdSig (dmdSigInfo fn_info)
    
    610 617
         new_fn_id      = zap_join_cpr $ zap_usage fn_id
    
    ... ... @@ -613,14 +620,13 @@ tryWW ww_opts is_rec fn_id rhs
    613 620
             -- See Note [Zapping DmdEnv after Demand Analyzer] and
    
    614 621
             -- See Note [Zapping Used Once info in WorkWrap]
    
    615 622
     
    
    616
    -    zap_join_cpr id
    
    617
    -      | isJoinId id = id `setIdCprSig` topCprSig
    
    618
    -      | otherwise   = id
    
    623
    +    zap_join_cpr id | is_join   = id `setIdCprSig` topCprSig
    
    624
    +                    | otherwise = id
    
    619 625
             -- See Note [Don't w/w join points for CPR]
    
    620 626
     
    
    621
    -    is_fun     = notNull wrap_dmds || isJoinId fn_id
    
    622
    -    is_thunk   = not is_fun && not (exprIsHNF rhs) && not (isJoinId fn_id)
    
    623
    -                            && not (isUnliftedType (idType fn_id))
    
    627
    +    is_fun     = notNull wrap_dmds || is_join
    
    628
    +    is_thunk   = not (exprIsHNF rhs)
    
    629
    +                 && not (isUnliftedType (idType fn_id))
    
    624 630
     
    
    625 631
     {-
    
    626 632
     Note [Zapping DmdEnv after Demand Analyzer]
    
    ... ... @@ -806,7 +812,7 @@ splitFun ww_opts fn_id rhs
    806 812
     
    
    807 813
         (wrap_dmds, div) = splitDmdSig (dmdSigInfo fn_info)
    
    808 814
     
    
    809
    -    cpr_ty = getCprSig (cprSigInfo fn_info)
    
    815
    +    cpr_ty = cprSigType (cprSigInfo fn_info)
    
    810 816
         -- Arity of the CPR sig should match idArity when it's not a join point.
    
    811 817
         -- See Note [Arity trimming for CPR signatures] in GHC.Core.Opt.CprAnal
    
    812 818
         cpr = assertPpr (isJoinId fn_id || cpr_ty == topCprType || ct_arty cpr_ty == arityInfo fn_info)
    
    ... ... @@ -957,114 +963,182 @@ the form [Demand=<L,1*(C(1,...(C(1,U))))>]
    957 963
     
    
    958 964
     Note [Thunk splitting]
    
    959 965
     ~~~~~~~~~~~~~~~~~~~~~~
    
    960
    -Suppose x is used strictly; never mind whether it has the CPR
    
    961
    -property.  I'll use a '*' to mean "x* is demanded strictly".
    
    962
    -
    
    963
    -      let
    
    964
    -        x* = x-rhs
    
    966
    +The worker/wrapper split mainly affects let-bound /functions/.  But we can also use
    
    967
    +demand and CPR information to improve let-bound /thunks/.  Specifically:
    
    968
    +
    
    969
    +* (A) Demand-led thunk splitting:
    
    970
    +  If a thunk is demanded strictly, perhaps nestedly, we can turn it into a
    
    971
    +  case, perhaps nestedly.  For example
    
    972
    +       let x :: (Int, Int)
    
    973
    +           {- Dmd = SP(S,L) -}
    
    974
    +           x = rhs
    
    975
    +       in body
    
    976
    +   We would ultimately like to get
    
    977
    +        case rhs of x { (a,b) ->
    
    978
    +        case a of { I# a# ->
    
    979
    +        body
    
    980
    +
    
    981
    +   This is much better: no thunk for `rhs`; and known-data-con unfoldings for `x`
    
    982
    +   and `a` inside `body`.
    
    983
    +
    
    984
    +* (B) CPR-led thunk splitting:
    
    985
    +  If a thunk has the (possibly-nested) CPR property /and/ is demanded strictly
    
    986
    +  at top level, we can again generate a case
    
    987
    +       let x :: (Int, Int)
    
    988
    +           {- Dmd = S, Cpr = (_, I# _) -}
    
    989
    +           x = rhs
    
    990
    +       in body
    
    991
    +   The CPR info says that if `x` is evaluated (which it is), it'll return a pair,
    
    992
    +   whose second component can very cheaply be evaluated to a (I# b#).  We would
    
    993
    +   like to end up with
    
    994
    +        case rhs of x { (a,b) ->
    
    995
    +        case b of { I# b# ->
    
    996
    +        body
    
    997
    +   which is good for the same reasons as before.  See (TS3) for an example.
    
    998
    +
    
    999
    +Implementation
    
    1000
    +~~~~~~~~~~~~~~
    
    1001
    +The worker/wrapper pass does not generate these nested case expressions directly.
    
    1002
    +Instead it generates a regular let-binding but, since the binder is marked as
    
    1003
    +strict, any `case` expressions in the RHS will float out.  Specifically:
    
    1004
    +
    
    1005
    +(TS1) For (A), `splitThunkStr` generates the binding
    
    1006
    +      let x! = case rhs of { (a,b) ->
    
    1007
    +               case a of { I# a# ->
    
    1008
    +               (I# a, b)
    
    1009
    +  Now when the Simplifier floats the `case` expressions out, we get
    
    1010
    +      case rhs of { (a,b) ->
    
    1011
    +      case a of { I# a# ->
    
    1012
    +      let x = (I# a, b)
    
    965 1013
           in body
    
    1014
    +  which is equivalent to the expression in (A) above.
    
    966 1015
     
    
    967
    -splitThunk transforms like this:
    
    968
    -      let
    
    969
    -        x* = let x = x-rhs in
    
    970
    -             case x of { I# a -> I# a }
    
    971
    -      in body
    
    1016
    +  `splitThunkStr` also works on /absent/ thunks: see (TS6).
    
    972 1017
     
    
    973
    -This is a little strange: we are re-using the same `x` in the RHS; and
    
    974
    -the RHS takes `x` apart and reboxes it. But because the outer 'let' is
    
    975
    -strict, and the inner let mentions `x` only once, the simplifier
    
    976
    -transform it to
    
    977
    -      case x-rhs of
    
    978
    -        I# a -> let x* = I# a
    
    979
    -                in body
    
    980
    -
    
    981
    -That is good: in `body` we know the form of `x`, which
    
    982
    -  * gives the CPR property, and
    
    983
    -  * allows case-of-case to happen on x
    
    984
    -
    
    985
    -Notes
    
    986
    -* I tried transforming like this:
    
    987
    -      let
    
    988
    -        x* = let x = x-rhs in
    
    989
    -             case x of { I# a -> x }
    
    990
    -      in body
    
    991
    -  where I return `x` itself, rather than reboxing it.  But this
    
    992
    -  turned out to cause some regressions, which I never fully
    
    993
    -  investigated.
    
    994
    -
    
    995
    -* Suppose x-rhs is itself a case:
    
    996
    -        x-rhs = case e of { T -> I# e1; F -> I# e2 }
    
    997
    -  Then we'll get
    
    998
    -      join j a = let x* = I# a in body
    
    999
    -      in case e of { T -> j e1; F -> j e2 }
    
    1000
    -  which is good (no boxing).  But in the original, unsplit program
    
    1001
    -  we would transform
    
    1002
    -      let x* = case e of ... in body
    
    1003
    -  ==> join j2 x = body
    
    1004
    -      in case e of { T -> j2 (I# e1); F -> j (I# e2) }
    
    1005
    -  which is not good (boxing).
    
    1018
    +  Rather cleverly, `splitThunkStr` uses `mkWWstr_one`, the /existing/ function
    
    1019
    +  argument w/w splitting function, to do the unpacking.  This automatically
    
    1020
    +  deals with nested strictness.
    
    1006 1021
     
    
    1007
    -* In fact, splitThunk uses the function argument w/w splitting
    
    1008
    -  function, mkWWstr_one, so that if x's demand is deeper (say U(U(L,L),L))
    
    1009
    -  then the splitting will go deeper too.
    
    1022
    +(TS2) For (B), `splitThunkCpr` behaves exactly analogously, again
    
    1023
    +  using `mkWWcpr_one` to do the unpacking. It works only for /demanded/ thunks.
    
    1010 1024
     
    
    1011
    -* For recursive thunks, the Simplifier is unable to float `x-rhs` out of
    
    1012
    -  `x*`'s RHS, because `x*` occurs freely in `x-rhs`, and will just change it
    
    1013
    -  back to the original definition, so we just split non-recursive thunks.
    
    1025
    +Wrinkles:
    
    1014 1026
     
    
    1015
    -Note [Thunk splitting for top-level binders]
    
    1016
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    1017
    -Top-level bindings are never strict. Yet they can be absent, as T14270 shows:
    
    1018
    -
    
    1019
    -  module T14270 (mkTrApp) where
    
    1020
    -  mkTrApp x y
    
    1021
    -    | Just ... <- ... typeRepKind x ...
    
    1022
    -    = undefined
    
    1023
    -    | otherwise
    
    1024
    -    = undefined
    
    1025
    -  typeRepKind = Tick scc undefined
    
    1026
    -
    
    1027
    -(T19180 is a profiling-free test case for this)
    
    1028
    -Note that `typeRepKind` is not exported and its only use site in
    
    1029
    -`mkTrApp` guards a bottoming expression. Thus, demand analysis
    
    1030
    -figures out that `typeRepKind` is absent and splits the thunk to
    
    1031
    -
    
    1032
    -  typeRepKind =
    
    1033
    -    let typeRepKind = Tick scc undefined in
    
    1034
    -    let typeRepKind = absentError in
    
    1035
    -    typeRepKind
    
    1036
    -
    
    1037
    -But now we have a local binding with an External Name
    
    1038
    -(See Note [About the NameSorts]). That will trigger a CoreLint error, which we
    
    1039
    -get around by localising the Id for the auxiliary bindings in 'splitThunk'.
    
    1027
    +(TS3) Here's an example of (B), thunk-splitting based on CPR information.
    
    1028
    +  Suppose we have
    
    1029
    +        let x! = case e of { T -> Just e1; F -> Just e2 }
    
    1030
    +        in body
    
    1031
    +  If the Simplifier floats the `case` out, we get
    
    1032
    +      join j2 x = body
    
    1033
    +      in case e of { T -> j2 (Just e1); F -> j2 (Just e2) }
    
    1034
    +  which is not good (boxing).
    
    1035
    +
    
    1036
    +  If we first do the thunk-splitting transformation, we get
    
    1037
    +        let x! = case (case e of { T -> Just e1; F -> Just e2 }) of
    
    1038
    +                   Just a -> Just a
    
    1039
    +        in body
    
    1040
    +
    
    1041
    +  Now when the Simplifier floats we will get:
    
    1042
    +      join j a = let x = Just a in body
    
    1043
    +      in case e of { T -> j e1; F -> j e2 }
    
    1044
    +  which is much better (no boxing).   But see (TS9).
    
    1045
    +
    
    1046
    +(TS4) We only do thunk-splitting for thunks that are non-recursive
    
    1047
    +  For recursive thunks, the Simplifier is unable to float `rhs` out of
    
    1048
    +  x's RHS, because `x` occurs freely in `rhs`, and will just change it
    
    1049
    +  back to the original definition.
    
    1050
    +
    
    1051
    +(TS5) Notice that (B) CPR-led thunk splitting can be useful:
    
    1052
    +  * when multi-constructor data types are involved, so that the argument-unboxing
    
    1053
    +    mechanism (A) is impotent.  See the example in (TS3), which uses `Maybe`.
    
    1054
    +  * when the binder is only demanded head-strictly, but CPR has nested information.
    
    1055
    +
    
    1056
    +  So (A) and (B) have complementary benefits.  We might do even better by
    
    1057
    +  /combining/ (A) and (B), but at the moment we try (A) first, and then try (B)
    
    1058
    +  if (A) is impotent.  Combining them would be more work.
    
    1059
    +
    
    1060
    +(TS6) We can also exploit /absence/.  Consider
    
    1061
    +         let x {-# Dmd = A #-} = rhs
    
    1062
    +         in body
    
    1063
    +   Generally speaking `x` will be absent becuase it is passed to functions that
    
    1064
    +   don't use it, in which case worker/wrapper on those calls will make `x` unused.
    
    1065
    +   But suppose `x` is absent inside a /lazy/ argument:
    
    1066
    +         let f p = (fst p, 99) in
    
    1067
    +         let x = rhs in
    
    1068
    +         f (True, x)
    
    1069
    +   Here f's argument is lazy, but `x` is definitely absent, and we could replace
    
    1070
    +   `x` with an absent filler.  Using (TS1) would give us
    
    1071
    +         let x = absentError "urk" in ...
    
    1072
    +   which is great.
    
    1073
    +
    
    1074
    +   So `splitThunkStr` works /regardless/ of the demand on `x`; whether it fires is
    
    1075
    +   determined only by the  `useful` flag returned by `mkWWstr_one`.
    
    1076
    +
    
    1077
    +(TS7) Adopting (TS6) leads to one other complication: a top-level binder with
    
    1078
    +   an External Name (see Note [About the NameSorts]) can be  Absent.  If so,
    
    1079
    +   it must not be used as a local binder in the `Let` created by `splitThunkStr`.
    
    1080
    +   T19180 is a test case for this rather obscure situation.
    
    1081
    +
    
    1082
    +   Solution: use `localiseId` to localise the binder for the `Let`.
    
    1083
    +
    
    1084
    +(TS8) Consider out poster child test case for `splitThunkCpr`, in (TS3).
    
    1085
    +         x! = case e of { True -> Just 1; False -> Just 2 }
    
    1086
    +  But suppose we have `-fworker-wrapper-cbv` enabled (reminder: see
    
    1087
    +  Note [Worker/wrapper for strict arguments]).  Then alas `splitThunkStr`
    
    1088
    +  will fire, but it'll be a no-op in this case.  But since it fires, `splitThunkCpr`
    
    1089
    +  never gets a chance.
    
    1090
    +
    
    1091
    +  Hacky but effective solution: switch off `wo_unlift_strict` locally in `splitThunkStr`.
    
    1092
    +
    
    1093
    +(TS9) `splitThunkStr` implicitly relies on floating a case out of a strict binding.
    
    1094
    +  But if the thunk has a RULE or INLINE/NOINLINE pragma that won't happen; see
    
    1095
    +  (SB4) in Note [StrictBind] in GHC.Core.Opt.Simplify.Iteration.  So we test
    
    1096
    +  these things before applying thunk splitting.
    
    1040 1097
     -}
    
    1041 1098
     
    
    1042
    --- | See Note [Thunk splitting].
    
    1043
    ---
    
    1044
    --- splitThunk converts the *non-recursive* binding
    
    1099
    +-- | splitThunkStr converts the *non-recursive* binding
    
    1045 1100
     --      x = e
    
    1046 1101
     -- into
    
    1047
    ---      x = let x' = e in
    
    1048
    ---          case x' of I# y -> let x' = I# y in x'
    
    1049
    --- See comments above. Is it not beautifully short?
    
    1050
    --- Moreover, it works just as well when there are
    
    1051
    --- several binders, and if the binders are lifted
    
    1052
    --- E.g.     x = e
    
    1053
    ---     -->  x = let x' = e in
    
    1054
    ---              case x' of (a,b) -> let x' = (a,b)  in x'
    
    1055
    --- Here, x' is a localised version of x, in case x is a
    
    1056
    --- top-level Id with an External Name, because Lint rejects local binders with
    
    1057
    --- External Names; see Note [About the NameSorts] in GHC.Types.Name.
    
    1058
    ---
    
    1059
    --- How can we do thunk-splitting on a top-level binder?  See
    
    1060
    --- Note [Thunk splitting for top-level binders].
    
    1061
    -splitThunk :: WwOpts -> RecFlag -> Var -> Expr Var -> UniqSM [(Var, Expr Var)]
    
    1062
    -splitThunk ww_opts is_rec x rhs
    
    1063
    -  = assert (not (isJoinId x)) $
    
    1064
    -    do { let x' = localiseId x -- See comment above
    
    1065
    -       ; (useful,_args, wrap_fn, fn_arg)
    
    1066
    -           <- mkWWstr_one ww_opts x' NotMarkedStrict
    
    1067
    -       ; let res = [ (x, Let (NonRec x' rhs) (wrap_fn fn_arg)) ]
    
    1068
    -       ; if useful then assertPpr (isNonRec is_rec) (ppr x) -- The thunk must be non-recursive
    
    1069
    -                   return res
    
    1070
    -                   else return [(x, rhs)] }
    1102
    +--      x = let x = e in
    
    1103
    +--          case x of I# y -> I# y
    
    1104
    +-- See Note [Thunk splitting].
    
    1105
    +splitThunkStr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
    
    1106
    +splitThunkStr ww_opts x rhs
    
    1107
    +  = -- NB: does not depend on x's demand being strict; it might be absent, see (TS6)
    
    1108
    +    do { let x' = localiseId x -- See (TS7)
    
    1109
    +             ww_opts' = ww_opts { wo_unlift_strict = False }  -- See (TS8)
    
    1110
    +       ; (useful, _transit_vars, wrap_fn, fn_arg) <- mkWWstr_one ww_opts' x' NotMarkedStrict
    
    1111
    +            -- Use mkWWstr_one: see (TS1) in Note [Thunk splitting]
    
    1112
    +
    
    1113
    +       ; if useful
    
    1114
    +         then return (Just (Let (NonRec x' rhs) $
    
    1115
    +                            wrap_fn fn_arg))
    
    1116
    +         else return Nothing }
    
    1117
    +
    
    1118
    +splitThunkCpr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
    
    1119
    +-- See Note [Thunk splitting]
    
    1120
    +-- Given x* = rhs, where x* is used outermost-strictly, and x* has a (nested) CPR
    
    1121
    +-- property, say Just (Just _), return this new RHS:
    
    1122
    +--     let x' = rhs in
    
    1123
    +--     case x' of { Just p -> case p of { Just q ->   -- Unpacking code
    
    1124
    +--       Just (Just q) }}                             -- Repacking code
    
    1125
    +-- Works for multi-constructor data types, where splitThunkStr will fail
    
    1126
    +splitThunkCpr ww_opts x rhs
    
    1127
    +  | wo_cpr_anal ww_opts   --  See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal
    
    1128
    +  , isStrUsedDmd (idDemandInfo x) -- See (TS2)
    
    1129
    +  = assertPpr (cprTypeArity cpr_type == 0) (ppr x) $   -- It's a thunk
    
    1130
    +    do { (useful, _transit_vars, rebuild_result, unpacker) <- mkWWcpr_one ww_opts x cpr
    
    1131
    +            -- Use mkWWcpr_one: see (TS2) in Note [Thunk splitting]
    
    1132
    +       ; if useful
    
    1133
    +         then return (Just (Let (NonRec x rhs) $
    
    1134
    +                            unpacker rebuild_result))
    
    1135
    +         else return Nothing }
    
    1136
    +
    
    1137
    +  | otherwise
    
    1138
    +  = return Nothing
    
    1139
    +  where
    
    1140
    +    cpr_type :: CprType
    
    1141
    +    cpr_type = cprSigType (idCprSig x)
    
    1142
    +    cpr :: Cpr
    
    1143
    +    cpr = cprTypeCpr cpr_type
    
    1144
    +

  • compiler/GHC/Core/Opt/WorkWrap/Utils.hs
    ... ... @@ -8,7 +8,7 @@ A library for the ``worker\/wrapper'' back-end to the strictness analyser
    8 8
     {-# LANGUAGE ViewPatterns #-}
    
    9 9
     
    
    10 10
     module GHC.Core.Opt.WorkWrap.Utils
    
    11
    -   ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one
    
    11
    +   ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one, mkWWcpr_one
    
    12 12
        , needsVoidWorkerArg
    
    13 13
        , DataConPatContext(..)
    
    14 14
        , UnboxingDecision(..), canUnboxArg
    
    ... ... @@ -139,13 +139,18 @@ data WwOpts
    139 139
       = MkWwOpts
    
    140 140
       { -- | Environment of type/data family instances
    
    141 141
         wo_fam_envs          :: !FamInstEnvs
    
    142
    +
    
    142 143
       , -- | Options for the "Simple optimiser"
    
    143 144
         wo_simple_opts       :: !SimpleOpts
    
    145
    +
    
    144 146
       , -- | Whether to enable "Constructed Product Result" analysis.
    
    145 147
         -- (Originally from DOI: 10.1017/S0956796803004751)
    
    148
    +    --  See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal
    
    146 149
         wo_cpr_anal          :: !Bool
    
    150
    +
    
    147 151
       , -- | Used for absent argument error message
    
    148 152
         wo_module            :: !Module
    
    153
    +
    
    149 154
       , -- | Generate workers even if the only effect is some args get passed
    
    150 155
         -- unlifted. See Note [WW for calling convention]
    
    151 156
         wo_unlift_strict     :: !Bool }
    
    ... ... @@ -230,8 +235,7 @@ mkWwBodies opts fun_id ww_arity arg_vars res_ty demands res_cpr
    230 235
             ; let (work_args, work_marks) = unzip work_args_str
    
    231 236
     
    
    232 237
             -- Do CPR w/w.  See Note [Always do CPR w/w]
    
    233
    -        ; (useful2, wrap_fn_cpr, work_fn_cpr)
    
    234
    -              <- mkWWcpr_entry opts res_ty' res_cpr
    
    238
    +        ; (useful2, wrap_fn_cpr, work_fn_cpr) <- mkWWcpr_entry opts res_ty' res_cpr
    
    235 239
     
    
    236 240
             ; let (work_lam_args, work_call_args, work_call_str)
    
    237 241
                     | needsVoidWorkerArg fun_id arg_vars work_args
    
    ... ... @@ -662,8 +666,10 @@ canUnboxResult fam_envs ty cpr
    662 666
       = DontUnbox
    
    663 667
     
    
    664 668
       where
    
    665
    -    -- See Note [non-algebraic or open body type warning]
    
    666
    -    open_body_ty_warning = warnPprTrace True "canUnboxResult: non-algebraic or open body type" (ppr ty) Nothing
    
    669
    +    -- See Note [Non-algebraic or open body type warning]
    
    670
    +    open_body_ty_warning
    
    671
    +      = warnPprTrace True "canUnboxResult: non-algebraic or open body type"
    
    672
    +                     (ppr ty) Nothing
    
    667 673
     
    
    668 674
     
    
    669 675
     
    
    ... ... @@ -808,7 +814,7 @@ match the number of constructor arguments; this happened in #8037.
    808 814
     If so, the worker/wrapper split doesn't work right and we get a Core Lint
    
    809 815
     bug.  The fix here is simply to decline to do w/w if that happens.
    
    810 816
     
    
    811
    -Note [non-algebraic or open body type warning]
    
    817
    +Note [Non-algebraic or open body type warning]
    
    812 818
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    813 819
     There are a few cases where the W/W transformation is told that something
    
    814 820
     returns a constructor, but the type at hand doesn't really match this. One
    
    ... ... @@ -829,8 +835,60 @@ This warning also triggers for the stream fusion library within `text`.
    829 835
     We can't easily W/W constructed results like `Stream` because we have no simple
    
    830 836
     way to express existential types in the worker's type signature.
    
    831 837
     
    
    838
    +Note [Worker/wrapper for strict arguments]
    
    839
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    840
    +Consider
    
    841
    +    f x = case x of
    
    842
    +             []     -> blah
    
    843
    +             (y:ys) -> f ys
    
    844
    +
    
    845
    +Clearly `f` is strict, but its argument is not a product type, so by default
    
    846
    +we don't worker/wrapper it.  But it is arguably valuable to do so.  We could
    
    847
    +do this:
    
    848
    +
    
    849
    +   f x = case x of xx { DEFAULT -> $wf xx }
    
    850
    +   $wf xx = case xx of
    
    851
    +              []     -> blah
    
    852
    +              (y:ys) -> f ys
    
    853
    +
    
    854
    +Now the worker `$wf` knows that its argument `xx` will be evaluated
    
    855
    +and properly tagged, so the code for the `case xx` does not need to do
    
    856
    +an "eval" (see `GHC.StgToCmm.Expr.cgCase`).  A call (f (a:as)) will
    
    857
    +have the wrapper inlined, and will drop the `case x`, so no eval
    
    858
    +happens at all.
    
    859
    +
    
    860
    +The worker `$wf` is a CBV function (see `Note [CBV Function Ids: overview]`
    
    861
    +in GHC.Types.Id.Info) and the code generator guarantees that every
    
    862
    +call to `$wf` has a properly tagged argument (see `GHC.Stg.EnforceEpt.Rewrite`).
    
    863
    +
    
    864
    +Is this a win?  Not always:
    
    865
    +* It can cause slight code size increases. This is since we push evals to every
    
    866
    +  call sites which there might be many. And the evals will only disappear at
    
    867
    +  call sites where we already known that the argument is evaluated.
    
    868
    +
    
    869
    +* It will also cause many more functions to get a worker/wrapper split
    
    870
    +  which can play badly with rules (see Ticket #20364).  In particular
    
    871
    +  if you depend on rules firing on functions marked as NOINLINE
    
    872
    +  without marking use sites of these functions as INLINE or INLINEABLE
    
    873
    +  then things will break.
    
    874
    +
    
    875
    +  But if you want a function to match in a RULE, it is /in any case/ good
    
    876
    +  practice to have a `INLINE[1]` or `NOINLNE[1]` pragma, to ensure that it
    
    877
    +  doesn't inline until the rule has had a chance to fire.
    
    878
    +
    
    879
    +So there is a flag, `-fworker-wrapper-cbv`, to control whether we do
    
    880
    +w/w on strict arguments (internally `Opt_WorkerWrapperUnlift`).  The
    
    881
    +flag is off by default.  The choice is made in
    
    882
    +GHC.Core.Opt.WorkWrap.Utils.wwUseForUnlifting
    
    883
    +
    
    884
    +See also `Note [WW for calling convention]`
    
    885
    +
    
    832 886
     Note [WW for calling convention]
    
    833 887
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    888
    +   NB: This Note is more of a discussion.
    
    889
    +       Read Note [Worker/wrapper for strict arguments] first,
    
    890
    +       which covers the same ground with more precision
    
    891
    +
    
    834 892
     If we know a function f will always evaluate a particular argument
    
    835 893
     we might decide that it should rather get evaluated by the caller.
    
    836 894
     We call this "unlifting" the argument.
    
    ... ... @@ -856,10 +914,9 @@ Hence we have the following strategies with different trade-offs:
    856 914
     
    
    857 915
     A) Never do W/W *just* for unlifting of arguments.
    
    858 916
       + Very conservative - doesn't break any rules
    
    859
    -  - Lot's of performance left on the table
    
    917
    +  - Lots of performance left on the table
    
    860 918
     
    
    861
    -B) Do W/W on just about anything where it might be
    
    862
    -  beneficial.
    
    919
    +B) Do W/W on just about anything where it might be beneficial.
    
    863 920
       + Exploits pretty much every opportunity for unlifting.
    
    864 921
       - A bit of compile time/code size cost for all the wrappers.
    
    865 922
       - Can break rules which would otherwise fire. See #20364.
    
    ... ... @@ -883,10 +940,10 @@ C) Unlift *any* (non-boot exported) functions arguments if they are strict.
    883 940
           functionality. I haven't tried this approach because it's not trivial to
    
    884 941
           implement and doing W/W splits seems to work well enough.
    
    885 942
     
    
    886
    -Currently we use the first approach A) by default, with a flag that allows users
    
    887
    -to fall back to the more aggressive approach B).
    
    943
    +Currently we use the first approach (A) by default, with a flag `-fworker-wrapper-cbv`
    
    944
    +that allows users to fall back to the more aggressive approach (B).
    
    888 945
     
    
    889
    -I also tried the third approach C) using eta-expansion at call sites to avoid
    
    946
    +I also tried the third approach (C) using eta-expansion at call sites to avoid
    
    890 947
     modifying the PAP-handling code which wasn't fruitful. See
    
    891 948
     https://gitlab.haskell.org/ghc/ghc/-/merge_requests/5614#note_389903.  We could
    
    892 949
     still try to do C) in the future by having PAP calls which will evaluate the
    
    ... ... @@ -895,53 +952,6 @@ be neither a small nor simple change so we stick with A) and a flag for B) for
    895 952
     now.
    
    896 953
     
    
    897 954
     See also Note [EPT enforcement] and Note [CBV Function Ids: overview]
    
    898
    -
    
    899
    -Note [Worker/wrapper for strict arguments]
    
    900
    -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    901
    -Consider
    
    902
    -    f x = case x of
    
    903
    -             []     -> blah
    
    904
    -             (y:ys) -> f ys
    
    905
    -
    
    906
    -Clearly `f` is strict, but its argument is not a product type, so by default
    
    907
    -we don't worker/wrapper it.  But it is arguably valuable to do so.  We could
    
    908
    -do this:
    
    909
    -
    
    910
    -   f x = case x of xx { DEFAULT -> $wf xx }
    
    911
    -   $wf xx = case xx of
    
    912
    -              []     -> blah
    
    913
    -              (y:ys) -> f ys
    
    914
    -
    
    915
    -Now the worker `$wf` knows that its argument `xx` will be evaluated
    
    916
    -and properly tagged, so the code for the `case xx` does not need to do
    
    917
    -an "eval" (see `GHC.StgToCmm.Expr.cgCase`).  A call (f (a:as)) will
    
    918
    -have the wrapper inlined, and will drop the `case x`, so no eval
    
    919
    -happens at all.
    
    920
    -
    
    921
    -The worker `$wf` is a CBV function (see `Note [CBV Function Ids: overview]`
    
    922
    -in GHC.Types.Id.Info) and the code generator guarantees that every
    
    923
    -call to `$wf` has a properly tagged argument (see `GHC.Stg.EnforceEpt.Rewrite`).
    
    924
    -
    
    925
    -Is this a win?  Not always:
    
    926
    -* It can cause slight codesize increases. This is since we push evals to every
    
    927
    -  call sites which there might be many. And the evals will only disappear at
    
    928
    -  call sites where we already known that the argument is evaluated.
    
    929
    -
    
    930
    -* It will also cause many more functions to get a worker/wrapper split
    
    931
    -  which can play badly with rules (see Ticket #20364).  In particular
    
    932
    -  if you depend on rules firing on functions marked as NOINLINE
    
    933
    -  without marking use sites of these functions as INLINE or INLINEABLE
    
    934
    -  then things will break.
    
    935
    -  But if you want a function to match in a RULE, it is /in any case/ good practice to
    
    936
    -  have a `INLINE[1]` or `NOINLNE[1]` pragma, to ensure that it doesn't inline until
    
    937
    -  the rule has had a chance to fire.
    
    938
    -
    
    939
    -So there is a flag, `-fworker-wrapper-cbv`, to control whether we do
    
    940
    -w/w on strict arguments (internally `Opt_WorkerWrapperUnlift`).  The
    
    941
    -flag is off by default.  The choice is made in
    
    942
    -GHC.Core.Opt.WorkWrape.Utils.wwUseForUnlifting
    
    943
    -
    
    944
    -See also `Note [WW for calling convention]` in GHC.Core.Opt.WorkWrap.Utils
    
    945 955
     -}
    
    946 956
     
    
    947 957
     {-
    
    ... ... @@ -985,6 +995,12 @@ mkWWstr opts args str_marks
    985 995
     --   * wrap_arg assumes work_args are in scope, and builds a ConApp that
    
    986 996
     --        reconstructs the RHS of wrap_var that we pass to the original RHS
    
    987 997
     -- See Note [Worker/wrapper for Strictness and Absence]
    
    998
    +--
    
    999
    +-- E.g. mkWWstr_one (x :: (Int,Int) with strictess saying to unbox the pair and second Int
    
    1000
    +--        = ( True                                             -- useful
    
    1001
    +--          , [p,q#],                                          -- work_args
    
    1002
    +--          , \e -> case x of (p,q) -> case q of I# q# -> e    -- wrap_fn
    
    1003
    +--          , (p, I# q) )                                      -- wrap_arg
    
    988 1004
     mkWWstr_one :: WwOpts
    
    989 1005
                 -> Var
    
    990 1006
                 -> StrictnessMark
    
    ... ... @@ -1008,7 +1024,7 @@ mkWWstr_one opts arg str_mark =
    1008 1024
     
    
    1009 1025
         DontUnbox
    
    1010 1026
           | isStrictDmd arg_dmd || isMarkedStrict str_mark
    
    1011
    -      , wwUseForUnlifting opts  -- See Note [WW for calling convention]
    
    1027
    +      , wwUseForUnlifting opts  -- See Note [Worker/wrapper for strict arguments]
    
    1012 1028
           , not (isFunTy arg_ty)
    
    1013 1029
           , not (isUnliftedType arg_ty) -- Already unlifted!
    
    1014 1030
             -- NB: function arguments have a fixed RuntimeRep,
    
    ... ... @@ -1163,7 +1179,7 @@ function is worthy for splitting:
    1163 1179
     2b But if e.g. a large tuple or product type is always demanded we might
    
    1164 1180
        decide to "unlift" it. That is tighten the calling convention for that
    
    1165 1181
        argument to require it to be passed as a pointer to the value itself.
    
    1166
    -   See Note [WW for calling convention].
    
    1182
    +   See Note [Worker/wrapper for strict arguments]
    
    1167 1183
     
    
    1168 1184
     3. In all other cases (e.g., lazy, used demand and not eval'd),
    
    1169 1185
        'finaliseArgBoxities' will have cleared the Boxity flag to 'Boxed'
    
    ... ... @@ -1604,7 +1620,9 @@ mkWWcpr_entry
    1604 1620
                  CoreExpr -> CoreExpr)     -- New worker.  'nop_fn' if not useful
    
    1605 1621
     -- ^ Entrypoint to CPR W/W. See Note [Worker/wrapper for CPR] for an overview.
    
    1606 1622
     mkWWcpr_entry opts body_ty body_cpr
    
    1607
    -  | not (wo_cpr_anal opts) = return (boringSplit, nop_fn, nop_fn)
    
    1623
    +  | not (wo_cpr_anal opts) --  See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal
    
    1624
    +  = return (boringSplit, nop_fn, nop_fn)
    
    1625
    +
    
    1608 1626
       | otherwise = do
    
    1609 1627
         -- Part (1)
    
    1610 1628
         res_bndr <- mk_res_bndr body_ty
    
    ... ... @@ -1637,7 +1655,9 @@ mk_res_bndr body_ty = do
    1637 1655
     --   1. A 'WwUse' capturing whether the split does anything useful.
    
    1638 1656
     --   2. The list of transit variables (see the Note).
    
    1639 1657
     --   3. The result builder expression for the wrapper.  The original case binder if not useful.
    
    1640
    ---   4. The result unpacking expression for the worker. 'nop_fn' if not useful.
    
    1658
    +--      Assumes that the transit vars are in scope
    
    1659
    +--   4. The result unpacking expression for the worker. 'nop_fn' if not useful
    
    1660
    +--      Brings the transit vars into scope
    
    1641 1661
     type CprWwResultOne  = (WwUse, OrdList Var,  CoreExpr , CoreExpr -> CoreExpr)
    
    1642 1662
     type CprWwResultMany = (WwUse, OrdList Var, [CoreExpr], CoreExpr -> CoreExpr)
    
    1643 1663
     
    
    ... ... @@ -1768,7 +1788,7 @@ To achieve said transformation, 'mkWWcpr_entry'
    1768 1788
          what belongs in the case scrutinee of the unpacker through the communicated
    
    1769 1789
          Id `r`: The unpacking expression will be free in that variable.
    
    1770 1790
          (This is a similar contract as that of 'mkWWstr_one' for strict args.)
    
    1771
    -  3. 'mkWWstr_one' produces a bunch of *transit vars*: Those result variables
    
    1791
    +  3. 'mkWWcpr_one' produces a bunch of *transit vars*: Those result variables
    
    1772 1792
          that have to be transferred from the worker to the wrapper, where the
    
    1773 1793
          constructed result can be rebuilt, `a` and `b` above. Part (3) is
    
    1774 1794
          responsible for tupling them up in the worker and taking the tuple apart
    

  • compiler/GHC/Types/Cpr.hs
    ... ... @@ -8,6 +8,7 @@
    8 8
     module GHC.Types.Cpr (
    
    9 9
         Cpr (ConCpr), topCpr, botCpr, flatConCpr, asConCpr,
    
    10 10
         CprType (..), topCprType, botCprType, flatConCprType,
    
    11
    +    cprTypeArity, cprTypeCpr,
    
    11 12
         lubCprType, applyCprTy, abstractCprTy, trimCprTy,
    
    12 13
         UnpackConFieldsResult (..), unpackConFieldsCpr,
    
    13 14
         CprSig (..), topCprSig, isTopCprSig, mkCprSigForArity, mkCprSig,
    
    ... ... @@ -106,6 +107,12 @@ data CprType
    106 107
                           --   'ct_arty' arguments
    
    107 108
       }
    
    108 109
     
    
    110
    +cprTypeArity :: CprType -> Arity
    
    111
    +cprTypeArity = ct_arty
    
    112
    +
    
    113
    +cprTypeCpr :: CprType -> Cpr
    
    114
    +cprTypeCpr = ct_cpr
    
    115
    +
    
    109 116
     instance Eq CprType where
    
    110 117
       a == b =  ct_cpr a == ct_cpr b
    
    111 118
              && (ct_arty a == ct_arty b || ct_cpr a == topCpr)
    
    ... ... @@ -167,7 +174,7 @@ seqCprTy (CprType _ cpr) = seqCpr cpr
    167 174
     
    
    168 175
     -- | The arity of the wrapped 'CprType' is the arity at which it is safe
    
    169 176
     -- to unleash. See Note [Understanding DmdType and DmdSig] in "GHC.Types.Demand"
    
    170
    -newtype CprSig = CprSig { getCprSig :: CprType }
    
    177
    +newtype CprSig = CprSig { cprSigType :: CprType }
    
    171 178
       deriving (Eq, Binary)
    
    172 179
     
    
    173 180
     -- | Turns a 'CprType' computed for the particular 'Arity' into a 'CprSig'
    

  • compiler/GHC/Types/Id/Info.hs
    ... ... @@ -32,7 +32,7 @@ module GHC.Types.Id.Info (
    32 32
             setOneShotInfo,
    
    33 33
     
    
    34 34
             -- ** Zapping various forms of Info
    
    35
    -        zapLamInfo, zapFragileInfo,
    
    35
    +        zapLamInfo, zapFragileInfo, hasRulesOrInline,
    
    36 36
             lazifyDemandInfo, floatifyDemandInfo,
    
    37 37
             zapUsageInfo, zapUsageEnvInfo, zapUsedOnceInfo,
    
    38 38
             zapTailCallInfo, zapCallArityInfo, trimUnfolding,
    
    ... ... @@ -963,3 +963,10 @@ zapTailCallInfo info
    963 963
     
    
    964 964
     zapCallArityInfo :: IdInfo -> IdInfo
    
    965 965
     zapCallArityInfo info = setCallArityInfo info 0
    
    966
    +
    
    967
    +hasRulesOrInline :: IdInfo -> Bool
    
    968
    +-- See (SB3) of Note [StrictBind]
    
    969
    +hasRulesOrInline info
    
    970
    +  = isStableUnfolding (unfoldingInfo info)
    
    971
    +    || not (isEmptyRuleInfo (ruleInfo info))
    
    972
    +    || not (isAlwaysActive (inlinePragmaActivation (inlinePragInfo info)))

  • compiler/GHC/Utils/Monad.hs
    ... ... @@ -16,7 +16,7 @@ module GHC.Utils.Monad
    16 16
             , mapAccumLM
    
    17 17
             , mapSndM
    
    18 18
             , concatMapM
    
    19
    -        , mapMaybeM
    
    19
    +        , mapMaybeM, orElseM
    
    20 20
             , anyM, allM, orM
    
    21 21
             , foldlM, foldlM_, foldrM, foldMapM
    
    22 22
             , whenM, unlessM
    
    ... ... @@ -250,6 +250,14 @@ unlessM :: Monad m => m Bool -> m () -> m ()
    250 250
     unlessM condM acc = do { cond <- condM
    
    251 251
                            ; unless cond acc }
    
    252 252
     
    
    253
    +-- | Monadic version of @orElse@
    
    254
    +infixr 4 `orElseM`
    
    255
    +orElseM :: Monad m => m (Maybe a) -> m a -> m a
    
    256
    +orElseM ma def = do { mb_r <- ma
    
    257
    +                    ; case mb_r of
    
    258
    +                        Just x  -> return x
    
    259
    +                        Nothing -> def }
    
    260
    +
    
    253 261
     -- | Like 'filterM', only it reverses the sense of the test.
    
    254 262
     filterOutM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a]
    
    255 263
     filterOutM p =
    

  • testsuite/tests/simplCore/should_compile/T28158.hs
    1
    +{-# OPTIONS_GHC -fworker-wrapper-cbv #-}
    
    2
    +-- Adding this option makes things harder for splitThunkCpr, which
    
    3
    +-- this test is testing.  See (TS8) in Note [Thunk splitting]
    
    4
    +
    
    5
    +module T28158 where
    
    6
    +
    
    7
    +-- Here we miss CPR on y
    
    8
    +-- It's a bit of an obscure example, but still; see #28158
    
    9
    +f :: a -> a -> a -> [Int] -> [Int]
    
    10
    +f a b c xs = let y = case xs of
    
    11
    +                      [0] -> Just a
    
    12
    +                      [1] -> Just b
    
    13
    +                      _   -> Just c
    
    14
    +             in h y (case y of
    
    15
    +                       Just z  -> reverse (reverse (reverse (
    
    16
    +                                  reverse (reverse (reverse (
    
    17
    +                                  reverse (reverse xs)))))))
    
    18
    +                       Nothing -> xs++xs)
    
    19
    +
    
    20
    +h :: Maybe a -> b -> b
    
    21
    +h (Just y) e = h Nothing e
    
    22
    +h Nothing  e = e

  • testsuite/tests/simplCore/should_compile/T28158.stderr
    1
    +
    
    2
    +==================== Tidy Core ====================
    
    3
    +Result size of Tidy Core
    
    4
    +  = {terms: 98, types: 108, coercions: 0, joins: 1/1}
    
    5
    +
    
    6
    +Rec {
    
    7
    +$wh
    
    8
    +  = \ @a @b ds e ->
    
    9
    +      case ds of ds1 { __DEFAULT ->
    
    10
    +      case e of e1 { __DEFAULT ->
    
    11
    +      case ds1 of {
    
    12
    +        Nothing -> e1;
    
    13
    +        Just y -> $wh Nothing e1
    
    14
    +      }
    
    15
    +      }
    
    16
    +      }
    
    17
    +end Rec }
    
    18
    +
    
    19
    +h = \ @a @b ds e -> $wh ds e
    
    20
    +
    
    21
    +$wf
    
    22
    +  = \ @a a1 b c xs ->
    
    23
    +      join {
    
    24
    +        $j ww
    
    25
    +          = $wh
    
    26
    +              (Just ww)
    
    27
    +              (reverse1
    
    28
    +                 (reverse1
    
    29
    +                    (reverse1
    
    30
    +                       (reverse1
    
    31
    +                          (reverse1 (reverse1 (reverse1 (reverse1 xs []) []) []) []) [])
    
    32
    +                       [])
    
    33
    +                    [])
    
    34
    +                 []) } in
    
    35
    +      case xs of {
    
    36
    +        [] -> jump $j c;
    
    37
    +        : ds ds1 ->
    
    38
    +          case ds of { I# ds2 ->
    
    39
    +          case ds2 of {
    
    40
    +            __DEFAULT -> jump $j c;
    
    41
    +            0# ->
    
    42
    +              case ds1 of {
    
    43
    +                [] -> jump $j a1;
    
    44
    +                : ipv ipv1 -> jump $j c
    
    45
    +              };
    
    46
    +            1# ->
    
    47
    +              case ds1 of {
    
    48
    +                [] -> jump $j b;
    
    49
    +                : ipv ipv1 -> jump $j c
    
    50
    +              }
    
    51
    +          }
    
    52
    +          }
    
    53
    +      }
    
    54
    +
    
    55
    +f = \ @a a1 b c xs -> $wf a1 b c xs
    
    56
    +
    
    57
    +
    
    58
    +

  • testsuite/tests/simplCore/should_compile/all.T
    ... ... @@ -637,5 +637,5 @@ test('T27963', [grep_errmsg(r'f/42')], compile, ['-O -ddump-rule-firings'])
    637 637
     test('T27965', normal, compile, ['-O'])
    
    638 638
     test('T27965a', normal, compile, ['-O'])
    
    639 639
     test('T27965b', normal, compile, ['-O'])
    
    640
    -
    
    640
    +test('T28158', normal, compile, ['-O -dno-typeable-binds -dsuppress-all -dsuppress-uniques -ddump-simpl'])
    
    641 641