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