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