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