2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %************************************************************************
6 \section[OccurAnal]{Occurrence analysis pass}
8 %************************************************************************
10 The occurrence analyser re-typechecks a core expression, returning a new
11 core expression with (hopefully) improved usage information.
15 occurAnalyseBinds, occurAnalyseGlobalExpr, occurAnalyseRule
18 #include "HsVersions.h"
21 import CoreFVs ( idRuleVars )
22 import CoreUtils ( exprIsTrivial )
23 import Id ( isDataConId, isOneShotLambda, setOneShotLambda,
24 idOccInfo, setIdOccInfo,
25 isExportedId, modifyIdInfo, idInfo,
26 idSpecialisation, isLocalId,
29 import IdInfo ( OccInfo(..), shortableIdInfo, copyIdInfo )
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 )
46 %************************************************************************
48 \subsection[OccurAnal-main]{Counting occurrences: main function}
50 %************************************************************************
52 Here's the externally-callable interface:
55 occurAnalyseExpr :: (Id -> Bool) -- Tells if a variable is interesting
57 -> (IdEnv OccInfo, -- Occ info for interesting free vars
60 occurAnalyseExpr interesting expr
61 = occAnal initial_env expr
63 initial_env = OccEnv interesting emptyVarSet []
65 occurAnalyseGlobalExpr :: CoreExpr -> CoreExpr
66 occurAnalyseGlobalExpr expr
67 = -- Top level expr, so no interesting free vars, and
68 -- discard occurence info returned
69 snd (occurAnalyseExpr (\_ -> False) expr)
71 occurAnalyseRule :: CoreRule -> CoreRule
72 occurAnalyseRule rule@(BuiltinRule _) = rule
73 occurAnalyseRule (Rule str tpl_vars tpl_args rhs)
74 -- Add occ info to tpl_vars, rhs
75 = Rule str tpl_vars' tpl_args rhs'
77 (rhs_uds, rhs') = occurAnalyseExpr isLocalId rhs
78 (_, tpl_vars') = tagBinders rhs_uds tpl_vars
82 %************************************************************************
84 \subsection{Top level stuff}
86 %************************************************************************
88 In @occAnalTop@ we do indirection-shorting. That is, if we have this:
90 x_local = <expression>
94 where exp is exported, and loc is not, then we replace it with this:
97 x_exported = <expression>
100 Without this we never get rid of the x_exported = x_local thing. This
101 save a gratuitous jump (from \tr{x_exported} to \tr{x_local}), and
102 makes strictness information propagate better. This used to happen in
103 the final phase, but it's tidier to do it here.
105 If more than one exported thing is equal to a local thing (i.e., the
106 local thing really is shared), then we do one only:
109 x_exported1 = x_local
110 x_exported2 = x_local
114 x_exported2 = x_exported1
117 We rely on prior eta reduction to simplify things like
119 x_exported = /\ tyvars -> x_local tyvars
123 Hence,there's a possibility of leaving unchanged something like this:
126 x_exported1 = x_local Int
128 By the time we've thrown away the types in STG land this
129 could be eliminated. But I don't think it's very common
130 and it's dangerous to do this fiddling in STG land
131 because we might elminate a binding that's mentioned in the
132 unfolding for something.
135 occurAnalyseBinds :: [CoreBind] -> [CoreBind]
137 occurAnalyseBinds binds
140 (_, _, binds') = go initialTopEnv binds
142 go :: OccEnv -> [CoreBind]
143 -> (UsageDetails, -- Occurrence info
144 IdEnv Id, -- Indirection elimination info
145 -- Maps local-id -> exported-id, but it embodies
146 -- bindings of the form exported-id = local-id in
147 -- the argument to go
148 [CoreBind]) -- Occ-analysed bindings, less the exported-id=local-id ones
150 go env [] = (emptyDetails, emptyVarEnv, [])
152 go env (bind : binds)
154 new_env = env `addNewCands` (bindersOf bind)
155 (scope_usage, ind_env, binds') = go new_env binds
156 (final_usage, new_binds) = occAnalBind env (zapBind ind_env bind) scope_usage
157 -- NB: I zap before occur-analysing, so
158 -- I don't need to worry about getting the
159 -- occ info on the new bindings right.
162 NonRec exported_id (Var local_id)
163 | shortMeOut ind_env exported_id local_id
164 -- Special case for eliminating indirections
165 -- Note: it's a shortcoming that this only works for
166 -- non-recursive bindings. Elminating indirections
167 -- makes perfect sense for recursive bindings too, but
168 -- it's more complicated to implement, so I haven't done so
169 -> (scope_usage, ind_env', binds')
171 ind_env' = extendVarEnv ind_env local_id exported_id
173 other -> -- Ho ho! The normal case
174 (final_usage, ind_env, new_binds ++ binds')
176 initialTopEnv = OccEnv isLocalId -- Anything local is interesting
181 -- Deal with any indirections
182 zapBind ind_env (NonRec bndr rhs)
183 | bndr `elemVarEnv` ind_env = Rec (zap ind_env (bndr,rhs))
184 -- The Rec isn't strictly necessary, but it's convenient
185 zapBind ind_env (Rec pairs)
186 | or [id `elemVarEnv` ind_env | (id,_) <- pairs] = Rec (concat (map (zap ind_env) pairs))
188 zapBind ind_env bind = bind
190 zap ind_env pair@(local_id,rhs)
191 = case lookupVarEnv ind_env local_id of
193 Just exported_id -> [(local_id, Var exported_id),
196 exported_id' = modifyIdInfo (copyIdInfo (idInfo local_id)) exported_id
198 shortMeOut ind_env exported_id local_id
199 -- The if-then-else stuff is just so I can get a pprTrace to see
200 -- how often I don't get shorting out becuase of IdInfo stuff
201 = if isExportedId exported_id && -- Only if this is exported
203 isLocalId local_id && -- Only if this one is defined in this
204 -- module, so that we *can* change its
205 -- binding to be the exported thing!
207 not (isExportedId local_id) && -- Only if this one is not itself exported,
208 -- since the transformation will nuke it
210 not (local_id `elemVarEnv` ind_env) -- Only if not already substituted for
212 if shortableIdInfo (idInfo exported_id) -- Only if its IdInfo is 'shortable'
213 -- (see the defn of IdInfo.shortableIdInfo)
215 else pprTrace "shortMeOut:" (ppr exported_id) False
221 %************************************************************************
223 \subsection[OccurAnal-main]{Counting occurrences: main function}
225 %************************************************************************
231 type IdWithOccInfo = Id -- An Id with fresh PragmaInfo attached
233 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
234 -- which is gotten from the Id.
235 type Details1 = (Id, UsageDetails, CoreExpr)
236 type Details2 = (IdWithOccInfo, CoreExpr)
239 occAnalBind :: OccEnv
241 -> UsageDetails -- Usage details of scope
242 -> (UsageDetails, -- Of the whole let(rec)
245 occAnalBind env (NonRec binder rhs) body_usage
246 | not (binder `usedIn` body_usage) -- It's not mentioned
249 | otherwise -- It's mentioned in the body
250 = (final_body_usage `combineUsageDetails` rhs_usage,
251 [NonRec tagged_binder rhs'])
254 (final_body_usage, tagged_binder) = tagBinder body_usage binder
255 (rhs_usage, rhs') = occAnalRhs env binder rhs
258 Dropping dead code for recursive bindings is done in a very simple way:
260 the entire set of bindings is dropped if none of its binders are
261 mentioned in its body; otherwise none are.
263 This seems to miss an obvious improvement.
278 Now @f@ is unused. But dependency analysis will sort this out into a
279 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
280 It isn't easy to do a perfect job in one blow. Consider
294 occAnalBind env (Rec pairs) body_usage
295 = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
297 binders = map fst pairs
298 rhs_env = env `addNewCands` binders
300 analysed_pairs :: [Details1]
301 analysed_pairs = [ (bndr, rhs_usage, rhs')
302 | (bndr, rhs) <- pairs,
303 let (rhs_usage, rhs') = occAnalRhs rhs_env bndr rhs
306 sccs :: [SCC (Node Details1)]
307 sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
310 ---- stuff for dependency analysis of binds -------------------------------
311 edges :: [Node Details1]
312 edges = _scc_ "occAnalBind.assoc"
313 [ (details, idUnique id, edges_from rhs_usage)
314 | details@(id, rhs_usage, rhs) <- analysed_pairs
317 -- (a -> b) means a mentions b
318 -- Given the usage details (a UFM that gives occ info for each free var of
319 -- the RHS) we can get the list of free vars -- or rather their Int keys --
320 -- by just extracting the keys from the finite map. Grimy, but fast.
321 -- Previously we had this:
322 -- [ bndr | bndr <- bndrs,
323 -- maybeToBool (lookupVarEnv rhs_usage bndr)]
324 -- which has n**2 cost, and this meant that edges_from alone
325 -- consumed 10% of total runtime!
326 edges_from :: UsageDetails -> [Unique]
327 edges_from rhs_usage = _scc_ "occAnalBind.edges_from"
330 ---- stuff to "re-constitute" bindings from dependency-analysis info ------
333 do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
334 | not (bndr `usedIn` body_usage)
335 = (body_usage, binds_so_far) -- Dead code
337 = (combined_usage, new_bind : binds_so_far)
339 total_usage = combineUsageDetails body_usage rhs_usage
340 (combined_usage, tagged_bndr) = tagBinder total_usage bndr
341 new_bind = NonRec tagged_bndr rhs'
344 do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
345 | not (any (`usedIn` body_usage) bndrs) -- NB: look at body_usage, not total_usage
346 = (body_usage, binds_so_far) -- Dead code
348 = (combined_usage, final_bind:binds_so_far)
350 details = [details | (details, _, _) <- cycle]
351 bndrs = [bndr | (bndr, _, _) <- details]
352 rhs_usages = [rhs_usage | (_, rhs_usage, _) <- details]
353 total_usage = foldr combineUsageDetails body_usage rhs_usages
354 (combined_usage, tagged_bndrs) = tagBinders total_usage bndrs
355 final_bind = Rec (reOrderRec env new_cycle)
357 new_cycle = CyclicSCC (zipWithEqual "occAnalBind" mk_new_bind tagged_bndrs cycle)
358 mk_new_bind tagged_bndr ((_, _, rhs'), key, keys) = ((tagged_bndr, rhs'), key, keys)
361 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
362 strongly connected component (there's guaranteed to be a cycle). It returns the
364 a) in a better order,
365 b) with some of the Ids having a IMustNotBeINLINEd pragma
367 The "no-inline" Ids are sufficient to break all cycles in the SCC. This means
368 that the simplifier can guarantee not to loop provided it never records an inlining
369 for these no-inline guys.
371 Furthermore, the order of the binds is such that if we neglect dependencies
372 on the no-inline Ids then the binds are topologically sorted. This means
373 that the simplifier will generally do a good job if it works from top bottom,
374 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
377 [June 98: I don't understand the following paragraphs, and I've
378 changed the a=b case again so that it isn't a special case any more.]
380 Here's a case that bit me:
388 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
390 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
391 Perhaps something cleverer would suffice.
394 You might think that you can prevent non-termination simply by making
395 sure that we simplify a recursive binding's RHS in an environment that
396 simply clones the recursive Id. But no. Consider
398 letrec f = \x -> let z = f x' in ...
405 We bind n to its *simplified* RHS, we then *re-simplify* it when
406 we inline n. Then we may well inline f; and then the same thing
409 I don't think it's possible to prevent non-termination by environment
410 manipulation in this way. Apart from anything else, successive
411 iterations of the simplifier may unroll recursive loops in cases like
412 that above. The idea of beaking every recursive loop with an
413 IMustNotBeINLINEd pragma is much much better.
419 -> SCC (Node Details2)
421 -- Sorted into a plausible order. Enough of the Ids have
422 -- dontINLINE pragmas that there are no loops left.
424 -- Non-recursive case
425 reOrderRec env (AcyclicSCC (bind, _, _)) = [bind]
427 -- Common case of simple self-recursion
428 reOrderRec env (CyclicSCC [bind])
429 = [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
431 ((tagged_bndr, rhs), _, _) = bind
433 reOrderRec env (CyclicSCC (bind : binds))
434 = -- Choose a loop breaker, mark it no-inline,
435 -- do SCC analysis on the rest, and recursively sort them out
436 concat (map (reOrderRec env) (stronglyConnCompR unchosen))
438 [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
441 (chosen_pair, unchosen) = choose_loop_breaker bind (score bind) [] binds
442 (tagged_bndr, rhs) = chosen_pair
444 -- This loop looks for the bind with the lowest score
445 -- to pick as the loop breaker. The rest accumulate in
446 choose_loop_breaker (details,_,_) loop_sc acc []
447 = (details, acc) -- Done
449 choose_loop_breaker loop_bind loop_sc acc (bind : binds)
450 | sc < loop_sc -- Lower score so pick this new one
451 = choose_loop_breaker bind sc (loop_bind : acc) binds
453 | otherwise -- No lower so don't pick it
454 = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
458 score :: Node Details2 -> Int -- Higher score => less likely to be picked as loop breaker
459 score ((bndr, rhs), _, _)
460 | exprIsTrivial rhs = 4 -- Practically certain to be inlined
461 -- Used to have also: && not (isExportedId bndr)
462 -- But I found this sometimes cost an extra iteration when we have
463 -- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
464 -- where df is the exported dictionary. Then df makes a really
465 -- bad choice for loop breaker
467 | not_fun_ty (idType bndr) = 3 -- Data types help with cases
468 -- This used to have a lower score than inlineCandidate, but
469 -- it's *really* helpful if dictionaries get inlined fast,
470 -- so I'm experimenting with giving higher priority to data-typed things
472 | inlineCandidate bndr rhs = 2 -- Likely to be inlined
474 | not (isEmptyCoreRules (idSpecialisation bndr)) = 1
475 -- Avoid things with specialisations; we'd like
476 -- to take advantage of them in the subsequent bindings
480 inlineCandidate :: Id -> CoreExpr -> Bool
481 inlineCandidate id (Note InlineMe _) = True
482 inlineCandidate id rhs = case idOccInfo id of
486 -- Real example (the Enum Ordering instance from PrelBase):
487 -- rec f = \ x -> case d of (p,q,r) -> p x
488 -- g = \ x -> case d of (p,q,r) -> q x
491 -- Here, f and g occur just once; but we can't inline them into d.
492 -- On the other hand we *could* simplify those case expressions if
493 -- we didn't stupidly choose d as the loop breaker.
494 -- But we won't because constructor args are marked "Many".
496 not_fun_ty ty = not (maybeToBool (splitFunTy_maybe rho_ty))
498 (_, rho_ty) = splitForAllTys ty
501 @occAnalRhs@ deals with the question of bindings where the Id is marked
502 by an INLINE pragma. For these we record that anything which occurs
503 in its RHS occurs many times. This pessimistically assumes that ths
504 inlined binder also occurs many times in its scope, but if it doesn't
505 we'll catch it next time round. At worst this costs an extra simplifier pass.
506 ToDo: try using the occurrence info for the inline'd binder.
508 [March 97] We do the same for atomic RHSs. Reason: see notes with reOrderRec.
509 [June 98, SLPJ] I've undone this change; I don't understand it. See notes with reOrderRec.
514 -> Id -> CoreExpr -- Binder and rhs
515 -> (UsageDetails, CoreExpr)
517 occAnalRhs env id rhs
518 = (final_usage, rhs')
520 (rhs_usage, rhs') = occAnal (zapCtxt env) rhs
522 -- [March 98] A new wrinkle is that if the binder has specialisations inside
523 -- it then we count the specialised Ids as "extra rhs's". That way
524 -- the "parent" keeps the specialised "children" alive. If the parent
525 -- dies (because it isn't referenced any more), then the children will
526 -- die too unless they are already referenced directly.
528 final_usage = foldVarSet add rhs_usage (idRuleVars id)
529 add v u = addOneOcc u v NoOccInfo -- Give a non-committal binder info
530 -- (i.e manyOcc) because many copies
531 -- of the specialised thing can appear
539 -> (UsageDetails, -- Gives info only about the "interesting" Ids
542 occAnal env (Type t) = (emptyDetails, Type t)
547 var_uds | isCandidate env v = unitVarEnv v oneOcc
548 | otherwise = emptyDetails
550 -- At one stage, I gathered the idRuleVars for v here too,
551 -- which in a way is the right thing to do.
552 -- But that went wrong right after specialisation, when
553 -- the *occurrences* of the overloaded function didn't have any
554 -- rules in them, so the *specialised* versions looked as if they
555 -- weren't used at all.
559 We regard variables that occur as constructor arguments as "dangerousToDup":
563 f x = let y = expensive x in
565 (case z of {(p,q)->q}, case z of {(p,q)->q})
568 We feel free to duplicate the WHNF (True,y), but that means
569 that y may be duplicated thereby.
571 If we aren't careful we duplicate the (expensive x) call!
572 Constructors are rather like lambdas in this way.
575 occAnal env expr@(Lit lit) = (emptyDetails, expr)
579 occAnal env (Note InlineMe body)
580 = case occAnal env body of { (usage, body') ->
581 (mapVarEnv markMany usage, Note InlineMe body')
584 occAnal env (Note note@(SCC cc) body)
585 = case occAnal env body of { (usage, body') ->
586 (mapVarEnv markInsideSCC usage, Note note body')
589 occAnal env (Note note body)
590 = case occAnal env body of { (usage, body') ->
591 (usage, Note note body')
596 occAnal env app@(App fun arg)
597 = occAnalApp env (collectArgs app)
599 -- Ignore type variables altogether
600 -- (a) occurrences inside type lambdas only not marked as InsideLam
601 -- (b) type variables not in environment
603 occAnal env expr@(Lam x body) | isTyVar x
604 = case occAnal env body of { (body_usage, body') ->
605 (body_usage, Lam x body')
608 -- For value lambdas we do a special hack. Consider
610 -- If we did nothing, x is used inside the \y, so would be marked
611 -- as dangerous to dup. But in the common case where the abstraction
612 -- is applied to two arguments this is over-pessimistic.
613 -- So instead, we just mark each binder with its occurrence
614 -- info in the *body* of the multiple lambda.
615 -- Then, the simplifier is careful when partially applying lambdas.
617 occAnal env expr@(Lam _ _)
618 = case occAnal (env_body `addNewCands` binders) body of { (body_usage, body') ->
620 (final_usage, tagged_binders) = tagBinders body_usage binders
621 -- URGH! Sept 99: we don't seem to be able to use binders' here, because
622 -- we get linear-typed things in the resulting program that we can't handle yet.
623 -- (e.g. PrelShow) TODO
625 really_final_usage = if linear then
628 mapVarEnv markInsideLam final_usage
631 mkLams tagged_binders body') }
633 (binders, body) = collectBinders expr
634 (linear, env_body, _) = oneShotGroup env binders
636 occAnal env (Case scrut bndr alts)
637 = case mapAndUnzip (occAnalAlt alt_env) alts of { (alts_usage_s, alts') ->
638 case occAnal (zapCtxt env) scrut of { (scrut_usage, scrut') ->
640 alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
641 alts_usage' = addCaseBndrUsage alts_usage
642 (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
643 total_usage = scrut_usage `combineUsageDetails` alts_usage1
645 total_usage `seq` (total_usage, Case scrut' tagged_bndr alts') }}
647 alt_env = env `addNewCand` bndr
649 -- The case binder gets a usage of either "many" or "dead", never "one".
650 -- Reason: we like to inline single occurrences, to eliminate a binding,
651 -- but inlining a case binder *doesn't* eliminate a binding.
652 -- We *don't* want to transform
653 -- case x of w { (p,q) -> f w }
655 -- case x of w { (p,q) -> f (p,q) }
656 addCaseBndrUsage usage = case lookupVarEnv usage bndr of
658 Just occ -> extendVarEnv usage bndr (markMany occ)
660 occAnal env (Let bind body)
661 = case occAnal new_env body of { (body_usage, body') ->
662 case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
663 (final_usage, mkLets new_binds body') }}
665 new_env = env `addNewCands` (bindersOf bind)
668 = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
669 (foldr combineUsageDetails emptyDetails arg_uds_s, args')}
671 arg_env = zapCtxt env
674 Applications are dealt with specially because we want
675 the "build hack" to work.
678 -- Hack for build, fold, runST
679 occAnalApp env (Var fun, args)
680 = case args_stuff of { (args_uds, args') ->
682 final_uds = fun_uds `combineUsageDetails` args_uds
684 (final_uds, mkApps (Var fun) args') }
686 fun_uniq = idUnique fun
688 fun_uds | isCandidate env fun = unitVarEnv fun oneOcc
689 | otherwise = emptyDetails
691 args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
692 | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
693 | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
694 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
696 | isDataConId fun = case occAnalArgs env args of
697 (arg_uds, args') -> (mapVarEnv markMany arg_uds, args')
698 -- We mark the free vars of the argument of a constructor as "many"
699 -- This means that nothing gets inlined into a constructor argument
700 -- position, which is what we want. Typically those constructor
701 -- arguments are just variables, or trivial expressions.
703 | otherwise = occAnalArgs env args
706 occAnalApp env (fun, args)
707 = case occAnal (zapCtxt env) fun of { (fun_uds, fun') ->
708 case occAnalArgs env args of { (args_uds, args') ->
710 final_uds = fun_uds `combineUsageDetails` args_uds
712 (final_uds, mkApps fun' args') }}
714 appSpecial :: OccEnv -> Int -> CtxtTy -> [CoreExpr] -> (UsageDetails, [CoreExpr])
715 appSpecial env n ctxt args
718 go n [] = (emptyDetails, []) -- Too few args
720 go 1 (arg:args) -- The magic arg
721 = case occAnal (setCtxt env ctxt) arg of { (arg_uds, arg') ->
722 case occAnalArgs env args of { (args_uds, args') ->
723 (combineUsageDetails arg_uds args_uds, arg':args') }}
726 = case occAnal env arg of { (arg_uds, arg') ->
727 case go (n-1) args of { (args_uds, args') ->
728 (combineUsageDetails arg_uds args_uds, arg':args') }}
735 occAnalAlt env (con, bndrs, rhs)
736 = case occAnal (env `addNewCands` bndrs) rhs of { (rhs_usage, rhs') ->
738 (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
740 (final_usage, (con, tagged_bndrs, rhs')) }
744 %************************************************************************
746 \subsection[OccurAnal-types]{Data types}
748 %************************************************************************
751 -- We gather inforamtion for variables that are either
756 OccEnv (Id -> Bool) -- Tells whether an Id occurrence is interesting,
757 IdSet -- In-scope Ids
758 CtxtTy -- Tells about linearity
763 -- True:ctxt Analysing a function-valued expression that will be
766 -- False:ctxt Analysing a function-valued expression that may
767 -- be applied many times; but when it is,
768 -- the CtxtTy inside applies
770 isCandidate :: OccEnv -> Id -> Bool
771 isCandidate (OccEnv ifun cands _) id = id `elemVarSet` cands || ifun id
773 addNewCands :: OccEnv -> [Id] -> OccEnv
774 addNewCands (OccEnv ifun cands ctxt) ids
775 = OccEnv ifun (cands `unionVarSet` mkVarSet ids) ctxt
777 addNewCand :: OccEnv -> Id -> OccEnv
778 addNewCand (OccEnv ifun cands ctxt) id
779 = OccEnv ifun (extendVarSet cands id) ctxt
781 setCtxt :: OccEnv -> CtxtTy -> OccEnv
782 setCtxt (OccEnv ifun cands _) ctxt = OccEnv ifun cands ctxt
784 oneShotGroup :: OccEnv -> [CoreBndr] -> (Bool, OccEnv, [CoreBndr])
785 -- True <=> this is a one-shot linear lambda group
786 -- The [CoreBndr] are the binders.
788 -- The result binders have one-shot-ness set that they might not have had originally.
789 -- This happens in (build (\cn -> e)). Here the occurrence analyser
790 -- linearity context knows that c,n are one-shot, and it records that fact in
791 -- the binder. This is useful to guide subsequent float-in/float-out tranformations
793 oneShotGroup (OccEnv ifun cands ctxt) bndrs
794 = case go ctxt bndrs [] of
795 (new_ctxt, new_bndrs) -> (all is_one_shot new_bndrs, OccEnv ifun cands new_ctxt, new_bndrs)
797 is_one_shot b = isId b && isOneShotLambda b
799 go ctxt [] rev_bndrs = (ctxt, reverse rev_bndrs)
801 go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
802 | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
804 bndr' | lin_ctxt = setOneShotLambda bndr
807 go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
810 zapCtxt env@(OccEnv ifun cands []) = env
811 zapCtxt (OccEnv ifun cands _ ) = OccEnv ifun cands []
813 type UsageDetails = IdEnv OccInfo -- A finite map from ids to their usage
815 combineUsageDetails, combineAltsUsageDetails
816 :: UsageDetails -> UsageDetails -> UsageDetails
818 combineUsageDetails usage1 usage2
819 = plusVarEnv_C addOccInfo usage1 usage2
821 combineAltsUsageDetails usage1 usage2
822 = plusVarEnv_C orOccInfo usage1 usage2
824 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
825 addOneOcc usage id info
826 = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
827 -- ToDo: make this more efficient
829 emptyDetails = (emptyVarEnv :: UsageDetails)
831 usedIn :: Id -> UsageDetails -> Bool
832 v `usedIn` details = isExportedId v || v `elemVarEnv` details
834 tagBinders :: UsageDetails -- Of scope
836 -> (UsageDetails, -- Details with binders removed
837 [IdWithOccInfo]) -- Tagged binders
839 tagBinders usage binders
841 usage' = usage `delVarEnvList` binders
842 uss = map (setBinderOcc usage) binders
844 usage' `seq` (usage', uss)
846 tagBinder :: UsageDetails -- Of scope
848 -> (UsageDetails, -- Details with binders removed
849 IdWithOccInfo) -- Tagged binders
851 tagBinder usage binder
853 usage' = usage `delVarEnv` binder
854 binder' = setBinderOcc usage binder
856 usage' `seq` (usage', binder')
858 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
859 setBinderOcc usage bndr
860 | isTyVar bndr = bndr
861 | isExportedId bndr = case idOccInfo bndr of
863 other -> setIdOccInfo bndr NoOccInfo
864 -- Don't use local usage info for visible-elsewhere things
865 -- BUT *do* erase any IAmALoopBreaker annotation, because we're
866 -- about to re-generate it and it shouldn't be "sticky"
868 | otherwise = setIdOccInfo bndr occ_info
870 occ_info = lookupVarEnv usage bndr `orElse` IAmDead
874 %************************************************************************
876 \subsection{Operations over OccInfo}
878 %************************************************************************
882 oneOcc = OneOcc False True
884 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
886 markMany IAmDead = IAmDead
887 markMany other = NoOccInfo
889 markInsideSCC occ = markMany occ
891 markInsideLam (OneOcc _ one_br) = OneOcc True one_br
892 markInsideLam occ = occ
894 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
896 addOccInfo IAmDead info2 = info2
897 addOccInfo info1 IAmDead = info1
898 addOccInfo info1 info2 = NoOccInfo
900 -- (orOccInfo orig new) is used
901 -- when combining occurrence info from branches of a case
903 orOccInfo IAmDead info2 = info2
904 orOccInfo info1 IAmDead = info1
905 orOccInfo (OneOcc in_lam1 one_branch1)
906 (OneOcc in_lam2 one_branch2)
907 = OneOcc (in_lam1 || in_lam2)
908 False -- False, because it occurs in both branches
910 orOccInfo info1 info2 = NoOccInfo