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