Wibble to the OccurAnal fix for RULEs and loop-breakers
[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 {-# OPTIONS -w #-}
15 -- The above warning supression flag is a temporary kludge.
16 -- While working on this module you are encouraged to remove it and fix
17 -- any warnings in the module. See
18 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
19 -- for details
20
21 module OccurAnal (
22         occurAnalysePgm, occurAnalyseExpr
23     ) where
24
25 #include "HsVersions.h"
26
27 import CoreSyn
28 import CoreFVs
29 import CoreUtils        ( exprIsTrivial, isDefaultAlt )
30 import Id
31 import IdInfo
32 import BasicTypes       ( OccInfo(..), isOneOcc, InterestingCxt )
33
34 import VarSet
35 import VarEnv
36
37 import Maybes           ( orElse )
38 import Digraph          ( stronglyConnCompR, SCC(..) )
39 import PrelNames        ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
40 import Unique           ( Unique )
41 import UniqFM           ( keysUFM, intersectsUFM, intersectUFM_C, foldUFM_Directly )  
42 import Util             ( mapAndUnzip )
43 import Outputable
44
45 import Data.List
46 \end{code}
47
48
49 %************************************************************************
50 %*                                                                      *
51 \subsection[OccurAnal-main]{Counting occurrences: main function}
52 %*                                                                      *
53 %************************************************************************
54
55 Here's the externally-callable interface:
56
57 \begin{code}
58 occurAnalysePgm :: [CoreBind] -> [CoreBind]
59 occurAnalysePgm binds
60   = snd (go initOccEnv binds)
61   where
62     go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
63     go env [] 
64         = (emptyDetails, [])
65     go env (bind:binds) 
66         = (final_usage, bind' ++ binds')
67         where
68            (bs_usage, binds')   = go env binds
69            (final_usage, bind') = occAnalBind env bind bs_usage
70
71 occurAnalyseExpr :: CoreExpr -> CoreExpr
72         -- Do occurrence analysis, and discard occurence info returned
73 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
74 \end{code}
75
76
77 %************************************************************************
78 %*                                                                      *
79 \subsection[OccurAnal-main]{Counting occurrences: main function}
80 %*                                                                      *
81 %************************************************************************
82
83 Bindings
84 ~~~~~~~~
85
86 \begin{code}
87 occAnalBind :: OccEnv
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   | not (binder `usedIn` body_usage)            -- It's not mentioned
95   = (body_usage, [])
96
97   | otherwise                   -- It's mentioned in the body
98   = (body_usage' +++ addRuleUsage rhs_usage binder,     -- Note [Rules are extra RHSs]
99      [NonRec tagged_binder rhs'])
100   where
101     (body_usage', tagged_binder) = tagBinder body_usage binder
102     (rhs_usage, rhs')            = occAnalRhs env tagged_binder rhs
103 \end{code}
104
105 Note [Dead code]
106 ~~~~~~~~~~~~~~~~
107 Dropping dead code for recursive bindings is done in a very simple way:
108
109         the entire set of bindings is dropped if none of its binders are
110         mentioned in its body; otherwise none are.
111
112 This seems to miss an obvious improvement.
113
114         letrec  f = ...g...
115                 g = ...f...
116         in
117         ...g...
118 ===>
119         letrec f = ...g...
120                g = ...(...g...)...
121         in
122         ...g...
123
124 Now 'f' is unused! But it's OK!  Dependency analysis will sort this
125 out into a letrec for 'g' and a 'let' for 'f', and then 'f' will get
126 dropped.  It isn't easy to do a perfect job in one blow.  Consider
127
128         letrec f = ...g...
129                g = ...h...
130                h = ...k...
131                k = ...m...
132                m = ...m...
133         in
134         ...m...
135
136
137 Note [Loop breaking and RULES]
138 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
139 Loop breaking is surprisingly subtle.  First read the section 4 of 
140 "Secrets of the GHC inliner".  This describes our basic plan.
141
142 However things are made quite a bit more complicated by RULES.  Remember
143
144   * Note [Rules are extra RHSs]
145     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
146     A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
147     keeps the specialised "children" alive.  If the parent dies
148     (because it isn't referenced any more), then the children will die
149     too (unless they are already referenced directly).
150
151     To that end, we build a Rec group for each cyclic strongly
152     connected component,
153         *treating f's rules as extra RHSs for 'f'*.
154
155     When we make the Rec groups we include variables free in *either*
156     LHS *or* RHS of the rule.  The former might seems silly, but see
157     Note [Rule dependency info].
158  
159     So in Example [eftInt], eftInt and eftIntFB will be put in the
160     same Rec, even though their 'main' RHSs are both non-recursive.
161
162   * Note [Rules are visible in their own rec group]
163     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
164     We want the rules for 'f' to be visible in f's right-hand side.
165     And we'd like them to be visible in other functions in f's Rec
166     group.  E.g. in Example [Specialisation rules] we want f' rule
167     to be visible in both f's RHS, and fs's RHS.
168
169     This means that we must simplify the RULEs first, before looking
170     at any of the definitions.  This is done by Simplify.simplRecBind,
171     when it calls addLetIdInfo.
172
173   * Note [Choosing loop breakers]
174     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
175     We avoid infinite inlinings by choosing loop breakers, and
176     ensuring that a loop breaker cuts each loop.  But what is a
177     "loop"?  In particular, a RULES is like an equation for 'f' that
178     is *always* inlined if it are applicable.  We do *not* disable
179     rules for loop-breakers.  It's up to whoever makes the rules to
180     make sure that the rules themselves alwasys terminate.  See Note
181     [Rules for recursive functions] in Simplify.lhs
182
183     Hence, if 
184         f's RHS mentions g, and
185         g has a RULE that mentions h, and
186         h has a RULE that mentions f
187
188     then we *must* choose f to be a loop breaker.  In general, take the
189     free variables of f's RHS, and augment it with all the variables
190     reachable by RULES from those starting points.  That is the whole
191     reason for computing rule_fv_env in occAnalBind.  (Of course we
192     only consider free vars that are also binders in this Rec group.)
193
194     Note that when we compute this rule_fv_env, we only consider variables
195     free in the *RHS* of the rule, in contrast to the way we build the 
196     Rec group in the first place (Note [Rule dependency info])
197
198     Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
199     chosen as a loop breaker, because their RHSs don't mention each other.
200     And indeed both can be inlined safely.
201
202     Note that the edges of the graph we use for computing loop breakers
203     are not the same as the edges we use for computing the Rec blocks.
204     That's why we compute 
205         rec_edges          for the Rec block analysis
206         loop_breaker_edges for the loop breaker analysis
207
208
209   * Note [Weak loop breakers]
210     ~~~~~~~~~~~~~~~~~~~~~~~~~
211     There is a last nasty wrinkle.  Suppose we have
212
213         Rec { f = f_rhs
214               RULE f [] = g
215             
216               h = h_rhs
217               g = h 
218               ...more...
219         }
220
221     Remmber that we simplify the RULES before any RHS (see Note
222     [Rules are visible in their own rec group] above).
223
224     So we must *not* postInlineUnconditionally 'g', even though
225     its RHS turns out to be trivial.  (I'm assuming that 'g' is
226     not choosen as a loop breaker.)
227
228     We "solve" this by making g a "weak" or "rules-only" loop breaker,
229     with OccInfo = IAmLoopBreaker True.  A normal "strong" loop breaker
230     has IAmLoopBreaker False.  So
231
232                                 Inline  postInlineUnconditinoally
233         IAmLoopBreaker False    no      no
234         IAmLoopBreaker True     yes     no
235         other                   yes     yes
236
237     The **sole** reason for this kind of loop breaker is so that
238     postInlineUnconditionally does not fire.  Ugh.
239
240   * Note [Rule dependency info]
241     ~~~~~~~~~~~~~~~~~~~~~~~~~~~
242     The VarSet in a SpecInfo is used for dependency analysis in the 
243     occurrence analyser.  We must track free vars in *both* lhs and rhs.  Why both?  
244     Consider
245         x = y
246         RULE f x = 4
247     Then if we substitute y for x, we'd better do so in the
248     rule's LHS too, so we'd better ensure the dependency is respected
249
250
251 Example [eftInt]
252 ~~~~~~~~~~~~~~~
253 Example (from GHC.Enum):
254
255   eftInt :: Int# -> Int# -> [Int]
256   eftInt x y = ...(non-recursive)...
257
258   {-# INLINE [0] eftIntFB #-}
259   eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
260   eftIntFB c n x y = ...(non-recursive)...
261
262   {-# RULES
263   "eftInt"  [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
264   "eftIntList"  [1] eftIntFB  (:) [] = eftInt
265    #-}
266
267 Example [Specialisation rules]
268 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
269 Consider this group, which is typical of what SpecConstr builds:
270
271    fs a = ....f (C a)....
272    f  x = ....f (C a)....
273    {-# RULE f (C a) = fs a #-}
274
275 So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
276
277 But watch out!  If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
278         - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
279         - fs is inlined (say it's small)
280         - now there's another opportunity to apply the RULE
281
282 This showed up when compiling Control.Concurrent.Chan.getChanContents.
283
284
285 \begin{code}
286 occAnalBind env (Rec pairs) body_usage
287   | not (any (`usedIn` body_usage) bndrs)       -- NB: look at body_usage, not total_usage
288   = (body_usage, [])                            -- Dead code
289   | otherwise
290   = (final_usage, map ({-# SCC "occAnalBind.dofinal" #-} do_final_bind) sccs)
291   where
292     bndrs    = map fst pairs
293     bndr_set = mkVarSet bndrs
294
295         ---------------------------------------
296         -- See Note [Loop breaking]
297         ---------------------------------------
298
299     -------------Dependency analysis ------------------------------
300     occ_anald :: [(Id, (UsageDetails, CoreExpr))]
301         -- The UsageDetails here are strictly those arising from the RHS
302         -- *not* from any rules in the Id
303     occ_anald = [(bndr, occAnalRhs env bndr rhs) | (bndr,rhs) <- pairs]
304
305     total_usage        = foldl add_usage body_usage occ_anald
306     add_usage body_usage (bndr, (rhs_usage, _))
307         = body_usage +++ addRuleUsage rhs_usage bndr
308
309     (final_usage, tagged_bndrs) = tagBinders total_usage bndrs
310     final_bndrs | isEmptyVarSet all_rule_fvs = tagged_bndrs
311                 | otherwise = map tag_rule_var tagged_bndrs
312                 
313     tag_rule_var bndr | bndr `elemVarSet` all_rule_fvs = makeLoopBreaker True bndr
314                       | otherwise                      = bndr
315     all_rule_fvs = bndr_set `intersectVarSet` foldr (unionVarSet . idRuleVars) emptyVarSet bndrs
316         -- Mark the binder with OccInfo saying "no preInlineUnconditionally" if
317         -- it is used in any rule (lhs or rhs) of the recursive group
318
319     ---- stuff for dependency analysis of binds -------------------------------
320     sccs :: [SCC (Node Details)]
321     sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompR rec_edges
322
323     rec_edges :: [Node Details] -- The binders are tagged with correct occ-info
324     rec_edges = {-# SCC "occAnalBind.assoc" #-} zipWith make_node final_bndrs occ_anald
325     make_node tagged_bndr (_bndr, (rhs_usage, rhs))
326         = ((tagged_bndr, rhs, rhs_fvs), idUnique tagged_bndr, out_edges)
327         where
328           rhs_fvs = intersectUFM_C (\b _ -> b) bndr_set rhs_usage
329           out_edges = keysUFM (rhs_fvs `unionVarSet` idRuleVars tagged_bndr)
330         
331
332         -- (a -> b) means a mentions b
333         -- Given the usage details (a UFM that gives occ info for each free var of
334         -- the RHS) we can get the list of free vars -- or rather their Int keys --
335         -- by just extracting the keys from the finite map.  Grimy, but fast.
336         -- Previously we had this:
337         --      [ bndr | bndr <- bndrs,
338         --               maybeToBool (lookupVarEnv rhs_usage bndr)]
339         -- which has n**2 cost, and this meant that edges_from alone 
340         -- consumed 10% of total runtime!
341
342     ---- Stuff to "re-constitute" bindings from dependency-analysis info ------
343     do_final_bind (AcyclicSCC ((bndr, rhs, _), _, _)) = NonRec bndr rhs
344     do_final_bind (CyclicSCC cycle)
345         | no_rules  = Rec (reOrderCycle cycle)
346         | otherwise = Rec (concatMap reOrderRec (stronglyConnCompR loop_breaker_edges))
347         where   -- See Note [Choosing loop breakers] for looop_breker_edges
348           loop_breaker_edges = map mk_node cycle
349           mk_node (details@(bndr, rhs, rhs_fvs), k, _) = (details, k, new_ks)
350                 where
351                   new_ks = keysUFM (extendFvs rule_fv_env rhs_fvs rhs_fvs)
352
353         
354     ------------------------------------
355     rule_fv_env :: IdEnv IdSet  -- Variables from this group mentioned in RHS of rules
356                                 -- Domain is *subset* of bound vars (others have no rule fvs)
357     rule_fv_env = rule_loop init_rule_fvs
358
359     no_rules      = null init_rule_fvs
360     init_rule_fvs = [(b, rule_fvs)
361                     | b <- bndrs 
362                     , let rule_fvs = idRuleRhsVars b `intersectVarSet` bndr_set
363                     , not (isEmptyVarSet rule_fvs)]
364
365     rule_loop :: [(Id,IdSet)] -> IdEnv IdSet    -- Finds fixpoint
366     rule_loop fv_list 
367         | no_change = env
368         | otherwise = rule_loop new_fv_list
369         where
370           env = mkVarEnv init_rule_fvs
371           (no_change, new_fv_list) = mapAccumL bump True fv_list
372           bump no_change (b,fvs) 
373                 | new_fvs `subVarSet` fvs = (no_change, (b,fvs))
374                 | otherwise               = (False,     (b,new_fvs `unionVarSet` fvs))
375                 where
376                   new_fvs = extendFvs env emptyVarSet fvs
377
378 idRuleRhsVars :: Id -> VarSet
379 -- Just the variables free on the *rhs* of a rule
380 -- See Note [Choosing loop breakers]
381 idRuleRhsVars id = foldr (unionVarSet . ruleRhsFreeVars) emptyVarSet (idCoreRules id)
382
383 extendFvs :: IdEnv IdSet -> IdSet -> IdSet -> IdSet
384 -- (extendFVs env fvs s) returns (fvs `union` env(s))
385 extendFvs env fvs id_set
386   = foldUFM_Directly add fvs id_set
387   where
388     add uniq _ fvs 
389         = case lookupVarEnv_Directly env uniq  of
390             Just fvs' -> fvs' `unionVarSet` fvs
391             Nothing   -> fvs
392 \end{code}
393
394 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
395 strongly connected component (there's guaranteed to be a cycle).  It returns the
396 same pairs, but 
397         a) in a better order,
398         b) with some of the Ids having a IAmALoopBreaker pragma
399
400 The "loop-breaker" Ids are sufficient to break all cycles in the SCC.  This means
401 that the simplifier can guarantee not to loop provided it never records an inlining
402 for these no-inline guys.
403
404 Furthermore, the order of the binds is such that if we neglect dependencies
405 on the no-inline Ids then the binds are topologically sorted.  This means
406 that the simplifier will generally do a good job if it works from top bottom,
407 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
408
409 ==============
410 [June 98: I don't understand the following paragraphs, and I've 
411           changed the a=b case again so that it isn't a special case any more.]
412
413 Here's a case that bit me:
414
415         letrec
416                 a = b
417                 b = \x. BIG
418         in
419         ...a...a...a....
420
421 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
422
423 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
424 Perhaps something cleverer would suffice.
425 ===============
426
427
428 \begin{code}
429 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
430                                                 -- which is gotten from the Id.
431 type Details = (Id,             -- Binder
432                 CoreExpr,       -- RHS
433                 IdSet)          -- RHS free vars (*not* include rules)
434
435 reOrderRec :: SCC (Node Details)
436            -> [(Id,CoreExpr)]
437 -- Sorted into a plausible order.  Enough of the Ids have
438 --      IAmALoopBreaker pragmas that there are no loops left.
439 reOrderRec (AcyclicSCC ((bndr, rhs, _), _, _)) = [(bndr, rhs)]
440 reOrderRec (CyclicSCC cycle)                   = reOrderCycle cycle
441
442 reOrderCycle :: [Node Details] -> [(Id,CoreExpr)]
443 reOrderCycle []
444   = panic "reOrderCycle"
445 reOrderCycle [bind]     -- Common case of simple self-recursion
446   = [(makeLoopBreaker False bndr, rhs)]
447   where
448     ((bndr, rhs, _), _, _) = bind
449
450 reOrderCycle (bind : binds)
451   =     -- Choose a loop breaker, mark it no-inline,
452         -- do SCC analysis on the rest, and recursively sort them out
453     concatMap reOrderRec (stronglyConnCompR unchosen) ++
454     [(makeLoopBreaker False bndr, rhs)]
455
456   where
457     (chosen_bind, unchosen) = choose_loop_breaker bind (score bind) [] binds
458     (bndr, rhs, _)  = chosen_bind
459
460         -- This loop looks for the bind with the lowest score
461         -- to pick as the loop  breaker.  The rest accumulate in 
462     choose_loop_breaker (details,_,_) loop_sc acc []
463         = (details, acc)        -- Done
464
465     choose_loop_breaker loop_bind loop_sc acc (bind : binds)
466         | sc < loop_sc  -- Lower score so pick this new one
467         = choose_loop_breaker bind sc (loop_bind : acc) binds
468
469         | otherwise     -- No lower so don't pick it
470         = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
471         where
472           sc = score bind
473           
474     score :: Node Details -> Int        -- Higher score => less likely to be picked as loop breaker
475     score ((bndr, rhs, _), _, _)
476         | workerExists (idWorkerInfo bndr)      = 10
477                 -- Note [Worker inline loop]
478
479         | exprIsTrivial rhs        = 4  -- Practically certain to be inlined
480                 -- Used to have also: && not (isExportedId bndr)
481                 -- But I found this sometimes cost an extra iteration when we have
482                 --      rec { d = (a,b); a = ...df...; b = ...df...; df = d }
483                 -- where df is the exported dictionary. Then df makes a really
484                 -- bad choice for loop breaker
485           
486         | is_con_app rhs = 2    -- Data types help with cases
487                 -- Note [conapp]
488
489         | inlineCandidate bndr rhs = 1  -- Likely to be inlined
490                 -- Note [Inline candidates]
491
492         | otherwise = 0
493
494     inlineCandidate :: Id -> CoreExpr -> Bool
495     inlineCandidate id (Note InlineMe _) = True
496     inlineCandidate id rhs               = isOneOcc (idOccInfo id)
497
498         -- Note [conapp]
499         --
500         -- It's really really important to inline dictionaries.  Real
501         -- example (the Enum Ordering instance from GHC.Base):
502         --
503         --      rec     f = \ x -> case d of (p,q,r) -> p x
504         --              g = \ x -> case d of (p,q,r) -> q x
505         --              d = (v, f, g)
506         --
507         -- Here, f and g occur just once; but we can't inline them into d.
508         -- On the other hand we *could* simplify those case expressions if
509         -- we didn't stupidly choose d as the loop breaker.
510         -- But we won't because constructor args are marked "Many".
511         -- Inlining dictionaries is really essential to unravelling
512         -- the loops in static numeric dictionaries, see GHC.Float.
513
514         -- Cheap and cheerful; the simplifer moves casts out of the way
515         -- The lambda case is important to spot x = /\a. C (f a)
516         -- which comes up when C is a dictionary constructor and
517         -- f is a default method.  
518         -- Example: the instance for Show (ST s a) in GHC.ST
519         --
520         -- However we *also* treat (\x. C p q) as a con-app-like thing, 
521         --      Note [Closure conversion]
522     is_con_app (Var v)    = isDataConWorkId v
523     is_con_app (App f _)  = is_con_app f
524     is_con_app (Lam b e)  = is_con_app e
525     is_con_app (Note _ e) = is_con_app e
526     is_con_app other      = False
527
528 makeLoopBreaker :: Bool -> Id -> Id
529 -- Set the loop-breaker flag
530 -- See Note [Weak loop breakers]
531 makeLoopBreaker weak bndr = setIdOccInfo bndr (IAmALoopBreaker weak)
532 \end{code}
533
534 Note [Worker inline loop]
535 ~~~~~~~~~~~~~~~~~~~~~~~~
536 Never choose a wrapper as the loop breaker!  Because
537 wrappers get auto-generated inlinings when importing, and
538 that can lead to an infinite inlining loop.  For example:
539   rec {
540         $wfoo x = ....foo x....
541         
542         {-loop brk-} foo x = ...$wfoo x...
543   }
544
545 The interface file sees the unfolding for $wfoo, and sees that foo is
546 strict (and hence it gets an auto-generated wrapper).  Result: an
547 infinite inlining in the importing scope.  So be a bit careful if you
548 change this.  A good example is Tree.repTree in
549 nofib/spectral/minimax. If the repTree wrapper is chosen as the loop
550 breaker then compiling Game.hs goes into an infinite loop (this
551 happened when we gave is_con_app a lower score than inline candidates).
552
553 Note [Closure conversion]
554 ~~~~~~~~~~~~~~~~~~~~~~~~~
555 We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
556 The immediate motivation came from the result of a closure-conversion transformation
557 which generated code like this:
558
559     data Clo a b = forall c. Clo (c -> a -> b) c
560
561     ($:) :: Clo a b -> a -> b
562     Clo f env $: x = f env x
563
564     rec { plus = Clo plus1 ()
565
566         ; plus1 _ n = Clo plus2 n
567
568         ; plus2 Zero     n = n
569         ; plus2 (Succ m) n = Succ (plus $: m $: n) }
570
571 If we inline 'plus' and 'plus1', everything unravels nicely.  But if
572 we choose 'plus1' as the loop breaker (which is entirely possible
573 otherwise), the loop does not unravel nicely.
574
575
576 @occAnalRhs@ deals with the question of bindings where the Id is marked
577 by an INLINE pragma.  For these we record that anything which occurs
578 in its RHS occurs many times.  This pessimistically assumes that ths
579 inlined binder also occurs many times in its scope, but if it doesn't
580 we'll catch it next time round.  At worst this costs an extra simplifier pass.
581 ToDo: try using the occurrence info for the inline'd binder.
582
583 [March 97] We do the same for atomic RHSs.  Reason: see notes with reOrderRec.
584 [June 98, SLPJ]  I've undone this change; I don't understand it.  See notes with reOrderRec.
585
586
587 \begin{code}
588 occAnalRhs :: OccEnv
589            -> Id -> CoreExpr    -- Binder and rhs
590                                 -- For non-recs the binder is alrady tagged
591                                 -- with occurrence info
592            -> (UsageDetails, CoreExpr)
593
594 occAnalRhs env id rhs
595   = occAnal ctxt rhs
596   where
597     ctxt | certainly_inline id = env
598          | otherwise           = rhsCtxt
599         -- Note that we generally use an rhsCtxt.  This tells the occ anal n
600         -- that it's looking at an RHS, which has an effect in occAnalApp
601         --
602         -- But there's a problem.  Consider
603         --      x1 = a0 : []
604         --      x2 = a1 : x1
605         --      x3 = a2 : x2
606         --      g  = f x3
607         -- First time round, it looks as if x1 and x2 occur as an arg of a 
608         -- let-bound constructor ==> give them a many-occurrence.
609         -- But then x3 is inlined (unconditionally as it happens) and
610         -- next time round, x2 will be, and the next time round x1 will be
611         -- Result: multiple simplifier iterations.  Sigh.  
612         -- Crude solution: use rhsCtxt for things that occur just once...
613
614     certainly_inline id = case idOccInfo id of
615                             OneOcc in_lam one_br _ -> not in_lam && one_br
616                             other                  -> False
617 \end{code}
618
619
620
621 \begin{code}
622 addRuleUsage :: UsageDetails -> Id -> UsageDetails
623 -- Add the usage from RULES in Id to the usage
624 addRuleUsage usage id
625   = foldVarSet add usage (idRuleVars id)
626   where
627     add v u = addOneOcc u v NoOccInfo           -- Give a non-committal binder info
628                                                 -- (i.e manyOcc) because many copies
629                                                 -- of the specialised thing can appear
630 \end{code}
631
632 Expressions
633 ~~~~~~~~~~~
634 \begin{code}
635 occAnal :: OccEnv
636         -> CoreExpr
637         -> (UsageDetails,       -- Gives info only about the "interesting" Ids
638             CoreExpr)
639
640 occAnal env (Type t)  = (emptyDetails, Type t)
641 occAnal env (Var v)   = (mkOneOcc env v False, Var v)
642     -- At one stage, I gathered the idRuleVars for v here too,
643     -- which in a way is the right thing to do.
644     -- Btu that went wrong right after specialisation, when
645     -- the *occurrences* of the overloaded function didn't have any
646     -- rules in them, so the *specialised* versions looked as if they
647     -- weren't used at all.
648 \end{code}
649
650 We regard variables that occur as constructor arguments as "dangerousToDup":
651
652 \begin{verbatim}
653 module A where
654 f x = let y = expensive x in 
655       let z = (True,y) in 
656       (case z of {(p,q)->q}, case z of {(p,q)->q})
657 \end{verbatim}
658
659 We feel free to duplicate the WHNF (True,y), but that means
660 that y may be duplicated thereby.
661
662 If we aren't careful we duplicate the (expensive x) call!
663 Constructors are rather like lambdas in this way.
664
665 \begin{code}
666 occAnal env expr@(Lit lit) = (emptyDetails, expr)
667 \end{code}
668
669 \begin{code}
670 occAnal env (Note InlineMe body)
671   = case occAnal env body of { (usage, body') -> 
672     (mapVarEnv markMany usage, Note InlineMe body')
673     }
674
675 occAnal env (Note note@(SCC cc) body)
676   = case occAnal env body of { (usage, body') ->
677     (mapVarEnv markInsideSCC usage, Note note body')
678     }
679
680 occAnal env (Note note body)
681   = case occAnal env body of { (usage, body') ->
682     (usage, Note note body')
683     }
684
685 occAnal env (Cast expr co)
686   = case occAnal env expr of { (usage, expr') ->
687     (markRhsUds env True usage, Cast expr' co)
688         -- If we see let x = y `cast` co
689         -- then mark y as 'Many' so that we don't
690         -- immediately inline y again. 
691     }
692 \end{code}
693
694 \begin{code}
695 occAnal env app@(App fun arg)
696   = occAnalApp env (collectArgs app) False
697
698 -- Ignore type variables altogether
699 --   (a) occurrences inside type lambdas only not marked as InsideLam
700 --   (b) type variables not in environment
701
702 occAnal env expr@(Lam x body) | isTyVar x
703   = case occAnal env body of { (body_usage, body') ->
704     (body_usage, Lam x body')
705     }
706
707 -- For value lambdas we do a special hack.  Consider
708 --      (\x. \y. ...x...)
709 -- If we did nothing, x is used inside the \y, so would be marked
710 -- as dangerous to dup.  But in the common case where the abstraction
711 -- is applied to two arguments this is over-pessimistic.
712 -- So instead, we just mark each binder with its occurrence
713 -- info in the *body* of the multiple lambda.
714 -- Then, the simplifier is careful when partially applying lambdas.
715
716 occAnal env expr@(Lam _ _)
717   = case occAnal env_body body of { (body_usage, body') ->
718     let
719         (final_usage, tagged_binders) = tagBinders body_usage binders
720         --      URGH!  Sept 99: we don't seem to be able to use binders' here, because
721         --      we get linear-typed things in the resulting program that we can't handle yet.
722         --      (e.g. PrelShow)  TODO 
723
724         really_final_usage = if linear then
725                                 final_usage
726                              else
727                                 mapVarEnv markInsideLam final_usage
728     in
729     (really_final_usage,
730      mkLams tagged_binders body') }
731   where
732     env_body        = vanillaCtxt                       -- Body is (no longer) an RhsContext
733     (binders, body) = collectBinders expr
734     binders'        = oneShotGroup env binders
735     linear          = all is_one_shot binders'
736     is_one_shot b   = isId b && isOneShotBndr b
737
738 occAnal env (Case scrut bndr ty alts)
739   = case occ_anal_scrut scrut alts                  of { (scrut_usage, scrut') ->
740     case mapAndUnzip (occAnalAlt alt_env bndr) alts of { (alts_usage_s, alts')   -> 
741     let
742         alts_usage  = foldr1 combineAltsUsageDetails alts_usage_s
743         alts_usage' = addCaseBndrUsage alts_usage
744         (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
745         total_usage = scrut_usage +++ alts_usage1
746     in
747     total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
748   where
749         -- The case binder gets a usage of either "many" or "dead", never "one".
750         -- Reason: we like to inline single occurrences, to eliminate a binding,
751         -- but inlining a case binder *doesn't* eliminate a binding.
752         -- We *don't* want to transform
753         --      case x of w { (p,q) -> f w }
754         -- into
755         --      case x of w { (p,q) -> f (p,q) }
756     addCaseBndrUsage usage = case lookupVarEnv usage bndr of
757                                 Nothing  -> usage
758                                 Just occ -> extendVarEnv usage bndr (markMany occ)
759
760     alt_env = setVanillaCtxt env
761         -- Consider     x = case v of { True -> (p,q); ... }
762         -- Then it's fine to inline p and q
763
764     occ_anal_scrut (Var v) (alt1 : other_alts)
765                                 | not (null other_alts) || not (isDefaultAlt alt1)
766                                 = (mkOneOcc env v True, Var v)
767     occ_anal_scrut scrut alts   = occAnal vanillaCtxt scrut
768                                         -- No need for rhsCtxt
769
770 occAnal env (Let bind body)
771   = case occAnal env body                of { (body_usage, body') ->
772     case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
773        (final_usage, mkLets new_binds body') }}
774
775 occAnalArgs env args
776   = case mapAndUnzip (occAnal arg_env) args of  { (arg_uds_s, args') ->
777     (foldr (+++) emptyDetails arg_uds_s, args')}
778   where
779     arg_env = vanillaCtxt
780 \end{code}
781
782 Applications are dealt with specially because we want
783 the "build hack" to work.
784
785 \begin{code}
786 occAnalApp env (Var fun, args) is_rhs
787   = case args_stuff of { (args_uds, args') ->
788     let
789         final_args_uds = markRhsUds env is_pap args_uds
790     in
791     (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
792   where
793     fun_uniq = idUnique fun
794     fun_uds  = mkOneOcc env fun (valArgCount args > 0)
795     is_pap = isDataConWorkId fun || valArgCount args < idArity fun
796
797                 -- Hack for build, fold, runST
798     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
799                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
800                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
801                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]       args
802                         -- (foldr k z xs) may call k many times, but it never
803                         -- shares a partial application of k; hence [False,True]
804                         -- This means we can optimise
805                         --      foldr (\x -> let v = ...x... in \y -> ...v...) z xs
806                         -- by floating in the v
807
808                 | otherwise = occAnalArgs env args
809
810
811 occAnalApp env (fun, args) is_rhs
812   = case occAnal (addAppCtxt env args) fun of   { (fun_uds, fun') ->
813         -- The addAppCtxt is a bit cunning.  One iteration of the simplifier
814         -- often leaves behind beta redexs like
815         --      (\x y -> e) a1 a2
816         -- Here we would like to mark x,y as one-shot, and treat the whole
817         -- thing much like a let.  We do this by pushing some True items
818         -- onto the context stack.
819
820     case occAnalArgs env args of        { (args_uds, args') ->
821     let
822         final_uds = fun_uds +++ args_uds
823     in
824     (final_uds, mkApps fun' args') }}
825     
826
827 markRhsUds :: OccEnv            -- Check if this is a RhsEnv
828            -> Bool              -- and this is true
829            -> UsageDetails      -- The do markMany on this
830            -> UsageDetails
831 -- We mark the free vars of the argument of a constructor or PAP 
832 -- as "many", if it is the RHS of a let(rec).
833 -- This means that nothing gets inlined into a constructor argument
834 -- position, which is what we want.  Typically those constructor
835 -- arguments are just variables, or trivial expressions.
836 --
837 -- This is the *whole point* of the isRhsEnv predicate
838 markRhsUds env is_pap arg_uds
839   | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
840   | otherwise              = arg_uds
841
842
843 appSpecial :: OccEnv 
844            -> Int -> CtxtTy     -- Argument number, and context to use for it
845            -> [CoreExpr]
846            -> (UsageDetails, [CoreExpr])
847 appSpecial env n ctxt args
848   = go n args
849   where
850     arg_env = vanillaCtxt
851
852     go n [] = (emptyDetails, [])        -- Too few args
853
854     go 1 (arg:args)                     -- The magic arg
855       = case occAnal (setCtxt arg_env ctxt) arg of      { (arg_uds, arg') ->
856         case occAnalArgs env args of                    { (args_uds, args') ->
857         (arg_uds +++ args_uds, arg':args') }}
858     
859     go n (arg:args)
860       = case occAnal arg_env arg of     { (arg_uds, arg') ->
861         case go (n-1) args of           { (args_uds, args') ->
862         (arg_uds +++ args_uds, arg':args') }}
863 \end{code}
864
865     
866 Case alternatives
867 ~~~~~~~~~~~~~~~~~
868 If the case binder occurs at all, the other binders effectively do too.  
869 For example
870         case e of x { (a,b) -> rhs }
871 is rather like
872         let x = (a,b) in rhs
873 If e turns out to be (e1,e2) we indeed get something like
874         let a = e1; b = e2; x = (a,b) in rhs
875
876 Note [Aug 06]: I don't think this is necessary any more, and it helpe
877                to know when binders are unused.  See esp the call to
878                isDeadBinder in Simplify.mkDupableAlt
879
880 \begin{code}
881 occAnalAlt env case_bndr (con, bndrs, rhs)
882   = case occAnal env rhs of { (rhs_usage, rhs') ->
883     let
884         (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
885         final_bndrs = tagged_bndrs      -- See Note [Aug06] above
886 {-
887         final_bndrs | case_bndr `elemVarEnv` final_usage = bndrs
888                     | otherwise                         = tagged_bndrs
889                 -- Leave the binders untagged if the case 
890                 -- binder occurs at all; see note above
891 -}
892     in
893     (final_usage, (con, final_bndrs, rhs')) }
894 \end{code}
895
896
897 %************************************************************************
898 %*                                                                      *
899 \subsection[OccurAnal-types]{OccEnv}
900 %*                                                                      *
901 %************************************************************************
902
903 \begin{code}
904 data OccEnv
905   = OccEnv OccEncl      -- Enclosing context information
906            CtxtTy       -- Tells about linearity
907
908 -- OccEncl is used to control whether to inline into constructor arguments
909 -- For example:
910 --      x = (p,q)               -- Don't inline p or q
911 --      y = /\a -> (p a, q a)   -- Still don't inline p or q
912 --      z = f (p,q)             -- Do inline p,q; it may make a rule fire
913 -- So OccEncl tells enought about the context to know what to do when
914 -- we encounter a contructor application or PAP.
915
916 data OccEncl
917   = OccRhs              -- RHS of let(rec), albeit perhaps inside a type lambda
918                         -- Don't inline into constructor args here
919   | OccVanilla          -- Argument of function, body of lambda, scruintee of case etc.
920                         -- Do inline into constructor args here
921
922 type CtxtTy = [Bool]
923         -- []           No info
924         --
925         -- True:ctxt    Analysing a function-valued expression that will be
926         --                      applied just once
927         --
928         -- False:ctxt   Analysing a function-valued expression that may
929         --                      be applied many times; but when it is, 
930         --                      the CtxtTy inside applies
931
932 initOccEnv :: OccEnv
933 initOccEnv = OccEnv OccRhs []
934
935 vanillaCtxt = OccEnv OccVanilla []
936 rhsCtxt     = OccEnv OccRhs     []
937
938 isRhsEnv (OccEnv OccRhs     _) = True
939 isRhsEnv (OccEnv OccVanilla _) = False
940
941 setVanillaCtxt :: OccEnv -> OccEnv
942 setVanillaCtxt (OccEnv OccRhs ctxt_ty) = OccEnv OccVanilla ctxt_ty
943 setVanillaCtxt other_env               = other_env
944
945 setCtxt :: OccEnv -> CtxtTy -> OccEnv
946 setCtxt (OccEnv encl _) ctxt = OccEnv encl ctxt
947
948 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
949         -- The result binders have one-shot-ness set that they might not have had originally.
950         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
951         -- linearity context knows that c,n are one-shot, and it records that fact in
952         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
953
954 oneShotGroup (OccEnv encl ctxt) bndrs 
955   = go ctxt bndrs []
956   where
957     go ctxt [] rev_bndrs = reverse rev_bndrs
958
959     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
960         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
961         where
962           bndr' | lin_ctxt  = setOneShotLambda bndr
963                 | otherwise = bndr
964
965     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
966
967 addAppCtxt (OccEnv encl ctxt) args 
968   = OccEnv encl (replicate (valArgCount args) True ++ ctxt)
969 \end{code}
970
971 %************************************************************************
972 %*                                                                      *
973 \subsection[OccurAnal-types]{OccEnv}
974 %*                                                                      *
975 %************************************************************************
976
977 \begin{code}
978 type UsageDetails = IdEnv OccInfo       -- A finite map from ids to their usage
979
980 (+++), combineAltsUsageDetails
981         :: UsageDetails -> UsageDetails -> UsageDetails
982
983 (+++) usage1 usage2
984   = plusVarEnv_C addOccInfo usage1 usage2
985
986 combineAltsUsageDetails usage1 usage2
987   = plusVarEnv_C orOccInfo usage1 usage2
988
989 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
990 addOneOcc usage id info
991   = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
992         -- ToDo: make this more efficient
993
994 emptyDetails = (emptyVarEnv :: UsageDetails)
995
996 usedIn :: Id -> UsageDetails -> Bool
997 v `usedIn` details =  isExportedId v || v `elemVarEnv` details
998
999 type IdWithOccInfo = Id
1000
1001 tagBinders :: UsageDetails          -- Of scope
1002            -> [Id]                  -- Binders
1003            -> (UsageDetails,        -- Details with binders removed
1004               [IdWithOccInfo])    -- Tagged binders
1005
1006 tagBinders usage binders
1007  = let
1008      usage' = usage `delVarEnvList` binders
1009      uss    = map (setBinderOcc usage) binders
1010    in
1011    usage' `seq` (usage', uss)
1012
1013 tagBinder :: UsageDetails           -- Of scope
1014           -> Id                     -- Binders
1015           -> (UsageDetails,         -- Details with binders removed
1016               IdWithOccInfo)        -- Tagged binders
1017
1018 tagBinder usage binder
1019  = let
1020      usage'  = usage `delVarEnv` binder
1021      binder' = setBinderOcc usage binder
1022    in
1023    usage' `seq` (usage', binder')
1024
1025 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
1026 setBinderOcc usage bndr
1027   | isTyVar bndr      = bndr
1028   | isExportedId bndr = case idOccInfo bndr of
1029                           NoOccInfo -> bndr
1030                           other     -> setIdOccInfo bndr NoOccInfo
1031             -- Don't use local usage info for visible-elsewhere things
1032             -- BUT *do* erase any IAmALoopBreaker annotation, because we're
1033             -- about to re-generate it and it shouldn't be "sticky"
1034                           
1035   | otherwise = setIdOccInfo bndr occ_info
1036   where
1037     occ_info = lookupVarEnv usage bndr `orElse` IAmDead
1038 \end{code}
1039
1040
1041 %************************************************************************
1042 %*                                                                      *
1043 \subsection{Operations over OccInfo}
1044 %*                                                                      *
1045 %************************************************************************
1046
1047 \begin{code}
1048 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
1049 mkOneOcc env id int_cxt
1050   | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
1051   | otherwise    = emptyDetails
1052
1053 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
1054
1055 markMany IAmDead = IAmDead
1056 markMany other   = NoOccInfo
1057
1058 markInsideSCC occ = markMany occ
1059
1060 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
1061 markInsideLam occ                       = occ
1062
1063 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
1064
1065 addOccInfo IAmDead info2       = info2
1066 addOccInfo info1 IAmDead       = info1
1067 addOccInfo info1 info2         = NoOccInfo
1068
1069 -- (orOccInfo orig new) is used
1070 -- when combining occurrence info from branches of a case
1071
1072 orOccInfo IAmDead info2 = info2
1073 orOccInfo info1 IAmDead = info1
1074 orOccInfo (OneOcc in_lam1 one_branch1 int_cxt1)
1075           (OneOcc in_lam2 one_branch2 int_cxt2)
1076   = OneOcc (in_lam1 || in_lam2)
1077            False        -- False, because it occurs in both branches
1078            (int_cxt1 && int_cxt2)
1079 orOccInfo info1 info2 = NoOccInfo
1080 \end{code}