[project @ 2001-12-14 17:24:03 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, idArity,
26                           idSpecialisation, isLocalId,
27                           idType, idUnique, Id
28                         )
29 import IdInfo           ( shortableIdInfo, copyIdInfo )
30 import BasicTypes       ( OccInfo(..), isOneOcc )
31
32 import VarSet
33 import VarEnv
34
35 import Type             ( splitFunTy_maybe, splitForAllTys )
36 import Maybes           ( maybeToBool, orElse )
37 import Digraph          ( stronglyConnCompR, SCC(..) )
38 import PrelNames        ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
39 import Unique           ( Unique )
40 import UniqFM           ( keysUFM )  
41 import Util             ( zipWithEqual, mapAndUnzip )
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 occurAnalyseGlobalExpr :: CoreExpr -> CoreExpr
56 occurAnalyseGlobalExpr expr
57   =     -- Top level expr, so no interesting free vars, and
58         -- discard occurence info returned
59     snd (occAnal (initOccEnv emptyVarSet) expr)
60
61 occurAnalyseRule :: CoreRule -> CoreRule
62 occurAnalyseRule rule@(BuiltinRule _ _) = rule
63 occurAnalyseRule (Rule str act tpl_vars tpl_args rhs)
64                 -- Add occ info to tpl_vars, rhs
65   = Rule str act tpl_vars' tpl_args rhs'
66   where
67     (rhs_uds, rhs') = occAnal (initOccEnv (mkVarSet tpl_vars)) rhs
68     (_, tpl_vars')  = tagBinders rhs_uds tpl_vars
69 \end{code}
70
71
72 %************************************************************************
73 %*                                                                      *
74 \subsection{Top level stuff}
75 %*                                                                      *
76 %************************************************************************
77
78 In @occAnalTop@ we do indirection-shorting.  That is, if we have this:
79
80         x_local = <expression>
81         ...
82         x_exported = loc
83
84 where exp is exported, and loc is not, then we replace it with this:
85
86         x_local = x_exported
87         x_exported = <expression>
88         ...
89
90 Without this we never get rid of the x_exported = x_local thing.  This
91 save a gratuitous jump (from \tr{x_exported} to \tr{x_local}), and
92 makes strictness information propagate better.  This used to happen in
93 the final phase, but it's tidier to do it here.
94
95 If more than one exported thing is equal to a local thing (i.e., the
96 local thing really is shared), then we do one only:
97 \begin{verbatim}
98         x_local = ....
99         x_exported1 = x_local
100         x_exported2 = x_local
101 ==>
102         x_exported1 = ....
103
104         x_exported2 = x_exported1
105 \end{verbatim}
106
107 We rely on prior eta reduction to simplify things like
108 \begin{verbatim}
109         x_exported = /\ tyvars -> x_local tyvars
110 ==>
111         x_exported = x_local
112 \end{verbatim}
113 Hence,there's a possibility of leaving unchanged something like this:
114 \begin{verbatim}
115         x_local = ....
116         x_exported1 = x_local Int
117 \end{verbatim}
118 By the time we've thrown away the types in STG land this 
119 could be eliminated.  But I don't think it's very common
120 and it's dangerous to do this fiddling in STG land 
121 because we might elminate a binding that's mentioned in the
122 unfolding for something.
123
124 \begin{code}
125 occurAnalyseBinds :: [CoreBind] -> [CoreBind]
126
127 occurAnalyseBinds binds
128   = binds'
129   where
130     (_, _, binds') = go (initOccEnv emptyVarSet) binds
131
132     go :: OccEnv -> [CoreBind]
133        -> (UsageDetails,        -- Occurrence info
134            IdEnv Id,            -- Indirection elimination info
135                                 --   Maps local-id -> exported-id, but it embodies
136                                 --   bindings of the form exported-id = local-id in
137                                 --   the argument to go
138            [CoreBind])          -- Occ-analysed bindings, less the exported-id=local-id ones
139
140     go env [] = (emptyDetails, emptyVarEnv, [])
141
142     go env (bind : binds)
143       = let
144             new_env                        = env `addNewCands` (bindersOf bind)
145             (scope_usage, ind_env, binds') = go new_env binds
146             (final_usage, new_binds)       = occAnalBind env (zapBind ind_env bind) scope_usage
147                                                 -- NB: I zap before occur-analysing, so
148                                                 -- I don't need to worry about getting the
149                                                 -- occ info on the new bindings right.
150         in
151         case bind of
152             NonRec exported_id (Var local_id) 
153                 | shortMeOut ind_env exported_id local_id
154                 -- Special case for eliminating indirections
155                 --   Note: it's a shortcoming that this only works for
156                 --         non-recursive bindings.  Elminating indirections
157                 --         makes perfect sense for recursive bindings too, but
158                 --         it's more complicated to implement, so I haven't done so
159                 -> (scope_usage, ind_env', binds')
160                 where
161                    ind_env' = extendVarEnv ind_env local_id exported_id
162
163             other ->    -- Ho ho! The normal case
164                      (final_usage, ind_env, new_binds ++ binds')
165                    
166
167 -- Deal with any indirections
168 zapBind ind_env (NonRec bndr rhs) 
169   | bndr `elemVarEnv` ind_env                      = Rec (zap ind_env (bndr,rhs))
170                 -- The Rec isn't strictly necessary, but it's convenient
171 zapBind ind_env (Rec pairs)
172   | or [id `elemVarEnv` ind_env | (id,_) <- pairs] = Rec (concat (map (zap ind_env) pairs))
173
174 zapBind ind_env bind = bind
175
176 zap ind_env pair@(local_id,rhs)
177   = case lookupVarEnv ind_env local_id of
178         Nothing          -> [pair]
179         Just exported_id -> [(local_id, Var exported_id),
180                              (exported_id', rhs)]
181                          where
182                             exported_id' = modifyIdInfo (copyIdInfo (idInfo local_id)) exported_id
183                         
184 shortMeOut ind_env exported_id local_id
185 -- The if-then-else stuff is just so I can get a pprTrace to see
186 -- how often I don't get shorting out becuase of IdInfo stuff
187   = if isExportedId exported_id &&              -- Only if this is exported
188
189        isLocalId local_id &&                    -- Only if this one is defined in this
190                                                 --      module, so that we *can* change its
191                                                 --      binding to be the exported thing!
192
193        not (isExportedId local_id) &&           -- Only if this one is not itself exported,
194                                                 --      since the transformation will nuke it
195    
196        not (local_id `elemVarEnv` ind_env)      -- Only if not already substituted for
197     then
198         if shortableIdInfo (idInfo exported_id)         -- Only if its IdInfo is 'shortable'
199                                                         -- (see the defn of IdInfo.shortableIdInfo)
200         then True
201         else 
202 #ifdef DEBUG 
203           pprTrace "shortMeOut:" (ppr exported_id)
204 #endif
205                                                 False
206     else
207         False
208 \end{code}
209
210
211 %************************************************************************
212 %*                                                                      *
213 \subsection[OccurAnal-main]{Counting occurrences: main function}
214 %*                                                                      *
215 %************************************************************************
216
217 Bindings
218 ~~~~~~~~
219
220 \begin{code}
221 type IdWithOccInfo = Id                 -- An Id with fresh PragmaInfo attached
222
223 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
224                                                 -- which is gotten from the Id.
225 type Details1     = (Id, UsageDetails, CoreExpr)
226 type Details2     = (IdWithOccInfo, CoreExpr)
227
228
229 occAnalBind :: OccEnv
230             -> CoreBind
231             -> UsageDetails             -- Usage details of scope
232             -> (UsageDetails,           -- Of the whole let(rec)
233                 [CoreBind])
234
235 occAnalBind env (NonRec binder rhs) body_usage
236   | not (binder `usedIn` body_usage)            -- It's not mentioned
237   = (body_usage, [])
238
239   | otherwise                   -- It's mentioned in the body
240   = (final_body_usage `combineUsageDetails` rhs_usage,
241      [NonRec tagged_binder rhs'])
242
243   where
244     (final_body_usage, tagged_binder) = tagBinder body_usage binder
245     (rhs_usage, rhs')                 = occAnalRhs env binder rhs
246 \end{code}
247
248 Dropping dead code for recursive bindings is done in a very simple way:
249
250         the entire set of bindings is dropped if none of its binders are
251         mentioned in its body; otherwise none are.
252
253 This seems to miss an obvious improvement.
254 @
255         letrec  f = ...g...
256                 g = ...f...
257         in
258         ...g...
259
260 ===>
261
262         letrec f = ...g...
263                g = ...(...g...)...
264         in
265         ...g...
266 @
267
268 Now @f@ is unused. But dependency analysis will sort this out into a
269 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
270 It isn't easy to do a perfect job in one blow.  Consider
271
272 @
273         letrec f = ...g...
274                g = ...h...
275                h = ...k...
276                k = ...m...
277                m = ...m...
278         in
279         ...m...
280 @
281
282
283 \begin{code}
284 occAnalBind env (Rec pairs) body_usage
285   = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
286   where
287     binders = map fst pairs
288     rhs_env = env `addNewCands` binders
289
290     analysed_pairs :: [Details1]
291     analysed_pairs  = [ (bndr, rhs_usage, rhs')
292                       | (bndr, rhs) <- pairs,
293                         let (rhs_usage, rhs') = occAnalRhs rhs_env bndr rhs
294                       ]
295
296     sccs :: [SCC (Node Details1)]
297     sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
298
299
300     ---- stuff for dependency analysis of binds -------------------------------
301     edges :: [Node Details1]
302     edges = _scc_ "occAnalBind.assoc"
303             [ (details, idUnique id, edges_from rhs_usage)
304             | details@(id, rhs_usage, rhs) <- analysed_pairs
305             ]
306
307         -- (a -> b) means a mentions b
308         -- Given the usage details (a UFM that gives occ info for each free var of
309         -- the RHS) we can get the list of free vars -- or rather their Int keys --
310         -- by just extracting the keys from the finite map.  Grimy, but fast.
311         -- Previously we had this:
312         --      [ bndr | bndr <- bndrs,
313         --               maybeToBool (lookupVarEnv rhs_usage bndr)]
314         -- which has n**2 cost, and this meant that edges_from alone 
315         -- consumed 10% of total runtime!
316     edges_from :: UsageDetails -> [Unique]
317     edges_from rhs_usage = _scc_ "occAnalBind.edges_from"
318                            keysUFM rhs_usage
319
320     ---- stuff to "re-constitute" bindings from dependency-analysis info ------
321
322         -- Non-recursive SCC
323     do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
324       | not (bndr `usedIn` body_usage)
325       = (body_usage, binds_so_far)                      -- Dead code
326       | otherwise
327       = (combined_usage, new_bind : binds_so_far)       
328       where
329         total_usage                   = combineUsageDetails body_usage rhs_usage
330         (combined_usage, tagged_bndr) = tagBinder total_usage bndr
331         new_bind                      = NonRec tagged_bndr rhs'
332
333         -- Recursive SCC
334     do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
335       | not (any (`usedIn` body_usage) bndrs)           -- NB: look at body_usage, not total_usage
336       = (body_usage, binds_so_far)                      -- Dead code
337       | otherwise
338       = (combined_usage, final_bind:binds_so_far)
339       where
340         details                        = [details   | (details, _, _) <- cycle]
341         bndrs                          = [bndr      | (bndr, _, _)      <- details]
342         rhs_usages                     = [rhs_usage | (_, rhs_usage, _) <- details]
343         total_usage                    = foldr combineUsageDetails body_usage rhs_usages
344         (combined_usage, tagged_bndrs) = tagBinders total_usage bndrs
345         final_bind                     = Rec (reOrderRec env new_cycle)
346
347         new_cycle = CyclicSCC (zipWithEqual "occAnalBind" mk_new_bind tagged_bndrs cycle)
348         mk_new_bind tagged_bndr ((_, _, rhs'), key, keys) = ((tagged_bndr, rhs'), key, keys)
349 \end{code}
350
351 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
352 strongly connected component (there's guaranteed to be a cycle).  It returns the
353 same pairs, but 
354         a) in a better order,
355         b) with some of the Ids having a IMustNotBeINLINEd pragma
356
357 The "no-inline" Ids are sufficient to break all cycles in the SCC.  This means
358 that the simplifier can guarantee not to loop provided it never records an inlining
359 for these no-inline guys.
360
361 Furthermore, the order of the binds is such that if we neglect dependencies
362 on the no-inline Ids then the binds are topologically sorted.  This means
363 that the simplifier will generally do a good job if it works from top bottom,
364 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
365
366 ==============
367 [June 98: I don't understand the following paragraphs, and I've 
368           changed the a=b case again so that it isn't a special case any more.]
369
370 Here's a case that bit me:
371
372         letrec
373                 a = b
374                 b = \x. BIG
375         in
376         ...a...a...a....
377
378 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
379
380 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
381 Perhaps something cleverer would suffice.
382 ===============
383
384 You might think that you can prevent non-termination simply by making
385 sure that we simplify a recursive binding's RHS in an environment that
386 simply clones the recursive Id.  But no.  Consider
387
388                 letrec f = \x -> let z = f x' in ...
389
390                 in
391                 let n = f y
392                 in
393                 case n of { ... }
394
395 We bind n to its *simplified* RHS, we then *re-simplify* it when
396 we inline n.  Then we may well inline f; and then the same thing
397 happens with z!
398
399 I don't think it's possible to prevent non-termination by environment
400 manipulation in this way.  Apart from anything else, successive
401 iterations of the simplifier may unroll recursive loops in cases like
402 that above.  The idea of beaking every recursive loop with an
403 IMustNotBeINLINEd pragma is much much better.
404
405
406 \begin{code}
407 reOrderRec
408         :: OccEnv
409         -> SCC (Node Details2)
410         -> [Details2]
411                         -- Sorted into a plausible order.  Enough of the Ids have
412                         --      dontINLINE pragmas that there are no loops left.
413
414         -- Non-recursive case
415 reOrderRec env (AcyclicSCC (bind, _, _)) = [bind]
416
417         -- Common case of simple self-recursion
418 reOrderRec env (CyclicSCC [bind])
419   = [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
420   where
421     ((tagged_bndr, rhs), _, _) = bind
422
423 reOrderRec env (CyclicSCC (bind : binds))
424   =     -- Choose a loop breaker, mark it no-inline,
425         -- do SCC analysis on the rest, and recursively sort them out
426     concat (map (reOrderRec env) (stronglyConnCompR unchosen))
427     ++ 
428     [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
429
430   where
431     (chosen_pair, unchosen) = choose_loop_breaker bind (score bind) [] binds
432     (tagged_bndr, rhs)      = chosen_pair
433
434         -- This loop looks for the bind with the lowest score
435         -- to pick as the loop  breaker.  The rest accumulate in 
436     choose_loop_breaker (details,_,_) loop_sc acc []
437         = (details, acc)        -- Done
438
439     choose_loop_breaker loop_bind loop_sc acc (bind : binds)
440         | sc < loop_sc  -- Lower score so pick this new one
441         = choose_loop_breaker bind sc (loop_bind : acc) binds
442
443         | otherwise     -- No lower so don't pick it
444         = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
445         where
446           sc = score bind
447           
448     score :: Node Details2 -> Int       -- Higher score => less likely to be picked as loop breaker
449     score ((bndr, rhs), _, _)
450         | exprIsTrivial rhs        = 4  -- Practically certain to be inlined
451                 -- Used to have also: && not (isExportedId bndr)
452                 -- But I found this sometimes cost an extra iteration when we have
453                 --      rec { d = (a,b); a = ...df...; b = ...df...; df = d }
454                 -- where df is the exported dictionary. Then df makes a really
455                 -- bad choice for loop breaker
456           
457         | not_fun_ty (idType bndr) = 3  -- Data types help with cases
458                 -- This used to have a lower score than inlineCandidate, but
459                 -- it's *really* helpful if dictionaries get inlined fast,
460                 -- so I'm experimenting with giving higher priority to data-typed things
461
462         | inlineCandidate bndr rhs = 2  -- Likely to be inlined
463
464         | not (isEmptyCoreRules (idSpecialisation bndr)) = 1
465                 -- Avoid things with specialisations; we'd like
466                 -- to take advantage of them in the subsequent bindings
467
468         | otherwise = 0
469
470     inlineCandidate :: Id -> CoreExpr -> Bool
471     inlineCandidate id (Note InlineMe _) = True
472     inlineCandidate id rhs               = isOneOcc (idOccInfo id)
473
474         -- Real example (the Enum Ordering instance from PrelBase):
475         --      rec     f = \ x -> case d of (p,q,r) -> p x
476         --              g = \ x -> case d of (p,q,r) -> q x
477         --              d = (v, f, g)
478         --
479         -- Here, f and g occur just once; but we can't inline them into d.
480         -- On the other hand we *could* simplify those case expressions if
481         -- we didn't stupidly choose d as the loop breaker.
482         -- But we won't because constructor args are marked "Many".
483
484     not_fun_ty ty = not (maybeToBool (splitFunTy_maybe rho_ty))
485                   where
486                     (_, rho_ty) = splitForAllTys ty
487 \end{code}
488
489 @occAnalRhs@ deals with the question of bindings where the Id is marked
490 by an INLINE pragma.  For these we record that anything which occurs
491 in its RHS occurs many times.  This pessimistically assumes that ths
492 inlined binder also occurs many times in its scope, but if it doesn't
493 we'll catch it next time round.  At worst this costs an extra simplifier pass.
494 ToDo: try using the occurrence info for the inline'd binder.
495
496 [March 97] We do the same for atomic RHSs.  Reason: see notes with reOrderRec.
497 [June 98, SLPJ]  I've undone this change; I don't understand it.  See notes with reOrderRec.
498
499
500 \begin{code}
501 occAnalRhs :: OccEnv
502            -> Id -> CoreExpr    -- Binder and rhs
503            -> (UsageDetails, CoreExpr)
504
505 occAnalRhs env id rhs
506   = (final_usage, rhs')
507   where
508     (rhs_usage, rhs') = occAnal (rhsCtxt env) rhs
509         -- Note that we use an rhsCtxt.  This tells the occ anal that it's
510         -- looking at an RHS, which has an effect in occAnalApp
511         --
512         -- But there's a problem.  Consider
513         --      x1 = a0 : []
514         --      x2 = a1 : x1
515         --      x3 = a2 : x2
516         --      g  = f x2
517         -- First time round, it looks as if x1 and x2 occur as an arg of a 
518         -- let-bound constructor ==> give them a many-occurrence.
519         -- But then x3 is inlined (unconditionally as it happens) and
520         -- next time round, x2 will be, and the next time round x1 will be
521         -- Result: multiple simplifier iterations.  Sigh.  
522         -- Possible solution: use rhsCtxt for things that occur just once...
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 NoOccInfo           -- 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 oneOcc
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) False
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 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, env1, _) = oneShotGroup env binders
637     env2              = env1 `addNewCands` binders      -- Add in-scope binders
638     env_body          = vanillaCtxt env2                -- Body is (no longer) an RhsContext
639
640 occAnal env (Case scrut bndr alts)
641   = case mapAndUnzip (occAnalAlt alt_env bndr) alts of { (alts_usage_s, alts')   -> 
642     case occAnal (vanillaCtxt env) scrut                    of { (scrut_usage, scrut') ->
643         -- No need for rhsCtxt
644     let
645         alts_usage  = foldr1 combineAltsUsageDetails alts_usage_s
646         alts_usage' = addCaseBndrUsage alts_usage
647         (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
648         total_usage = scrut_usage `combineUsageDetails` alts_usage1
649     in
650     total_usage `seq` (total_usage, Case scrut' tagged_bndr alts') }}
651   where
652     alt_env = env `addNewCand` bndr
653
654         -- The case binder gets a usage of either "many" or "dead", never "one".
655         -- Reason: we like to inline single occurrences, to eliminate a binding,
656         -- but inlining a case binder *doesn't* eliminate a binding.
657         -- We *don't* want to transform
658         --      case x of w { (p,q) -> f w }
659         -- into
660         --      case x of w { (p,q) -> f (p,q) }
661     addCaseBndrUsage usage = case lookupVarEnv usage bndr of
662                                 Nothing  -> usage
663                                 Just occ -> extendVarEnv usage bndr (markMany occ)
664
665 occAnal env (Let bind body)
666   = case occAnal new_env body            of { (body_usage, body') ->
667     case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
668        (final_usage, mkLets new_binds body') }}
669   where
670     new_env = env `addNewCands` (bindersOf bind)
671
672 occAnalArgs env args
673   = case mapAndUnzip (occAnal arg_env) args of  { (arg_uds_s, args') ->
674     (foldr combineUsageDetails emptyDetails arg_uds_s, args')}
675   where
676     arg_env = vanillaCtxt env
677 \end{code}
678
679 Applications are dealt with specially because we want
680 the "build hack" to work.
681
682 \begin{code}
683 -- Hack for build, fold, runST
684 occAnalApp env (Var fun, args) is_rhs
685   = case args_stuff of { (args_uds, args') ->
686     let
687         -- We mark the free vars of the argument of a constructor or PAP 
688         -- as "many", if it is the RHS of a let(rec).
689         -- This means that nothing gets inlined into a constructor argument
690         -- position, which is what we want.  Typically those constructor
691         -- arguments are just variables, or trivial expressions.
692         --
693         -- This is the *whole point* of the isRhsEnv predicate
694         final_args_uds
695                 | isRhsEnv env,
696                   isDataConId fun || valArgCount args < idArity fun
697                 = mapVarEnv markMany args_uds
698                 | otherwise = args_uds
699     in
700     (fun_uds `combineUsageDetails` final_args_uds, mkApps (Var fun) args') }
701   where
702     fun_uniq = idUnique fun
703
704     fun_uds | isCandidate env fun = unitVarEnv fun oneOcc
705             | otherwise           = emptyDetails
706
707     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
708                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
709                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
710                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]       args
711                         -- (foldr k z xs) may call k many times, but it never
712                         -- shares a partial application of k; hence [False,True]
713                         -- This means we can optimise
714                         --      foldr (\x -> let v = ...x... in \y -> ...v...) z xs
715                         -- by floating in the v
716
717                 | otherwise = occAnalArgs env args
718
719
720 occAnalApp env (fun, args) is_rhs
721   = case occAnal (addAppCtxt env args) fun of   { (fun_uds, fun') ->
722         -- The addAppCtxt is a bit cunning.  One iteration of the simplifier
723         -- often leaves behind beta redexs like
724         --      (\x y -> e) a1 a2
725         -- Here we would like to mark x,y as one-shot, and treat the whole
726         -- thing much like a let.  We do this by pushing some True items
727         -- onto the context stack.
728
729     case occAnalArgs env args of        { (args_uds, args') ->
730     let
731         final_uds = fun_uds `combineUsageDetails` args_uds
732     in
733     (final_uds, mkApps fun' args') }}
734     
735 appSpecial :: OccEnv 
736            -> Int -> CtxtTy     -- Argument number, and context to use for it
737            -> [CoreExpr]
738            -> (UsageDetails, [CoreExpr])
739 appSpecial env n ctxt args
740   = go n args
741   where
742     arg_env = vanillaCtxt env
743
744     go n [] = (emptyDetails, [])        -- Too few args
745
746     go 1 (arg:args)                     -- The magic arg
747       = case occAnal (setCtxt arg_env ctxt) arg of      { (arg_uds, arg') ->
748         case occAnalArgs env args of                    { (args_uds, args') ->
749         (combineUsageDetails arg_uds args_uds, arg':args') }}
750     
751     go n (arg:args)
752       = case occAnal arg_env arg of     { (arg_uds, arg') ->
753         case go (n-1) args of           { (args_uds, args') ->
754         (combineUsageDetails arg_uds args_uds, arg':args') }}
755 \end{code}
756
757     
758 Case alternatives
759 ~~~~~~~~~~~~~~~~~
760 If the case binder occurs at all, the other binders effectively do too.  
761 For example
762         case e of x { (a,b) -> rhs }
763 is rather like
764         let x = (a,b) in rhs
765 If e turns out to be (e1,e2) we indeed get something like
766         let a = e1; b = e2; x = (a,b) in rhs
767
768 \begin{code}
769 occAnalAlt env case_bndr (con, bndrs, rhs)
770   = case occAnal (env `addNewCands` bndrs) rhs of { (rhs_usage, rhs') ->
771     let
772         (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
773         final_bndrs | case_bndr `elemVarEnv` final_usage = bndrs
774                     | otherwise                         = tagged_bndrs
775                 -- Leave the binders untagged if the case 
776                 -- binder occurs at all; see note above
777     in
778     (final_usage, (con, final_bndrs, rhs')) }
779 \end{code}
780
781
782 %************************************************************************
783 %*                                                                      *
784 \subsection[OccurAnal-types]{OccEnv}
785 %*                                                                      *
786 %************************************************************************
787
788 \begin{code}
789 data OccEnv
790   = OccEnv IdSet        -- In-scope Ids; we gather info about these only
791            OccEncl      -- Enclosing context information
792            CtxtTy       -- Tells about linearity
793
794 -- OccEncl is used to control whether to inline into constructor arguments
795 -- For example:
796 --      x = (p,q)               -- Don't inline p or q
797 --      y = /\a -> (p a, q a)   -- Still don't inline p or q
798 --      z = f (p,q)             -- Do inline p,q; it may make a rule fire
799 -- So OccEncl tells enought about the context to know what to do when
800 -- we encounter a contructor application or PAP.
801
802 data OccEncl
803   = OccRhs              -- RHS of let(rec), albeit perhaps inside a type lambda
804                         -- Don't inline into constructor args here
805   | OccVanilla          -- Argument of function, body of lambda, scruintee of case etc.
806                         -- Do inline into constructor args here
807
808 type CtxtTy = [Bool]
809         -- []           No info
810         --
811         -- True:ctxt    Analysing a function-valued expression that will be
812         --                      applied just once
813         --
814         -- False:ctxt   Analysing a function-valued expression that may
815         --                      be applied many times; but when it is, 
816         --                      the CtxtTy inside applies
817
818 initOccEnv :: VarSet -> OccEnv
819 initOccEnv vars = OccEnv vars OccRhs []
820
821 isRhsEnv (OccEnv _ OccRhs     _) = True
822 isRhsEnv (OccEnv _ OccVanilla _) = False
823
824 isCandidate :: OccEnv -> Id -> Bool
825 isCandidate (OccEnv cands encl _) id = id `elemVarSet` cands 
826
827 addNewCands :: OccEnv -> [Id] -> OccEnv
828 addNewCands (OccEnv cands encl ctxt) ids
829   = OccEnv (cands `unionVarSet` mkVarSet ids) encl ctxt
830
831 addNewCand :: OccEnv -> Id -> OccEnv
832 addNewCand (OccEnv cands encl ctxt) id
833   = OccEnv (extendVarSet cands id) encl ctxt
834
835 setCtxt :: OccEnv -> CtxtTy -> OccEnv
836 setCtxt (OccEnv cands encl _) ctxt = OccEnv cands encl ctxt
837
838 oneShotGroup :: OccEnv -> [CoreBndr] -> (Bool, OccEnv, [CoreBndr])
839         -- True <=> this is a one-shot linear lambda group
840         -- The [CoreBndr] are the binders.
841
842         -- The result binders have one-shot-ness set that they might not have had originally.
843         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
844         -- linearity context knows that c,n are one-shot, and it records that fact in
845         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
846
847 oneShotGroup (OccEnv cands encl ctxt) bndrs 
848   = case go ctxt bndrs [] of
849         (new_ctxt, new_bndrs) -> (all is_one_shot new_bndrs, OccEnv cands encl new_ctxt, new_bndrs)
850   where
851     is_one_shot b = isId b && isOneShotLambda b
852
853     go ctxt [] rev_bndrs = (ctxt, reverse rev_bndrs)
854
855     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
856         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
857         where
858           bndr' | lin_ctxt  = setOneShotLambda bndr
859                 | otherwise = bndr
860
861     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
862
863
864 vanillaCtxt (OccEnv cands _ _) = OccEnv cands OccVanilla []
865 rhsCtxt     (OccEnv cands _ _) = OccEnv cands OccRhs     []
866
867 addAppCtxt (OccEnv cands encl ctxt) args 
868   = OccEnv cands encl (replicate (valArgCount args) True ++ ctxt)
869 \end{code}
870
871 %************************************************************************
872 %*                                                                      *
873 \subsection[OccurAnal-types]{OccEnv}
874 %*                                                                      *
875 %************************************************************************
876
877 \begin{code}
878 type UsageDetails = IdEnv OccInfo       -- A finite map from ids to their usage
879
880 combineUsageDetails, combineAltsUsageDetails
881         :: UsageDetails -> UsageDetails -> UsageDetails
882
883 combineUsageDetails usage1 usage2
884   = plusVarEnv_C addOccInfo usage1 usage2
885
886 combineAltsUsageDetails usage1 usage2
887   = plusVarEnv_C orOccInfo usage1 usage2
888
889 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
890 addOneOcc usage id info
891   = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
892         -- ToDo: make this more efficient
893
894 emptyDetails = (emptyVarEnv :: UsageDetails)
895
896 usedIn :: Id -> UsageDetails -> Bool
897 v `usedIn` details =  isExportedId v || v `elemVarEnv` details
898
899 tagBinders :: UsageDetails          -- Of scope
900            -> [Id]                  -- Binders
901            -> (UsageDetails,        -- Details with binders removed
902               [IdWithOccInfo])    -- Tagged binders
903
904 tagBinders usage binders
905  = let
906      usage' = usage `delVarEnvList` binders
907      uss    = map (setBinderOcc usage) binders
908    in
909    usage' `seq` (usage', uss)
910
911 tagBinder :: UsageDetails           -- Of scope
912           -> Id                     -- Binders
913           -> (UsageDetails,         -- Details with binders removed
914               IdWithOccInfo)        -- Tagged binders
915
916 tagBinder usage binder
917  = let
918      usage'  = usage `delVarEnv` binder
919      binder' = setBinderOcc usage binder
920    in
921    usage' `seq` (usage', binder')
922
923 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
924 setBinderOcc usage bndr
925   | isTyVar bndr      = bndr
926   | isExportedId bndr = case idOccInfo bndr of
927                           NoOccInfo -> bndr
928                           other     -> setIdOccInfo bndr NoOccInfo
929             -- Don't use local usage info for visible-elsewhere things
930             -- BUT *do* erase any IAmALoopBreaker annotation, because we're
931             -- about to re-generate it and it shouldn't be "sticky"
932                           
933   | otherwise = setIdOccInfo bndr occ_info
934   where
935     occ_info = lookupVarEnv usage bndr `orElse` IAmDead
936 \end{code}
937
938
939 %************************************************************************
940 %*                                                                      *
941 \subsection{Operations over OccInfo}
942 %*                                                                      *
943 %************************************************************************
944
945 \begin{code}
946 oneOcc :: OccInfo
947 oneOcc = OneOcc False True
948
949 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
950
951 markMany IAmDead = IAmDead
952 markMany other   = NoOccInfo
953
954 markInsideSCC occ = markMany occ
955
956 markInsideLam (OneOcc _ one_br) = OneOcc True one_br
957 markInsideLam occ               = occ
958
959 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
960
961 addOccInfo IAmDead info2 = info2
962 addOccInfo info1 IAmDead = info1
963 addOccInfo info1 info2   = NoOccInfo
964
965 -- (orOccInfo orig new) is used
966 -- when combining occurrence info from branches of a case
967
968 orOccInfo IAmDead info2 = info2
969 orOccInfo info1 IAmDead = info1
970 orOccInfo (OneOcc in_lam1 one_branch1)
971           (OneOcc in_lam2 one_branch2)
972   = OneOcc (in_lam1 || in_lam2)
973            False        -- False, because it occurs in both branches
974
975 orOccInfo info1 info2 = NoOccInfo
976 \end{code}