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