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

Commits:

13 changed files:

Changes:

  • compiler/GHC/Core/Coercion.hs
    ... ... @@ -74,7 +74,7 @@ module GHC.Core.Coercion (
    74 74
             isReflCoVar_maybe, assertGoodForAllCo,
    
    75 75
     
    
    76 76
     
    
    77
    -        coToMCo, kindCoToMKindCo,
    
    77
    +        coToMCo, kindCoToMKindCo, mCoToCo,
    
    78 78
             mkTransMCo, mkTransMCoL, mkTransMCoR, mkCastTyMCo, mkSymMCo,
    
    79 79
             mkFunResMCo, mkPiMCos,
    
    80 80
             isReflMCo, checkReflexiveMCo,
    

  • compiler/GHC/Core/Opt/Arity.hs
    ... ... @@ -886,8 +886,14 @@ findRhsArity :: ArityOpts -> RecFlag -> Id -> CoreExpr
    886 886
     -- This implements the fixpoint loop for arity analysis
    
    887 887
     -- See Note [Arity analysis]
    
    888 888
     --
    
    889
    --- The Bool is True if the returned arity is greater than (exprArity rhs)
    
    890
    ---     so the caller should do eta-expansion
    
    889
    +-- The Bool is True if
    
    890
    +--            the returned arity is greater than (exprArity rhs)
    
    891
    +-- so the caller should do eta-expansion
    
    892
    +-- NB: `exprArity`, not `manifestArity`:
    
    893
    +--     a PAP such as (\x. f x), where f has arity 3, has exprArity 3,
    
    894
    +--     so we do not eta-expand it to (\x y z. f x y z)
    
    895
    +--     See Note [Do not eta-expand PAPs] in GHC.Core.Opt.Simplify.Utils
    
    896
    +--
    
    891 897
     -- That Bool is never True for join points, which are never eta-expanded
    
    892 898
     --
    
    893 899
     -- Returns an SafeArityType that is guaranteed trimmed to typeArity of 'bndr'
    
    ... ... @@ -903,10 +909,11 @@ findRhsArity opts is_rec bndr rhs
    903 909
     
    
    904 910
       | otherwise
    
    905 911
       = (arity_increased, non_join_arity_type)
    
    906
    -    -- arity_increased: eta-expand if we'll get more lambdas
    
    907
    -    -- to the top of the RHS
    
    912
    +    -- arity_increased: eta-expand if the analysis finds a greater arity
    
    913
    +    -- than exprArity, which already takes account of PAPs
    
    908 914
       where
    
    909
    -    old_arity = exprArity rhs
    
    915
    +    old_arity = exprArity rhs   -- See Note [Do not eta-expand PAPs]
    
    916
    +                                -- in GHC.Core.Opt.Simplify.Utils
    
    910 917
     
    
    911 918
         init_env :: ArityEnv
    
    912 919
         init_env = findRhsArityEnv opts (isJoinId bndr)
    
    ... ... @@ -2388,6 +2395,7 @@ mkEtaForAllMCo (Bndr tcv vis) ty mco
    2388 2395
         -- and is SymCo'd in `etaInfoAbs`.  Hence the orientation of the visibility
    
    2389 2396
         -- flags.  A bit of a brain-strain (#27557).
    
    2390 2397
     
    
    2398
    +
    
    2391 2399
     {-
    
    2392 2400
     ************************************************************************
    
    2393 2401
     *                                                                      *
    
    ... ... @@ -2452,16 +2460,20 @@ perform eta reduction on an expression with n leading lambdas `\xs. e xs`
    2452 2460
     (checked in 'is_eta_reduction_sound' in 'tryEtaReduce', which focuses on the
    
    2453 2461
     case where `e` is trivial):
    
    2454 2462
     
    
    2455
    -(A) It is sound to eta-reduce n arguments as long as n does not exceed the
    
    2456
    -    `exprArity` of `e`. (Needs Arity analysis.)
    
    2457
    -    This criterion exploits information about how `e` is *defined*.
    
    2463
    +(EtaA) It is sound to eta-reduce n arguments as long as n does not exceed the
    
    2464
    +    `exprArity` of `e`. (Needs Arity analysis.) This criterion exploits information
    
    2465
    +    about how `e` is *defined*.  For example:
    
    2466
    +      f = \xy. g x y   ===>    f = g
    
    2467
    +    This eta-reduction is good only if `g` has arity at least 2, otherwise
    
    2468
    +    f's arity will decrease from 2 to 1.
    
    2469
    +    c.f. Note [Arity robustness] in GHC.Core.Opt.Simplify.Env.
    
    2458 2470
     
    
    2459
    -    Example: If `e = \x. bot` then we know it won't diverge until it is called
    
    2460
    -    with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`.
    
    2471
    +    Another example: If `e = \x. bot` then we know it won't diverge until it
    
    2472
    +    is called with one argument. Hence it is safe to eta-reduce `\x. e x` to `e`.
    
    2461 2473
         By contrast, it would be *unsound* to eta-reduce 2 args, `\x y. e x y` to `e`:
    
    2462 2474
         `e 42` diverges when `(\x y. e x y) 42` does not.
    
    2463 2475
     
    
    2464
    -(S) It is sound to eta-reduce n arguments in an evaluation context in which all
    
    2476
    +(EtaS) It is sound to eta-reduce n arguments in an evaluation context in which all
    
    2465 2477
         calls happen with at least n arguments. (Needs Strictness analysis.)
    
    2466 2478
         NB: This treats evaluations like a call with 0 args.
    
    2467 2479
         NB: This criterion exploits information about how `e` is *used*.
    
    ... ... @@ -2483,35 +2495,31 @@ case where `e` is trivial):
    2483 2495
         But it is unsound to eta-reduce the arg in `g2 (\x y. e x y)` to `g2 e`
    
    2484 2496
         when `e = \x. if x then bot else id`, because the latter will diverge when
    
    2485 2497
         the former would not. Fortunately, the strictness analyser will report
    
    2486
    -    "Not always called with two arguments" for `g2` and we won't eta-expand.
    
    2498
    +    "Not always called with two arguments" for `g2` and we won't eta-reduce.
    
    2487 2499
     
    
    2488 2500
         See Note [Eta reduction based on evaluation context] for the implementation
    
    2489 2501
         details. This criterion is tested extensively in T21261.
    
    2490 2502
     
    
    2491
    -(R) Note [Eta reduction in recursive RHSs] tells us that we should not
    
    2503
    +(EtaR) Note [Eta reduction in recursive RHSs] tells us that we should not
    
    2492 2504
         eta-reduce `f` in its own RHS and describes our fix.
    
    2493 2505
         There we have `f = \x. f x` and we should not eta-reduce to `f=f`. Which
    
    2494 2506
         might change a terminating program (think @f `seq` e@) to a non-terminating
    
    2495 2507
         one.
    
    2496 2508
     
    
    2497
    -(E) (See fun_arity in tryEtaReduce.) As a perhaps special case on the
    
    2498
    -    boundary of (A) and (S), when we know that a fun binder `f` is in
    
    2499
    -    WHNF, we simply assume it has arity 1 and apply (A).  Example:
    
    2509
    +(EtaE) (See fun_arity in tryEtaReduce.) As a perhaps special case on the
    
    2510
    +    boundary of (EtaA) and (EtaS), when we know that a fun binder `f` is in
    
    2511
    +    WHNF, we simply assume it has arity 1 and apply (EtaA).  Example:
    
    2500 2512
            g f = f `seq` \x. f x
    
    2501 2513
         Here it's sound eta-reduce `\x. f x` to `f`, because `f` can't be bottom
    
    2502 2514
         after the `seq`. This turned up in #7542.
    
    2503 2515
     
    
    2504
    - T. If the binders are all type arguments, it's always safe to eta-reduce,
    
    2505
    -    regardless of the arity of f.
    
    2506
    -       /\a b. f @a @b  --> f
    
    2507
    -
    
    2508
    -2. Type and dictionary abstraction. Regardless of whether 'f' is a value, it
    
    2516
    +(EtaT) Type and dictionary abstraction. Regardless of whether 'f' is a value, it
    
    2509 2517
        is always sound to reduce /type lambdas/, thus:
    
    2510
    -        (/\a -> f a)  -->   f
    
    2518
    +        (/\a -> f @a)  -->   f
    
    2511 2519
        Moreover, we always want to, because it makes RULEs apply more often:
    
    2512
    -      This RULE:    `forall g. foldr (build (/\a -> g a))`
    
    2520
    +      This RULE:    `forall g. foldr (build (/\a -> g @a))`
    
    2513 2521
           should match  `foldr (build (/\b -> ...something complex...))`
    
    2514
    -   and the simplest way to do so is eta-reduce `/\a -> g a` in the RULE to `g`.
    
    2522
    +   and the simplest way to do so is eta-reduce `/\a -> g @a` in the RULE to `g`.
    
    2515 2523
     
    
    2516 2524
        More debatably, we extend this to dictionary arguments too, because the type
    
    2517 2525
        checker can insert these eta-expanded versions, with both type and dictionary
    
    ... ... @@ -2523,18 +2531,25 @@ case where `e` is trivial):
    2523 2531
     And here are a few more technical criteria for when it is *not* sound to
    
    2524 2532
     eta-reduce that are specific to Core and GHC:
    
    2525 2533
     
    
    2526
    -(J) We may not undersaturate join points.
    
    2534
    +(EtaJ) We may not undersaturate join points.
    
    2527 2535
         See Note [Invariants on join points] in GHC.Core, and #20599.
    
    2528 2536
     
    
    2529
    -(B) We may not undersaturate functions with no binding.
    
    2537
    +(EtaB) We may not undersaturate functions with no binding.
    
    2530 2538
         See Note [Eta expanding primops].
    
    2531 2539
     
    
    2532
    -(W) We may not undersaturate StrictWorkerIds.
    
    2540
    +(EtaW) We may not undersaturate StrictWorkerIds.
    
    2533 2541
         See Note [CBV Function Ids: overview] in GHC.Types.Id.Info.
    
    2534 2542
     
    
    2535
    -Here is a list of historic accidents surrounding unsound eta-reduction:
    
    2536 2543
     
    
    2537
    -* Consider
    
    2544
    +Here is a list of historic notes surrounding unsound eta-reduction:
    
    2545
    +
    
    2546
    +(EtaMult) We used to disable eta-reduction if performing it would change multiplicity.
    
    2547
    +  For example:
    
    2548
    +      (\x. K x) :: Int -> T    but    K :: Int %1 -> T
    
    2549
    +  But that (a) inhibits beneficial eta-reduction (b) costs extra work to check, and
    
    2550
    +  now we don't even try. See Note [Linting linearity] in GHC.Core.Lint, esp EXAMPLE 4
    
    2551
    +
    
    2552
    +(EtaBot) Consider
    
    2538 2553
             f = \x.f x
    
    2539 2554
             h y = case (case y of { True -> f `seq` True; False -> False }) of
    
    2540 2555
                     True -> ...; False -> ...
    
    ... ... @@ -2548,16 +2563,6 @@ Here is a list of historic accidents surrounding unsound eta-reduction:
    2548 2563
       Result: seg-fault because the boolean case actually gets a function value.
    
    2549 2564
       See #1947.
    
    2550 2565
     
    
    2551
    -* Never *reduce* arity. For example
    
    2552
    -      f = \xy. g x y
    
    2553
    -  Then if h has arity 1 we don't want to eta-reduce because then
    
    2554
    -  f's arity would decrease, and that is bad
    
    2555
    -  [SG in 2022: I don't understand this point. There is no `h`, perhaps that
    
    2556
    -   should have been `g`. Even then, this proposed eta-reduction is invalid by
    
    2557
    -   criterion (A), which might actually be the point this anecdote is trying to
    
    2558
    -   make. Perhaps the "no arity decrease" idea is also related to
    
    2559
    -   Note [Arity robustness]?]
    
    2560
    -
    
    2561 2566
     Note [Do not eta reduce PAPs]
    
    2562 2567
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2563 2568
     I considered eta-reducing if the result is a PAP:
    
    ... ... @@ -2598,11 +2603,14 @@ This should be eta-reduced to
    2598 2603
     
    
    2599 2604
     So we need to accumulate a coercion, pushing it inward (past
    
    2600 2605
     variable arguments only) thus:
    
    2601
    -   f (x |> co_arg) |> co  -->  (f |> (sym co_arg -> co)) x
    
    2602
    -   f (x:t)         |> co  -->  (f |> (t -> co)) x
    
    2603
    -   f @ a           |> co  -->  (f |> (forall a.co)) @ a
    
    2604
    -   f @ (g:t1~t2)   |> co  -->  (f |> (t1~t2 => co)) @ (g:t1~t2)
    
    2605
    -These are the equations for ok_arg.
    
    2606
    +(ECA1)   \x. f (x |> co_arg) |> co  -->  (f |> (sym co_arg -> co))
    
    2607
    +(ECA2)   \x. f (x:t)         |> co  -->  (f |> (t -> co))
    
    2608
    +(ECA3)   \x. f (x:t1~#t2)    |> co  -->  (f |> (t1~#t2 => co))
    
    2609
    +(ECA4)   \x. f @ a           |> co  -->  (f |> (forall a.co))
    
    2610
    +
    
    2611
    +(ECA1,2,4) are implemented by the `go` equations in `tryEtaReduce`.
    
    2612
    +However (ECA3) is not implemented -- it could be, perhaps by spotting
    
    2613
    +an argument that is (Coercion (CoVar x)), but it seems like a rare case.
    
    2606 2614
     
    
    2607 2615
     Note [Eta reduction with casted function]
    
    2608 2616
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    ... ... @@ -2620,7 +2628,7 @@ eta-expansion may be turned off (by sm_eta_expand).
    2620 2628
     
    
    2621 2629
     Note [Eta reduction based on evaluation context]
    
    2622 2630
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2623
    -Note [Eta reduction soundness], criterion (S) allows us to eta-reduce
    
    2631
    +Note [Eta reduction soundness], criterion (EtaS) allows us to eta-reduce
    
    2624 2632
     `g (\x y. e x y)` to `g e` when we know that `g` always calls its parameter with
    
    2625 2633
     at least 2 arguments. So how do we read that off `g`'s demand signature?
    
    2626 2634
     
    
    ... ... @@ -2713,13 +2721,13 @@ tryEtaReduce :: UnVarSet -> [Var] -> CoreExpr -> SubDemand -> Maybe CoreExpr
    2713 2721
     -- and Note [Eta reduction makes sense] when that is the case.
    
    2714 2722
     -- and Note [Eta reduction based on evaluation context] for the `eval_sd` arg
    
    2715 2723
     tryEtaReduce rec_ids bndrs body eval_sd
    
    2716
    -  = go (reverse bndrs) body (mkRepReflCo (exprType body))
    
    2724
    +  = go (reverse bndrs) body MRefl
    
    2717 2725
       where
    
    2718
    -    incoming_arity = count isId bndrs -- See Note [Eta reduction makes sense], point (2)
    
    2726
    +    incoming_arity = count isId bndrs -- See (EtaA) in Note [Eta reduction soundness]
    
    2719 2727
     
    
    2720 2728
         go :: [Var]            -- Binders, innermost first, types [a3,a2,a1]
    
    2721 2729
            -> CoreExpr         -- Of type tr
    
    2722
    -       -> Coercion         -- Of type tr ~ ts
    
    2730
    +       -> MCoercion        -- Of type tr ~ ts
    
    2723 2731
            -> Maybe CoreExpr   -- Of type a1 -> a2 -> a3 -> ts
    
    2724 2732
         -- See Note [Eta reduction with casted arguments]
    
    2725 2733
         -- for why we have an accumulating coercion
    
    ... ... @@ -2729,19 +2737,37 @@ tryEtaReduce rec_ids bndrs body eval_sd
    2729 2737
     
    
    2730 2738
         -- See Note [Eta reduction with casted function]
    
    2731 2739
         go bs (Cast e co1) co2
    
    2732
    -      = go bs e (co1 `mkTransCo` co2)
    
    2740
    +      = go bs e (co1 `mkTransMCoR` co2)
    
    2733 2741
     
    
    2734 2742
         go bs (Tick t e) co
    
    2735 2743
           | tickishFloatable t
    
    2736 2744
           = fmap (Tick t) $ go bs e co
    
    2737 2745
           -- Float app ticks: \x -> Tick t (e x) ==> Tick t e
    
    2738 2746
     
    
    2739
    -    go (b : bs) (App fun arg) co
    
    2740
    -      | Just (co', ticks) <- ok_arg b arg co (exprType fun)
    
    2741
    -      = fmap (flip (foldr mkTick) ticks) $ go bs fun co'
    
    2742
    -            -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e
    
    2747
    +    -- Implements (ECA4)
    
    2748
    +    go all_bs@(b : bs) all_e@(App fun (Type arg_ty)) mco
    
    2749
    +      | Just tv <- getTyVar_maybe arg_ty
    
    2750
    +      , b == tv
    
    2751
    +      , Just (bndr, body_ty) <- splitForAllForAllTyBinder_maybe (exprType fun)
    
    2752
    +      = go bs fun (mkEtaReduceForAllMCo bndr body_ty tv mco)
    
    2743 2753
     
    
    2744
    -    go remaining_bndrs fun co
    
    2754
    +      | otherwise
    
    2755
    +      = go_finish all_bs all_e mco
    
    2756
    +        -- Want to go to the finish case; see the call
    
    2757
    +        -- to (all isTyVar remaining_bndrs) there
    
    2758
    +
    
    2759
    +    -- Implements (ECA1,2)
    
    2760
    +    go (b : bs) (App fun val_arg) mco
    
    2761
    +      | Just (v, arg_mco, arg_ticks) <- getTrivialHead_maybe val_arg
    
    2762
    +      , b == v
    
    2763
    +      , Just co' <- mkEtaReduceFunCo (exprType fun) arg_mco mco
    
    2764
    +      = fmap (flip (foldr mkTick) arg_ticks) $
    
    2765
    +        go bs fun co'
    
    2766
    +        -- Float arg ticks: \x -> e (Tick t x) ==> Tick t e
    
    2767
    +
    
    2768
    +    go bs fun co = go_finish bs fun co
    
    2769
    +
    
    2770
    +    go_finish remaining_bndrs fun co
    
    2745 2771
           | all isTyVar remaining_bndrs
    
    2746 2772
                 -- If all the remaining_bnrs are tyvars, then the etad_exp
    
    2747 2773
                 --    will be trivial, which is what we want.
    
    ... ... @@ -2752,7 +2778,7 @@ tryEtaReduce rec_ids bndrs body eval_sd
    2752 2778
           , remaining_bndrs `ltLength` bndrs
    
    2753 2779
                 -- Only reply Just if /something/ has happened
    
    2754 2780
           , ok_fun fun
    
    2755
    -      , let used_vars     = exprFreeVars fun `unionVarSet` tyCoVarsOfCo co
    
    2781
    +      , let used_vars     = exprFreeVars fun `unionVarSet` tyCoVarsOfMCo co
    
    2756 2782
                 reduced_bndrs = mkVarSet (dropList remaining_bndrs bndrs)
    
    2757 2783
                 -- reduced_bndrs are the ones we are eta-reducing away
    
    2758 2784
           , used_vars `disjointVarSet` reduced_bndrs
    
    ... ... @@ -2761,10 +2787,10 @@ tryEtaReduce rec_ids bndrs body eval_sd
    2761 2787
               -- See Note [Eta reduction makes sense], intro and point (1)
    
    2762 2788
               -- NB: don't compute used_vars from exprFreeVars (mkCast fun co)
    
    2763 2789
               --     because the latter may be ill formed if the guard fails (#21801)
    
    2764
    -      = Just (mkLams (reverse remaining_bndrs) (mkCast fun co))
    
    2790
    +      = Just (mkLams (reverse remaining_bndrs) (mkCastMCo fun co))
    
    2765 2791
     
    
    2766
    -    go _remaining_bndrs _fun  _  = -- pprTrace "tER fail" (ppr _fun $$ ppr _remaining_bndrs) $
    
    2767
    -                                   Nothing
    
    2792
    +      | otherwise
    
    2793
    +      = Nothing
    
    2768 2794
     
    
    2769 2795
         ---------------
    
    2770 2796
         -- See Note [Eta reduction makes sense], point (1)
    
    ... ... @@ -2777,18 +2803,18 @@ tryEtaReduce rec_ids bndrs body eval_sd
    2777 2803
         ---------------
    
    2778 2804
         -- See Note [Eta reduction soundness], this is THE place to check soundness!
    
    2779 2805
         is_eta_reduction_sound fun
    
    2780
    -      | fun `elemUnVarSet` rec_ids          -- Criterion (R)
    
    2806
    +      | fun `elemUnVarSet` rec_ids          -- Criterion (EtaR)
    
    2781 2807
           = False -- Don't eta-reduce in fun in its own recursive RHSs
    
    2782 2808
     
    
    2783
    -      | cantEtaReduceFun fun                -- Criteria (J), (W), (B)
    
    2809
    +      | cantEtaReduceFun fun                -- Criteria (EtaJ), (EtaW), (EtaB)
    
    2784 2810
           = False -- Function can't be eta reduced to arity 0
    
    2785 2811
                   -- without violating invariants of Core and GHC
    
    2786 2812
     
    
    2787 2813
           | otherwise
    
    2788 2814
           = -- Check that eta-reduction won't make the program stricter...
    
    2789
    -        fun_arity fun >= incoming_arity          -- Criterion (A) and (E)
    
    2790
    -        || all_calls_with_arity incoming_arity   -- Criterion (S)
    
    2791
    -        || all ok_lam bndrs                      -- Criterion (T)
    
    2815
    +        fun_arity fun >= incoming_arity          -- Criterion (EtaA) and (EtaE)
    
    2816
    +        || all_calls_with_arity incoming_arity   -- Criterion (EtaS)
    
    2817
    +        || all ok_lam bndrs                      -- Criterion (EtaT)
    
    2792 2818
     
    
    2793 2819
         all_calls_with_arity n = isStrict (fst $ peelManyCalls n eval_sd)
    
    2794 2820
            -- See Note [Eta reduction based on evaluation context]
    
    ... ... @@ -2797,57 +2823,76 @@ tryEtaReduce rec_ids bndrs body eval_sd
    2797 2823
         fun_arity fun
    
    2798 2824
            | arity > 0                           = arity
    
    2799 2825
            | isEvaldUnfolding (idUnfolding fun)  = 1
    
    2800
    -           -- See Note [Eta reduction soundness], criterion (E)
    
    2826
    +           -- See Note [Eta reduction soundness], criterion (EtaE)
    
    2801 2827
            | otherwise                           = 0
    
    2802 2828
            where
    
    2803 2829
              arity = idArity fun
    
    2804 2830
     
    
    2805 2831
         ---------------
    
    2806 2832
         ok_lam v = isTyVar v || isEvId v
    
    2807
    -    -- See Note [Eta reduction makes sense], point (2)
    
    2808
    -
    
    2809
    -    ---------------
    
    2810
    -    ok_arg :: Var              -- Of type bndr_t
    
    2811
    -           -> CoreExpr         -- Of type arg_t
    
    2812
    -           -> Coercion         -- Of kind (t1~t2)
    
    2813
    -           -> Type             -- Type (arg_t -> t1) of the function
    
    2814
    -                               --      to which the argument is supplied
    
    2815
    -           -> Maybe (Coercion  -- Of type (arg_t -> t1 ~  bndr_t -> t2)
    
    2816
    -                               --   (and similarly for tyvars, coercion args)
    
    2817
    -                    , [CoreTickish])
    
    2818
    -    -- See Note [Eta reduction with casted arguments]
    
    2819
    -    ok_arg bndr (Type arg_ty) co fun_ty
    
    2820
    -       | Just tv <- getTyVar_maybe arg_ty
    
    2821
    -       , bndr == tv  = case splitForAllForAllTyBinder_maybe fun_ty of
    
    2822
    -           Just (Bndr _ vis, _) -> Just (fco, [])
    
    2823
    -             where !fco = mkForAllCo tv vis coreTyLamForAllTyFlag MRefl co
    
    2824
    -                   -- The lambda we are eta-reducing always has visibility
    
    2825
    -                   -- 'coreTyLamForAllTyFlag' which may or may not match
    
    2826
    -                   -- the visibility on the inner function (#24014)
    
    2827
    -           Nothing -> pprPanic "tryEtaReduce: type arg to non-forall type"
    
    2828
    -                               (text "fun:" <+> ppr bndr
    
    2829
    -                                $$ text "arg:" <+> ppr arg_ty
    
    2830
    -                                $$ text "fun_ty:" <+> ppr fun_ty)
    
    2831
    -    ok_arg bndr (Var v) co fun_ty
    
    2832
    -       | bndr == v
    
    2833
    -       , let mult = idMult bndr
    
    2834
    -       , Just (_af, fun_mult, _, _) <- splitFunTy_maybe fun_ty
    
    2835
    -       , mult `eqType` fun_mult -- There is no change in multiplicity, otherwise we must abort
    
    2836
    -       = Just (mkFunResCo Representational bndr co, [])
    
    2837
    -    ok_arg bndr (Cast e co_arg) co fun_ty
    
    2838
    -       | (ticks, Var v) <- stripTicksTop tickishFloatable e
    
    2839
    -       , Just (_, fun_mult, _, _) <- splitFunTy_maybe fun_ty
    
    2840
    -       , bndr == v
    
    2841
    -       , fun_mult `eqType` idMult bndr
    
    2842
    -       = Just (mkFunCoNoFTF Representational (multToCo fun_mult) (mkSymCo co_arg) co, ticks)
    
    2843
    -       -- The simplifier combines multiple casts into one,
    
    2844
    -       -- so we can have a simple-minded pattern match here
    
    2845
    -    ok_arg bndr (Tick t arg) co fun_ty
    
    2846
    -       | tickishFloatable t, Just (co', ticks) <- ok_arg bndr arg co fun_ty
    
    2847
    -       = Just (co', t:ticks)
    
    2848
    -
    
    2849
    -    ok_arg _ _ _ _ = Nothing
    
    2833
    +    -- See Note [Eta reduction soundness], point (EtaT)
    
    2834
    +
    
    2835
    +
    
    2836
    +-----------------
    
    2837
    +getTrivialHead_maybe :: CoreExpr -> Maybe (Id, MCoercion, [CoreTickish])
    
    2838
    +-- (getTrivialHead_maybe e) returns (Just (fn, co,ts))
    
    2839
    +-- if `e` looks like (Tick ts (fn |> co)) and ts are floatable
    
    2840
    +-- So  co :: fn_ty ~ arg_ty
    
    2841
    +
    
    2842
    +getTrivialHead_maybe (Var v)
    
    2843
    +   = Just (v, MRefl, [])
    
    2844
    +
    
    2845
    +getTrivialHead_maybe (Cast e co_outer)
    
    2846
    +   = do { (v, mco_inner, ticks) <- getTrivialHead_maybe e
    
    2847
    +        ; return (v, mco_inner `mkTransMCoL` co_outer, ticks) }
    
    2848
    +
    
    2849
    +getTrivialHead_maybe (Tick t arg)
    
    2850
    +   | tickishFloatable t
    
    2851
    +   = do { (v, co, ticks) <- getTrivialHead_maybe arg
    
    2852
    +        ; return (v, co, t:ticks) }
    
    2853
    +
    
    2854
    +getTrivialHead_maybe _ = Nothing
    
    2855
    +
    
    2856
    +-----------------
    
    2857
    +mkEtaReduceFunCo :: Type -> MCoercion -> MCoercion -> Maybe MCoercion
    
    2858
    +mkEtaReduceFunCo _ MRefl MRefl
    
    2859
    +  = Just MRefl    -- Very common case
    
    2860
    +mkEtaReduceFunCo fun_ty arg_mco res_mco
    
    2861
    +  | Just (ftf, mult, arg_ty, res_ty) <- splitFunTy_maybe fun_ty
    
    2862
    +  --   fun_ty = arg_ty -> res_ty
    
    2863
    +  --   sym arg_mco : arg_ty ~ inner_arg_ty
    
    2864
    +  --       res_mco : res_ty ~ outer_res_ty
    
    2865
    +  , let arg_co  = mCoToCo Representational arg_ty arg_mco
    
    2866
    +        res_co  = mCoToCo Representational res_ty res_mco
    
    2867
    +        mult_co = multToCo mult
    
    2868
    +        ftf'    = chooseFunTyFlag (coercionLKind arg_co) (coercionRKind res_co)
    
    2869
    +  = Just (MCo (mkFunCo2 Representational ftf ftf' mult_co (mkSymCo arg_co) res_co))
    
    2870
    +              -- (arg_ty -> res_ty) ~ (inner_arg_ty -> outer_res_ty)
    
    2871
    +  | otherwise
    
    2872
    +  = Nothing
    
    2850 2873
     
    
    2874
    +-----------------
    
    2875
    +mkEtaReduceForAllMCo :: ForAllTyBinder -> Type -> TyVar -> MCoercion -> MCoercion
    
    2876
    +-- Very similar to mkEtaForAllMCo, but with
    
    2877
    +-- the visibilities the other way around.  Tiresome.
    
    2878
    +--   mkEtaReduceForAllMCo (forall a[vis]. body_ty) b (co :: ty1 ~ ty2)
    
    2879
    +--     (where `b` may be free in `ty1` and `ty2`)
    
    2880
    +--   = ForAllCo b[vis]~[spec]. (co :: ty1 ~ ty2)
    
    2881
    +-- where `coreTyLamForAllTyFlag` is  [spec]
    
    2882
    +mkEtaReduceForAllMCo (Bndr fun_tv vis) body_ty tv mco
    
    2883
    +  = case mco of
    
    2884
    +      MRefl  | isCoreTyLamForAllTyFlag vis
    
    2885
    +                -- The lambda we are eta-reducing always has visibility
    
    2886
    +                -- 'coreTyLamForAllTyFlag' which may or may not match the
    
    2887
    +                -- visibility on the inner function (#24014)
    
    2888
    +             -> MRefl
    
    2889
    +             | otherwise
    
    2890
    +             -> MCo $ mkForAllCo fun_tv vis coreTyLamForAllTyFlag MRefl refl_co
    
    2891
    +      MCo co -> MCo $ mkForAllCo tv     vis coreTyLamForAllTyFlag MRefl co
    
    2892
    +                -- Tricky: `fun_tv` scopes over `body_ty` and hence over `refl_co`
    
    2893
    +                --    but: `tv` scopes over `mco` and hence over `co`
    
    2894
    +  where
    
    2895
    +    refl_co = mkRepReflCo body_ty
    
    2851 2896
     
    
    2852 2897
     {- *********************************************************************
    
    2853 2898
     *                                                                      *
    

  • compiler/GHC/Core/Opt/OccurAnal.hs
    ... ... @@ -42,7 +42,6 @@ import GHC.Core.Utils ( exprIsTrivial, isDefaultAlt, isExpandableApp,
    42 42
     import GHC.Core.Opt.Arity   ( joinRhsArity, isOneShotBndr )
    
    43 43
     import GHC.Core.Coercion
    
    44 44
     import GHC.Core.Type
    
    45
    -import GHC.Core.TyCo.FVs    ( tyCoVarsOfMCo )
    
    46 45
     
    
    47 46
     import GHC.Data.Maybe( orElse )
    
    48 47
     import GHC.Data.Graph.Directed ( SCC(..), Node(..)
    

  • compiler/GHC/Core/Opt/Simplify/Env.hs
    ... ... @@ -1240,6 +1240,8 @@ out_id so that its arity is visible in its RHS. Examples:
    1240 1240
         Example: `f = \x. f x`. See Note [Eta reduction in recursive RHSs] for how
    
    1241 1241
         we prevent that.
    
    1242 1242
     
    
    1243
    +c.f. (EtaA) in Note [Eta reduction soundness] in GHC.Core.Opt.Arity.
    
    1244
    +
    
    1243 1245
     Note [Robust OccInfo]
    
    1244 1246
     ~~~~~~~~~~~~~~~~~~~~~
    
    1245 1247
     It's important that we *do* retain the loop-breaker OccInfo, because
    

  • compiler/GHC/Core/Opt/Simplify/Iteration.hs
    ... ... @@ -3143,7 +3143,7 @@ There have been various earlier versions of this patch:
    3143 3143
         case_bndr_evald_next _               = False
    
    3144 3144
     
    
    3145 3145
       This patch was part of fixing #7542. See also
    
    3146
    -  Note [Eta reduction soundness], criterion (E) in GHC.Core.Utils.)
    
    3146
    +  Note [Eta reduction soundness], criterion (EtaE) in GHC.Core.Opt.Arity.)
    
    3147 3147
     
    
    3148 3148
     
    
    3149 3149
     Further notes about case elimination
    

  • compiler/GHC/Core/Opt/Simplify/Utils.hs
    ... ... @@ -2110,8 +2110,9 @@ tryEtaExpandRhs :: SimplEnv -> BindContext -> OutId -> OutExpr
    2110 2110
     tryEtaExpandRhs env bind_cxt bndr rhs
    
    2111 2111
       | seEtaExpand env         -- If Eta-expansion is on
    
    2112 2112
       , wantEtaExpansion rhs    -- and we'd like to eta-expand e
    
    2113
    -  , do_eta_expand           -- and e's manifest arity is lower than
    
    2114
    -                            --     what it could be
    
    2113
    +  , do_eta_expand           -- and arity analysis finds a greater arity
    
    2114
    +                            --     than (exprArity e); NB: not manifestArity
    
    2115
    +                            --     See Note [Do not eta-expand PAPs]
    
    2115 2116
                                 --     (never true for join points)
    
    2116 2117
       =                         -- Do eta-expansion.
    
    2117 2118
         assertPpr( not (isJoinBC bind_cxt) ) (ppr bndr) $
    
    ... ... @@ -2130,7 +2131,8 @@ tryEtaExpandRhs env bind_cxt bndr rhs
    2130 2131
         (do_eta_expand, arity_type) = findRhsArity arity_opts is_rec bndr rhs
    
    2131 2132
     
    
    2132 2133
     wantEtaExpansion :: CoreExpr -> Bool
    
    2133
    --- Mostly True; but False of PAPs which will immediately eta-reduce again
    
    2134
    +-- Mostly True; but False of trivial RHSs, and of PAPs at the top of the RHS
    
    2135
    +-- (PAPs under value lambdas are dealt with by findRhsArity)
    
    2134 2136
     -- See Note [Which RHSs do we eta-expand?]
    
    2135 2137
     wantEtaExpansion (Cast e _)             = wantEtaExpansion e
    
    2136 2138
     wantEtaExpansion (Tick _ e)             = wantEtaExpansion e
    
    ... ... @@ -2168,7 +2170,22 @@ seems like a Good idea.
    2168 2170
     
    
    2169 2171
     Note [Do not eta-expand PAPs]
    
    2170 2172
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    2171
    -We used to have old_arity = manifestArity rhs, which meant that we
    
    2173
    +We do not eta-expand a RHS that is a partial application (PAP).  This
    
    2174
    +is achieved in two places:
    
    2175
    +
    
    2176
    +(DEP1) A PAP at the top of the RHS, such as
    
    2177
    +          f = g d       -- g has arity 2
    
    2178
    +       is rejected by `wantEtaExpansion`.
    
    2179
    +
    
    2180
    +(DEP2) A PAP under value lambdas, such as
    
    2181
    +          f = \x. g x   -- g has arity 3
    
    2182
    +       is not eta-expanded because `findRhsArity` asks for eta-expansion
    
    2183
    +       only if the arity it finds is greater than (exprArity rhs), and
    
    2184
    +       `exprArity` takes account of PAPs: here (exprArity rhs) = 3.
    
    2185
    +       Using `manifestArity` (which is 1 here) instead would eta-expand
    
    2186
    +       to f = \x y z. g x y z.
    
    2187
    +
    
    2188
    +Up to 2014 we used old_arity = manifestArity rhs, which meant that we
    
    2172 2189
     would eta-expand even PAPs.  But this gives no particular advantage,
    
    2173 2190
     and can lead to a massive blow-up in code size, exhibited by #9020.
    
    2174 2191
     Suppose we have a PAP
    
    ... ... @@ -2184,6 +2201,17 @@ coercions and whatnot that eventually disappear again. For T9020, GHC
    2184 2201
     allocated 6.6G before, and 0.8G afterwards; and residency dropped from
    
    2185 2202
     1.8G to 45M.
    
    2186 2203
     
    
    2204
    +#27212 tried switching (DEP2) back to manifestArity, with these results:
    
    2205
    +
    
    2206
    +* T13960: bytestring's
    
    2207
    +      cstring1 = \(a::Addr#) @r. cstring2 @r a     -- cstring2 has arity 4
    
    2208
    +  was eta-expanded to (\a @r k br s. cstring2 @r a k br s).  That bigger
    
    2209
    +  unfolding is inlined at every string literal, adding 6 terms per
    
    2210
    +  literal; compile-time allocation went up by 9%.
    
    2211
    +
    
    2212
    +* T13056: a derived-instance method (\ @a d. lvl @a), where `lvl` is
    
    2213
    +  bottoming, was eta-expanded, and then needlessly worker/wrappered.
    
    2214
    +
    
    2187 2215
     Moreover, if we eta expand
    
    2188 2216
             f = g d  ==>  f = \x. g d x
    
    2189 2217
     that might in turn make g inline (if it has an inline pragma), which
    

  • compiler/GHC/Core/TyCo/Make.hs
    ... ... @@ -58,7 +58,7 @@ module GHC.Core.TyCo.Make (
    58 58
         , mkAxInstCo
    
    59 59
         , mkTransCo, mkTransMCo, mkTransMCoL, mkTransMCoR
    
    60 60
         , mkProofIrrelCo
    
    61
    -    , coToMCo, kindCoToMKindCo
    
    61
    +    , coToMCo, kindCoToMKindCo, mCoToCo
    
    62 62
         , mkCoherenceLeftCo, mkCoherenceRightCo, mkCoherenceRightMCo
    
    63 63
         , toPhantomCo, mkPhantomCo
    
    64 64
         , isReflCo, isReflMCo, isReflKindCo, isReflKindMCo, isReflCo_maybe
    
    ... ... @@ -860,7 +860,7 @@ mkHomoForAllCos vs orig_co
    860 860
       = foldr go orig_co vs
    
    861 861
       where
    
    862 862
         go :: ForAllTyBinder -> Coercion -> Coercion
    
    863
    -    go (Bndr var vis) co = mk_forall_co var vis vis MRefl co
    
    863
    +    go (Bndr var vis) co = mkForAllCoNonRefl var vis vis MRefl co
    
    864 864
     
    
    865 865
     mkHomoForAllCo :: TyVar -> Coercion -> Coercion
    
    866 866
     -- Specialised for a single TyVar,
    
    ... ... @@ -869,7 +869,7 @@ mkHomoForAllCo tv orig_co
    869 869
       | Just (ty, r) <- isReflCo_maybe orig_co
    
    870 870
       = mkReflCo r (mkForAllTy (Bndr tv vis) ty)
    
    871 871
       | otherwise
    
    872
    -  = mk_forall_co tv vis vis MRefl orig_co
    
    872
    +  = mkForAllCoNonRefl tv vis vis MRefl orig_co
    
    873 873
       where
    
    874 874
         vis  = coreTyLamForAllTyFlag
    
    875 875
     
    
    ... ... @@ -892,15 +892,15 @@ mkForAllCo v visL visR kind_co co
    892 892
       | Just refl_co <- isReflForAllCo v visL visR kind_co co
    
    893 893
       = refl_co
    
    894 894
       | otherwise
    
    895
    -  = mk_forall_co v visL visR kind_co co
    
    895
    +  = mkForAllCoNonRefl v visL visR kind_co co
    
    896 896
     
    
    897
    --- | `mk_forall_co` just builds a ForAllCo.
    
    897
    +-- | `mkForAllCoNonRefl` just builds a ForAllCo.
    
    898 898
     -- With debug on, it checks invariants (e.g. he kind of the tycovar should
    
    899 899
     --   be the left-hand kind of the kind coercion).
    
    900 900
     -- Callers should have done any isReflCo short-cutting.
    
    901
    -mk_forall_co :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag
    
    902
    -             -> KindMCoercion -> Coercion -> Coercion
    
    903
    -mk_forall_co tcv visL visR kind_co co
    
    901
    +mkForAllCoNonRefl :: TyCoVar -> ForAllTyFlag -> ForAllTyFlag
    
    902
    +                  -> KindMCoercion -> Coercion -> Coercion
    
    903
    +mkForAllCoNonRefl tcv visL visR kind_co co
    
    904 904
       = assertGoodForAllCo tcv visL visR kind_co co $
    
    905 905
         assertPpr (not (isReflCo co && isReflMCo kind_co && visL `eqForAllVis` visR)) (ppr co) $
    
    906 906
         ForAllCo { fco_tcv = tcv, fco_visL = visL, fco_visR = visR
    
    ... ... @@ -1289,6 +1289,10 @@ coToMCo :: Coercion -> MCoercion
    1289 1289
     coToMCo co | isReflCo co = MRefl
    
    1290 1290
                | otherwise   = MCo co
    
    1291 1291
     
    
    1292
    +mCoToCo :: Role -> Type -> MCoercion -> Coercion
    
    1293
    +mCoToCo role ty MRefl    = mkReflCo role ty
    
    1294
    +mCoToCo _    _  (MCo co) = co
    
    1295
    +
    
    1292 1296
     kindCoToMKindCo :: KindCoercion -> KindMCoercion
    
    1293 1297
     -- Convert a KindCoercion to a KindMCoercion,
    
    1294 1298
     -- coToMCo doesn't eliminate GRefl, but kindCoToMCo can
    

  • compiler/GHC/Core/Type.hs
    ... ... @@ -160,7 +160,7 @@ module GHC.Core.Type (
    160 160
     
    
    161 161
             -- * Type free variables
    
    162 162
             tyCoVarsOfType, tyCoVarsOfTypes, tyCoVarsOfTypeDSet,
    
    163
    -        coVarsOfType, coVarsOfTypes,
    
    163
    +        tyCoVarsOfMCo, coVarsOfType, coVarsOfTypes,
    
    164 164
     
    
    165 165
             anyFreeVarsOfType, anyFreeVarsOfTypes,
    
    166 166
             noFreeVarsOfType,
    

  • compiler/GHC/Core/Utils.hs
    ... ... @@ -2392,7 +2392,7 @@ canCollectArgsThroughTick id t
    2392 2392
       = tickishFloatable t || cantEtaReduceFun id
    
    2393 2393
     
    
    2394 2394
     -- | Can we eta-reduce the given function?
    
    2395
    --- See Note [Eta reduction soundness], criteria (B), (J), and (W).
    
    2395
    +-- See Note [Eta reduction soundness], criteria (EtaB), (EtaJ), and (EtaW).
    
    2396 2396
     cantEtaReduceFun :: Id -> Bool
    
    2397 2397
     cantEtaReduceFun fun
    
    2398 2398
       =    hasNoBinding fun -- (B)
    

  • testsuite/tests/dmdanal/sigs/T21888a.stderr
    ... ... @@ -7,7 +7,7 @@ T21888a.wombat: <S!P(S)>b
    7 7
     
    
    8 8
     
    
    9 9
     ==================== Cpr signatures ====================
    
    10
    -T21888a.f: 2
    
    10
    +T21888a.f:
    
    11 11
     T21888a.g: 1
    
    12 12
     T21888a.wombat: b
    
    13 13
     
    

  • testsuite/tests/printer/T18052a.stderr
    ... ... @@ -10,11 +10,11 @@ Dependent packages: [(normal, base-4.23.0.0)]
    10 10
     
    
    11 11
     ==================== Tidy Core ====================
    
    12 12
     Result size of Tidy Core
    
    13
    -  = {terms: 24, types: 52, coercions: 0, joins: 0/0}
    
    13
    +  = {terms: 18, types: 46, coercions: 0, joins: 0/0}
    
    14 14
     
    
    15
    --- RHS size: {terms: 7, types: 6, coercions: 0, joins: 0/0}
    
    15
    +-- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
    
    16 16
     T18052a.$b:||: :: forall {a} {b}. a -> b -> (a, b)
    
    17
    -T18052a.$b:||: = \ (@a) (@b) (x :: a) (y :: b) -> (x, y)
    
    17
    +T18052a.$b:||: = GHC.Internal.Tuple.(,)
    
    18 18
     
    
    19 19
     -- RHS size: {terms: 1, types: 0, coercions: 0, joins: 0/0}
    
    20 20
     (+++) :: forall {a}. [a] -> [a] -> [a]
    

  • testsuite/tests/simplCore/should_compile/T27212.hs
    1
    +{-# OPTIONS_GHC -Wno-inaccessible-code  -Wno-overlapping-patterns #-}
    
    2
    +module T27212 where
    
    3
    +
    
    4
    +import Unsafe.Coerce
    
    5
    +
    
    6
    +class Given a where given :: a
    
    7
    +newtype Gift a r = Gift (Given a => r)
    
    8
    +
    
    9
    +useIt :: Given Int => Int
    
    10
    +useIt = given + 1
    
    11
    +{-# NOINLINE useIt #-}
    
    12
    +
    
    13
    +foo :: [Int] -> [Int]
    
    14
    +foo xs = case unsafeEqualityProof @(Gift Int Int) @(Int -> Int) of
    
    15
    +  UnsafeRefl -> map (\y -> (Gift useIt :: Gift Int Int) y) xs
    
    16
    +    -- That (\y. glah y) can eta-reduce to `glah`
    
    17
    +    -- but doing so makes a FunCo coercion that crosses from
    
    18
    +    -- Type to constraint. Tricky.

  • testsuite/tests/simplCore/should_compile/all.T
    ... ... @@ -631,3 +631,4 @@ 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
    +test('T27212', normal, compile, ['-O'])