[project @ 2000-10-12 15:07:02 by simonmar]
[ghc-hetmet.git] / ghc / 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         occurAnalyseBinds, occurAnalyseGlobalExpr, occurAnalyseRule
16     ) where
17
18 #include "HsVersions.h"
19
20 import BinderInfo
21 import CoreSyn
22 import CoreFVs          ( idRuleVars )
23 import CoreUtils        ( exprIsTrivial )
24 import Id               ( isDataConId, isOneShotLambda, setOneShotLambda, 
25                           idOccInfo, setIdOccInfo,
26                           isExportedId, modifyIdInfo, idInfo,
27                           idSpecialisation, 
28                           idType, idUnique, Id
29                         )
30 import IdInfo           ( OccInfo(..), shortableIdInfo, copyIdInfo )
31
32 import VarSet
33 import VarEnv
34
35 import Name             ( isLocallyDefined )
36 import Type             ( splitFunTy_maybe, splitForAllTys )
37 import Maybes           ( maybeToBool )
38 import Digraph          ( stronglyConnCompR, SCC(..) )
39 import PrelNames        ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
40 import Unique           ( u2i )
41 import UniqFM           ( keysUFM )  
42 import Util             ( zipWithEqual, mapAndUnzip )
43 import FastTypes
44 import Outputable
45 \end{code}
46
47
48 %************************************************************************
49 %*                                                                      *
50 \subsection[OccurAnal-main]{Counting occurrences: main function}
51 %*                                                                      *
52 %************************************************************************
53
54 Here's the externally-callable interface:
55
56 \begin{code}
57 occurAnalyseExpr :: (Id -> Bool)        -- Tells if a variable is interesting
58                  -> CoreExpr
59                  -> (IdEnv BinderInfo,  -- Occ info for interesting free vars
60                      CoreExpr)
61
62 occurAnalyseExpr interesting expr
63   = occAnal initial_env expr
64   where
65     initial_env = OccEnv interesting emptyVarSet []
66
67 occurAnalyseGlobalExpr :: CoreExpr -> CoreExpr
68 occurAnalyseGlobalExpr expr
69   =     -- Top level expr, so no interesting free vars, and
70         -- discard occurence info returned
71     snd (occurAnalyseExpr (\_ -> False) expr)
72
73 occurAnalyseRule :: CoreRule -> CoreRule
74 occurAnalyseRule rule@(BuiltinRule _) = rule
75 occurAnalyseRule (Rule str tpl_vars tpl_args rhs)
76                 -- Add occ info to tpl_vars, rhs
77   = Rule str tpl_vars' tpl_args rhs'
78   where
79     (rhs_uds, rhs') = occurAnalyseExpr isLocallyDefined rhs
80     (_, tpl_vars')  = tagBinders rhs_uds tpl_vars
81 \end{code}
82
83
84 %************************************************************************
85 %*                                                                      *
86 \subsection{Top level stuff}
87 %*                                                                      *
88 %************************************************************************
89
90 In @occAnalTop@ we do indirection-shorting.  That is, if we have this:
91
92         x_local = <expression>
93         ...
94         x_exported = loc
95
96 where exp is exported, and loc is not, then we replace it with this:
97
98         x_local = x_exported
99         x_exported = <expression>
100         ...
101
102 Without this we never get rid of the x_exported = x_local thing.  This
103 save a gratuitous jump (from \tr{x_exported} to \tr{x_local}), and
104 makes strictness information propagate better.  This used to happen in
105 the final phase, but it's tidier to do it here.
106
107 If more than one exported thing is equal to a local thing (i.e., the
108 local thing really is shared), then we do one only:
109 \begin{verbatim}
110         x_local = ....
111         x_exported1 = x_local
112         x_exported2 = x_local
113 ==>
114         x_exported1 = ....
115
116         x_exported2 = x_exported1
117 \end{verbatim}
118
119 We rely on prior eta reduction to simplify things like
120 \begin{verbatim}
121         x_exported = /\ tyvars -> x_local tyvars
122 ==>
123         x_exported = x_local
124 \end{verbatim}
125 Hence,there's a possibility of leaving unchanged something like this:
126 \begin{verbatim}
127         x_local = ....
128         x_exported1 = x_local Int
129 \end{verbatim}
130 By the time we've thrown away the types in STG land this 
131 could be eliminated.  But I don't think it's very common
132 and it's dangerous to do this fiddling in STG land 
133 because we might elminate a binding that's mentioned in the
134 unfolding for something.
135
136 \begin{code}
137 occurAnalyseBinds :: [CoreBind] -> [CoreBind]
138
139 occurAnalyseBinds binds
140   = binds'
141   where
142     (_, _, binds') = go initialTopEnv binds
143
144     go :: OccEnv -> [CoreBind]
145        -> (UsageDetails,        -- Occurrence info
146            IdEnv Id,            -- Indirection elimination info
147                                 --   Maps local-id -> exported-id, but it embodies
148                                 --   bindings of the form exported-id = local-id in
149                                 --   the argument to go
150            [CoreBind])          -- Occ-analysed bindings, less the exported-id=local-id ones
151
152     go env [] = (emptyDetails, emptyVarEnv, [])
153
154     go env (bind : binds)
155       = let
156             new_env                        = env `addNewCands` (bindersOf bind)
157             (scope_usage, ind_env, binds') = go new_env binds
158             (final_usage, new_binds)       = occAnalBind env (zapBind ind_env bind) scope_usage
159                                                 -- NB: I zap before occur-analysing, so
160                                                 -- I don't need to worry about getting the
161                                                 -- occ info on the new bindings right.
162         in
163         case bind of
164             NonRec exported_id (Var local_id) 
165                 | shortMeOut ind_env exported_id local_id
166                 -- Special case for eliminating indirections
167                 --   Note: it's a shortcoming that this only works for
168                 --         non-recursive bindings.  Elminating indirections
169                 --         makes perfect sense for recursive bindings too, but
170                 --         it's more complicated to implement, so I haven't done so
171                 -> (scope_usage, ind_env', binds')
172                 where
173                    ind_env' = extendVarEnv ind_env local_id exported_id
174
175             other ->    -- Ho ho! The normal case
176                      (final_usage, ind_env, new_binds ++ binds')
177                    
178 initialTopEnv = OccEnv isLocallyDefined -- Anything local is interesting
179                        emptyVarSet
180                        []
181
182
183 -- Deal with any indirections
184 zapBind ind_env (NonRec bndr rhs) 
185   | bndr `elemVarEnv` ind_env                      = Rec (zap ind_env (bndr,rhs))
186                 -- The Rec isn't strictly necessary, but it's convenient
187 zapBind ind_env (Rec pairs)
188   | or [id `elemVarEnv` ind_env | (id,_) <- pairs] = Rec (concat (map (zap ind_env) pairs))
189
190 zapBind ind_env bind = bind
191
192 zap ind_env pair@(local_id,rhs)
193   = case lookupVarEnv ind_env local_id of
194         Nothing          -> [pair]
195         Just exported_id -> [(local_id, Var exported_id),
196                              (exported_id', rhs)]
197                          where
198                             exported_id' = modifyIdInfo (copyIdInfo (idInfo local_id)) exported_id
199                         
200 shortMeOut ind_env exported_id local_id
201 -- The if-then-else stuff is just so I can get a pprTrace to see
202 -- how often I don't get shorting out becuase of IdInfo stuff
203   = if isExportedId exported_id &&              -- Only if this is exported
204
205        isLocallyDefined local_id &&             -- Only if this one is defined in this
206                                                 --      module, so that we *can* change its
207                                                 --      binding to be the exported thing!
208
209        not (isExportedId local_id) &&           -- Only if this one is not itself exported,
210                                                 --      since the transformation will nuke it
211    
212        not (local_id `elemVarEnv` ind_env)      -- Only if not already substituted for
213     then
214         if shortableIdInfo (idInfo exported_id)         -- Only if its IdInfo is 'shortable'
215                                                         -- (see the defn of IdInfo.shortableIdInfo
216         then True
217         else pprTrace "shortMeOut:" (ppr exported_id) False
218     else
219         False
220 \end{code}
221
222
223 %************************************************************************
224 %*                                                                      *
225 \subsection[OccurAnal-main]{Counting occurrences: main function}
226 %*                                                                      *
227 %************************************************************************
228
229 Bindings
230 ~~~~~~~~
231
232 \begin{code}
233 type IdWithOccInfo = Id                 -- An Id with fresh PragmaInfo attached
234
235 type Node details = (details, Int, [Int])       -- The Ints are gotten from the Unique,
236                                                 -- which is gotten from the Id.
237 type Details1     = (Id, UsageDetails, CoreExpr)
238 type Details2     = (IdWithOccInfo, CoreExpr)
239
240
241 occAnalBind :: OccEnv
242             -> CoreBind
243             -> UsageDetails             -- Usage details of scope
244             -> (UsageDetails,           -- Of the whole let(rec)
245                 [CoreBind])
246
247 occAnalBind env (NonRec binder rhs) body_usage
248   | not (binder `usedIn` body_usage)            -- It's not mentioned
249   = (body_usage, [])
250
251   | otherwise                   -- It's mentioned in the body
252   = (final_body_usage `combineUsageDetails` rhs_usage,
253      [NonRec tagged_binder rhs'])
254
255   where
256     (final_body_usage, tagged_binder) = tagBinder body_usage binder
257     (rhs_usage, rhs')                 = occAnalRhs env binder rhs
258 \end{code}
259
260 Dropping dead code for recursive bindings is done in a very simple way:
261
262         the entire set of bindings is dropped if none of its binders are
263         mentioned in its body; otherwise none are.
264
265 This seems to miss an obvious improvement.
266 @
267         letrec  f = ...g...
268                 g = ...f...
269         in
270         ...g...
271
272 ===>
273
274         letrec f = ...g...
275                g = ...(...g...)...
276         in
277         ...g...
278 @
279
280 Now @f@ is unused. But dependency analysis will sort this out into a
281 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
282 It isn't easy to do a perfect job in one blow.  Consider
283
284 @
285         letrec f = ...g...
286                g = ...h...
287                h = ...k...
288                k = ...m...
289                m = ...m...
290         in
291         ...m...
292 @
293
294
295 \begin{code}
296 occAnalBind env (Rec pairs) body_usage
297   = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
298   where
299     binders = map fst pairs
300     rhs_env = env `addNewCands` binders
301
302     analysed_pairs :: [Details1]
303     analysed_pairs  = [ (bndr, rhs_usage, rhs')
304                       | (bndr, rhs) <- pairs,
305                         let (rhs_usage, rhs') = occAnalRhs rhs_env bndr rhs
306                       ]
307
308     sccs :: [SCC (Node Details1)]
309     sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
310
311
312     ---- stuff for dependency analysis of binds -------------------------------
313     edges :: [Node Details1]
314     edges = _scc_ "occAnalBind.assoc"
315             [ (details, iBox (u2i (idUnique id)), edges_from rhs_usage)
316             | details@(id, rhs_usage, rhs) <- analysed_pairs
317             ]
318
319         -- (a -> b) means a mentions b
320         -- Given the usage details (a UFM that gives occ info for each free var of
321         -- the RHS) we can get the list of free vars -- or rather their Int keys --
322         -- by just extracting the keys from the finite map.  Grimy, but fast.
323         -- Previously we had this:
324         --      [ bndr | bndr <- bndrs,
325         --               maybeToBool (lookupVarEnv rhs_usage bndr)]
326         -- which has n**2 cost, and this meant that edges_from alone 
327         -- consumed 10% of total runtime!
328     edges_from :: UsageDetails -> [Int]
329     edges_from rhs_usage = _scc_ "occAnalBind.edges_from"
330                            keysUFM rhs_usage
331
332     ---- stuff to "re-constitute" bindings from dependency-analysis info ------
333
334         -- Non-recursive SCC
335     do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
336       | not (bndr `usedIn` body_usage)
337       = (body_usage, binds_so_far)                      -- Dead code
338       | otherwise
339       = (combined_usage, new_bind : binds_so_far)       
340       where
341         total_usage                   = combineUsageDetails body_usage rhs_usage
342         (combined_usage, tagged_bndr) = tagBinder total_usage bndr
343         new_bind                      = NonRec tagged_bndr rhs'
344
345         -- Recursive SCC
346     do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
347       | not (any (`usedIn` body_usage) bndrs)           -- NB: look at body_usage, not total_usage
348       = (body_usage, binds_so_far)                      -- Dead code
349       | otherwise
350       = (combined_usage, final_bind:binds_so_far)
351       where
352         details                        = [details   | (details, _, _) <- cycle]
353         bndrs                          = [bndr      | (bndr, _, _)      <- details]
354         rhs_usages                     = [rhs_usage | (_, rhs_usage, _) <- details]
355         total_usage                    = foldr combineUsageDetails body_usage rhs_usages
356         (combined_usage, tagged_bndrs) = tagBinders total_usage bndrs
357         final_bind                     = Rec (reOrderRec env new_cycle)
358
359         new_cycle = CyclicSCC (zipWithEqual "occAnalBind" mk_new_bind tagged_bndrs cycle)
360         mk_new_bind tagged_bndr ((_, _, rhs'), key, keys) = ((tagged_bndr, rhs'), key, keys)
361 \end{code}
362
363 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
364 strongly connected component (there's guaranteed to be a cycle).  It returns the
365 same pairs, but 
366         a) in a better order,
367         b) with some of the Ids having a IMustNotBeINLINEd pragma
368
369 The "no-inline" Ids are sufficient to break all cycles in the SCC.  This means
370 that the simplifier can guarantee not to loop provided it never records an inlining
371 for these no-inline guys.
372
373 Furthermore, the order of the binds is such that if we neglect dependencies
374 on the no-inline Ids then the binds are topologically sorted.  This means
375 that the simplifier will generally do a good job if it works from top bottom,
376 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
377
378 ==============
379 [June 98: I don't understand the following paragraphs, and I've 
380           changed the a=b case again so that it isn't a special case any more.]
381
382 Here's a case that bit me:
383
384         letrec
385                 a = b
386                 b = \x. BIG
387         in
388         ...a...a...a....
389
390 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
391
392 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
393 Perhaps something cleverer would suffice.
394 ===============
395
396 You might think that you can prevent non-termination simply by making
397 sure that we simplify a recursive binding's RHS in an environment that
398 simply clones the recursive Id.  But no.  Consider
399
400                 letrec f = \x -> let z = f x' in ...
401
402                 in
403                 let n = f y
404                 in
405                 case n of { ... }
406
407 We bind n to its *simplified* RHS, we then *re-simplify* it when
408 we inline n.  Then we may well inline f; and then the same thing
409 happens with z!
410
411 I don't think it's possible to prevent non-termination by environment
412 manipulation in this way.  Apart from anything else, successive
413 iterations of the simplifier may unroll recursive loops in cases like
414 that above.  The idea of beaking every recursive loop with an
415 IMustNotBeINLINEd pragma is much much better.
416
417
418 \begin{code}
419 reOrderRec
420         :: OccEnv
421         -> SCC (Node Details2)
422         -> [Details2]
423                         -- Sorted into a plausible order.  Enough of the Ids have
424                         --      dontINLINE pragmas that there are no loops left.
425
426         -- Non-recursive case
427 reOrderRec env (AcyclicSCC (bind, _, _)) = [bind]
428
429         -- Common case of simple self-recursion
430 reOrderRec env (CyclicSCC [bind])
431   = [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
432   where
433     ((tagged_bndr, rhs), _, _) = bind
434
435 reOrderRec env (CyclicSCC (bind : binds))
436   =     -- Choose a loop breaker, mark it no-inline,
437         -- do SCC analysis on the rest, and recursively sort them out
438     concat (map (reOrderRec env) (stronglyConnCompR unchosen))
439     ++ 
440     [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
441
442   where
443     (chosen_pair, unchosen) = choose_loop_breaker bind (score bind) [] binds
444     (tagged_bndr, rhs)      = chosen_pair
445
446         -- This loop looks for the bind with the lowest score
447         -- to pick as the loop  breaker.  The rest accumulate in 
448     choose_loop_breaker (details,_,_) loop_sc acc []
449         = (details, acc)        -- Done
450
451     choose_loop_breaker loop_bind loop_sc acc (bind : binds)
452         | sc < loop_sc  -- Lower score so pick this new one
453         = choose_loop_breaker bind sc (loop_bind : acc) binds
454
455         | otherwise     -- No lower so don't pick it
456         = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
457         where
458           sc = score bind
459           
460     score :: Node Details2 -> Int       -- Higher score => less likely to be picked as loop breaker
461     score ((bndr, rhs), _, _)
462         | exprIsTrivial rhs        = 4  -- Practically certain to be inlined
463                 -- Used to have also: && not (isExportedId bndr)
464                 -- But I found this sometimes cost an extra iteration when we have
465                 --      rec { d = (a,b); a = ...df...; b = ...df...; df = d }
466                 -- where df is the exported dictionary. Then df makes a really
467                 -- bad choice for loop breaker
468           
469         | not_fun_ty (idType bndr) = 3  -- Data types help with cases
470                 -- This used to have a lower score than inlineCandidate, but
471                 -- it's *really* helpful if dictionaries get inlined fast,
472                 -- so I'm experimenting with giving higher priority to data-typed things
473
474         | inlineCandidate bndr rhs = 2  -- Likely to be inlined
475
476         | not (isEmptyCoreRules (idSpecialisation bndr)) = 1
477                 -- Avoid things with specialisations; we'd like
478                 -- to take advantage of them in the subsequent bindings
479
480         | otherwise = 0
481
482     inlineCandidate :: Id -> CoreExpr -> Bool
483     inlineCandidate id (Note InlineMe _) = True
484     inlineCandidate id rhs               = case idOccInfo id of
485                                                 OneOcc _ _ -> True
486                                                 other      -> False
487
488         -- Real example (the Enum Ordering instance from PrelBase):
489         --      rec     f = \ x -> case d of (p,q,r) -> p x
490         --              g = \ x -> case d of (p,q,r) -> q x
491         --              d = (v, f, g)
492         --
493         -- Here, f and g occur just once; but we can't inline them into d.
494         -- On the other hand we *could* simplify those case expressions if
495         -- we didn't stupidly choose d as the loop breaker.
496         -- But we won't because constructor args are marked "Many".
497
498     not_fun_ty ty = not (maybeToBool (splitFunTy_maybe rho_ty))
499                   where
500                     (_, rho_ty) = splitForAllTys ty
501 \end{code}
502
503 @occAnalRhs@ deals with the question of bindings where the Id is marked
504 by an INLINE pragma.  For these we record that anything which occurs
505 in its RHS occurs many times.  This pessimistically assumes that ths
506 inlined binder also occurs many times in its scope, but if it doesn't
507 we'll catch it next time round.  At worst this costs an extra simplifier pass.
508 ToDo: try using the occurrence info for the inline'd binder.
509
510 [March 97] We do the same for atomic RHSs.  Reason: see notes with reOrderRec.
511 [June 98, SLPJ]  I've undone this change; I don't understand it.  See notes with reOrderRec.
512
513
514 \begin{code}
515 occAnalRhs :: OccEnv
516            -> Id -> CoreExpr    -- Binder and rhs
517            -> (UsageDetails, CoreExpr)
518
519 occAnalRhs env id rhs
520   = (final_usage, rhs')
521   where
522     (rhs_usage, rhs') = occAnal (zapCtxt env) rhs
523
524         -- [March 98] A new wrinkle is that if the binder has specialisations inside
525         -- it then we count the specialised Ids as "extra rhs's".  That way
526         -- the "parent" keeps the specialised "children" alive.  If the parent
527         -- dies (because it isn't referenced any more), then the children will
528         -- die too unless they are already referenced directly.
529
530     final_usage = foldVarSet add rhs_usage (idRuleVars id)
531     add v u = addOneOcc u v noBinderInfo        -- Give a non-committal binder info
532                                                 -- (i.e manyOcc) because many copies
533                                                 -- of the specialised thing can appear
534 \end{code}
535
536 Expressions
537 ~~~~~~~~~~~
538 \begin{code}
539 occAnal :: OccEnv
540         -> CoreExpr
541         -> (UsageDetails,       -- Gives info only about the "interesting" Ids
542             CoreExpr)
543
544 occAnal env (Type t)  = (emptyDetails, Type t)
545
546 occAnal env (Var v) 
547   = (var_uds, Var v)
548   where
549     var_uds | isCandidate env v = unitVarEnv v funOccZero
550             | otherwise         = emptyDetails
551
552     -- At one stage, I gathered the idRuleVars for v here too,
553     -- which in a way is the right thing to do.
554     -- But that went wrong right after specialisation, when
555     -- the *occurrences* of the overloaded function didn't have any
556     -- rules in them, so the *specialised* versions looked as if they
557     -- weren't used at all.
558
559 \end{code}
560
561 We regard variables that occur as constructor arguments as "dangerousToDup":
562
563 \begin{verbatim}
564 module A where
565 f x = let y = expensive x in 
566       let z = (True,y) in 
567       (case z of {(p,q)->q}, case z of {(p,q)->q})
568 \end{verbatim}
569
570 We feel free to duplicate the WHNF (True,y), but that means
571 that y may be duplicated thereby.
572
573 If we aren't careful we duplicate the (expensive x) call!
574 Constructors are rather like lambdas in this way.
575
576 \begin{code}
577 occAnal env expr@(Lit lit) = (emptyDetails, expr)
578 \end{code}
579
580 \begin{code}
581 occAnal env (Note InlineMe body)
582   = case occAnal env body of { (usage, body') -> 
583     (mapVarEnv markMany usage, Note InlineMe body')
584     }
585
586 occAnal env (Note note@(SCC cc) body)
587   = case occAnal env body of { (usage, body') ->
588     (mapVarEnv markInsideSCC usage, Note note body')
589     }
590
591 occAnal env (Note note body)
592   = case occAnal env body of { (usage, body') ->
593     (usage, Note note body')
594     }
595 \end{code}
596
597 \begin{code}
598 occAnal env app@(App fun arg)
599   = occAnalApp env (collectArgs app)
600
601 -- Ignore type variables altogether
602 --   (a) occurrences inside type lambdas only not marked as InsideLam
603 --   (b) type variables not in environment
604
605 occAnal env expr@(Lam x body) | isTyVar x
606   = case occAnal env body of { (body_usage, body') ->
607     (body_usage, Lam x body')
608     }
609
610 -- For value lambdas we do a special hack.  Consider
611 --      (\x. \y. ...x...)
612 -- If we did nothing, x is used inside the \y, so would be marked
613 -- as dangerous to dup.  But in the common case where the abstraction
614 -- is applied to two arguments this is over-pessimistic.
615 -- So instead, we just mark each binder with its occurrence
616 -- info in the *body* of the multiple lambda.
617 -- Then, the simplifier is careful when partially applying lambdas.
618
619 occAnal env expr@(Lam _ _)
620   = case occAnal (env_body `addNewCands` binders) body of { (body_usage, body') ->
621     let
622         (final_usage, tagged_binders) = tagBinders body_usage binders
623         --      URGH!  Sept 99: we don't seem to be able to use binders' here, because
624         --      we get linear-typed things in the resulting program that we can't handle yet.
625         --      (e.g. PrelShow)  TODO 
626
627         really_final_usage = if linear then
628                                 final_usage
629                              else
630                                 mapVarEnv markInsideLam final_usage
631     in
632     (really_final_usage,
633      mkLams tagged_binders body') }
634   where
635     (binders, body)       = collectBinders expr
636     (linear, env_body, _) = oneShotGroup env binders
637
638 occAnal env (Case scrut bndr alts)
639   = case mapAndUnzip (occAnalAlt alt_env) alts of { (alts_usage_s, alts')   -> 
640     case occAnal (zapCtxt env) scrut           of { (scrut_usage, scrut') ->
641     let
642         alts_usage  = foldr1 combineAltsUsageDetails alts_usage_s
643         alts_usage' = addCaseBndrUsage alts_usage
644         (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
645         total_usage = scrut_usage `combineUsageDetails` alts_usage1
646     in
647     total_usage `seq` (total_usage, Case scrut' tagged_bndr alts') }}
648   where
649     alt_env = env `addNewCand` bndr
650
651         -- The case binder gets a usage of either "many" or "dead", never "one".
652         -- Reason: we like to inline single occurrences, to eliminate a binding,
653         -- but inlining a case binder *doesn't* eliminate a binding.
654         -- We *don't* want to transform
655         --      case x of w { (p,q) -> f w }
656         -- into
657         --      case x of w { (p,q) -> f (p,q) }
658     addCaseBndrUsage usage = case lookupVarEnv usage bndr of
659                                 Nothing  -> usage
660                                 Just occ -> extendVarEnv usage bndr (markMany occ)
661
662 occAnal env (Let bind body)
663   = case occAnal new_env body            of { (body_usage, body') ->
664     case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
665        (final_usage, mkLets new_binds body') }}
666   where
667     new_env = env `addNewCands` (bindersOf bind)
668
669 occAnalArgs env args
670   = case mapAndUnzip (occAnal arg_env) args of  { (arg_uds_s, args') ->
671     (foldr combineUsageDetails emptyDetails arg_uds_s, args')}
672   where
673     arg_env = zapCtxt env
674 \end{code}
675
676 Applications are dealt with specially because we want
677 the "build hack" to work.
678
679 \begin{code}
680 -- Hack for build, fold, runST
681 occAnalApp env (Var fun, args)
682   = case args_stuff of { (args_uds, args') ->
683     let
684         final_uds = fun_uds `combineUsageDetails` args_uds
685     in
686     (final_uds, mkApps (Var fun) args') }
687   where
688     fun_uniq = idUnique fun
689
690     fun_uds | isCandidate env fun = unitVarEnv fun funOccZero
691             | otherwise           = emptyDetails
692
693     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
694                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
695                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
696                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]    args
697
698                 | isDataConId fun           = case occAnalArgs env args of
699                                                 (arg_uds, args') -> (mapVarEnv markMany arg_uds, args')
700                                                    -- We mark the free vars of the argument of a constructor as "many"
701                                                    -- This means that nothing gets inlined into a constructor argument
702                                                    -- position, which is what we want.  Typically those constructor
703                                                    -- arguments are just variables, or trivial expressions.
704
705                 | otherwise                 = occAnalArgs env args
706
707
708 occAnalApp env (fun, args)
709   = case occAnal (zapCtxt env) fun of           { (fun_uds, fun') ->
710     case occAnalArgs env args of                { (args_uds, args') ->
711     let
712         final_uds = fun_uds `combineUsageDetails` args_uds
713     in
714     (final_uds, mkApps fun' args') }}
715     
716 appSpecial :: OccEnv -> Int -> CtxtTy -> [CoreExpr] -> (UsageDetails, [CoreExpr])
717 appSpecial env n ctxt args
718   = go n args
719   where
720     go n [] = (emptyDetails, [])        -- Too few args
721
722     go 1 (arg:args)                     -- The magic arg
723       = case occAnal (setCtxt env ctxt) arg of  { (arg_uds, arg') ->
724         case occAnalArgs env args of            { (args_uds, args') ->
725         (combineUsageDetails arg_uds args_uds, arg':args') }}
726     
727     go n (arg:args)
728       = case occAnal env arg of         { (arg_uds, arg') ->
729         case go (n-1) args of           { (args_uds, args') ->
730         (combineUsageDetails arg_uds args_uds, arg':args') }}
731 \end{code}
732
733     
734 Case alternatives
735 ~~~~~~~~~~~~~~~~~
736 \begin{code}
737 occAnalAlt env (con, bndrs, rhs)
738   = case occAnal (env `addNewCands` bndrs) rhs of { (rhs_usage, rhs') ->
739     let
740         (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
741     in
742     (final_usage, (con, tagged_bndrs, rhs')) }
743 \end{code}
744
745
746 %************************************************************************
747 %*                                                                      *
748 \subsection[OccurAnal-types]{Data types}
749 %*                                                                      *
750 %************************************************************************
751
752 \begin{code}
753 -- We gather inforamtion for variables that are either
754 --      (a) in scope or
755 --      (b) interesting
756
757 data OccEnv =
758   OccEnv (Id -> Bool)   -- Tells whether an Id occurrence is interesting,
759          IdSet          -- In-scope Ids
760          CtxtTy         -- Tells about linearity
761
762 type CtxtTy = [Bool]
763         -- []           No info
764         --
765         -- True:ctxt    Analysing a function-valued expression that will be
766         --                      applied just once
767         --
768         -- False:ctxt   Analysing a function-valued expression that may
769         --                      be applied many times; but when it is, 
770         --                      the CtxtTy inside applies
771
772 isCandidate :: OccEnv -> Id -> Bool
773 isCandidate (OccEnv ifun cands _) id = id `elemVarSet` cands || ifun id
774
775 addNewCands :: OccEnv -> [Id] -> OccEnv
776 addNewCands (OccEnv ifun cands ctxt) ids
777   = OccEnv ifun (cands `unionVarSet` mkVarSet ids) ctxt
778
779 addNewCand :: OccEnv -> Id -> OccEnv
780 addNewCand (OccEnv ifun cands ctxt) id
781   = OccEnv ifun (extendVarSet cands id) ctxt
782
783 setCtxt :: OccEnv -> CtxtTy -> OccEnv
784 setCtxt (OccEnv ifun cands _) ctxt = OccEnv ifun cands ctxt
785
786 oneShotGroup :: OccEnv -> [CoreBndr] -> (Bool, OccEnv, [CoreBndr])
787         -- True <=> this is a one-shot linear lambda group
788         -- The [CoreBndr] are the binders.
789
790         -- The result binders have one-shot-ness set that they might not have had originally.
791         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
792         -- linearity context knows that c,n are one-shot, and it records that fact in
793         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
794
795 oneShotGroup (OccEnv ifun cands ctxt) bndrs 
796   = case go ctxt bndrs [] of
797         (new_ctxt, new_bndrs) -> (all is_one_shot new_bndrs, OccEnv ifun cands new_ctxt, new_bndrs)
798   where
799     is_one_shot b = isId b && isOneShotLambda b
800
801     go ctxt [] rev_bndrs = (ctxt, reverse rev_bndrs)
802
803     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
804         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
805         where
806           bndr' | lin_ctxt  = setOneShotLambda bndr
807                 | otherwise = bndr
808
809     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
810
811
812 zapCtxt env@(OccEnv ifun cands []) = env
813 zapCtxt     (OccEnv ifun cands _ ) = OccEnv ifun cands []
814
815 type UsageDetails = IdEnv BinderInfo    -- A finite map from ids to their usage
816
817 combineUsageDetails, combineAltsUsageDetails
818         :: UsageDetails -> UsageDetails -> UsageDetails
819
820 combineUsageDetails usage1 usage2
821   = plusVarEnv_C addBinderInfo usage1 usage2
822
823 combineAltsUsageDetails usage1 usage2
824   = plusVarEnv_C orBinderInfo usage1 usage2
825
826 addOneOcc :: UsageDetails -> Id -> BinderInfo -> UsageDetails
827 addOneOcc usage id info
828   = plusVarEnv_C addBinderInfo usage (unitVarEnv id info)
829         -- ToDo: make this more efficient
830
831 emptyDetails = (emptyVarEnv :: UsageDetails)
832
833 unitDetails id info = (unitVarEnv id info :: UsageDetails)
834
835 usedIn :: Id -> UsageDetails -> Bool
836 v `usedIn` details =  isExportedId v || v `elemVarEnv` details
837
838 tagBinders :: UsageDetails          -- Of scope
839            -> [Id]                  -- Binders
840            -> (UsageDetails,        -- Details with binders removed
841               [IdWithOccInfo])    -- Tagged binders
842
843 tagBinders usage binders
844  = let
845      usage' = usage `delVarEnvList` binders
846      uss    = map (setBinderOcc usage) binders
847    in
848    usage' `seq` (usage', uss)
849
850 tagBinder :: UsageDetails           -- Of scope
851           -> Id                     -- Binders
852           -> (UsageDetails,         -- Details with binders removed
853               IdWithOccInfo)        -- Tagged binders
854
855 tagBinder usage binder
856  = let
857      usage'  = usage `delVarEnv` binder
858      binder' = setBinderOcc usage binder
859    in
860    usage' `seq` (usage', binder')
861
862
863 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
864 setBinderOcc usage bndr
865   | isTyVar bndr      = bndr
866   | isExportedId bndr 
867   = -- Don't use local usage info for visible-elsewhere things
868     -- BUT *do* erase any IAmALoopBreaker annotation, because we're
869     -- about to re-generate it and it shouldn't be "sticky"
870     case idOccInfo bndr of
871         NoOccInfo -> bndr
872         other     -> setIdOccInfo bndr NoOccInfo
873                           
874   | otherwise         = setIdOccInfo bndr occ_info
875   where
876     occ_info = case lookupVarEnv usage bndr of
877                  Nothing   -> IAmDead
878                  Just info -> binderInfoToOccInfo info
879
880 funOccZero = funOccurrence 0
881 \end{code}