5824874b58179d34a16c6615d40817d66cadbb53
[ghc-hetmet.git] / compiler / simplCore / OccurAnal.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 %************************************************************************
5 %*                                                                      *
6 \section[OccurAnal]{Occurrence analysis pass}
7 %*                                                                      *
8 %************************************************************************
9
10 The occurrence analyser re-typechecks a core expression, returning a new
11 core expression with (hopefully) improved usage information.
12
13 \begin{code}
14 module OccurAnal (
15         occurAnalysePgm, occurAnalyseExpr
16     ) where
17
18 #include "HsVersions.h"
19
20 import CoreSyn
21 import CoreFVs
22 import Type             ( tyVarsOfType )
23 import CoreUtils        ( exprIsTrivial, isDefaultAlt, mkCoerceI )
24 import Coercion         ( CoercionI(..), mkSymCoI )
25 import Id
26 import Name             ( localiseName )
27 import BasicTypes
28
29 import VarSet
30 import VarEnv
31
32 import Maybes           ( orElse )
33 import Digraph          ( SCC(..), stronglyConnCompFromEdgedVerticesR )
34 import PrelNames        ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
35 import Unique           ( Unique )
36 import UniqFM           ( keysUFM, intersectUFM_C, foldUFM_Directly )
37 import Util             ( mapAndUnzip, filterOut )
38 import Bag
39 import Outputable
40
41 import Data.List
42 \end{code}
43
44
45 %************************************************************************
46 %*                                                                      *
47 \subsection[OccurAnal-main]{Counting occurrences: main function}
48 %*                                                                      *
49 %************************************************************************
50
51 Here's the externally-callable interface:
52
53 \begin{code}
54 occurAnalysePgm :: [CoreBind] -> [CoreRule] -> [CoreBind]
55 occurAnalysePgm binds rules
56   = snd (go initOccEnv binds)
57   where
58     initial_details = addIdOccs emptyDetails (rulesFreeVars rules)
59     -- The RULES keep things alive!
60
61     go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
62     go _ []
63         = (initial_details, [])
64     go env (bind:binds)
65         = (final_usage, bind' ++ binds')
66         where
67            (bs_usage, binds')   = go env binds
68            (final_usage, bind') = occAnalBind env env bind bs_usage
69
70 occurAnalyseExpr :: CoreExpr -> CoreExpr
71         -- Do occurrence analysis, and discard occurence info returned
72 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection[OccurAnal-main]{Counting occurrences: main function}
79 %*                                                                      *
80 %************************************************************************
81
82 Bindings
83 ~~~~~~~~
84
85 \begin{code}
86 occAnalBind :: OccEnv           -- The incoming OccEnv
87             -> OccEnv           -- Same, but trimmed by (binderOf bind)
88             -> CoreBind
89             -> UsageDetails             -- Usage details of scope
90             -> (UsageDetails,           -- Of the whole let(rec)
91                 [CoreBind])
92
93 occAnalBind env _ (NonRec binder rhs) body_usage
94   | isTyVar binder                      -- A type let; we don't gather usage info
95   = (body_usage, [NonRec binder rhs])
96
97   | not (binder `usedIn` body_usage)    -- It's not mentioned
98   = (body_usage, [])
99
100   | otherwise                   -- It's mentioned in the body
101   = (body_usage' +++ addRuleUsage rhs_usage binder,     -- Note [Rules are extra RHSs]
102      [NonRec tagged_binder rhs'])
103   where
104     (body_usage', tagged_binder) = tagBinder body_usage binder
105     (rhs_usage, rhs')            = occAnalRhs env tagged_binder rhs
106 \end{code}
107
108 Note [Dead code]
109 ~~~~~~~~~~~~~~~~
110 Dropping dead code for recursive bindings is done in a very simple way:
111
112         the entire set of bindings is dropped if none of its binders are
113         mentioned in its body; otherwise none are.
114
115 This seems to miss an obvious improvement.
116
117         letrec  f = ...g...
118                 g = ...f...
119         in
120         ...g...
121 ===>
122         letrec f = ...g...
123                g = ...(...g...)...
124         in
125         ...g...
126
127 Now 'f' is unused! But it's OK!  Dependency analysis will sort this
128 out into a letrec for 'g' and a 'let' for 'f', and then 'f' will get
129 dropped.  It isn't easy to do a perfect job in one blow.  Consider
130
131         letrec f = ...g...
132                g = ...h...
133                h = ...k...
134                k = ...m...
135                m = ...m...
136         in
137         ...m...
138
139
140 Note [Loop breaking and RULES]
141 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
142 Loop breaking is surprisingly subtle.  First read the section 4 of
143 "Secrets of the GHC inliner".  This describes our basic plan.
144
145 However things are made quite a bit more complicated by RULES.  Remember
146
147   * Note [Rules are extra RHSs]
148     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
149     A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
150     keeps the specialised "children" alive.  If the parent dies
151     (because it isn't referenced any more), then the children will die
152     too (unless they are already referenced directly).
153
154     To that end, we build a Rec group for each cyclic strongly
155     connected component,
156         *treating f's rules as extra RHSs for 'f'*.
157
158     When we make the Rec groups we include variables free in *either*
159     LHS *or* RHS of the rule.  The former might seems silly, but see
160     Note [Rule dependency info].
161
162     So in Example [eftInt], eftInt and eftIntFB will be put in the
163     same Rec, even though their 'main' RHSs are both non-recursive.
164
165   * Note [Rules are visible in their own rec group]
166     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
167     We want the rules for 'f' to be visible in f's right-hand side.
168     And we'd like them to be visible in other functions in f's Rec
169     group.  E.g. in Example [Specialisation rules] we want f' rule
170     to be visible in both f's RHS, and fs's RHS.
171
172     This means that we must simplify the RULEs first, before looking
173     at any of the definitions.  This is done by Simplify.simplRecBind,
174     when it calls addLetIdInfo.
175
176   * Note [Choosing loop breakers]
177     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
178     We avoid infinite inlinings by choosing loop breakers, and
179     ensuring that a loop breaker cuts each loop.  But what is a
180     "loop"?  In particular, a RULE is like an equation for 'f' that
181     is *always* inlined if it is applicable.  We do *not* disable
182     rules for loop-breakers.  It's up to whoever makes the rules to
183     make sure that the rules themselves always terminate.  See Note
184     [Rules for recursive functions] in Simplify.lhs
185
186     Hence, if
187         f's RHS mentions g, and
188         g has a RULE that mentions h, and
189         h has a RULE that mentions f
190
191     then we *must* choose f to be a loop breaker.  In general, take the
192     free variables of f's RHS, and augment it with all the variables
193     reachable by RULES from those starting points.  That is the whole
194     reason for computing rule_fv_env in occAnalBind.  (Of course we
195     only consider free vars that are also binders in this Rec group.)
196
197     Note that when we compute this rule_fv_env, we only consider variables
198     free in the *RHS* of the rule, in contrast to the way we build the
199     Rec group in the first place (Note [Rule dependency info])
200
201     Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
202     chosen as a loop breaker, because their RHSs don't mention each other.
203     And indeed both can be inlined safely.
204
205     Note that the edges of the graph we use for computing loop breakers
206     are not the same as the edges we use for computing the Rec blocks.
207     That's why we compute
208         rec_edges          for the Rec block analysis
209         loop_breaker_edges for the loop breaker analysis
210
211
212   * Note [Weak loop breakers]
213     ~~~~~~~~~~~~~~~~~~~~~~~~~
214     There is a last nasty wrinkle.  Suppose we have
215
216         Rec { f = f_rhs
217               RULE f [] = g
218
219               h = h_rhs
220               g = h
221               ...more...
222         }
223
224     Remmber that we simplify the RULES before any RHS (see Note
225     [Rules are visible in their own rec group] above).
226
227     So we must *not* postInlineUnconditionally 'g', even though
228     its RHS turns out to be trivial.  (I'm assuming that 'g' is
229     not choosen as a loop breaker.)  Why not?  Because then we
230     drop the binding for 'g', which leaves it out of scope in the
231     RULE!
232
233     We "solve" this by making g a "weak" or "rules-only" loop breaker,
234     with OccInfo = IAmLoopBreaker True.  A normal "strong" loop breaker
235     has IAmLoopBreaker False.  So
236
237                                 Inline  postInlineUnconditionally
238         IAmLoopBreaker False    no      no
239         IAmLoopBreaker True     yes     no
240         other                   yes     yes
241
242     The **sole** reason for this kind of loop breaker is so that
243     postInlineUnconditionally does not fire.  Ugh.
244
245   * Note [Rule dependency info]
246     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
247     The VarSet in a SpecInfo is used for dependency analysis in the
248     occurrence analyser.  We must track free vars in *both* lhs and rhs.  
249     Hence use of idRuleVars, rather than idRuleRhsVars in addRuleUsage.  
250     Why both? Consider
251         x = y
252         RULE f x = 4
253     Then if we substitute y for x, we'd better do so in the
254     rule's LHS too, so we'd better ensure the dependency is respected
255
256
257   * Note [Inline rules]
258     ~~~~~~~~~~~~~~~~~~~
259     None of the above stuff about RULES applies to Inline Rules,
260     stored in a CoreUnfolding.  The unfolding, if any, is simplified
261     at the same time as the regular RHS of the function, so it should
262     be treated *exactly* like an extra RHS.
263
264
265 Example [eftInt]
266 ~~~~~~~~~~~~~~~
267 Example (from GHC.Enum):
268
269   eftInt :: Int# -> Int# -> [Int]
270   eftInt x y = ...(non-recursive)...
271
272   {-# INLINE [0] eftIntFB #-}
273   eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
274   eftIntFB c n x y = ...(non-recursive)...
275
276   {-# RULES
277   "eftInt"  [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
278   "eftIntList"  [1] eftIntFB  (:) [] = eftInt
279    #-}
280
281 Example [Specialisation rules]
282 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
283 Consider this group, which is typical of what SpecConstr builds:
284
285    fs a = ....f (C a)....
286    f  x = ....f (C a)....
287    {-# RULE f (C a) = fs a #-}
288
289 So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
290
291 But watch out!  If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
292         - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
293         - fs is inlined (say it's small)
294         - now there's another opportunity to apply the RULE
295
296 This showed up when compiling Control.Concurrent.Chan.getChanContents.
297
298
299 \begin{code}
300 occAnalBind _ env (Rec pairs) body_usage
301   = foldr occAnalRec (body_usage, []) sccs
302         -- For a recursive group, we 
303         --      * occ-analyse all the RHSs
304         --      * compute strongly-connected components
305         --      * feed those components to occAnalRec
306   where
307     -------------Dependency analysis ------------------------------
308     bndr_set = mkVarSet (map fst pairs)
309
310     sccs :: [SCC (Node Details)]
311     sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompFromEdgedVerticesR rec_edges
312
313     rec_edges :: [Node Details]
314     rec_edges = {-# SCC "occAnalBind.assoc" #-}  map make_node pairs
315     
316     make_node (bndr, rhs)
317         = (ND bndr rhs' all_rhs_usage rhs_fvs, idUnique bndr, out_edges)
318         where
319           (rhs_usage, rhs') = occAnalRhs env bndr rhs
320           all_rhs_usage = addRuleUsage rhs_usage bndr    -- Note [Rules are extra RHSs]
321           rhs_fvs = intersectUFM_C (\b _ -> b) bndr_set rhs_usage
322           out_edges = keysUFM (rhs_fvs `unionVarSet` idRuleVars bndr)
323         -- (a -> b) means a mentions b
324         -- Given the usage details (a UFM that gives occ info for each free var of
325         -- the RHS) we can get the list of free vars -- or rather their Int keys --
326         -- by just extracting the keys from the finite map.  Grimy, but fast.
327         -- Previously we had this:
328         --      [ bndr | bndr <- bndrs,
329         --               maybeToBool (lookupVarEnv rhs_usage bndr)]
330         -- which has n**2 cost, and this meant that edges_from alone
331         -- consumed 10% of total runtime!
332
333 -----------------------------
334 occAnalRec :: SCC (Node Details) -> (UsageDetails, [CoreBind])
335                                  -> (UsageDetails, [CoreBind])
336
337         -- The NonRec case is just like a Let (NonRec ...) above
338 occAnalRec (AcyclicSCC (ND bndr rhs rhs_usage _, _, _)) (body_usage, binds)
339   | not (bndr `usedIn` body_usage) 
340   = (body_usage, binds)
341
342   | otherwise                   -- It's mentioned in the body
343   = (body_usage' +++ rhs_usage, 
344      NonRec tagged_bndr rhs : binds)
345   where
346     (body_usage', tagged_bndr) = tagBinder body_usage bndr
347
348
349         -- The Rec case is the interesting one
350         -- See Note [Loop breaking]
351 occAnalRec (CyclicSCC nodes) (body_usage, binds)
352   | not (any (`usedIn` body_usage) bndrs)       -- NB: look at body_usage, not total_usage
353   = (body_usage, binds)                         -- Dead code
354
355   | otherwise   -- At this point we always build a single Rec
356   = (final_usage, Rec pairs : binds)
357
358   where
359     bndrs    = [b | (ND b _ _ _, _, _) <- nodes]
360     bndr_set = mkVarSet bndrs
361
362         ----------------------------
363         -- Tag the binders with their occurrence info
364     total_usage = foldl add_usage body_usage nodes
365     add_usage usage_so_far (ND _ _ rhs_usage _, _, _) = usage_so_far +++ rhs_usage
366     (final_usage, tagged_nodes) = mapAccumL tag_node total_usage nodes
367
368     tag_node :: UsageDetails -> Node Details -> (UsageDetails, Node Details)
369         -- (a) Tag the binders in the details with occ info
370         -- (b) Mark the binder with "weak loop-breaker" OccInfo 
371         --      saying "no preInlineUnconditionally" if it is used
372         --      in any rule (lhs or rhs) of the recursive group
373         --      See Note [Weak loop breakers]
374     tag_node usage (ND bndr rhs rhs_usage rhs_fvs, k, ks)
375       = (usage `delVarEnv` bndr, (ND bndr2 rhs rhs_usage rhs_fvs, k, ks))
376       where
377         bndr2 | bndr `elemVarSet` all_rule_fvs = makeLoopBreaker True bndr1
378               | otherwise                      = bndr1
379         bndr1 = setBinderOcc usage bndr
380     all_rule_fvs = bndr_set `intersectVarSet` foldr (unionVarSet . idRuleVars) 
381                                                     emptyVarSet bndrs
382
383         ----------------------------
384         -- Now reconstruct the cycle
385     pairs | no_rules  = reOrderCycle 0 tagged_nodes []
386           | otherwise = foldr (reOrderRec 0) [] $
387                         stronglyConnCompFromEdgedVerticesR loop_breaker_edges
388
389         -- See Note [Choosing loop breakers] for loop_breaker_edges
390     loop_breaker_edges = map mk_node tagged_nodes
391     mk_node (details@(ND _ _ _ rhs_fvs), k, _) = (details, k, new_ks)
392         where
393           new_ks = keysUFM (extendFvs rule_fv_env rhs_fvs rhs_fvs)
394
395     ------------------------------------
396     rule_fv_env :: IdEnv IdSet  -- Variables from this group mentioned in RHS of rules
397                                 -- Domain is *subset* of bound vars (others have no rule fvs)
398     rule_fv_env = rule_loop init_rule_fvs
399
400     no_rules      = null init_rule_fvs
401     init_rule_fvs = [(b, rule_fvs)
402                     | b <- bndrs
403                     , let rule_fvs = idRuleRhsVars b `intersectVarSet` bndr_set
404                     , not (isEmptyVarSet rule_fvs)]
405
406     rule_loop :: [(Id,IdSet)] -> IdEnv IdSet    -- Finds fixpoint
407     rule_loop fv_list
408         | no_change = env
409         | otherwise = rule_loop new_fv_list
410         where
411           env = mkVarEnv init_rule_fvs
412           (no_change, new_fv_list) = mapAccumL bump True fv_list
413           bump no_change (b,fvs)
414                 | new_fvs `subVarSet` fvs = (no_change, (b,fvs))
415                 | otherwise               = (False,     (b,new_fvs `unionVarSet` fvs))
416                 where
417                   new_fvs = extendFvs env emptyVarSet fvs
418
419 extendFvs :: IdEnv IdSet -> IdSet -> IdSet -> IdSet
420 -- (extendFVs env fvs s) returns (fvs `union` env(s))
421 extendFvs env fvs id_set
422   = foldUFM_Directly add fvs id_set
423   where
424     add uniq _ fvs
425         = case lookupVarEnv_Directly env uniq  of
426             Just fvs' -> fvs' `unionVarSet` fvs
427             Nothing   -> fvs
428 \end{code}
429
430 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
431 strongly connected component (there's guaranteed to be a cycle).  It returns the
432 same pairs, but
433         a) in a better order,
434         b) with some of the Ids having a IAmALoopBreaker pragma
435
436 The "loop-breaker" Ids are sufficient to break all cycles in the SCC.  This means
437 that the simplifier can guarantee not to loop provided it never records an inlining
438 for these no-inline guys.
439
440 Furthermore, the order of the binds is such that if we neglect dependencies
441 on the no-inline Ids then the binds are topologically sorted.  This means
442 that the simplifier will generally do a good job if it works from top bottom,
443 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
444
445 ==============
446 [June 98: I don't understand the following paragraphs, and I've
447           changed the a=b case again so that it isn't a special case any more.]
448
449 Here's a case that bit me:
450
451         letrec
452                 a = b
453                 b = \x. BIG
454         in
455         ...a...a...a....
456
457 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
458
459 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
460 Perhaps something cleverer would suffice.
461 ===============
462
463
464 \begin{code}
465 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
466                                                 -- which is gotten from the Id.
467 data Details = ND Id            -- Binder
468                   CoreExpr      -- RHS
469
470                   UsageDetails  -- Full usage from RHS, 
471                                 -- including *both* RULES *and* InlineRule unfolding
472
473                   IdSet         -- Other binders *from this Rec group* mentioned in
474                                 --   * the  RHS
475                                 --   * any InlineRule unfolding
476                                 -- but *excluding* any RULES
477
478 reOrderRec :: Int -> SCC (Node Details)
479            -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
480 -- Sorted into a plausible order.  Enough of the Ids have
481 --      IAmALoopBreaker pragmas that there are no loops left.
482 reOrderRec _ (AcyclicSCC (ND bndr rhs _ _, _, _)) pairs = (bndr, rhs) : pairs
483 reOrderRec depth (CyclicSCC cycle)                pairs = reOrderCycle depth cycle pairs
484
485 reOrderCycle :: Int -> [Node Details] -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
486 reOrderCycle _ [] _
487   = panic "reOrderCycle"
488 reOrderCycle _ [bind] pairs    -- Common case of simple self-recursion
489   = (makeLoopBreaker False bndr, rhs) : pairs
490   where
491     (ND bndr rhs _ _, _, _) = bind
492
493 reOrderCycle depth (bind : binds) pairs
494   =     -- Choose a loop breaker, mark it no-inline,
495         -- do SCC analysis on the rest, and recursively sort them out
496 --    pprTrace "reOrderCycle" (ppr [b | (ND b _ _ _, _, _) <- bind:binds]) $
497     foldr (reOrderRec new_depth)
498           ([ (makeLoopBreaker False bndr, rhs) 
499            | (ND bndr rhs _ _, _, _) <- chosen_binds] ++ pairs)
500           (stronglyConnCompFromEdgedVerticesR unchosen) 
501   where
502     (chosen_binds, unchosen) = choose_loop_breaker [bind] (score bind) [] binds
503
504     approximate_loop_breaker = depth >= 2
505     new_depth | approximate_loop_breaker = 0
506               | otherwise                = depth+1
507         -- After two iterations (d=0, d=1) give up
508         -- and approximate, returning to d=0
509
510         -- This loop looks for the bind with the lowest score
511         -- to pick as the loop  breaker.  The rest accumulate in
512     choose_loop_breaker loop_binds _loop_sc acc []
513         = (loop_binds, acc)        -- Done
514
515         -- If approximate_loop_breaker is True, we pick *all*
516         -- nodes with lowest score, else just one
517         -- See Note [Complexity of loop breaking]
518     choose_loop_breaker loop_binds loop_sc acc (bind : binds)
519         | sc < loop_sc  -- Lower score so pick this new one
520         = choose_loop_breaker [bind] sc (loop_binds ++ acc) binds
521
522         | approximate_loop_breaker && sc == loop_sc
523         = choose_loop_breaker (bind : loop_binds) loop_sc acc binds
524         
525         | otherwise     -- Higher score so don't pick it
526         = choose_loop_breaker loop_binds loop_sc (bind : acc) binds
527         where
528           sc = score bind
529
530     score :: Node Details -> Int        -- Higher score => less likely to be picked as loop breaker
531     score (ND bndr rhs _ _, _, _)
532         | isDFunId bndr = 9   -- Never choose a DFun as a loop breaker
533                               -- Note [DFuns should not be loop breakers]
534
535         | Just (inl_rule_info, _) <- isInlineRule_maybe (idUnfolding bndr)
536         = case inl_rule_info of
537              InlWrapper {} -> 10  -- Note [INLINE pragmas]
538              _other        ->  3  -- Data structures are more important than this
539                                   -- so that dictionary/method recursion unravels
540                 -- Note that this case hits all InlineRule things, so we
541                 -- never look at 'rhs for InlineRule stuff. That's right, because
542                 -- 'rhs' is irrelevant for inlining things with an InlineRule
543                 
544         | is_con_app rhs = 5  -- Data types help with cases: Note [Constructor applications]
545                 
546         | exprIsTrivial rhs = 10  -- Practically certain to be inlined
547                 -- Used to have also: && not (isExportedId bndr)
548                 -- But I found this sometimes cost an extra iteration when we have
549                 --      rec { d = (a,b); a = ...df...; b = ...df...; df = d }
550                 -- where df is the exported dictionary. Then df makes a really
551                 -- bad choice for loop breaker
552
553         
554 -- If an Id is marked "never inline" then it makes a great loop breaker
555 -- The only reason for not checking that here is that it is rare
556 -- and I've never seen a situation where it makes a difference,
557 -- so it probably isn't worth the time to test on every binder
558 --      | isNeverActive (idInlinePragma bndr) = -10
559
560         | isOneOcc (idOccInfo bndr) = 2  -- Likely to be inlined
561
562         | canUnfold (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_pap 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_pap = isConLikeId fun || valArgCount args < idArity fun
950            -- See Note [CONLIKE pragma] in BasicTypes
951
952                 -- Hack for build, fold, runST
953     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
954                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
955                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
956                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]       args
957                         -- (foldr k z xs) may call k many times, but it never
958                         -- shares a partial application of k; hence [False,True]
959                         -- This means we can optimise
960                         --      foldr (\x -> let v = ...x... in \y -> ...v...) z xs
961                         -- by floating in the v
962
963                 | otherwise = occAnalArgs env args
964
965
966 occAnalApp env (fun, args)
967   = case occAnal (addAppCtxt env args) fun of   { (fun_uds, fun') ->
968         -- The addAppCtxt is a bit cunning.  One iteration of the simplifier
969         -- often leaves behind beta redexs like
970         --      (\x y -> e) a1 a2
971         -- Here we would like to mark x,y as one-shot, and treat the whole
972         -- thing much like a let.  We do this by pushing some True items
973         -- onto the context stack.
974
975     case occAnalArgs env args of        { (args_uds, args') ->
976     let
977         final_uds = fun_uds +++ args_uds
978     in
979     (final_uds, mkApps fun' args') }}
980
981
982 markRhsUds :: OccEnv            -- Check if this is a RhsEnv
983            -> Bool              -- and this is true
984            -> UsageDetails      -- The do markMany on this
985            -> UsageDetails
986 -- We mark the free vars of the argument of a constructor or PAP
987 -- as "many", if it is the RHS of a let(rec).
988 -- This means that nothing gets inlined into a constructor argument
989 -- position, which is what we want.  Typically those constructor
990 -- arguments are just variables, or trivial expressions.
991 --
992 -- This is the *whole point* of the isRhsEnv predicate
993 markRhsUds env is_pap arg_uds
994   | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
995   | otherwise              = arg_uds
996
997
998 appSpecial :: OccEnv
999            -> Int -> CtxtTy     -- Argument number, and context to use for it
1000            -> [CoreExpr]
1001            -> (UsageDetails, [CoreExpr])
1002 appSpecial env n ctxt args
1003   = go n args
1004   where
1005     arg_env = vanillaCtxt env
1006
1007     go _ [] = (emptyDetails, [])        -- Too few args
1008
1009     go 1 (arg:args)                     -- The magic arg
1010       = case occAnal (setCtxtTy arg_env ctxt) arg of    { (arg_uds, arg') ->
1011         case occAnalArgs env args of                    { (args_uds, args') ->
1012         (arg_uds +++ args_uds, arg':args') }}
1013
1014     go n (arg:args)
1015       = case occAnal arg_env arg of     { (arg_uds, arg') ->
1016         case go (n-1) args of           { (args_uds, args') ->
1017         (arg_uds +++ args_uds, arg':args') }}
1018 \end{code}
1019
1020
1021 Note [Binders in case alternatives]
1022 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1023 Consider
1024     case x of y { (a,b) -> f y }
1025 We treat 'a', 'b' as dead, because they don't physically occur in the
1026 case alternative.  (Indeed, a variable is dead iff it doesn't occur in
1027 its scope in the output of OccAnal.)  It really helps to know when
1028 binders are unused.  See esp the call to isDeadBinder in
1029 Simplify.mkDupableAlt
1030
1031 In this example, though, the Simplifier will bring 'a' and 'b' back to
1032 life, beause it binds 'y' to (a,b) (imagine got inlined and
1033 scrutinised y).
1034
1035 \begin{code}
1036 occAnalAlt :: OccEnv
1037            -> CoreBndr
1038            -> CoreAlt
1039            -> (UsageDetails, Alt IdWithOccInfo)
1040 occAnalAlt env case_bndr (con, bndrs, rhs)
1041   = let 
1042         env' = trimOccEnv env bndrs
1043     in 
1044     case occAnal env' rhs of { (rhs_usage1, rhs1) ->
1045     let
1046         proxies = getProxies env' case_bndr 
1047         (rhs_usage2, rhs2) = foldrBag wrapProxy (rhs_usage1, rhs1) proxies
1048         (alt_usg, tagged_bndrs) = tagLamBinders rhs_usage2 bndrs
1049         bndrs' = tagged_bndrs      -- See Note [Binders in case alternatives]
1050     in
1051     (alt_usg, (con, bndrs', rhs2)) }
1052
1053 wrapProxy :: ProxyBind -> (UsageDetails, CoreExpr) -> (UsageDetails, CoreExpr)
1054 wrapProxy (bndr, rhs_var, co) (body_usg, body)
1055   | not (bndr `usedIn` body_usg) 
1056   = (body_usg, body)
1057   | otherwise
1058   = (body_usg' +++ rhs_usg, Let (NonRec tagged_bndr rhs) body)
1059   where
1060     (body_usg', tagged_bndr) = tagBinder body_usg bndr
1061     rhs_usg = unitVarEnv rhs_var NoOccInfo      -- We don't need exact info
1062     rhs = mkCoerceI co (Var rhs_var)
1063 \end{code}
1064
1065
1066 %************************************************************************
1067 %*                                                                      *
1068                     OccEnv                                                                      
1069 %*                                                                      *
1070 %************************************************************************
1071
1072 \begin{code}
1073 data OccEnv
1074   = OccEnv { occ_encl  :: !OccEncl      -- Enclosing context information
1075            , occ_ctxt  :: !CtxtTy       -- Tells about linearity
1076            , occ_proxy :: ProxyEnv }
1077
1078
1079 -----------------------------
1080 -- OccEncl is used to control whether to inline into constructor arguments
1081 -- For example:
1082 --      x = (p,q)               -- Don't inline p or q
1083 --      y = /\a -> (p a, q a)   -- Still don't inline p or q
1084 --      z = f (p,q)             -- Do inline p,q; it may make a rule fire
1085 -- So OccEncl tells enought about the context to know what to do when
1086 -- we encounter a contructor application or PAP.
1087
1088 data OccEncl
1089   = OccRhs              -- RHS of let(rec), albeit perhaps inside a type lambda
1090                         -- Don't inline into constructor args here
1091   | OccVanilla          -- Argument of function, body of lambda, scruintee of case etc.
1092                         -- Do inline into constructor args here
1093
1094 type CtxtTy = [Bool]
1095         -- []           No info
1096         --
1097         -- True:ctxt    Analysing a function-valued expression that will be
1098         --                      applied just once
1099         --
1100         -- False:ctxt   Analysing a function-valued expression that may
1101         --                      be applied many times; but when it is,
1102         --                      the CtxtTy inside applies
1103
1104 initOccEnv :: OccEnv
1105 initOccEnv = OccEnv { occ_encl  = OccVanilla
1106                     , occ_ctxt  = []
1107                     , occ_proxy = PE emptyVarEnv emptyVarSet }
1108
1109 vanillaCtxt :: OccEnv -> OccEnv
1110 vanillaCtxt env = OccEnv { occ_encl = OccVanilla
1111                          , occ_ctxt = []
1112                          , occ_proxy = occ_proxy env }
1113
1114 rhsCtxt :: OccEnv -> OccEnv
1115 rhsCtxt env = OccEnv { occ_encl = OccRhs, occ_ctxt = []
1116                      , occ_proxy = occ_proxy env }
1117
1118 setCtxtTy :: OccEnv -> CtxtTy -> OccEnv
1119 setCtxtTy env ctxt = env { occ_ctxt = ctxt }
1120
1121 isRhsEnv :: OccEnv -> Bool
1122 isRhsEnv (OccEnv { occ_encl = OccRhs })     = True
1123 isRhsEnv (OccEnv { occ_encl = OccVanilla }) = False
1124
1125 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
1126         -- The result binders have one-shot-ness set that they might not have had originally.
1127         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
1128         -- linearity context knows that c,n are one-shot, and it records that fact in
1129         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
1130
1131 oneShotGroup (OccEnv { occ_ctxt = ctxt }) bndrs
1132   = go ctxt bndrs []
1133   where
1134     go _ [] rev_bndrs = reverse rev_bndrs
1135
1136     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
1137         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
1138         where
1139           bndr' | lin_ctxt  = setOneShotLambda bndr
1140                 | otherwise = bndr
1141
1142     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
1143
1144 addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
1145 addAppCtxt env@(OccEnv { occ_ctxt = ctxt }) args
1146   = env { occ_ctxt = replicate (valArgCount args) True ++ ctxt }
1147 \end{code}
1148
1149 %************************************************************************
1150 %*                                                                      *
1151                     ProxyEnv                                                                    
1152 %*                                                                      *
1153 %************************************************************************
1154
1155 \begin{code}
1156 data ProxyEnv 
1157    = PE (IdEnv (Id, [(Id,CoercionI)])) VarSet
1158         -- Main env, and its free variables (of both range and domain)
1159 \end{code}
1160
1161 Note [ProxyEnv]
1162 ~~~~~~~~~~~~~~~
1163 The ProxyEnv keeps track of the connection between case binders and
1164 scrutinee.  Specifically, if
1165      sc |-> (sc, [...(cb, co)...])
1166 is a binding in the ProxyEnv, then
1167      cb = sc |> coi
1168 Typically we add such a binding when encountering the case expression
1169      case (sc |> coi) of cb { ... }
1170
1171 Things to note:
1172   * The domain of the ProxyEnv is the variable (or casted variable) 
1173     scrutinees of enclosing cases.  This is additionally used
1174     to ensure we gather occurrence info even for GlobalId scrutinees;
1175     see Note [Binder swap for GlobalId scrutinee]
1176
1177   * The ProxyEnv is just an optimisation; you can throw away any 
1178     element without losing correctness.  And we do so when pushing
1179     it inside a binding (see trimProxyEnv).
1180
1181   * Once scrutinee might map to many case binders:  Eg
1182       case sc of cb1 { DEFAULT -> ....case sc of cb2 { ... } .. }
1183
1184 INVARIANTS
1185  * If sc1 |-> (sc2, [...(cb, co)...]), then sc1==sc2
1186    It's a UniqFM and we sometimes need the domain Id
1187
1188  * Any particular case binder 'cb' occurs only once in entire range
1189
1190  * No loops
1191
1192 The Main Reason for having a ProxyEnv is so that when we encounter
1193     case e of cb { pi -> ri }
1194 we can find all the in-scope variables derivable from 'cb', 
1195 and effectively add let-bindings for them thus:
1196     case e of cb { pi -> let { x = ..cb..; y = ...cb.. }
1197                          in ri }
1198 The function getProxies finds these bindings; then we 
1199 add just the necessary ones, using wrapProxy. 
1200
1201 More info under Note [Binder swap]
1202
1203 Note [Binder swap]
1204 ~~~~~~~~~~~~~~~~~~
1205 We do these two transformations right here:
1206
1207  (1)   case x of b { pi -> ri }
1208     ==>
1209       case x of b { pi -> let x=b in ri }
1210
1211  (2)  case (x |> co) of b { pi -> ri }
1212     ==>
1213       case (x |> co) of b { pi -> let x = b |> sym co in ri }
1214
1215     Why (2)?  See Note [Case of cast]
1216
1217 In both cases, in a particular alternative (pi -> ri), we only 
1218 add the binding if
1219   (a) x occurs free in (pi -> ri)
1220         (ie it occurs in ri, but is not bound in pi)
1221   (b) the pi does not bind b (or the free vars of co)
1222 We need (a) and (b) for the inserted binding to be correct.
1223
1224 For the alternatives where we inject the binding, we can transfer
1225 all x's OccInfo to b.  And that is the point.
1226
1227 Notice that 
1228   * The deliberate shadowing of 'x'. 
1229   * That (a) rapidly becomes false, so no bindings are injected.
1230
1231 The reason for doing these transformations here is because it allows
1232 us to adjust the OccInfo for 'x' and 'b' as we go.
1233
1234   * Suppose the only occurrences of 'x' are the scrutinee and in the
1235     ri; then this transformation makes it occur just once, and hence
1236     get inlined right away.
1237
1238   * If we do this in the Simplifier, we don't know whether 'x' is used
1239     in ri, so we are forced to pessimistically zap b's OccInfo even
1240     though it is typically dead (ie neither it nor x appear in the
1241     ri).  There's nothing actually wrong with zapping it, except that
1242     it's kind of nice to know which variables are dead.  My nose
1243     tells me to keep this information as robustly as possible.
1244
1245 The Maybe (Id,CoreExpr) passed to occAnalAlt is the extra let-binding
1246 {x=b}; it's Nothing if the binder-swap doesn't happen.
1247
1248 There is a danger though.  Consider
1249       let v = x +# y
1250       in case (f v) of w -> ...v...v...
1251 And suppose that (f v) expands to just v.  Then we'd like to
1252 use 'w' instead of 'v' in the alternative.  But it may be too
1253 late; we may have substituted the (cheap) x+#y for v in the 
1254 same simplifier pass that reduced (f v) to v.
1255
1256 I think this is just too bad.  CSE will recover some of it.
1257
1258 Note [Case of cast]
1259 ~~~~~~~~~~~~~~~~~~~
1260 Consider        case (x `cast` co) of b { I# ->
1261                 ... (case (x `cast` co) of {...}) ...
1262 We'd like to eliminate the inner case.  That is the motivation for
1263 equation (2) in Note [Binder swap].  When we get to the inner case, we
1264 inline x, cancel the casts, and away we go.
1265
1266 Note [Binder swap on GlobalId scrutinees]
1267 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1268 When the scrutinee is a GlobalId we must take care in two ways
1269
1270  i) In order to *know* whether 'x' occurs free in the RHS, we need its
1271     occurrence info. BUT, we don't gather occurrence info for
1272     GlobalIds.  That's one use for the (small) occ_proxy env in OccEnv is
1273     for: it says "gather occurrence info for these.
1274
1275  ii) We must call localiseId on 'x' first, in case it's a GlobalId, or
1276      has an External Name. See, for example, SimplEnv Note [Global Ids in
1277      the substitution].
1278
1279 Note [getProxies is subtle]
1280 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1281 The code for getProxies isn't all that obvious. Consider
1282
1283   case v |> cov  of x { DEFAULT ->
1284   case x |> cox1 of y { DEFAULT ->
1285   case x |> cox2 of z { DEFAULT -> r
1286
1287 These will give us a ProxyEnv looking like:
1288   x |-> (x, [(y, cox1), (z, cox2)])
1289   v |-> (v, [(x, cov)])
1290
1291 From this we want to extract the bindings
1292     x = z |> sym cox2
1293     v = x |> sym cov
1294     y = x |> cox1
1295
1296 Notice that later bindings may mention earlier ones, and that
1297 we need to go "both ways".
1298
1299 Historical note [no-case-of-case]
1300 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1301 We *used* to suppress the binder-swap in case expressions when 
1302 -fno-case-of-case is on.  Old remarks:
1303     "This happens in the first simplifier pass,
1304     and enhances full laziness.  Here's the bad case:
1305             f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1306     If we eliminate the inner case, we trap it inside the I# v -> arm,
1307     which might prevent some full laziness happening.  I've seen this
1308     in action in spectral/cichelli/Prog.hs:
1309              [(m,n) | m <- [1..max], n <- [1..max]]
1310     Hence the check for NoCaseOfCase."
1311 However, now the full-laziness pass itself reverses the binder-swap, so this
1312 check is no longer necessary.
1313
1314 Historical note [Suppressing the case binder-swap]
1315 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1316 This old note describes a problem that is also fixed by doing the
1317 binder-swap in OccAnal:
1318
1319     There is another situation when it might make sense to suppress the
1320     case-expression binde-swap. If we have
1321
1322         case x of w1 { DEFAULT -> case x of w2 { A -> e1; B -> e2 }
1323                        ...other cases .... }
1324
1325     We'll perform the binder-swap for the outer case, giving
1326
1327         case x of w1 { DEFAULT -> case w1 of w2 { A -> e1; B -> e2 }
1328                        ...other cases .... }
1329
1330     But there is no point in doing it for the inner case, because w1 can't
1331     be inlined anyway.  Furthermore, doing the case-swapping involves
1332     zapping w2's occurrence info (see paragraphs that follow), and that
1333     forces us to bind w2 when doing case merging.  So we get
1334
1335         case x of w1 { A -> let w2 = w1 in e1
1336                        B -> let w2 = w1 in e2
1337                        ...other cases .... }
1338
1339     This is plain silly in the common case where w2 is dead.
1340
1341     Even so, I can't see a good way to implement this idea.  I tried
1342     not doing the binder-swap if the scrutinee was already evaluated
1343     but that failed big-time:
1344
1345             data T = MkT !Int
1346
1347             case v of w  { MkT x ->
1348             case x of x1 { I# y1 ->
1349             case x of x2 { I# y2 -> ...
1350
1351     Notice that because MkT is strict, x is marked "evaluated".  But to
1352     eliminate the last case, we must either make sure that x (as well as
1353     x1) has unfolding MkT y1.  THe straightforward thing to do is to do
1354     the binder-swap.  So this whole note is a no-op.
1355
1356 It's fixed by doing the binder-swap in OccAnal because we can do the
1357 binder-swap unconditionally and still get occurrence analysis
1358 information right.
1359
1360 \begin{code}
1361 extendProxyEnv :: ProxyEnv -> Id -> CoercionI -> Id -> ProxyEnv
1362 -- (extendPE x co y) typically arises from 
1363 --                case (x |> co) of y { ... }
1364 -- It extends the proxy env with the binding 
1365 --                     y = x |> co
1366 extendProxyEnv pe scrut co case_bndr
1367   | scrut == case_bndr = PE env1 fvs1   -- If case_bndr shadows scrut,
1368   | otherwise          = PE env2 fvs2   --   don't extend
1369   where
1370     PE env1 fvs1 = trimProxyEnv pe [case_bndr]
1371     env2 = extendVarEnv_C add env1 scrut1 (scrut1, [(case_bndr,co)])
1372     add (x, cb_cos) _ = (x, (case_bndr,co):cb_cos)
1373     fvs2 = fvs1 `unionVarSet`  freeVarsCoI co
1374                 `extendVarSet` case_bndr
1375                 `extendVarSet` scrut1
1376
1377     scrut1 = mkLocalId (localiseName (idName scrut)) (idType scrut)
1378         -- Localise the scrut_var before shadowing it; we're making a 
1379         -- new binding for it, and it might have an External Name, or
1380         -- even be a GlobalId; Note [Binder swap on GlobalId scrutinees]
1381         -- Also we don't want any INLILNE or NOINLINE pragmas!
1382
1383 -----------
1384 type ProxyBind = (Id, Id, CoercionI)
1385
1386 getProxies :: OccEnv -> Id -> Bag ProxyBind
1387 -- Return a bunch of bindings [...(xi,ei)...] 
1388 -- such that  let { ...; xi=ei; ... } binds the xi using y alone
1389 -- See Note [getProxies is subtle]
1390 getProxies (OccEnv { occ_proxy = PE pe _ }) case_bndr
1391   = -- pprTrace "wrapProxies" (ppr case_bndr) $
1392     go_fwd case_bndr
1393   where
1394     fwd_pe :: IdEnv (Id, CoercionI)
1395     fwd_pe = foldVarEnv add1 emptyVarEnv pe
1396            where
1397              add1 (x,ycos) env = foldr (add2 x) env ycos
1398              add2 x (y,co) env = extendVarEnv env y (x,co)
1399
1400     go_fwd :: Id -> Bag ProxyBind
1401         -- Return bindings derivable from case_bndr
1402     go_fwd case_bndr = -- pprTrace "go_fwd" (vcat [ppr case_bndr, text "fwd_pe =" <+> ppr fwd_pe, 
1403                        --                         text "pe =" <+> ppr pe]) $ 
1404                        go_fwd' case_bndr
1405
1406     go_fwd' case_bndr
1407         | Just (scrut, co) <- lookupVarEnv fwd_pe case_bndr
1408         = unitBag (scrut,  case_bndr, mkSymCoI co)
1409           `unionBags` go_fwd scrut
1410           `unionBags` go_bwd scrut [pr | pr@(cb,_) <- lookup_bwd scrut
1411                                        , cb /= case_bndr]
1412         | otherwise 
1413         = emptyBag
1414
1415     lookup_bwd :: Id -> [(Id, CoercionI)]
1416         -- Return case_bndrs that are connected to scrut 
1417     lookup_bwd scrut = case lookupVarEnv pe scrut of
1418                           Nothing          -> []
1419                           Just (_, cb_cos) -> cb_cos
1420
1421     go_bwd :: Id -> [(Id, CoercionI)] -> Bag ProxyBind
1422     go_bwd scrut cb_cos = foldr (unionBags . go_bwd1 scrut) emptyBag cb_cos
1423
1424     go_bwd1 :: Id -> (Id, CoercionI) -> Bag ProxyBind
1425     go_bwd1 scrut (case_bndr, co) 
1426        = -- pprTrace "go_bwd1" (ppr case_bndr) $
1427          unitBag (case_bndr, scrut, co)
1428          `unionBags` go_bwd case_bndr (lookup_bwd case_bndr)
1429
1430 -----------
1431 mkAltEnv :: OccEnv -> CoreExpr -> Id -> OccEnv
1432 -- Does two things: a) makes the occ_ctxt = OccVanilla
1433 --                  b) extends the ProxyEnv if possible
1434 mkAltEnv env scrut cb
1435   = env { occ_encl  = OccVanilla, occ_proxy = pe' }
1436   where
1437     pe  = occ_proxy env
1438     pe' = case scrut of
1439              Var v           -> extendProxyEnv pe v IdCo     cb
1440              Cast (Var v) co -> extendProxyEnv pe v (ACo co) cb
1441              _other          -> trimProxyEnv pe [cb]
1442
1443 -----------
1444 trimOccEnv :: OccEnv -> [CoreBndr] -> OccEnv
1445 trimOccEnv env bndrs = env { occ_proxy = trimProxyEnv (occ_proxy env) bndrs }
1446
1447 -----------
1448 trimProxyEnv :: ProxyEnv -> [CoreBndr] -> ProxyEnv
1449 -- We are about to push this ProxyEnv inside a binding for 'bndrs'
1450 -- So dump any ProxyEnv bindings which mention any of the bndrs
1451 trimProxyEnv (PE pe fvs) bndrs 
1452   | not (bndr_set `intersectsVarSet` fvs) 
1453   = PE pe fvs
1454   | otherwise
1455   = PE pe' (fvs `minusVarSet` bndr_set)
1456   where
1457     pe' = mapVarEnv trim pe
1458     bndr_set = mkVarSet bndrs
1459     trim (scrut, cb_cos) | scrut `elemVarSet` bndr_set = (scrut, [])
1460                          | otherwise = (scrut, filterOut discard cb_cos)
1461     discard (cb,co) = bndr_set `intersectsVarSet` 
1462                       extendVarSet (freeVarsCoI co) cb
1463                              
1464 -----------
1465 freeVarsCoI :: CoercionI -> VarSet
1466 freeVarsCoI IdCo     = emptyVarSet
1467 freeVarsCoI (ACo co) = tyVarsOfType co
1468 \end{code}
1469
1470
1471 %************************************************************************
1472 %*                                                                      *
1473 \subsection[OccurAnal-types]{OccEnv}
1474 %*                                                                      *
1475 %************************************************************************
1476
1477 \begin{code}
1478 type UsageDetails = IdEnv OccInfo       -- A finite map from ids to their usage
1479                 -- INVARIANT: never IAmDead
1480                 -- (Deadness is signalled by not being in the map at all)
1481
1482 (+++), combineAltsUsageDetails
1483         :: UsageDetails -> UsageDetails -> UsageDetails
1484
1485 (+++) usage1 usage2
1486   = plusVarEnv_C addOccInfo usage1 usage2
1487
1488 combineAltsUsageDetails usage1 usage2
1489   = plusVarEnv_C orOccInfo usage1 usage2
1490
1491 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
1492 addOneOcc usage id info
1493   = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
1494         -- ToDo: make this more efficient
1495
1496 emptyDetails :: UsageDetails
1497 emptyDetails = (emptyVarEnv :: UsageDetails)
1498
1499 localUsedIn, usedIn :: Id -> UsageDetails -> Bool
1500 v `localUsedIn` details = v `elemVarEnv` details
1501 v `usedIn`      details =  isExportedId v || v `localUsedIn` details
1502
1503 type IdWithOccInfo = Id
1504
1505 tagLamBinders :: UsageDetails          -- Of scope
1506               -> [Id]                  -- Binders
1507               -> (UsageDetails,        -- Details with binders removed
1508                  [IdWithOccInfo])    -- Tagged binders
1509 -- Used for lambda and case binders
1510 -- It copes with the fact that lambda bindings can have InlineRule 
1511 -- unfoldings, used for join points
1512 tagLamBinders usage binders = usage' `seq` (usage', bndrs')
1513   where
1514     (usage', bndrs') = mapAccumR tag_lam usage binders
1515     tag_lam usage bndr = (usage2, setBinderOcc usage bndr)
1516       where
1517         usage1 = usage `delVarEnv` bndr
1518         usage2 | isId bndr = addIdOccs usage1 (idUnfoldingVars bndr)
1519                | otherwise = usage1
1520
1521 tagBinder :: UsageDetails           -- Of scope
1522           -> Id                     -- Binders
1523           -> (UsageDetails,         -- Details with binders removed
1524               IdWithOccInfo)        -- Tagged binders
1525
1526 tagBinder usage binder
1527  = let
1528      usage'  = usage `delVarEnv` binder
1529      binder' = setBinderOcc usage binder
1530    in
1531    usage' `seq` (usage', binder')
1532
1533 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
1534 setBinderOcc usage bndr
1535   | isTyVar bndr      = bndr
1536   | isExportedId bndr = case idOccInfo bndr of
1537                           NoOccInfo -> bndr
1538                           _         -> setIdOccInfo bndr NoOccInfo
1539             -- Don't use local usage info for visible-elsewhere things
1540             -- BUT *do* erase any IAmALoopBreaker annotation, because we're
1541             -- about to re-generate it and it shouldn't be "sticky"
1542
1543   | otherwise = setIdOccInfo bndr occ_info
1544   where
1545     occ_info = lookupVarEnv usage bndr `orElse` IAmDead
1546 \end{code}
1547
1548
1549 %************************************************************************
1550 %*                                                                      *
1551 \subsection{Operations over OccInfo}
1552 %*                                                                      *
1553 %************************************************************************
1554
1555 \begin{code}
1556 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
1557 mkOneOcc env id int_cxt
1558   | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
1559   | PE env _ <- occ_proxy env
1560   , id `elemVarEnv` env = unitVarEnv id NoOccInfo
1561   | otherwise           = emptyDetails
1562
1563 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
1564
1565 markMany _  = NoOccInfo
1566
1567 markInsideSCC occ = markMany occ
1568
1569 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
1570 markInsideLam occ                       = occ
1571
1572 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
1573
1574 addOccInfo a1 a2  = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
1575                     NoOccInfo   -- Both branches are at least One
1576                                 -- (Argument is never IAmDead)
1577
1578 -- (orOccInfo orig new) is used
1579 -- when combining occurrence info from branches of a case
1580
1581 orOccInfo (OneOcc in_lam1 _ int_cxt1)
1582           (OneOcc in_lam2 _ int_cxt2)
1583   = OneOcc (in_lam1 || in_lam2)
1584            False        -- False, because it occurs in both branches
1585            (int_cxt1 && int_cxt2)
1586 orOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
1587                   NoOccInfo
1588 \end{code}