[project @ 1999-11-01 17:09:54 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, occurAnalyseExpr, occurAnalyseGlobalExpr,
16         markBinderInsideLambda, tagBinders,
17         UsageDetails
18     ) where
19
20 #include "HsVersions.h"
21
22 import BinderInfo
23 import CmdLineOpts      ( SimplifierSwitch(..) )
24 import CoreSyn
25 import CoreFVs          ( idRuleVars )
26 import CoreUtils        ( exprIsTrivial )
27 import Const            ( Con(..), Literal(..) )
28 import Id               ( isSpecPragmaId, isOneShotLambda, setOneShotLambda, 
29                           getIdOccInfo, setIdOccInfo,
30                           isExportedId, modifyIdInfo, idInfo,
31                           getIdSpecialisation, 
32                           idType, idUnique, Id
33                         )
34 import IdInfo           ( OccInfo(..), insideLam, copyIdInfo )
35
36 import VarSet
37 import VarEnv
38
39 import ThinAir          ( noRepStrIds, noRepIntegerIds )
40 import Name             ( isLocallyDefined )
41 import Type             ( splitFunTy_maybe, splitForAllTys )
42 import Maybes           ( maybeToBool )
43 import Digraph          ( stronglyConnCompR, SCC(..) )
44 import Unique           ( u2i, buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
45 import UniqFM           ( keysUFM )  
46 import Util             ( zipWithEqual, mapAndUnzip, count )
47 import Outputable
48 \end{code}
49
50
51 %************************************************************************
52 %*                                                                      *
53 \subsection[OccurAnal-main]{Counting occurrences: main function}
54 %*                                                                      *
55 %************************************************************************
56
57 Here's the externally-callable interface:
58
59 \begin{code}
60 occurAnalyseExpr :: (Id -> Bool)        -- Tells if a variable is interesting
61                  -> CoreExpr
62                  -> (IdEnv BinderInfo,  -- Occ info for interesting free vars
63                      CoreExpr)
64
65 occurAnalyseExpr interesting expr
66   = occAnal initial_env expr
67   where
68     initial_env = OccEnv interesting emptyVarSet []
69
70 occurAnalyseGlobalExpr :: CoreExpr -> CoreExpr
71 occurAnalyseGlobalExpr expr
72   =     -- Top level expr, so no interesting free vars, and
73         -- discard occurence info returned
74     snd (occurAnalyseExpr (\_ -> False) expr)
75 \end{code}
76
77
78 %************************************************************************
79 %*                                                                      *
80 \subsection{Top level stuff}
81 %*                                                                      *
82 %************************************************************************
83
84 In @occAnalTop@ we do indirection-shorting.  That is, if we have this:
85
86         loc = <expression>
87         ...
88         exp = loc
89
90 where exp is exported, and loc is not, then we replace it with this:
91
92         loc = exp
93         exp = <expression>
94         ...
95
96 Without this we never get rid of the exp = loc thing.
97 This save a gratuitous jump
98 (from \tr{x_exported} to \tr{x_local}), and makes strictness
99 information propagate better.
100 This used to happen in the final phase, but it's tidier to do it here.
101
102
103 If more than one exported thing is equal to a local thing (i.e., the
104 local thing really is shared), then we do one only:
105 \begin{verbatim}
106         x_local = ....
107         x_exported1 = x_local
108         x_exported2 = x_local
109 ==>
110         x_exported1 = ....
111
112         x_exported2 = x_exported1
113 \end{verbatim}
114
115 We rely on prior eta reduction to simplify things like
116 \begin{verbatim}
117         x_exported = /\ tyvars -> x_local tyvars
118 ==>
119         x_exported = x_local
120 \end{verbatim}
121 Hence,there's a possibility of leaving unchanged something like this:
122 \begin{verbatim}
123         x_local = ....
124         x_exported1 = x_local Int
125 \end{verbatim}
126 By the time we've thrown away the types in STG land this 
127 could be eliminated.  But I don't think it's very common
128 and it's dangerous to do this fiddling in STG land 
129 because we might elminate a binding that's mentioned in the
130 unfolding for something.
131
132 \begin{code}
133 occurAnalyseBinds :: [CoreBind] -> [CoreBind]
134
135 occurAnalyseBinds binds
136   = binds'
137   where
138     (_, _, binds') = go initialTopEnv binds
139
140     go :: OccEnv -> [CoreBind]
141        -> (UsageDetails,        -- Occurrence info
142            IdEnv Id,            -- Indirection elimination info
143            [CoreBind])
144
145     go env [] = (emptyDetails, emptyVarEnv, [])
146
147     go env (bind : binds)
148       = let
149             new_env                        = env `addNewCands` (bindersOf bind)
150             (scope_usage, ind_env, binds') = go new_env binds
151             (final_usage, new_binds)       = occAnalBind env (zapBind ind_env bind) scope_usage
152                                                 -- NB: I zap before occur-analysing, so
153                                                 -- I don't need to worry about getting the
154                                                 -- occ info on the new bindings right.
155         in
156         case bind of
157             NonRec exported_id (Var local_id) 
158                 | shortMeOut ind_env exported_id local_id
159                 -- Special case for eliminating indirections
160                 --   Note: it's a shortcoming that this only works for
161                 --         non-recursive bindings.  Elminating indirections
162                 --         makes perfect sense for recursive bindings too, but
163                 --         it's more complicated to implement, so I haven't done so
164                 -> (scope_usage, ind_env', binds')
165                 where
166                    ind_env' = extendVarEnv ind_env local_id exported_id
167
168             other ->    -- Ho ho! The normal case
169                    (final_usage, ind_env, new_binds ++ binds')
170                    
171 initialTopEnv = OccEnv isLocallyDefined -- Anything local is interesting
172                        emptyVarSet
173                        []
174
175
176 -- Deal with any indirections
177 zapBind ind_env (NonRec bndr rhs) 
178   | bndr `elemVarEnv` ind_env                      = Rec (zap ind_env (bndr,rhs))
179                 -- The Rec isn't strictly necessary, but it's convenient
180 zapBind ind_env (Rec pairs)
181   | or [id `elemVarEnv` ind_env | (id,_) <- pairs] = Rec (concat (map (zap ind_env) pairs))
182
183 zapBind ind_env bind = bind
184
185 zap ind_env pair@(bndr,rhs)
186   = case lookupVarEnv ind_env bndr of
187         Nothing          -> [pair]
188         Just exported_id -> [(bndr, Var exported_id),
189                              (exported_id_w_info, rhs)]
190                          where
191                            exported_id_w_info = modifyIdInfo (copyIdInfo (idInfo bndr)) exported_id
192                                 -- See notes with copyIdInfo about propagating IdInfo from
193                                 -- one to t'other
194                         
195 shortMeOut ind_env exported_id local_id
196   = isExportedId exported_id &&         -- Only if this is exported
197
198     isLocallyDefined local_id &&        -- Only if this one is defined in this
199                                         --      module, so that we *can* change its
200                                         --      binding to be the exported thing!
201
202     not (isExportedId local_id) &&      -- Only if this one is not itself exported,
203                                         --      since the transformation will nuke it
204
205     not (local_id `elemVarEnv` ind_env)         -- Only if not already substituted for
206 \end{code}
207
208
209 %************************************************************************
210 %*                                                                      *
211 \subsection[OccurAnal-main]{Counting occurrences: main function}
212 %*                                                                      *
213 %************************************************************************
214
215 Bindings
216 ~~~~~~~~
217
218 \begin{code}
219 type IdWithOccInfo = Id                 -- An Id with fresh PragmaInfo attached
220
221 type Node details = (details, Int, [Int])       -- The Ints are gotten from the Unique,
222                                                 -- which is gotten from the Id.
223 type Details1     = (Id, UsageDetails, CoreExpr)
224 type Details2     = (IdWithOccInfo, CoreExpr)
225
226
227 occAnalBind :: OccEnv
228             -> CoreBind
229             -> UsageDetails             -- Usage details of scope
230             -> (UsageDetails,           -- Of the whole let(rec)
231                 [CoreBind])
232
233 occAnalBind env (NonRec binder rhs) body_usage
234   | not (binder `usedIn` body_usage)            -- It's not mentioned
235   = (body_usage, [])
236
237   | otherwise                   -- It's mentioned in the body
238   = (final_body_usage `combineUsageDetails` rhs_usage,
239      [NonRec tagged_binder rhs'])
240
241   where
242     (final_body_usage, tagged_binder) = tagBinder body_usage binder
243     (rhs_usage, rhs')                 = occAnalRhs env binder rhs
244 \end{code}
245
246 Dropping dead code for recursive bindings is done in a very simple way:
247
248         the entire set of bindings is dropped if none of its binders are
249         mentioned in its body; otherwise none are.
250
251 This seems to miss an obvious improvement.
252 @
253         letrec  f = ...g...
254                 g = ...f...
255         in
256         ...g...
257
258 ===>
259
260         letrec f = ...g...
261                g = ...(...g...)...
262         in
263         ...g...
264 @
265
266 Now @f@ is unused. But dependency analysis will sort this out into a
267 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
268 It isn't easy to do a perfect job in one blow.  Consider
269
270 @
271         letrec f = ...g...
272                g = ...h...
273                h = ...k...
274                k = ...m...
275                m = ...m...
276         in
277         ...m...
278 @
279
280
281 \begin{code}
282 occAnalBind env (Rec pairs) body_usage
283   = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
284   where
285     pp_item (_, bndr, _)     = ppr bndr
286
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, IBOX(u2i (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 -> [Int]
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 && 
451           not (isExportedId bndr)  = 3          -- Practically certain to be inlined
452         | inlineCandidate bndr rhs = 3          -- Likely to be inlined
453         | not_fun_ty (idType bndr) = 2          -- Data types help with cases
454         | not (isEmptyCoreRules (getIdSpecialisation bndr)) = 1
455                 -- Avoid things with specialisations; we'd like
456                 -- to take advantage of them in the subsequent bindings
457         | otherwise = 0
458
459     inlineCandidate :: Id -> CoreExpr -> Bool
460     inlineCandidate id (Note InlineMe _) = True
461     inlineCandidate id rhs               = case getIdOccInfo id of
462                                                 OneOcc _ _ -> True
463                                                 other      -> False
464
465         -- Real example (the Enum Ordering instance from PrelBase):
466         --      rec     f = \ x -> case d of (p,q,r) -> p x
467         --              g = \ x -> case d of (p,q,r) -> q x
468         --              d = (v, f, g)
469         --
470         -- Here, f and g occur just once; but we can't inline them into d.
471         -- On the other hand we *could* simplify those case expressions if
472         -- we didn't stupidly choose d as the loop breaker.
473         -- But we won't because constructor args are marked "Many".
474
475     not_fun_ty ty = not (maybeToBool (splitFunTy_maybe rho_ty))
476                   where
477                     (_, rho_ty) = splitForAllTys ty
478 \end{code}
479
480 @occAnalRhs@ deals with the question of bindings where the Id is marked
481 by an INLINE pragma.  For these we record that anything which occurs
482 in its RHS occurs many times.  This pessimistically assumes that ths
483 inlined binder also occurs many times in its scope, but if it doesn't
484 we'll catch it next time round.  At worst this costs an extra simplifier pass.
485 ToDo: try using the occurrence info for the inline'd binder.
486
487 [March 97] We do the same for atomic RHSs.  Reason: see notes with reOrderRec.
488 [June 98, SLPJ]  I've undone this change; I don't understand it.  See notes with reOrderRec.
489
490
491 \begin{code}
492 occAnalRhs :: OccEnv
493            -> Id -> CoreExpr    -- Binder and rhs
494            -> (UsageDetails, CoreExpr)
495
496 occAnalRhs env id rhs
497   = (final_usage, rhs')
498   where
499     (rhs_usage, rhs') = occAnal (zapCtxt env) rhs
500
501         -- [March 98] A new wrinkle is that if the binder has specialisations inside
502         -- it then we count the specialised Ids as "extra rhs's".  That way
503         -- the "parent" keeps the specialised "children" alive.  If the parent
504         -- dies (because it isn't referenced any more), then the children will
505         -- die too unless they are already referenced directly.
506
507     final_usage = foldVarSet add rhs_usage (idRuleVars id)
508     add v u = addOneOcc u v noBinderInfo        -- Give a non-committal binder info
509                                                 -- (i.e manyOcc) because many copies
510                                                 -- of the specialised thing can appear
511 \end{code}
512
513 Expressions
514 ~~~~~~~~~~~
515 \begin{code}
516 occAnal :: OccEnv
517         -> CoreExpr
518         -> (UsageDetails,       -- Gives info only about the "interesting" Ids
519             CoreExpr)
520
521 occAnal env (Type t)  = (emptyDetails, Type t)
522
523 occAnal env (Var v) 
524   = (var_uds, Var v)
525   where
526     var_uds | isCandidate env v = unitVarEnv v funOccZero
527             | otherwise         = emptyDetails
528
529     -- At one stage, I gathered the idRuleVars for v here too,
530     -- which in a way is the right thing to do.
531     -- But that went wrong right after specialisation, when
532     -- the *occurrences* of the overloaded function didn't have any
533     -- rules in them, so the *specialised* versions looked as if they
534     -- weren't used at all.
535
536 \end{code}
537
538 We regard variables that occur as constructor arguments as "dangerousToDup":
539
540 \begin{verbatim}
541 module A where
542 f x = let y = expensive x in 
543       let z = (True,y) in 
544       (case z of {(p,q)->q}, case z of {(p,q)->q})
545 \end{verbatim}
546
547 We feel free to duplicate the WHNF (True,y), but that means
548 that y may be duplicated thereby.
549
550 If we aren't careful we duplicate the (expensive x) call!
551 Constructors are rather like lambdas in this way.
552
553 \begin{code}
554         -- For NoRep literals we have to report an occurrence of
555         -- the things which tidyCore will later add, so that when
556         -- we are compiling the very module in which those thin-air Ids
557         -- are defined we have them in scope!
558 occAnal env expr@(Con (Literal lit) args)
559   = ASSERT( null args )
560     (mk_lit_uds lit, expr)
561   where
562     mk_lit_uds (NoRepStr _ _)     = try noRepStrIds
563     mk_lit_uds (NoRepInteger _ _) = try noRepIntegerIds
564     mk_lit_uds lit                = emptyDetails
565
566     try vs = foldr add emptyDetails vs
567     add v uds | isCandidate env v = extendVarEnv uds v funOccZero
568               | otherwise         = uds
569
570 occAnal env (Con con args)
571   = case occAnalArgs env args of { (arg_uds, args') ->
572     let 
573         -- We mark the free vars of the argument of a constructor as "many"
574         -- This means that nothing gets inlined into a constructor argument
575         -- position, which is what we want.  Typically those constructor
576         -- arguments are just variables, or trivial expressions.
577         final_arg_uds    = case con of
578                                 DataCon _ -> mapVarEnv markMany arg_uds
579                                 other     -> arg_uds
580     in
581     (final_arg_uds, Con con args')
582     }
583 \end{code}
584
585 \begin{code}
586 occAnal env (Note InlineMe body)
587   = case occAnal env body of { (usage, body') -> 
588     (mapVarEnv markMany usage, Note InlineMe body')
589     }
590
591 occAnal env (Note note@(SCC cc) body)
592   = case occAnal env body of { (usage, body') ->
593     (mapVarEnv markInsideSCC usage, Note note body')
594     }
595
596 occAnal env (Note note body)
597   = case occAnal env body of { (usage, body') ->
598     (usage, Note note body')
599     }
600 \end{code}
601
602 \begin{code}
603 occAnal env app@(App fun arg)
604   = occAnalApp env (collectArgs app)
605
606 -- Ignore type variables altogether
607 --   (a) occurrences inside type lambdas only not marked as InsideLam
608 --   (b) type variables not in environment
609
610 occAnal env expr@(Lam x body) | isTyVar x
611   = case occAnal env body of { (body_usage, body') ->
612     (body_usage, Lam x body')
613     }
614
615 -- For value lambdas we do a special hack.  Consider
616 --      (\x. \y. ...x...)
617 -- If we did nothing, x is used inside the \y, so would be marked
618 -- as dangerous to dup.  But in the common case where the abstraction
619 -- is applied to two arguments this is over-pessimistic.
620 -- So instead, we just mark each binder with its occurrence
621 -- info in the *body* of the multiple lambda.
622 -- Then, the simplifier is careful when partially applying lambdas.
623
624 occAnal env expr@(Lam _ _)
625   = case occAnal (env_body `addNewCands` binders) body of { (body_usage, body') ->
626     let
627         (final_usage, tagged_binders) = tagBinders body_usage binders
628         --      URGH!  Sept 99: we don't seem to be able to use binders' here, because
629         --      we get linear-typed things in the resulting program that we can't handle yet.
630         --      (e.g. PrelShow)  TODO 
631
632         really_final_usage = if linear then
633                                 final_usage
634                              else
635                                 mapVarEnv markInsideLam final_usage
636     in
637     (really_final_usage,
638      mkLams tagged_binders body') }
639   where
640     (binders, body)    = collectBinders expr
641     (linear, env_body, binders') = oneShotGroup env binders
642
643 occAnal env (Case scrut bndr alts)
644   = case mapAndUnzip (occAnalAlt alt_env) alts of { (alts_usage_s, alts')   -> 
645     case occAnal (zapCtxt env) scrut           of { (scrut_usage, scrut') ->
646     let
647         alts_usage  = foldr1 combineAltsUsageDetails alts_usage_s
648         alts_usage' = addCaseBndrUsage alts_usage
649         (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
650         total_usage = scrut_usage `combineUsageDetails` alts_usage1
651     in
652     total_usage `seq` (total_usage, Case scrut' tagged_bndr alts') }}
653   where
654     alt_env = env `addNewCand` bndr
655
656         -- The case binder gets a usage of either "many" or "dead", never "one".
657         -- Reason: we like to inline single occurrences, to eliminate a binding,
658         -- but inlining a case binder *doesn't* eliminate a binding.
659         -- We *don't* want to transform
660         --      case x of w { (p,q) -> f w }
661         -- into
662         --      case x of w { (p,q) -> f (p,q) }
663     addCaseBndrUsage usage = case lookupVarEnv usage bndr of
664                                 Nothing  -> usage
665                                 Just occ -> extendVarEnv usage bndr (markMany occ)
666
667 occAnal env (Let bind body)
668   = case occAnal new_env body            of { (body_usage, body') ->
669     case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
670        (final_usage, mkLets new_binds body') }}
671   where
672     new_env = env `addNewCands` (bindersOf bind)
673
674 occAnalArgs env args
675   = case mapAndUnzip (occAnal arg_env) args of  { (arg_uds_s, args') ->
676     (foldr combineUsageDetails emptyDetails arg_uds_s, args')}
677   where
678     arg_env = zapCtxt env
679 \end{code}
680
681 Applications are dealt with specially because we want
682 the "build hack" to work.
683
684 \begin{code}
685 -- Hack for build, fold, runST
686 occAnalApp env (Var fun, args)
687   = case args_stuff of { (args_uds, args') ->
688     let
689         final_uds = fun_uds `combineUsageDetails` args_uds
690     in
691     (final_uds, mkApps (Var fun) args') }
692   where
693     fun_uniq = idUnique fun
694
695     fun_uds | isCandidate env fun = unitVarEnv fun funOccZero
696             | otherwise           = emptyDetails
697
698     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
699                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
700                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
701                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]    args
702                 | otherwise                 = occAnalArgs env args
703
704 occAnalApp env (fun, args)
705   = case occAnal (zapCtxt env) fun of           { (fun_uds, fun') ->
706     case occAnalArgs env args of                { (args_uds, args') ->
707     let
708         final_uds = fun_uds `combineUsageDetails` args_uds
709     in
710     (final_uds, mkApps fun' args') }}
711     
712 appSpecial :: OccEnv -> Int -> CtxtTy -> [CoreExpr] -> (UsageDetails, [CoreExpr])
713 appSpecial env n ctxt args
714   = go n args
715   where
716     go n [] = (emptyDetails, [])        -- Too few args
717
718     go 1 (arg:args)                     -- The magic arg
719       = case occAnal (setCtxt env ctxt) arg of  { (arg_uds, arg') ->
720         case occAnalArgs env args of            { (args_uds, args') ->
721         (combineUsageDetails arg_uds args_uds, arg':args') }}
722     
723     go n (arg:args)
724       = case occAnal env arg of         { (arg_uds, arg') ->
725         case go (n-1) args of           { (args_uds, args') ->
726         (combineUsageDetails arg_uds args_uds, arg':args') }}
727 \end{code}
728
729     
730 Case alternatives
731 ~~~~~~~~~~~~~~~~~
732 \begin{code}
733 occAnalAlt env (con, bndrs, rhs)
734   = case occAnal (env `addNewCands` bndrs) rhs of { (rhs_usage, rhs') ->
735     let
736         (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
737     in
738     (final_usage, (con, tagged_bndrs, rhs')) }
739 \end{code}
740
741
742 %************************************************************************
743 %*                                                                      *
744 \subsection[OccurAnal-types]{Data types}
745 %*                                                                      *
746 %************************************************************************
747
748 \begin{code}
749 -- We gather inforamtion for variables that are either
750 --      (a) in scope or
751 --      (b) interesting
752
753 data OccEnv =
754   OccEnv (Id -> Bool)   -- Tells whether an Id occurrence is interesting,
755          IdSet          -- In-scope Ids
756          CtxtTy         -- Tells about linearity
757
758 type CtxtTy = [Bool]
759         -- []           No info
760         --
761         -- True:ctxt    Analysing a function-valued expression that will be
762         --                      applied just once
763         --
764         -- False:ctxt   Analysing a function-valued expression that may
765         --                      be applied many times; but when it is, 
766         --                      the CtxtTy inside applies
767
768 isCandidate :: OccEnv -> Id -> Bool
769 isCandidate (OccEnv ifun cands _) id = id `elemVarSet` cands || ifun id
770
771 addNewCands :: OccEnv -> [Id] -> OccEnv
772 addNewCands (OccEnv ifun cands ctxt) ids
773   = OccEnv ifun (cands `unionVarSet` mkVarSet ids) ctxt
774
775 addNewCand :: OccEnv -> Id -> OccEnv
776 addNewCand (OccEnv ifun cands ctxt) id
777   = OccEnv ifun (extendVarSet cands id) ctxt
778
779 setCtxt :: OccEnv -> CtxtTy -> OccEnv
780 setCtxt (OccEnv ifun cands _) ctxt = OccEnv ifun cands ctxt
781
782 oneShotGroup :: OccEnv -> [CoreBndr] -> (Bool, OccEnv, [CoreBndr])
783         -- True <=> this is a one-shot linear lambda group
784         -- The [CoreBndr] are the binders.
785
786         -- The result binders have one-shot-ness set that they might not have had originally.
787         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
788         -- linearity context knows that c,n are one-shot, and it records that fact in
789         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
790
791 oneShotGroup (OccEnv ifun cands ctxt) bndrs 
792   = case go ctxt bndrs [] of
793         (new_ctxt, new_bndrs) -> (all is_one_shot new_bndrs, OccEnv ifun cands new_ctxt, new_bndrs)
794   where
795     is_one_shot b = isId b && isOneShotLambda b
796
797     go ctxt [] rev_bndrs = (ctxt, reverse rev_bndrs)
798
799     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
800         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
801         where
802           bndr' | lin_ctxt  = setOneShotLambda bndr
803                 | otherwise = bndr
804
805     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
806
807
808 zapCtxt env@(OccEnv ifun cands []) = env
809 zapCtxt     (OccEnv ifun cands _ ) = OccEnv ifun cands []
810
811 type UsageDetails = IdEnv BinderInfo    -- A finite map from ids to their usage
812
813 combineUsageDetails, combineAltsUsageDetails
814         :: UsageDetails -> UsageDetails -> UsageDetails
815
816 combineUsageDetails usage1 usage2
817   = plusVarEnv_C addBinderInfo usage1 usage2
818
819 combineAltsUsageDetails usage1 usage2
820   = plusVarEnv_C orBinderInfo usage1 usage2
821
822 addOneOcc :: UsageDetails -> Id -> BinderInfo -> UsageDetails
823 addOneOcc usage id info
824   = plusVarEnv_C addBinderInfo usage (unitVarEnv id info)
825         -- ToDo: make this more efficient
826
827 emptyDetails = (emptyVarEnv :: UsageDetails)
828
829 unitDetails id info = (unitVarEnv id info :: UsageDetails)
830
831 usedIn :: Id -> UsageDetails -> Bool
832 v `usedIn` details =  isExportedId v || v `elemVarEnv` details
833
834 tagBinders :: UsageDetails          -- Of scope
835            -> [Id]                  -- Binders
836            -> (UsageDetails,        -- Details with binders removed
837               [IdWithOccInfo])    -- Tagged binders
838
839 tagBinders usage binders
840  = let
841      usage' = usage `delVarEnvList` binders
842      uss    = map (setBinderOcc usage) binders
843    in
844    usage' `seq` (usage', uss)
845
846 tagBinder :: UsageDetails           -- Of scope
847           -> Id                     -- Binders
848           -> (UsageDetails,         -- Details with binders removed
849               IdWithOccInfo)        -- Tagged binders
850
851 tagBinder usage binder
852  = let
853      usage'  = usage `delVarEnv` binder
854      binder' = setBinderOcc usage binder
855    in
856    usage' `seq` (usage', binder')
857
858
859 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
860 setBinderOcc usage bndr
861   | isTyVar bndr      = bndr
862   | isExportedId bndr 
863   = -- Don't use local usage info for visible-elsewhere things
864     -- BUT *do* erase any IAmALoopBreaker annotation, because we're
865     -- about to re-generate it and it shouldn't be "sticky"
866     case getIdOccInfo bndr of
867         NoOccInfo -> bndr
868         other     -> setIdOccInfo bndr NoOccInfo
869                           
870   | otherwise         = setIdOccInfo bndr occ_info
871   where
872     occ_info = case lookupVarEnv usage bndr of
873                  Nothing   -> IAmDead
874                  Just info -> binderInfoToOccInfo info
875
876 markBinderInsideLambda :: CoreBndr -> CoreBndr
877 markBinderInsideLambda bndr
878   | isTyVar bndr
879   = bndr
880
881   | otherwise
882   = case getIdOccInfo bndr of
883         OneOcc _ once -> bndr `setIdOccInfo` OneOcc insideLam once
884         other         -> bndr
885
886 funOccZero = funOccurrence 0
887 \end{code}