Re-implement the binder-swap stuff in OccurAnal
[ghc-hetmet.git] / compiler / simplCore / OccurAnal.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 %************************************************************************
5 %*                                                                      *
6 \section[OccurAnal]{Occurrence analysis pass}
7 %*                                                                      *
8 %************************************************************************
9
10 The occurrence analyser re-typechecks a core expression, returning a new
11 core expression with (hopefully) improved usage information.
12
13 \begin{code}
14 module OccurAnal (
15         occurAnalysePgm, occurAnalyseExpr
16     ) where
17
18 #include "HsVersions.h"
19
20 import CoreSyn
21 import CoreFVs
22 import Type             ( tyVarsOfType )
23 import CoreUtils        ( exprIsTrivial, isDefaultAlt, mkCoerceI )
24 import Coercion         ( CoercionI(..), mkSymCoI )
25 import Id
26 import Name             ( localiseName )
27 import BasicTypes
28
29 import VarSet
30 import VarEnv
31
32 import Maybes           ( orElse )
33 import Digraph          ( SCC(..), stronglyConnCompFromEdgedVerticesR )
34 import PrelNames        ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
35 import Unique           ( Unique )
36 import UniqFM           ( keysUFM, intersectUFM_C, foldUFM_Directly )
37 import Util             ( mapAndUnzip, filterOut )
38 import Bag
39 import Outputable
40
41 import Data.List
42 \end{code}
43
44
45 %************************************************************************
46 %*                                                                      *
47 \subsection[OccurAnal-main]{Counting occurrences: main function}
48 %*                                                                      *
49 %************************************************************************
50
51 Here's the externally-callable interface:
52
53 \begin{code}
54 occurAnalysePgm :: [CoreBind] -> [CoreRule] -> [CoreBind]
55 occurAnalysePgm binds rules
56   = snd (go initOccEnv binds)
57   where
58     initial_details = addIdOccs emptyDetails (rulesFreeVars rules)
59     -- The RULES keep things alive!
60
61     go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
62     go _ []
63         = (initial_details, [])
64     go env (bind:binds)
65         = (final_usage, bind' ++ binds')
66         where
67            (bs_usage, binds')   = go env binds
68            (final_usage, bind') = occAnalBind env env bind bs_usage
69
70 occurAnalyseExpr :: CoreExpr -> CoreExpr
71         -- Do occurrence analysis, and discard occurence info returned
72 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection[OccurAnal-main]{Counting occurrences: main function}
79 %*                                                                      *
80 %************************************************************************
81
82 Bindings
83 ~~~~~~~~
84
85 \begin{code}
86 occAnalBind :: OccEnv           -- The incoming OccEnv
87             -> OccEnv           -- Same, but trimmed by (binderOf bind)
88             -> CoreBind
89             -> UsageDetails             -- Usage details of scope
90             -> (UsageDetails,           -- Of the whole let(rec)
91                 [CoreBind])
92
93 occAnalBind env _ (NonRec binder rhs) body_usage
94   | isTyVar binder                      -- A type let; we don't gather usage info
95   = (body_usage, [NonRec binder rhs])
96
97   | not (binder `usedIn` body_usage)    -- It's not mentioned
98   = (body_usage, [])
99
100   | otherwise                   -- It's mentioned in the body
101   = (body_usage' +++ addRuleUsage rhs_usage binder,     -- Note [Rules are extra RHSs]
102      [NonRec tagged_binder rhs'])
103   where
104     (body_usage', tagged_binder) = tagBinder body_usage binder
105     (rhs_usage, rhs')            = occAnalRhs env tagged_binder rhs
106 \end{code}
107
108 Note [Dead code]
109 ~~~~~~~~~~~~~~~~
110 Dropping dead code for recursive bindings is done in a very simple way:
111
112         the entire set of bindings is dropped if none of its binders are
113         mentioned in its body; otherwise none are.
114
115 This seems to miss an obvious improvement.
116
117         letrec  f = ...g...
118                 g = ...f...
119         in
120         ...g...
121 ===>
122         letrec f = ...g...
123                g = ...(...g...)...
124         in
125         ...g...
126
127 Now 'f' is unused! But it's OK!  Dependency analysis will sort this
128 out into a letrec for 'g' and a 'let' for 'f', and then 'f' will get
129 dropped.  It isn't easy to do a perfect job in one blow.  Consider
130
131         letrec f = ...g...
132                g = ...h...
133                h = ...k...
134                k = ...m...
135                m = ...m...
136         in
137         ...m...
138
139
140 Note [Loop breaking and RULES]
141 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
142 Loop breaking is surprisingly subtle.  First read the section 4 of
143 "Secrets of the GHC inliner".  This describes our basic plan.
144
145 However things are made quite a bit more complicated by RULES.  Remember
146
147   * Note [Rules are extra RHSs]
148     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
149     A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
150     keeps the specialised "children" alive.  If the parent dies
151     (because it isn't referenced any more), then the children will die
152     too (unless they are already referenced directly).
153
154     To that end, we build a Rec group for each cyclic strongly
155     connected component,
156         *treating f's rules as extra RHSs for 'f'*.
157
158     When we make the Rec groups we include variables free in *either*
159     LHS *or* RHS of the rule.  The former might seems silly, but see
160     Note [Rule dependency info].
161
162     So in Example [eftInt], eftInt and eftIntFB will be put in the
163     same Rec, even though their 'main' RHSs are both non-recursive.
164
165   * Note [Rules are visible in their own rec group]
166     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
167     We want the rules for 'f' to be visible in f's right-hand side.
168     And we'd like them to be visible in other functions in f's Rec
169     group.  E.g. in Example [Specialisation rules] we want f' rule
170     to be visible in both f's RHS, and fs's RHS.
171
172     This means that we must simplify the RULEs first, before looking
173     at any of the definitions.  This is done by Simplify.simplRecBind,
174     when it calls addLetIdInfo.
175
176   * Note [Choosing loop breakers]
177     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178     We avoid infinite inlinings by choosing loop breakers, and
179     ensuring that a loop breaker cuts each loop.  But what is a
180     "loop"?  In particular, a RULE is like an equation for 'f' that
181     is *always* inlined if it is applicable.  We do *not* disable
182     rules for loop-breakers.  It's up to whoever makes the rules to
183     make sure that the rules themselves always terminate.  See Note
184     [Rules for recursive functions] in Simplify.lhs
185
186     Hence, if
187         f's RHS mentions g, and
188         g has a RULE that mentions h, and
189         h has a RULE that mentions f
190
191     then we *must* choose f to be a loop breaker.  In general, take the
192     free variables of f's RHS, and augment it with all the variables
193     reachable by RULES from those starting points.  That is the whole
194     reason for computing rule_fv_env in occAnalBind.  (Of course we
195     only consider free vars that are also binders in this Rec group.)
196
197     Note that when we compute this rule_fv_env, we only consider variables
198     free in the *RHS* of the rule, in contrast to the way we build the
199     Rec group in the first place (Note [Rule dependency info])
200
201     Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
202     chosen as a loop breaker, because their RHSs don't mention each other.
203     And indeed both can be inlined safely.
204
205     Note that the edges of the graph we use for computing loop breakers
206     are not the same as the edges we use for computing the Rec blocks.
207     That's why we compute
208         rec_edges          for the Rec block analysis
209         loop_breaker_edges for the loop breaker analysis
210
211
212   * Note [Weak loop breakers]
213     ~~~~~~~~~~~~~~~~~~~~~~~~~
214     There is a last nasty wrinkle.  Suppose we have
215
216         Rec { f = f_rhs
217               RULE f [] = g
218
219               h = h_rhs
220               g = h
221               ...more...
222         }
223
224     Remmber that we simplify the RULES before any RHS (see Note
225     [Rules are visible in their own rec group] above).
226
227     So we must *not* postInlineUnconditionally 'g', even though
228     its RHS turns out to be trivial.  (I'm assuming that 'g' is
229     not choosen as a loop breaker.)  Why not?  Because then we
230     drop the binding for 'g', which leaves it out of scope in the
231     RULE!
232
233     We "solve" this by making g a "weak" or "rules-only" loop breaker,
234     with OccInfo = IAmLoopBreaker True.  A normal "strong" loop breaker
235     has IAmLoopBreaker False.  So
236
237                                 Inline  postInlineUnconditionally
238         IAmLoopBreaker False    no      no
239         IAmLoopBreaker True     yes     no
240         other                   yes     yes
241
242     The **sole** reason for this kind of loop breaker is so that
243     postInlineUnconditionally does not fire.  Ugh.
244
245   * Note [Rule dependency info]
246     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
247     The VarSet in a SpecInfo is used for dependency analysis in the
248     occurrence analyser.  We must track free vars in *both* lhs and rhs.  
249     Hence use of idRuleVars, rather than idRuleRhsVars in addRuleUsage.  
250     Why both? Consider
251         x = y
252         RULE f x = 4
253     Then if we substitute y for x, we'd better do so in the
254     rule's LHS too, so we'd better ensure the dependency is respected
255
256
257   * Note [Inline rules]
258     ~~~~~~~~~~~~~~~~~~~
259     None of the above stuff about RULES applies to Inline Rules,
260     stored in a CoreUnfolding.  The unfolding, if any, is simplified
261     at the same time as the regular RHS of the function, so it should
262     be treated *exactly* like an extra RHS.
263
264
265 Example [eftInt]
266 ~~~~~~~~~~~~~~~
267 Example (from GHC.Enum):
268
269   eftInt :: Int# -> Int# -> [Int]
270   eftInt x y = ...(non-recursive)...
271
272   {-# INLINE [0] eftIntFB #-}
273   eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
274   eftIntFB c n x y = ...(non-recursive)...
275
276   {-# RULES
277   "eftInt"  [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
278   "eftIntList"  [1] eftIntFB  (:) [] = eftInt
279    #-}
280
281 Example [Specialisation rules]
282 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
283 Consider this group, which is typical of what SpecConstr builds:
284
285    fs a = ....f (C a)....
286    f  x = ....f (C a)....
287    {-# RULE f (C a) = fs a #-}
288
289 So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
290
291 But watch out!  If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
292         - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
293         - fs is inlined (say it's small)
294         - now there's another opportunity to apply the RULE
295
296 This showed up when compiling Control.Concurrent.Chan.getChanContents.
297
298
299 \begin{code}
300 occAnalBind _ env (Rec pairs) body_usage
301   = foldr occAnalRec (body_usage, []) sccs
302         -- For a recursive group, we 
303         --      * occ-analyse all the RHSs
304         --      * compute strongly-connected components
305         --      * feed those components to occAnalRec
306   where
307     -------------Dependency analysis ------------------------------
308     bndr_set = mkVarSet (map fst pairs)
309
310     sccs :: [SCC (Node Details)]
311     sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompFromEdgedVerticesR rec_edges
312
313     rec_edges :: [Node Details]
314     rec_edges = {-# SCC "occAnalBind.assoc" #-}  map make_node pairs
315     
316     make_node (bndr, rhs)
317         = (ND bndr rhs' all_rhs_usage rhs_fvs, idUnique bndr, out_edges)
318         where
319           (rhs_usage, rhs') = occAnalRhs env bndr rhs
320           all_rhs_usage = addRuleUsage rhs_usage bndr    -- Note [Rules are extra RHSs]
321           rhs_fvs = intersectUFM_C (\b _ -> b) bndr_set rhs_usage
322           out_edges = keysUFM (rhs_fvs `unionVarSet` idRuleVars bndr)
323         -- (a -> b) means a mentions b
324         -- Given the usage details (a UFM that gives occ info for each free var of
325         -- the RHS) we can get the list of free vars -- or rather their Int keys --
326         -- by just extracting the keys from the finite map.  Grimy, but fast.
327         -- Previously we had this:
328         --      [ bndr | bndr <- bndrs,
329         --               maybeToBool (lookupVarEnv rhs_usage bndr)]
330         -- which has n**2 cost, and this meant that edges_from alone
331         -- consumed 10% of total runtime!
332
333 -----------------------------
334 occAnalRec :: SCC (Node Details) -> (UsageDetails, [CoreBind])
335                                  -> (UsageDetails, [CoreBind])
336
337         -- The NonRec case is just like a Let (NonRec ...) above
338 occAnalRec (AcyclicSCC (ND bndr rhs rhs_usage _, _, _)) (body_usage, binds)
339   | not (bndr `usedIn` body_usage) 
340   = (body_usage, binds)
341
342   | otherwise                   -- It's mentioned in the body
343   = (body_usage' +++ rhs_usage, 
344      NonRec tagged_bndr rhs : binds)
345   where
346     (body_usage', tagged_bndr) = tagBinder body_usage bndr
347
348
349         -- The Rec case is the interesting one
350         -- See Note [Loop breaking]
351 occAnalRec (CyclicSCC nodes) (body_usage, binds)
352   | not (any (`usedIn` body_usage) bndrs)       -- NB: look at body_usage, not total_usage
353   = (body_usage, binds)                         -- Dead code
354
355   | otherwise   -- At this point we always build a single Rec
356   = (final_usage, Rec pairs : binds)
357
358   where
359     bndrs    = [b | (ND b _ _ _, _, _) <- nodes]
360     bndr_set = mkVarSet bndrs
361
362         ----------------------------
363         -- Tag the binders with their occurrence info
364     total_usage = foldl add_usage body_usage nodes
365     add_usage usage_so_far (ND _ _ rhs_usage _, _, _) = usage_so_far +++ rhs_usage
366     (final_usage, tagged_nodes) = mapAccumL tag_node total_usage nodes
367
368     tag_node :: UsageDetails -> Node Details -> (UsageDetails, Node Details)
369         -- (a) Tag the binders in the details with occ info
370         -- (b) Mark the binder with "weak loop-breaker" OccInfo 
371         --      saying "no preInlineUnconditionally" if it is used
372         --      in any rule (lhs or rhs) of the recursive group
373         --      See Note [Weak loop breakers]
374     tag_node usage (ND bndr rhs rhs_usage rhs_fvs, k, ks)
375       = (usage `delVarEnv` bndr, (ND bndr2 rhs rhs_usage rhs_fvs, k, ks))
376       where
377         bndr2 | bndr `elemVarSet` all_rule_fvs = makeLoopBreaker True bndr1
378               | otherwise                      = bndr1
379         bndr1 = setBinderOcc usage bndr
380     all_rule_fvs = bndr_set `intersectVarSet` foldr (unionVarSet . idRuleVars) 
381                                                     emptyVarSet bndrs
382
383         ----------------------------
384         -- Now reconstruct the cycle
385     pairs | no_rules  = reOrderCycle 0 tagged_nodes []
386           | otherwise = foldr (reOrderRec 0) [] $
387                         stronglyConnCompFromEdgedVerticesR loop_breaker_edges
388
389         -- See Note [Choosing loop breakers] for loop_breaker_edges
390     loop_breaker_edges = map mk_node tagged_nodes
391     mk_node (details@(ND _ _ _ rhs_fvs), k, _) = (details, k, new_ks)
392         where
393           new_ks = keysUFM (extendFvs rule_fv_env rhs_fvs rhs_fvs)
394
395     ------------------------------------
396     rule_fv_env :: IdEnv IdSet  -- Variables from this group mentioned in RHS of rules
397                                 -- Domain is *subset* of bound vars (others have no rule fvs)
398     rule_fv_env = rule_loop init_rule_fvs
399
400     no_rules      = null init_rule_fvs
401     init_rule_fvs = [(b, rule_fvs)
402                     | b <- bndrs
403                     , let rule_fvs = idRuleRhsVars b `intersectVarSet` bndr_set
404                     , not (isEmptyVarSet rule_fvs)]
405
406     rule_loop :: [(Id,IdSet)] -> IdEnv IdSet    -- Finds fixpoint
407     rule_loop fv_list
408         | no_change = env
409         | otherwise = rule_loop new_fv_list
410         where
411           env = mkVarEnv init_rule_fvs
412           (no_change, new_fv_list) = mapAccumL bump True fv_list
413           bump no_change (b,fvs)
414                 | new_fvs `subVarSet` fvs = (no_change, (b,fvs))
415                 | otherwise               = (False,     (b,new_fvs `unionVarSet` fvs))
416                 where
417                   new_fvs = extendFvs env emptyVarSet fvs
418
419 extendFvs :: IdEnv IdSet -> IdSet -> IdSet -> IdSet
420 -- (extendFVs env fvs s) returns (fvs `union` env(s))
421 extendFvs env fvs id_set
422   = foldUFM_Directly add fvs id_set
423   where
424     add uniq _ fvs
425         = case lookupVarEnv_Directly env uniq  of
426             Just fvs' -> fvs' `unionVarSet` fvs
427             Nothing   -> fvs
428 \end{code}
429
430 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
431 strongly connected component (there's guaranteed to be a cycle).  It returns the
432 same pairs, but
433         a) in a better order,
434         b) with some of the Ids having a IAmALoopBreaker pragma
435
436 The "loop-breaker" Ids are sufficient to break all cycles in the SCC.  This means
437 that the simplifier can guarantee not to loop provided it never records an inlining
438 for these no-inline guys.
439
440 Furthermore, the order of the binds is such that if we neglect dependencies
441 on the no-inline Ids then the binds are topologically sorted.  This means
442 that the simplifier will generally do a good job if it works from top bottom,
443 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
444
445 ==============
446 [June 98: I don't understand the following paragraphs, and I've
447           changed the a=b case again so that it isn't a special case any more.]
448
449 Here's a case that bit me:
450
451         letrec
452                 a = b
453                 b = \x. BIG
454         in
455         ...a...a...a....
456
457 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
458
459 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
460 Perhaps something cleverer would suffice.
461 ===============
462
463
464 \begin{code}
465 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
466                                                 -- which is gotten from the Id.
467 data Details = ND Id            -- Binder
468                   CoreExpr      -- RHS
469
470                   UsageDetails  -- Full usage from RHS, 
471                                 -- including *both* RULES *and* InlineRule unfolding
472
473                   IdSet         -- Other binders *from this Rec group* mentioned in
474                                 --   * the  RHS
475                                 --   * any InlineRule unfolding
476                                 -- but *excluding* any RULES
477
478 reOrderRec :: Int -> SCC (Node Details)
479            -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
480 -- Sorted into a plausible order.  Enough of the Ids have
481 --      IAmALoopBreaker pragmas that there are no loops left.
482 reOrderRec _ (AcyclicSCC (ND bndr rhs _ _, _, _)) pairs = (bndr, rhs) : pairs
483 reOrderRec depth (CyclicSCC cycle)                pairs = reOrderCycle depth cycle pairs
484
485 reOrderCycle :: Int -> [Node Details] -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
486 reOrderCycle _ [] _
487   = panic "reOrderCycle"
488 reOrderCycle _ [bind] pairs    -- Common case of simple self-recursion
489   = (makeLoopBreaker False bndr, rhs) : pairs
490   where
491     (ND bndr rhs _ _, _, _) = bind
492
493 reOrderCycle depth (bind : binds) pairs
494   =     -- Choose a loop breaker, mark it no-inline,
495         -- do SCC analysis on the rest, and recursively sort them out
496 --    pprTrace "reOrderCycle" (ppr [b | (ND b _ _ _, _, _) <- bind:binds]) $
497     foldr (reOrderRec new_depth)
498           ([ (makeLoopBreaker False bndr, rhs) 
499            | (ND bndr rhs _ _, _, _) <- chosen_binds] ++ pairs)
500           (stronglyConnCompFromEdgedVerticesR unchosen) 
501   where
502     (chosen_binds, unchosen) = choose_loop_breaker [bind] (score bind) [] binds
503
504     approximate_loop_breaker = depth >= 2
505     new_depth | approximate_loop_breaker = 0
506               | otherwise                = depth+1
507         -- After two iterations (d=0, d=1) give up
508         -- and approximate, returning to d=0
509
510         -- This loop looks for the bind with the lowest score
511         -- to pick as the loop  breaker.  The rest accumulate in
512     choose_loop_breaker loop_binds _loop_sc acc []
513         = (loop_binds, acc)        -- Done
514
515         -- If approximate_loop_breaker is True, we pick *all*
516         -- nodes with lowest score, else just one
517         -- See Note [Complexity of loop breaking]
518     choose_loop_breaker loop_binds loop_sc acc (bind : binds)
519         | sc < loop_sc  -- Lower score so pick this new one
520         = choose_loop_breaker [bind] sc (loop_binds ++ acc) binds
521
522         | approximate_loop_breaker && sc == loop_sc
523         = choose_loop_breaker (bind : loop_binds) loop_sc acc binds
524         
525         | otherwise     -- Higher score so don't pick it
526         = choose_loop_breaker loop_binds loop_sc (bind : acc) binds
527         where
528           sc = score bind
529
530     score :: Node Details -> Int        -- Higher score => less likely to be picked as loop breaker
531     score (ND bndr rhs _ _, _, _)
532         | isDFunId bndr = 9   -- Never choose a DFun as a loop breaker
533                               -- Note [DFuns should not be loop breakers]
534
535         | Just (inl_rule_info, _) <- isInlineRule_maybe (idUnfolding bndr)
536         = case inl_rule_info of
537              InlWrapper {} -> 10  -- Note [INLINE pragmas]
538              _other        ->  3  -- Data structures are more important than this
539                                   -- so that dictionary/method recursion unravels
540                 -- Note that this case hits all InlineRule things, so we
541                 -- never look at 'rhs for InlineRule stuff. That's right, because
542                 -- 'rhs' is irrelevant for inlining things with an InlineRule
543                 
544         | is_con_app rhs = 5  -- Data types help with cases: Note [Constructor applications]
545                 
546         | exprIsTrivial rhs = 10  -- Practically certain to be inlined
547                 -- Used to have also: && not (isExportedId bndr)
548                 -- But I found this sometimes cost an extra iteration when we have
549                 --      rec { d = (a,b); a = ...df...; b = ...df...; df = d }
550                 -- where df is the exported dictionary. Then df makes a really
551                 -- bad choice for loop breaker
552
553         
554 -- If an Id is marked "never inline" then it makes a great loop breaker
555 -- The only reason for not checking that here is that it is rare
556 -- and I've never seen a situation where it makes a difference,
557 -- so it probably isn't worth the time to test on every binder
558 --      | isNeverActive (idInlinePragma bndr) = -10
559
560         | isOneOcc (idOccInfo bndr) = 2  -- Likely to be inlined
561
562         | canUnfold (idUnfolding bndr) = 1
563                 -- the Id has some kind of unfolding
564
565         | otherwise = 0
566
567         -- Checking for a constructor application
568         -- Cheap and cheerful; the simplifer moves casts out of the way
569         -- The lambda case is important to spot x = /\a. C (f a)
570         -- which comes up when C is a dictionary constructor and
571         -- f is a default method.
572         -- Example: the instance for Show (ST s a) in GHC.ST
573         --
574         -- However we *also* treat (\x. C p q) as a con-app-like thing,
575         --      Note [Closure conversion]
576     is_con_app (Var v)    = isConLikeId v
577     is_con_app (App f _)  = is_con_app f
578     is_con_app (Lam _ e)  = is_con_app e
579     is_con_app (Note _ e) = is_con_app e
580     is_con_app _          = False
581
582 makeLoopBreaker :: Bool -> Id -> Id
583 -- Set the loop-breaker flag: see Note [Weak loop breakers]
584 makeLoopBreaker weak bndr = setIdOccInfo bndr (IAmALoopBreaker weak)
585 \end{code}
586
587 Note [Complexity of loop breaking]
588 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
589 The loop-breaking algorithm knocks out one binder at a time, and 
590 performs a new SCC analysis on the remaining binders.  That can
591 behave very badly in tightly-coupled groups of bindings; in the
592 worst case it can be (N**2)*log N, because it does a full SCC
593 on N, then N-1, then N-2 and so on.
594
595 To avoid this, we switch plans after 2 (or whatever) attempts:
596   Plan A: pick one binder with the lowest score, make it
597           a loop breaker, and try again
598   Plan B: pick *all* binders with the lowest score, make them
599           all loop breakers, and try again 
600 Since there are only a small finite number of scores, this will
601 terminate in a constant number of iterations, rather than O(N)
602 iterations.
603
604 You might thing that it's very unlikely, but RULES make it much
605 more likely.  Here's a real example from Trac #1969:
606   Rec { $dm = \d.\x. op d
607         {-# RULES forall d. $dm Int d  = $s$dm1
608                   forall d. $dm Bool d = $s$dm2 #-}
609         
610         dInt = MkD .... opInt ...
611         dInt = MkD .... opBool ...
612         opInt  = $dm dInt
613         opBool = $dm dBool
614
615         $s$dm1 = \x. op dInt
616         $s$dm2 = \x. op dBool }
617 The RULES stuff means that we can't choose $dm as a loop breaker
618 (Note [Choosing loop breakers]), so we must choose at least (say)
619 opInt *and* opBool, and so on.  The number of loop breakders is
620 linear in the number of instance declarations.
621
622 Note [INLINE pragmas]
623 ~~~~~~~~~~~~~~~~~~~~~
624 Avoid choosing a function with an INLINE pramga as the loop breaker!  
625 If such a function is mutually-recursive with a non-INLINE thing,
626 then the latter should be the loop-breaker.
627
628 Usually this is just a question of optimisation. But a particularly
629 bad case is wrappers generated by the demand analyser: if you make
630 then into a loop breaker you may get an infinite inlining loop.  For
631 example:
632   rec {
633         $wfoo x = ....foo x....
634
635         {-loop brk-} foo x = ...$wfoo x...
636   }
637 The interface file sees the unfolding for $wfoo, and sees that foo is
638 strict (and hence it gets an auto-generated wrapper).  Result: an
639 infinite inlining in the importing scope.  So be a bit careful if you
640 change this.  A good example is Tree.repTree in
641 nofib/spectral/minimax. If the repTree wrapper is chosen as the loop
642 breaker then compiling Game.hs goes into an infinite loop.  This
643 happened when we gave is_con_app a lower score than inline candidates:
644
645   Tree.repTree
646     = __inline_me (/\a. \w w1 w2 -> 
647                    case Tree.$wrepTree @ a w w1 w2 of
648                     { (# ww1, ww2 #) -> Branch @ a ww1 ww2 })
649   Tree.$wrepTree
650     = /\a w w1 w2 -> 
651       (# w2_smP, map a (Tree a) (Tree.repTree a w1 w) (w w2) #)
652
653 Here we do *not* want to choose 'repTree' as the loop breaker.
654
655 Note [DFuns should not be loop breakers]
656 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
657 It's particularly bad to make a DFun into a loop breaker.  See
658 Note [How instance declarations are translated] in TcInstDcls
659
660 We give DFuns a higher score than ordinary CONLIKE things because 
661 if there's a choice we want the DFun to be the non-looop breker. Eg
662  
663 rec { sc = /\ a \$dC. $fBWrap (T a) ($fCT @ a $dC)
664
665       $fCT :: forall a_afE. (Roman.C a_afE) => Roman.C (Roman.T a_afE)
666       {-# DFUN #-}
667       $fCT = /\a \$dC. MkD (T a) ((sc @ a $dC) |> blah) ($ctoF @ a $dC)
668     }
669
670 Here 'sc' (the superclass) looks CONLIKE, but we'll never get to it
671 if we can't unravel the DFun first.
672
673 Note [Constructor applications]
674 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
675 It's really really important to inline dictionaries.  Real
676 example (the Enum Ordering instance from GHC.Base):
677
678      rec     f = \ x -> case d of (p,q,r) -> p x
679              g = \ x -> case d of (p,q,r) -> q x
680              d = (v, f, g)
681
682 Here, f and g occur just once; but we can't inline them into d.
683 On the other hand we *could* simplify those case expressions if
684 we didn't stupidly choose d as the loop breaker.
685 But we won't because constructor args are marked "Many".
686 Inlining dictionaries is really essential to unravelling
687 the loops in static numeric dictionaries, see GHC.Float.
688
689 Note [Closure conversion]
690 ~~~~~~~~~~~~~~~~~~~~~~~~~
691 We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
692 The immediate motivation came from the result of a closure-conversion transformation
693 which generated code like this:
694
695     data Clo a b = forall c. Clo (c -> a -> b) c
696
697     ($:) :: Clo a b -> a -> b
698     Clo f env $: x = f env x
699
700     rec { plus = Clo plus1 ()
701
702         ; plus1 _ n = Clo plus2 n
703
704         ; plus2 Zero     n = n
705         ; plus2 (Succ m) n = Succ (plus $: m $: n) }
706
707 If we inline 'plus' and 'plus1', everything unravels nicely.  But if
708 we choose 'plus1' as the loop breaker (which is entirely possible
709 otherwise), the loop does not unravel nicely.
710
711
712 @occAnalRhs@ deals with the question of bindings where the Id is marked
713 by an INLINE pragma.  For these we record that anything which occurs
714 in its RHS occurs many times.  This pessimistically assumes that ths
715 inlined binder also occurs many times in its scope, but if it doesn't
716 we'll catch it next time round.  At worst this costs an extra simplifier pass.
717 ToDo: try using the occurrence info for the inline'd binder.
718
719 [March 97] We do the same for atomic RHSs.  Reason: see notes with reOrderRec.
720 [June 98, SLPJ]  I've undone this change; I don't understand it.  See notes with reOrderRec.
721
722
723 \begin{code}
724 occAnalRhs :: OccEnv
725            -> Id -> CoreExpr    -- Binder and rhs
726                                 -- For non-recs the binder is alrady tagged
727                                 -- with occurrence info
728            -> (UsageDetails, CoreExpr)
729               -- Returned usage details includes any INLINE rhs
730
731 occAnalRhs env id rhs
732   = (addIdOccs rhs_usage (idUnfoldingVars id), rhs')
733         -- Include occurrences for the "extra RHS" from a CoreUnfolding
734   where
735     (rhs_usage, rhs') = occAnal ctxt rhs
736     ctxt | certainly_inline id = env
737          | otherwise           = rhsCtxt env
738         -- Note that we generally use an rhsCtxt.  This tells the occ anal n
739         -- that it's looking at an RHS, which has an effect in occAnalApp
740         --
741         -- But there's a problem.  Consider
742         --      x1 = a0 : []
743         --      x2 = a1 : x1
744         --      x3 = a2 : x2
745         --      g  = f x3
746         -- First time round, it looks as if x1 and x2 occur as an arg of a
747         -- let-bound constructor ==> give them a many-occurrence.
748         -- But then x3 is inlined (unconditionally as it happens) and
749         -- next time round, x2 will be, and the next time round x1 will be
750         -- Result: multiple simplifier iterations.  Sigh.
751         -- Crude solution: use rhsCtxt for things that occur just once...
752
753     certainly_inline id = case idOccInfo id of
754                             OneOcc in_lam one_br _ -> not in_lam && one_br
755                             _                      -> False
756 \end{code}
757
758
759
760 \begin{code}
761 addRuleUsage :: UsageDetails -> Id -> UsageDetails
762 -- Add the usage from RULES in Id to the usage
763 addRuleUsage usage id = addIdOccs usage (idRuleVars id)
764         -- idRuleVars here: see Note [Rule dependency info]
765
766 addIdOccs :: UsageDetails -> VarSet -> UsageDetails
767 addIdOccs usage id_set = foldVarSet add usage id_set
768   where
769     add v u | isId v    = addOneOcc u v NoOccInfo
770             | otherwise = u
771         -- Give a non-committal binder info (i.e NoOccInfo) because
772         --   a) Many copies of the specialised thing can appear
773         --   b) We don't want to substitute a BIG expression inside a RULE
774         --      even if that's the only occurrence of the thing
775         --      (Same goes for INLINE.)
776 \end{code}
777
778 Expressions
779 ~~~~~~~~~~~
780 \begin{code}
781 occAnal :: OccEnv
782         -> CoreExpr
783         -> (UsageDetails,       -- Gives info only about the "interesting" Ids
784             CoreExpr)
785
786 occAnal _   (Type t)  = (emptyDetails, Type t)
787 occAnal env (Var v)   = (mkOneOcc env v False, Var v)
788     -- At one stage, I gathered the idRuleVars for v here too,
789     -- which in a way is the right thing to do.
790     -- But that went wrong right after specialisation, when
791     -- the *occurrences* of the overloaded function didn't have any
792     -- rules in them, so the *specialised* versions looked as if they
793     -- weren't used at all.
794 \end{code}
795
796 We regard variables that occur as constructor arguments as "dangerousToDup":
797
798 \begin{verbatim}
799 module A where
800 f x = let y = expensive x in
801       let z = (True,y) in
802       (case z of {(p,q)->q}, case z of {(p,q)->q})
803 \end{verbatim}
804
805 We feel free to duplicate the WHNF (True,y), but that means
806 that y may be duplicated thereby.
807
808 If we aren't careful we duplicate the (expensive x) call!
809 Constructors are rather like lambdas in this way.
810
811 \begin{code}
812 occAnal _   expr@(Lit _) = (emptyDetails, expr)
813 \end{code}
814
815 \begin{code}
816 occAnal env (Note note@(SCC _) body)
817   = case occAnal env body of { (usage, body') ->
818     (mapVarEnv markInsideSCC usage, Note note body')
819     }
820
821 occAnal env (Note note body)
822   = case occAnal env body of { (usage, body') ->
823     (usage, Note note body')
824     }
825
826 occAnal env (Cast expr co)
827   = case occAnal env expr of { (usage, expr') ->
828     (markRhsUds env True usage, Cast expr' co)
829         -- If we see let x = y `cast` co
830         -- then mark y as 'Many' so that we don't
831         -- immediately inline y again.
832     }
833 \end{code}
834
835 \begin{code}
836 occAnal env app@(App _ _)
837   = occAnalApp env (collectArgs app)
838
839 -- Ignore type variables altogether
840 --   (a) occurrences inside type lambdas only not marked as InsideLam
841 --   (b) type variables not in environment
842
843 occAnal env (Lam x body) | isTyVar x
844   = case occAnal env body of { (body_usage, body') ->
845     (body_usage, Lam x body')
846     }
847
848 -- For value lambdas we do a special hack.  Consider
849 --      (\x. \y. ...x...)
850 -- If we did nothing, x is used inside the \y, so would be marked
851 -- as dangerous to dup.  But in the common case where the abstraction
852 -- is applied to two arguments this is over-pessimistic.
853 -- So instead, we just mark each binder with its occurrence
854 -- info in the *body* of the multiple lambda.
855 -- Then, the simplifier is careful when partially applying lambdas.
856
857 occAnal env expr@(Lam _ _)
858   = case occAnal env_body body of { (body_usage, body') ->
859     let
860         (final_usage, tagged_binders) = tagLamBinders body_usage binders'
861                       -- Use binders' to put one-shot info on the lambdas
862
863         --      URGH!  Sept 99: we don't seem to be able to use binders' here, because
864         --      we get linear-typed things in the resulting program that we can't handle yet.
865         --      (e.g. PrelShow)  TODO
866
867         really_final_usage = if linear then
868                                 final_usage
869                              else
870                                 mapVarEnv markInsideLam final_usage
871     in
872     (really_final_usage,
873      mkLams tagged_binders body') }
874   where
875     env_body        = vanillaCtxt (trimOccEnv env binders)
876                         -- Body is (no longer) an RhsContext
877     (binders, body) = collectBinders expr
878     binders'        = oneShotGroup env binders
879     linear          = all is_one_shot binders'
880     is_one_shot b   = isId b && isOneShotBndr b
881
882 occAnal env (Case scrut bndr ty alts)
883   = case occ_anal_scrut scrut alts     of { (scrut_usage, scrut') ->
884     case mapAndUnzip occ_anal_alt alts of { (alts_usage_s, alts')   ->
885     let
886         alts_usage  = foldr1 combineAltsUsageDetails alts_usage_s
887         (alts_usage1, tagged_bndr) = tag_case_bndr alts_usage bndr
888         total_usage = scrut_usage +++ alts_usage1
889     in
890     total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
891   where
892         -- Note [Case binder usage]     
893         -- ~~~~~~~~~~~~~~~~~~~~~~~~
894         -- The case binder gets a usage of either "many" or "dead", never "one".
895         -- Reason: we like to inline single occurrences, to eliminate a binding,
896         -- but inlining a case binder *doesn't* eliminate a binding.
897         -- We *don't* want to transform
898         --      case x of w { (p,q) -> f w }
899         -- into
900         --      case x of w { (p,q) -> f (p,q) }
901     tag_case_bndr usage bndr
902       = case lookupVarEnv usage bndr of
903           Nothing -> (usage,                  setIdOccInfo bndr IAmDead)
904           Just _  -> (usage `delVarEnv` bndr, setIdOccInfo bndr NoOccInfo)
905
906     alt_env      = mkAltEnv env scrut bndr
907     occ_anal_alt = occAnalAlt alt_env bndr
908
909     occ_anal_scrut (Var v) (alt1 : other_alts)
910         | not (null other_alts) || not (isDefaultAlt alt1)
911         = (mkOneOcc env v True, Var v)  -- The 'True' says that the variable occurs
912                                         -- in an interesting context; the case has
913                                         -- at least one non-default alternative
914     occ_anal_scrut scrut _alts  
915         = occAnal (vanillaCtxt env) scrut    -- No need for rhsCtxt
916
917 occAnal env (Let bind body)
918   = case occAnal env_body body                    of { (body_usage, body') ->
919     case occAnalBind env env_body bind body_usage of { (final_usage, new_binds) ->
920        (final_usage, mkLets new_binds body') }}
921   where
922     env_body = trimOccEnv env (bindersOf bind)
923
924 occAnalArgs :: OccEnv -> [CoreExpr] -> (UsageDetails, [CoreExpr])
925 occAnalArgs env args
926   = case mapAndUnzip (occAnal arg_env) args of  { (arg_uds_s, args') ->
927     (foldr (+++) emptyDetails arg_uds_s, args')}
928   where
929     arg_env = vanillaCtxt env
930 \end{code}
931
932 Applications are dealt with specially because we want
933 the "build hack" to work.
934
935 \begin{code}
936 occAnalApp :: OccEnv
937            -> (Expr CoreBndr, [Arg CoreBndr])
938            -> (UsageDetails, Expr CoreBndr)
939 occAnalApp env (Var fun, args)
940   = case args_stuff of { (args_uds, args') ->
941     let
942         final_args_uds = markRhsUds env is_pap args_uds
943     in
944     (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
945   where
946     fun_uniq = idUnique fun
947     fun_uds  = mkOneOcc env fun (valArgCount args > 0)
948     is_pap = isConLikeId fun || valArgCount args < idArity fun
949            -- See Note [CONLIKE pragma] in BasicTypes
950
951                 -- Hack for build, fold, runST
952     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
953                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
954                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
955                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]       args
956                         -- (foldr k z xs) may call k many times, but it never
957                         -- shares a partial application of k; hence [False,True]
958                         -- This means we can optimise
959                         --      foldr (\x -> let v = ...x... in \y -> ...v...) z xs
960                         -- by floating in the v
961
962                 | otherwise = occAnalArgs env args
963
964
965 occAnalApp env (fun, args)
966   = case occAnal (addAppCtxt env args) fun of   { (fun_uds, fun') ->
967         -- The addAppCtxt is a bit cunning.  One iteration of the simplifier
968         -- often leaves behind beta redexs like
969         --      (\x y -> e) a1 a2
970         -- Here we would like to mark x,y as one-shot, and treat the whole
971         -- thing much like a let.  We do this by pushing some True items
972         -- onto the context stack.
973
974     case occAnalArgs env args of        { (args_uds, args') ->
975     let
976         final_uds = fun_uds +++ args_uds
977     in
978     (final_uds, mkApps fun' args') }}
979
980
981 markRhsUds :: OccEnv            -- Check if this is a RhsEnv
982            -> Bool              -- and this is true
983            -> UsageDetails      -- The do markMany on this
984            -> UsageDetails
985 -- We mark the free vars of the argument of a constructor or PAP
986 -- as "many", if it is the RHS of a let(rec).
987 -- This means that nothing gets inlined into a constructor argument
988 -- position, which is what we want.  Typically those constructor
989 -- arguments are just variables, or trivial expressions.
990 --
991 -- This is the *whole point* of the isRhsEnv predicate
992 markRhsUds env is_pap arg_uds
993   | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
994   | otherwise              = arg_uds
995
996
997 appSpecial :: OccEnv
998            -> Int -> CtxtTy     -- Argument number, and context to use for it
999            -> [CoreExpr]
1000            -> (UsageDetails, [CoreExpr])
1001 appSpecial env n ctxt args
1002   = go n args
1003   where
1004     arg_env = vanillaCtxt env
1005
1006     go _ [] = (emptyDetails, [])        -- Too few args
1007
1008     go 1 (arg:args)                     -- The magic arg
1009       = case occAnal (setCtxtTy arg_env ctxt) arg of    { (arg_uds, arg') ->
1010         case occAnalArgs env args of                    { (args_uds, args') ->
1011         (arg_uds +++ args_uds, arg':args') }}
1012
1013     go n (arg:args)
1014       = case occAnal arg_env arg of     { (arg_uds, arg') ->
1015         case go (n-1) args of           { (args_uds, args') ->
1016         (arg_uds +++ args_uds, arg':args') }}
1017 \end{code}
1018
1019
1020 Note [Binders in case alternatives]
1021 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1022 Consider
1023     case x of y { (a,b) -> f y }
1024 We treat 'a', 'b' as dead, because they don't physically occur in the
1025 case alternative.  (Indeed, a variable is dead iff it doesn't occur in
1026 its scope in the output of OccAnal.)  It really helps to know when
1027 binders are unused.  See esp the call to isDeadBinder in
1028 Simplify.mkDupableAlt
1029
1030 In this example, though, the Simplifier will bring 'a' and 'b' back to
1031 life, beause it binds 'y' to (a,b) (imagine got inlined and
1032 scrutinised y).
1033
1034 \begin{code}
1035 occAnalAlt :: OccEnv
1036            -> CoreBndr
1037            -> CoreAlt
1038            -> (UsageDetails, Alt IdWithOccInfo)
1039 occAnalAlt env case_bndr (con, bndrs, rhs)
1040   = let 
1041         env' = trimOccEnv env bndrs
1042     in 
1043     case occAnal env' rhs of { (rhs_usage1, rhs1) ->
1044     let
1045         proxies = getProxies env' case_bndr 
1046         (rhs_usage2, rhs2) = foldrBag wrapProxy (rhs_usage1, rhs1) proxies
1047         (alt_usg, tagged_bndrs) = tagLamBinders rhs_usage2 bndrs
1048         bndrs' = tagged_bndrs      -- See Note [Binders in case alternatives]
1049     in
1050     (alt_usg, (con, bndrs', rhs2)) }
1051
1052 wrapProxy :: ProxyBind -> (UsageDetails, CoreExpr) -> (UsageDetails, CoreExpr)
1053 wrapProxy (bndr, rhs_var, co) (body_usg, body)
1054   | not (bndr `usedIn` body_usg) 
1055   = (body_usg, body)
1056   | otherwise
1057   = (body_usg' +++ rhs_usg, Let (NonRec tagged_bndr rhs) body)
1058   where
1059     (body_usg', tagged_bndr) = tagBinder body_usg bndr
1060     rhs_usg = unitVarEnv rhs_var NoOccInfo      -- We don't need exact info
1061     rhs = mkCoerceI co (Var rhs_var)
1062 \end{code}
1063
1064
1065 %************************************************************************
1066 %*                                                                      *
1067                     OccEnv                                                                      
1068 %*                                                                      *
1069 %************************************************************************
1070
1071 \begin{code}
1072 data OccEnv
1073   = OccEnv { occ_encl  :: !OccEncl      -- Enclosing context information
1074            , occ_ctxt  :: !CtxtTy       -- Tells about linearity
1075            , occ_proxy :: ProxyEnv }
1076
1077
1078 -----------------------------
1079 -- OccEncl is used to control whether to inline into constructor arguments
1080 -- For example:
1081 --      x = (p,q)               -- Don't inline p or q
1082 --      y = /\a -> (p a, q a)   -- Still don't inline p or q
1083 --      z = f (p,q)             -- Do inline p,q; it may make a rule fire
1084 -- So OccEncl tells enought about the context to know what to do when
1085 -- we encounter a contructor application or PAP.
1086
1087 data OccEncl
1088   = OccRhs              -- RHS of let(rec), albeit perhaps inside a type lambda
1089                         -- Don't inline into constructor args here
1090   | OccVanilla          -- Argument of function, body of lambda, scruintee of case etc.
1091                         -- Do inline into constructor args here
1092
1093 type CtxtTy = [Bool]
1094         -- []           No info
1095         --
1096         -- True:ctxt    Analysing a function-valued expression that will be
1097         --                      applied just once
1098         --
1099         -- False:ctxt   Analysing a function-valued expression that may
1100         --                      be applied many times; but when it is,
1101         --                      the CtxtTy inside applies
1102
1103 initOccEnv :: OccEnv
1104 initOccEnv = OccEnv { occ_encl  = OccVanilla
1105                     , occ_ctxt  = []
1106                     , occ_proxy = PE emptyVarEnv emptyVarSet }
1107
1108 vanillaCtxt :: OccEnv -> OccEnv
1109 vanillaCtxt env = OccEnv { occ_encl = OccVanilla
1110                          , occ_ctxt = []
1111                          , occ_proxy = occ_proxy env }
1112
1113 rhsCtxt :: OccEnv -> OccEnv
1114 rhsCtxt env = OccEnv { occ_encl = OccRhs, occ_ctxt = []
1115                      , occ_proxy = occ_proxy env }
1116
1117 setCtxtTy :: OccEnv -> CtxtTy -> OccEnv
1118 setCtxtTy env ctxt = env { occ_ctxt = ctxt }
1119
1120 isRhsEnv :: OccEnv -> Bool
1121 isRhsEnv (OccEnv { occ_encl = OccRhs })     = True
1122 isRhsEnv (OccEnv { occ_encl = OccVanilla }) = False
1123
1124 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
1125         -- The result binders have one-shot-ness set that they might not have had originally.
1126         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
1127         -- linearity context knows that c,n are one-shot, and it records that fact in
1128         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
1129
1130 oneShotGroup (OccEnv { occ_ctxt = ctxt }) bndrs
1131   = go ctxt bndrs []
1132   where
1133     go _ [] rev_bndrs = reverse rev_bndrs
1134
1135     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
1136         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
1137         where
1138           bndr' | lin_ctxt  = setOneShotLambda bndr
1139                 | otherwise = bndr
1140
1141     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
1142
1143 addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
1144 addAppCtxt env@(OccEnv { occ_ctxt = ctxt }) args
1145   = env { occ_ctxt = replicate (valArgCount args) True ++ ctxt }
1146 \end{code}
1147
1148 %************************************************************************
1149 %*                                                                      *
1150                     ProxyEnv                                                                    
1151 %*                                                                      *
1152 %************************************************************************
1153
1154 \begin{code}
1155 data ProxyEnv 
1156    = PE (IdEnv (Id, [(Id,CoercionI)])) VarSet
1157         -- Main env, and its free variables (of both range and domain)
1158 \end{code}
1159
1160 Note [ProxyEnv]
1161 ~~~~~~~~~~~~~~~
1162 The ProxyEnv keeps track of the connection between case binders and
1163 scrutinee.  Specifically, if
1164      sc |-> (sc, [...(cb, co)...])
1165 is a binding in the ProxyEnv, then
1166      cb = sc |> coi
1167 Typically we add such a binding when encountering the case expression
1168      case (sc |> coi) of cb { ... }
1169
1170 Things to note:
1171   * The domain of the ProxyEnv is the variable (or casted variable) 
1172     scrutinees of enclosing cases.  This is additionally used
1173     to ensure we gather occurrence info even for GlobalId scrutinees;
1174     see Note [Binder swap for GlobalId scrutinee]
1175
1176   * The ProxyEnv is just an optimisation; you can throw away any 
1177     element without losing correctness.  And we do so when pushing
1178     it inside a binding (see trimProxyEnv).
1179
1180   * Once scrutinee might map to many case binders:  Eg
1181       case sc of cb1 { DEFAULT -> ....case sc of cb2 { ... } .. }
1182
1183 INVARIANTS
1184  * If sc1 |-> (sc2, [...(cb, co)...]), then sc1==sc2
1185    It's a UniqFM and we sometimes need the domain Id
1186
1187  * Any particular case binder 'cb' occurs only once in entire range
1188
1189  * No loops
1190
1191 The Main Reason for having a ProxyEnv is so that when we encounter
1192     case e of cb { pi -> ri }
1193 we can find all the in-scope variables derivable from 'cb', 
1194 and effectively add let-bindings for them thus:
1195     case e of cb { pi -> let { x = ..cb..; y = ...cb.. }
1196                          in ri }
1197 The function getProxies finds these bindings; then we 
1198 add just the necessary ones, using wrapProxy. 
1199
1200 More info under Note [Binder swap]
1201
1202 Note [Binder swap]
1203 ~~~~~~~~~~~~~~~~~~
1204 We do these two transformations right here:
1205
1206  (1)   case x of b { pi -> ri }
1207     ==>
1208       case x of b { pi -> let x=b in ri }
1209
1210  (2)  case (x |> co) of b { pi -> ri }
1211     ==>
1212       case (x |> co) of b { pi -> let x = b |> sym co in ri }
1213
1214     Why (2)?  See Note [Case of cast]
1215
1216 In both cases, in a particular alternative (pi -> ri), we only 
1217 add the binding if
1218   (a) x occurs free in (pi -> ri)
1219         (ie it occurs in ri, but is not bound in pi)
1220   (b) the pi does not bind b (or the free vars of co)
1221 We need (a) and (b) for the inserted binding to be correct.
1222
1223 For the alternatives where we inject the binding, we can transfer
1224 all x's OccInfo to b.  And that is the point.
1225
1226 Notice that 
1227   * The deliberate shadowing of 'x'. 
1228   * That (a) rapidly becomes false, so no bindings are injected.
1229
1230 The reason for doing these transformations here is because it allows
1231 us to adjust the OccInfo for 'x' and 'b' as we go.
1232
1233   * Suppose the only occurrences of 'x' are the scrutinee and in the
1234     ri; then this transformation makes it occur just once, and hence
1235     get inlined right away.
1236
1237   * If we do this in the Simplifier, we don't know whether 'x' is used
1238     in ri, so we are forced to pessimistically zap b's OccInfo even
1239     though it is typically dead (ie neither it nor x appear in the
1240     ri).  There's nothing actually wrong with zapping it, except that
1241     it's kind of nice to know which variables are dead.  My nose
1242     tells me to keep this information as robustly as possible.
1243
1244 The Maybe (Id,CoreExpr) passed to occAnalAlt is the extra let-binding
1245 {x=b}; it's Nothing if the binder-swap doesn't happen.
1246
1247 There is a danger though.  Consider
1248       let v = x +# y
1249       in case (f v) of w -> ...v...v...
1250 And suppose that (f v) expands to just v.  Then we'd like to
1251 use 'w' instead of 'v' in the alternative.  But it may be too
1252 late; we may have substituted the (cheap) x+#y for v in the 
1253 same simplifier pass that reduced (f v) to v.
1254
1255 I think this is just too bad.  CSE will recover some of it.
1256
1257 Note [Case of cast]
1258 ~~~~~~~~~~~~~~~~~~~
1259 Consider        case (x `cast` co) of b { I# ->
1260                 ... (case (x `cast` co) of {...}) ...
1261 We'd like to eliminate the inner case.  That is the motivation for
1262 equation (2) in Note [Binder swap].  When we get to the inner case, we
1263 inline x, cancel the casts, and away we go.
1264
1265 Note [Binder swap on GlobalId scrutinees]
1266 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1267 When the scrutinee is a GlobalId we must take care in two ways
1268
1269  i) In order to *know* whether 'x' occurs free in the RHS, we need its
1270     occurrence info. BUT, we don't gather occurrence info for
1271     GlobalIds.  That's one use for the (small) occ_proxy env in OccEnv is
1272     for: it says "gather occurrence info for these.
1273
1274  ii) We must call localiseId on 'x' first, in case it's a GlobalId, or
1275      has an External Name. See, for example, SimplEnv Note [Global Ids in
1276      the substitution].
1277
1278 Note [getProxies is subtle]
1279 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1280 The code for getProxies isn't all that obvious. Consider
1281
1282   case v |> cov  of x { DEFAULT ->
1283   case x |> cox1 of y { DEFAULT ->
1284   case x |> cox2 of z { DEFAULT -> r
1285
1286 These will give us a ProxyEnv looking like:
1287   x |-> (x, [(y, cox1), (z, cox2)])
1288   v |-> (v, [(x, cov)])
1289
1290 From this we want to extract the bindings
1291     x = z |> sym cox2
1292     v = x |> sym cov
1293     y = x |> cox1
1294
1295 Notice that later bindings may mention earlier ones, and that
1296 we need to go "both ways".
1297
1298 Historical note [no-case-of-case]
1299 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1300 We *used* to suppress the binder-swap in case expressions when 
1301 -fno-case-of-case is on.  Old remarks:
1302     "This happens in the first simplifier pass,
1303     and enhances full laziness.  Here's the bad case:
1304             f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1305     If we eliminate the inner case, we trap it inside the I# v -> arm,
1306     which might prevent some full laziness happening.  I've seen this
1307     in action in spectral/cichelli/Prog.hs:
1308              [(m,n) | m <- [1..max], n <- [1..max]]
1309     Hence the check for NoCaseOfCase."
1310 However, now the full-laziness pass itself reverses the binder-swap, so this
1311 check is no longer necessary.
1312
1313 Historical note [Suppressing the case binder-swap]
1314 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1315 This old note describes a problem that is also fixed by doing the
1316 binder-swap in OccAnal:
1317
1318     There is another situation when it might make sense to suppress the
1319     case-expression binde-swap. If we have
1320
1321         case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1322                        ...other cases .... }
1323
1324     We'll perform the binder-swap for the outer case, giving
1325
1326         case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1327                        ...other cases .... }
1328
1329     But there is no point in doing it for the inner case, because w1 can't
1330     be inlined anyway.  Furthermore, doing the case-swapping involves
1331     zapping w2's occurrence info (see paragraphs that follow), and that
1332     forces us to bind w2 when doing case merging.  So we get
1333
1334         case x of w1 { A -> let w2 = w1 in e1
1335                        B -> let w2 = w1 in e2
1336                        ...other cases .... }
1337
1338     This is plain silly in the common case where w2 is dead.
1339
1340     Even so, I can't see a good way to implement this idea.  I tried
1341     not doing the binder-swap if the scrutinee was already evaluated
1342     but that failed big-time:
1343
1344             data T = MkT !Int
1345
1346             case v of w  { MkT x ->
1347             case x of x1 { I# y1 ->
1348             case x of x2 { I# y2 -> ...
1349
1350     Notice that because MkT is strict, x is marked "evaluated".  But to
1351     eliminate the last case, we must either make sure that x (as well as
1352     x1) has unfolding MkT y1.  THe straightforward thing to do is to do
1353     the binder-swap.  So this whole note is a no-op.
1354
1355 It's fixed by doing the binder-swap in OccAnal because we can do the
1356 binder-swap unconditionally and still get occurrence analysis
1357 information right.
1358
1359 \begin{code}
1360 extendProxyEnv :: ProxyEnv -> Id -> CoercionI -> Id -> ProxyEnv
1361 -- (extendPE x co y) typically arises from 
1362 --                case (x |> co) of y { ... }
1363 -- It extends the proxy env with the binding 
1364 --                     y = x |> co
1365 extendProxyEnv pe scrut co case_bndr
1366   | scrut == case_bndr = PE env1 fvs1   -- If case_bndr shadows scrut,
1367   | otherwise          = PE env2 fvs2   --   don't extend
1368   where
1369     PE env1 fvs1 = trimProxyEnv pe [case_bndr]
1370     env2 = extendVarEnv_C add env1 scrut1 (scrut1, [(case_bndr,co)])
1371     add (x, cb_cos) _ = (x, (case_bndr,co):cb_cos)
1372     fvs2 = fvs1 `unionVarSet`  freeVarsCoI co
1373                 `extendVarSet` case_bndr
1374                 `extendVarSet` scrut1
1375
1376     scrut1 = mkLocalId (localiseName (idName scrut)) (idType scrut)
1377         -- Localise the scrut_var before shadowing it; we're making a 
1378         -- new binding for it, and it might have an External Name, or
1379         -- even be a GlobalId; Note [Binder swap on GlobalId scrutinees]
1380         -- Also we don't want any INLILNE or NOINLINE pragmas!
1381
1382 -----------
1383 type ProxyBind = (Id, Id, CoercionI)
1384
1385 getProxies :: OccEnv -> Id -> Bag ProxyBind
1386 -- Return a bunch of bindings [...(xi,ei)...] 
1387 -- such that  let { ...; xi=ei; ... } binds the xi using y alone
1388 -- See Note [getProxies is subtle]
1389 getProxies (OccEnv { occ_proxy = PE pe _ }) case_bndr
1390   = -- pprTrace "wrapProxies" (ppr case_bndr) $
1391     go_fwd case_bndr
1392   where
1393     fwd_pe :: IdEnv (Id, CoercionI)
1394     fwd_pe = foldVarEnv add1 emptyVarEnv pe
1395            where
1396              add1 (x,ycos) env = foldr (add2 x) env ycos
1397              add2 x (y,co) env = extendVarEnv env y (x,co)
1398
1399     go_fwd :: Id -> Bag ProxyBind
1400         -- Return bindings derivable from case_bndr
1401     go_fwd case_bndr = -- pprTrace "go_fwd" (vcat [ppr case_bndr, text "fwd_pe =" <+> ppr fwd_pe, 
1402                        --                         text "pe =" <+> ppr pe]) $ 
1403                        go_fwd' case_bndr
1404
1405     go_fwd' case_bndr
1406         | Just (scrut, co) <- lookupVarEnv fwd_pe case_bndr
1407         = unitBag (scrut,  case_bndr, mkSymCoI co)
1408           `unionBags` go_fwd scrut
1409           `unionBags` go_bwd scrut [pr | pr@(cb,_) <- lookup_bwd scrut
1410                                        , cb /= case_bndr]
1411         | otherwise 
1412         = emptyBag
1413
1414     lookup_bwd :: Id -> [(Id, CoercionI)]
1415         -- Return case_bndrs that are connected to scrut 
1416     lookup_bwd scrut = case lookupVarEnv pe scrut of
1417                           Nothing          -> []
1418                           Just (_, cb_cos) -> cb_cos
1419
1420     go_bwd :: Id -> [(Id, CoercionI)] -> Bag ProxyBind
1421     go_bwd scrut cb_cos = foldr (unionBags . go_bwd1 scrut) emptyBag cb_cos
1422
1423     go_bwd1 :: Id -> (Id, CoercionI) -> Bag ProxyBind
1424     go_bwd1 scrut (case_bndr, co) 
1425        = -- pprTrace "go_bwd1" (ppr case_bndr) $
1426          unitBag (case_bndr, scrut, co)
1427          `unionBags` go_bwd case_bndr (lookup_bwd case_bndr)
1428
1429 -----------
1430 mkAltEnv :: OccEnv -> CoreExpr -> Id -> OccEnv
1431 -- Does two things: a) makes the occ_ctxt = OccVanilla
1432 --                  b) extends the ProxyEnv if possible
1433 mkAltEnv env scrut cb
1434   = env { occ_encl  = OccVanilla, occ_proxy = pe' }
1435   where
1436     pe  = occ_proxy env
1437     pe' = case scrut of
1438              Var v           -> extendProxyEnv pe v IdCo     cb
1439              Cast (Var v) co -> extendProxyEnv pe v (ACo co) cb
1440              _other          -> trimProxyEnv pe [cb]
1441
1442 -----------
1443 trimOccEnv :: OccEnv -> [CoreBndr] -> OccEnv
1444 trimOccEnv env bndrs = env { occ_proxy = trimProxyEnv (occ_proxy env) bndrs }
1445
1446 -----------
1447 trimProxyEnv :: ProxyEnv -> [CoreBndr] -> ProxyEnv
1448 -- We are about to push this ProxyEnv inside a binding for 'bndrs'
1449 -- So dump any ProxyEnv bindings which mention any of the bndrs
1450 trimProxyEnv (PE pe fvs) bndrs 
1451   | not (bndr_set `intersectsVarSet` fvs) 
1452   = PE pe fvs
1453   | otherwise
1454   = PE pe' (fvs `minusVarSet` bndr_set)
1455   where
1456     pe' = mapVarEnv trim pe
1457     bndr_set = mkVarSet bndrs
1458     trim (scrut, cb_cos) | scrut `elemVarSet` bndr_set = (scrut, [])
1459                          | otherwise = (scrut, filterOut discard cb_cos)
1460     discard (cb,co) = bndr_set `intersectsVarSet` 
1461                       extendVarSet (freeVarsCoI co) cb
1462                              
1463 -----------
1464 freeVarsCoI :: CoercionI -> VarSet
1465 freeVarsCoI IdCo     = emptyVarSet
1466 freeVarsCoI (ACo co) = tyVarsOfType co
1467 \end{code}
1468
1469
1470 %************************************************************************
1471 %*                                                                      *
1472 \subsection[OccurAnal-types]{OccEnv}
1473 %*                                                                      *
1474 %************************************************************************
1475
1476 \begin{code}
1477 type UsageDetails = IdEnv OccInfo       -- A finite map from ids to their usage
1478                 -- INVARIANT: never IAmDead
1479                 -- (Deadness is signalled by not being in the map at all)
1480
1481 (+++), combineAltsUsageDetails
1482         :: UsageDetails -> UsageDetails -> UsageDetails
1483
1484 (+++) usage1 usage2
1485   = plusVarEnv_C addOccInfo usage1 usage2
1486
1487 combineAltsUsageDetails usage1 usage2
1488   = plusVarEnv_C orOccInfo usage1 usage2
1489
1490 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
1491 addOneOcc usage id info
1492   = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
1493         -- ToDo: make this more efficient
1494
1495 emptyDetails :: UsageDetails
1496 emptyDetails = (emptyVarEnv :: UsageDetails)
1497
1498 localUsedIn, usedIn :: Id -> UsageDetails -> Bool
1499 v `localUsedIn` details = v `elemVarEnv` details
1500 v `usedIn`      details =  isExportedId v || v `localUsedIn` details
1501
1502 type IdWithOccInfo = Id
1503
1504 tagLamBinders :: UsageDetails          -- Of scope
1505               -> [Id]                  -- Binders
1506               -> (UsageDetails,        -- Details with binders removed
1507                  [IdWithOccInfo])    -- Tagged binders
1508 -- Used for lambda and case binders
1509 -- It copes with the fact that lambda bindings can have InlineRule 
1510 -- unfoldings, used for join points
1511 tagLamBinders usage binders = usage' `seq` (usage', bndrs')
1512   where
1513     (usage', bndrs') = mapAccumR tag_lam usage binders
1514     tag_lam usage bndr = (usage2, setBinderOcc usage bndr)
1515       where
1516         usage1 = usage `delVarEnv` bndr
1517         usage2 | isId bndr = addIdOccs usage1 (idUnfoldingVars bndr)
1518                | otherwise = usage1
1519
1520 tagBinder :: UsageDetails           -- Of scope
1521           -> Id                     -- Binders
1522           -> (UsageDetails,         -- Details with binders removed
1523               IdWithOccInfo)        -- Tagged binders
1524
1525 tagBinder usage binder
1526  = let
1527      usage'  = usage `delVarEnv` binder
1528      binder' = setBinderOcc usage binder
1529    in
1530    usage' `seq` (usage', binder')
1531
1532 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
1533 setBinderOcc usage bndr
1534   | isTyVar bndr      = bndr
1535   | isExportedId bndr = case idOccInfo bndr of
1536                           NoOccInfo -> bndr
1537                           _         -> setIdOccInfo bndr NoOccInfo
1538             -- Don't use local usage info for visible-elsewhere things
1539             -- BUT *do* erase any IAmALoopBreaker annotation, because we're
1540             -- about to re-generate it and it shouldn't be "sticky"
1541
1542   | otherwise = setIdOccInfo bndr occ_info
1543   where
1544     occ_info = lookupVarEnv usage bndr `orElse` IAmDead
1545 \end{code}
1546
1547
1548 %************************************************************************
1549 %*                                                                      *
1550 \subsection{Operations over OccInfo}
1551 %*                                                                      *
1552 %************************************************************************
1553
1554 \begin{code}
1555 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
1556 mkOneOcc env id int_cxt
1557   | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
1558   | PE env _ <- occ_proxy env
1559   , id `elemVarEnv` env = unitVarEnv id NoOccInfo
1560   | otherwise           = emptyDetails
1561
1562 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
1563
1564 markMany _  = NoOccInfo
1565
1566 markInsideSCC occ = markMany occ
1567
1568 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
1569 markInsideLam occ                       = occ
1570
1571 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
1572
1573 addOccInfo a1 a2  = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
1574                     NoOccInfo   -- Both branches are at least One
1575                                 -- (Argument is never IAmDead)
1576
1577 -- (orOccInfo orig new) is used
1578 -- when combining occurrence info from branches of a case
1579
1580 orOccInfo (OneOcc in_lam1 _ int_cxt1)
1581           (OneOcc in_lam2 _ int_cxt2)
1582   = OneOcc (in_lam1 || in_lam2)
1583            False        -- False, because it occurs in both branches
1584            (int_cxt1 && int_cxt2)
1585 orOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
1586                   NoOccInfo
1587 \end{code}