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"
22 import CoreFVs ( idRuleVars )
23 import CoreUtils ( exprIsTrivial )
24 import Id ( isSpecPragmaId, isDataConId, isOneShotLambda, setOneShotLambda,
25 idOccInfo, setIdOccInfo,
26 isExportedId, modifyIdInfo, idInfo,
30 import IdInfo ( OccInfo(..), insideLam, copyIdInfo )
35 import Name ( isLocallyDefined )
36 import Type ( splitFunTy_maybe, splitForAllTys )
37 import Maybes ( maybeToBool )
38 import Digraph ( stronglyConnCompR, SCC(..) )
39 import Unique ( u2i, buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
40 import UniqFM ( keysUFM )
41 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 BinderInfo, -- 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 isLocallyDefined rhs
78 (rhs_uds1, 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:
94 where exp is exported, and loc is not, then we replace it with this:
100 Without this we never get rid of the exp = loc thing.
101 This save a gratuitous jump
102 (from \tr{x_exported} to \tr{x_local}), and makes strictness
103 information propagate better.
104 This used to happen in the final phase, but it's tidier to do it here.
107 If more than one exported thing is equal to a local thing (i.e., the
108 local thing really is shared), then we do one only:
111 x_exported1 = x_local
112 x_exported2 = x_local
116 x_exported2 = x_exported1
119 We rely on prior eta reduction to simplify things like
121 x_exported = /\ tyvars -> x_local tyvars
125 Hence,there's a possibility of leaving unchanged something like this:
128 x_exported1 = x_local Int
130 By the time we've thrown away the types in STG land this
131 could be eliminated. But I don't think it's very common
132 and it's dangerous to do this fiddling in STG land
133 because we might elminate a binding that's mentioned in the
134 unfolding for something.
137 occurAnalyseBinds :: [CoreBind] -> [CoreBind]
139 occurAnalyseBinds binds
142 (_, _, binds') = go initialTopEnv binds
144 go :: OccEnv -> [CoreBind]
145 -> (UsageDetails, -- Occurrence info
146 IdEnv Id, -- Indirection elimination info
149 go env [] = (emptyDetails, emptyVarEnv, [])
151 go env (bind : binds)
153 new_env = env `addNewCands` (bindersOf bind)
154 (scope_usage, ind_env, binds') = go new_env binds
155 (final_usage, new_binds) = occAnalBind env (zapBind ind_env bind) scope_usage
156 -- NB: I zap before occur-analysing, so
157 -- I don't need to worry about getting the
158 -- occ info on the new bindings right.
161 NonRec exported_id (Var local_id)
162 | shortMeOut ind_env exported_id local_id
163 -- Special case for eliminating indirections
164 -- Note: it's a shortcoming that this only works for
165 -- non-recursive bindings. Elminating indirections
166 -- makes perfect sense for recursive bindings too, but
167 -- it's more complicated to implement, so I haven't done so
168 -> (scope_usage, ind_env', binds')
170 ind_env' = extendVarEnv ind_env local_id exported_id
172 other -> -- Ho ho! The normal case
173 (final_usage, ind_env, new_binds ++ binds')
175 initialTopEnv = OccEnv isLocallyDefined -- Anything local is interesting
180 -- Deal with any indirections
181 zapBind ind_env (NonRec bndr rhs)
182 | bndr `elemVarEnv` ind_env = Rec (zap ind_env (bndr,rhs))
183 -- The Rec isn't strictly necessary, but it's convenient
184 zapBind ind_env (Rec pairs)
185 | or [id `elemVarEnv` ind_env | (id,_) <- pairs] = Rec (concat (map (zap ind_env) pairs))
187 zapBind ind_env bind = bind
189 zap ind_env pair@(bndr,rhs)
190 = case lookupVarEnv ind_env bndr of
192 Just exported_id -> [(bndr, Var exported_id),
193 (exported_id_w_info, rhs)]
195 exported_id_w_info = modifyIdInfo (copyIdInfo (idInfo bndr)) exported_id
196 -- See notes with copyIdInfo about propagating IdInfo from
199 shortMeOut ind_env exported_id local_id
200 = isExportedId exported_id && -- Only if this is exported
202 isLocallyDefined local_id && -- Only if this one is defined in this
203 -- module, so that we *can* change its
204 -- binding to be the exported thing!
206 not (isExportedId local_id) && -- Only if this one is not itself exported,
207 -- since the transformation will nuke it
209 not (local_id `elemVarEnv` ind_env) -- Only if not already substituted for
213 %************************************************************************
215 \subsection[OccurAnal-main]{Counting occurrences: main function}
217 %************************************************************************
223 type IdWithOccInfo = Id -- An Id with fresh PragmaInfo attached
225 type Node details = (details, Int, [Int]) -- The Ints are gotten from the Unique,
226 -- which is gotten from the Id.
227 type Details1 = (Id, UsageDetails, CoreExpr)
228 type Details2 = (IdWithOccInfo, CoreExpr)
231 occAnalBind :: OccEnv
233 -> UsageDetails -- Usage details of scope
234 -> (UsageDetails, -- Of the whole let(rec)
237 occAnalBind env (NonRec binder rhs) body_usage
238 | not (binder `usedIn` body_usage) -- It's not mentioned
241 | otherwise -- It's mentioned in the body
242 = (final_body_usage `combineUsageDetails` rhs_usage,
243 [NonRec tagged_binder rhs'])
246 (final_body_usage, tagged_binder) = tagBinder body_usage binder
247 (rhs_usage, rhs') = occAnalRhs env binder rhs
250 Dropping dead code for recursive bindings is done in a very simple way:
252 the entire set of bindings is dropped if none of its binders are
253 mentioned in its body; otherwise none are.
255 This seems to miss an obvious improvement.
270 Now @f@ is unused. But dependency analysis will sort this out into a
271 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
272 It isn't easy to do a perfect job in one blow. Consider
286 occAnalBind env (Rec pairs) body_usage
287 = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
289 pp_item (_, bndr, _) = ppr bndr
291 binders = map fst pairs
292 rhs_env = env `addNewCands` binders
294 analysed_pairs :: [Details1]
295 analysed_pairs = [ (bndr, rhs_usage, rhs')
296 | (bndr, rhs) <- pairs,
297 let (rhs_usage, rhs') = occAnalRhs rhs_env bndr rhs
300 sccs :: [SCC (Node Details1)]
301 sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
304 ---- stuff for dependency analysis of binds -------------------------------
305 edges :: [Node Details1]
306 edges = _scc_ "occAnalBind.assoc"
307 [ (details, IBOX(u2i (idUnique id)), edges_from rhs_usage)
308 | details@(id, rhs_usage, rhs) <- analysed_pairs
311 -- (a -> b) means a mentions b
312 -- Given the usage details (a UFM that gives occ info for each free var of
313 -- the RHS) we can get the list of free vars -- or rather their Int keys --
314 -- by just extracting the keys from the finite map. Grimy, but fast.
315 -- Previously we had this:
316 -- [ bndr | bndr <- bndrs,
317 -- maybeToBool (lookupVarEnv rhs_usage bndr)]
318 -- which has n**2 cost, and this meant that edges_from alone
319 -- consumed 10% of total runtime!
320 edges_from :: UsageDetails -> [Int]
321 edges_from rhs_usage = _scc_ "occAnalBind.edges_from"
324 ---- stuff to "re-constitute" bindings from dependency-analysis info ------
327 do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
328 | not (bndr `usedIn` body_usage)
329 = (body_usage, binds_so_far) -- Dead code
331 = (combined_usage, new_bind : binds_so_far)
333 total_usage = combineUsageDetails body_usage rhs_usage
334 (combined_usage, tagged_bndr) = tagBinder total_usage bndr
335 new_bind = NonRec tagged_bndr rhs'
338 do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
339 | not (any (`usedIn` body_usage) bndrs) -- NB: look at body_usage, not total_usage
340 = (body_usage, binds_so_far) -- Dead code
342 = (combined_usage, final_bind:binds_so_far)
344 details = [details | (details, _, _) <- cycle]
345 bndrs = [bndr | (bndr, _, _) <- details]
346 rhs_usages = [rhs_usage | (_, rhs_usage, _) <- details]
347 total_usage = foldr combineUsageDetails body_usage rhs_usages
348 (combined_usage, tagged_bndrs) = tagBinders total_usage bndrs
349 final_bind = Rec (reOrderRec env new_cycle)
351 new_cycle = CyclicSCC (zipWithEqual "occAnalBind" mk_new_bind tagged_bndrs cycle)
352 mk_new_bind tagged_bndr ((_, _, rhs'), key, keys) = ((tagged_bndr, rhs'), key, keys)
355 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
356 strongly connected component (there's guaranteed to be a cycle). It returns the
358 a) in a better order,
359 b) with some of the Ids having a IMustNotBeINLINEd pragma
361 The "no-inline" Ids are sufficient to break all cycles in the SCC. This means
362 that the simplifier can guarantee not to loop provided it never records an inlining
363 for these no-inline guys.
365 Furthermore, the order of the binds is such that if we neglect dependencies
366 on the no-inline Ids then the binds are topologically sorted. This means
367 that the simplifier will generally do a good job if it works from top bottom,
368 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
371 [June 98: I don't understand the following paragraphs, and I've
372 changed the a=b case again so that it isn't a special case any more.]
374 Here's a case that bit me:
382 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
384 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
385 Perhaps something cleverer would suffice.
388 You might think that you can prevent non-termination simply by making
389 sure that we simplify a recursive binding's RHS in an environment that
390 simply clones the recursive Id. But no. Consider
392 letrec f = \x -> let z = f x' in ...
399 We bind n to its *simplified* RHS, we then *re-simplify* it when
400 we inline n. Then we may well inline f; and then the same thing
403 I don't think it's possible to prevent non-termination by environment
404 manipulation in this way. Apart from anything else, successive
405 iterations of the simplifier may unroll recursive loops in cases like
406 that above. The idea of beaking every recursive loop with an
407 IMustNotBeINLINEd pragma is much much better.
413 -> SCC (Node Details2)
415 -- Sorted into a plausible order. Enough of the Ids have
416 -- dontINLINE pragmas that there are no loops left.
418 -- Non-recursive case
419 reOrderRec env (AcyclicSCC (bind, _, _)) = [bind]
421 -- Common case of simple self-recursion
422 reOrderRec env (CyclicSCC [bind])
423 = [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
425 ((tagged_bndr, rhs), _, _) = bind
427 reOrderRec env (CyclicSCC (bind : binds))
428 = -- Choose a loop breaker, mark it no-inline,
429 -- do SCC analysis on the rest, and recursively sort them out
430 concat (map (reOrderRec env) (stronglyConnCompR unchosen))
432 [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
435 (chosen_pair, unchosen) = choose_loop_breaker bind (score bind) [] binds
436 (tagged_bndr, rhs) = chosen_pair
438 -- This loop looks for the bind with the lowest score
439 -- to pick as the loop breaker. The rest accumulate in
440 choose_loop_breaker (details,_,_) loop_sc acc []
441 = (details, acc) -- Done
443 choose_loop_breaker loop_bind loop_sc acc (bind : binds)
444 | sc < loop_sc -- Lower score so pick this new one
445 = choose_loop_breaker bind sc (loop_bind : acc) binds
447 | otherwise -- No lower so don't pick it
448 = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
452 score :: Node Details2 -> Int -- Higher score => less likely to be picked as loop breaker
453 score ((bndr, rhs), _, _)
454 | exprIsTrivial rhs &&
455 not (isExportedId bndr) = 3 -- Practically certain to be inlined
456 | inlineCandidate bndr rhs = 3 -- Likely to be inlined
457 | not_fun_ty (idType bndr) = 2 -- Data types help with cases
458 | not (isEmptyCoreRules (idSpecialisation bndr)) = 1
459 -- Avoid things with specialisations; we'd like
460 -- to take advantage of them in the subsequent bindings
463 inlineCandidate :: Id -> CoreExpr -> Bool
464 inlineCandidate id (Note InlineMe _) = True
465 inlineCandidate id rhs = case idOccInfo id of
469 -- Real example (the Enum Ordering instance from PrelBase):
470 -- rec f = \ x -> case d of (p,q,r) -> p x
471 -- g = \ x -> case d of (p,q,r) -> q x
474 -- Here, f and g occur just once; but we can't inline them into d.
475 -- On the other hand we *could* simplify those case expressions if
476 -- we didn't stupidly choose d as the loop breaker.
477 -- But we won't because constructor args are marked "Many".
479 not_fun_ty ty = not (maybeToBool (splitFunTy_maybe rho_ty))
481 (_, rho_ty) = splitForAllTys ty
484 @occAnalRhs@ deals with the question of bindings where the Id is marked
485 by an INLINE pragma. For these we record that anything which occurs
486 in its RHS occurs many times. This pessimistically assumes that ths
487 inlined binder also occurs many times in its scope, but if it doesn't
488 we'll catch it next time round. At worst this costs an extra simplifier pass.
489 ToDo: try using the occurrence info for the inline'd binder.
491 [March 97] We do the same for atomic RHSs. Reason: see notes with reOrderRec.
492 [June 98, SLPJ] I've undone this change; I don't understand it. See notes with reOrderRec.
497 -> Id -> CoreExpr -- Binder and rhs
498 -> (UsageDetails, CoreExpr)
500 occAnalRhs env id rhs
501 = (final_usage, rhs')
503 (rhs_usage, rhs') = occAnal (zapCtxt env) rhs
505 -- [March 98] A new wrinkle is that if the binder has specialisations inside
506 -- it then we count the specialised Ids as "extra rhs's". That way
507 -- the "parent" keeps the specialised "children" alive. If the parent
508 -- dies (because it isn't referenced any more), then the children will
509 -- die too unless they are already referenced directly.
511 final_usage = foldVarSet add rhs_usage (idRuleVars id)
512 add v u = addOneOcc u v noBinderInfo -- Give a non-committal binder info
513 -- (i.e manyOcc) because many copies
514 -- of the specialised thing can appear
522 -> (UsageDetails, -- Gives info only about the "interesting" Ids
525 occAnal env (Type t) = (emptyDetails, Type t)
530 var_uds | isCandidate env v = unitVarEnv v funOccZero
531 | otherwise = emptyDetails
533 -- At one stage, I gathered the idRuleVars for v here too,
534 -- which in a way is the right thing to do.
535 -- But that went wrong right after specialisation, when
536 -- the *occurrences* of the overloaded function didn't have any
537 -- rules in them, so the *specialised* versions looked as if they
538 -- weren't used at all.
542 We regard variables that occur as constructor arguments as "dangerousToDup":
546 f x = let y = expensive x in
548 (case z of {(p,q)->q}, case z of {(p,q)->q})
551 We feel free to duplicate the WHNF (True,y), but that means
552 that y may be duplicated thereby.
554 If we aren't careful we duplicate the (expensive x) call!
555 Constructors are rather like lambdas in this way.
558 occAnal env expr@(Lit lit) = (emptyDetails, expr)
562 occAnal env (Note InlineMe body)
563 = case occAnal env body of { (usage, body') ->
564 (mapVarEnv markMany usage, Note InlineMe body')
567 occAnal env (Note note@(SCC cc) body)
568 = case occAnal env body of { (usage, body') ->
569 (mapVarEnv markInsideSCC usage, Note note body')
572 occAnal env (Note note body)
573 = case occAnal env body of { (usage, body') ->
574 (usage, Note note body')
579 occAnal env app@(App fun arg)
580 = occAnalApp env (collectArgs app)
582 -- Ignore type variables altogether
583 -- (a) occurrences inside type lambdas only not marked as InsideLam
584 -- (b) type variables not in environment
586 occAnal env expr@(Lam x body) | isTyVar x
587 = case occAnal env body of { (body_usage, body') ->
588 (body_usage, Lam x body')
591 -- For value lambdas we do a special hack. Consider
593 -- If we did nothing, x is used inside the \y, so would be marked
594 -- as dangerous to dup. But in the common case where the abstraction
595 -- is applied to two arguments this is over-pessimistic.
596 -- So instead, we just mark each binder with its occurrence
597 -- info in the *body* of the multiple lambda.
598 -- Then, the simplifier is careful when partially applying lambdas.
600 occAnal env expr@(Lam _ _)
601 = case occAnal (env_body `addNewCands` binders) body of { (body_usage, body') ->
603 (final_usage, tagged_binders) = tagBinders body_usage binders
604 -- URGH! Sept 99: we don't seem to be able to use binders' here, because
605 -- we get linear-typed things in the resulting program that we can't handle yet.
606 -- (e.g. PrelShow) TODO
608 really_final_usage = if linear then
611 mapVarEnv markInsideLam final_usage
614 mkLams tagged_binders body') }
616 (binders, body) = collectBinders expr
617 (linear, env_body, binders') = oneShotGroup env binders
619 occAnal env (Case scrut bndr alts)
620 = case mapAndUnzip (occAnalAlt alt_env) alts of { (alts_usage_s, alts') ->
621 case occAnal (zapCtxt env) scrut of { (scrut_usage, scrut') ->
623 alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
624 alts_usage' = addCaseBndrUsage alts_usage
625 (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
626 total_usage = scrut_usage `combineUsageDetails` alts_usage1
628 total_usage `seq` (total_usage, Case scrut' tagged_bndr alts') }}
630 alt_env = env `addNewCand` bndr
632 -- The case binder gets a usage of either "many" or "dead", never "one".
633 -- Reason: we like to inline single occurrences, to eliminate a binding,
634 -- but inlining a case binder *doesn't* eliminate a binding.
635 -- We *don't* want to transform
636 -- case x of w { (p,q) -> f w }
638 -- case x of w { (p,q) -> f (p,q) }
639 addCaseBndrUsage usage = case lookupVarEnv usage bndr of
641 Just occ -> extendVarEnv usage bndr (markMany occ)
643 occAnal env (Let bind body)
644 = case occAnal new_env body of { (body_usage, body') ->
645 case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
646 (final_usage, mkLets new_binds body') }}
648 new_env = env `addNewCands` (bindersOf bind)
651 = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
652 (foldr combineUsageDetails emptyDetails arg_uds_s, args')}
654 arg_env = zapCtxt env
657 Applications are dealt with specially because we want
658 the "build hack" to work.
661 -- Hack for build, fold, runST
662 occAnalApp env (Var fun, args)
663 = case args_stuff of { (args_uds, args') ->
665 final_uds = fun_uds `combineUsageDetails` args_uds
667 (final_uds, mkApps (Var fun) args') }
669 fun_uniq = idUnique fun
671 fun_uds | isCandidate env fun = unitVarEnv fun funOccZero
672 | otherwise = emptyDetails
674 args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
675 | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
676 | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
677 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
679 | isDataConId fun = case occAnalArgs env args of
680 (arg_uds, args') -> (mapVarEnv markMany arg_uds, args')
681 -- We mark the free vars of the argument of a constructor as "many"
682 -- This means that nothing gets inlined into a constructor argument
683 -- position, which is what we want. Typically those constructor
684 -- arguments are just variables, or trivial expressions.
686 | otherwise = occAnalArgs env args
689 occAnalApp env (fun, args)
690 = case occAnal (zapCtxt env) fun of { (fun_uds, fun') ->
691 case occAnalArgs env args of { (args_uds, args') ->
693 final_uds = fun_uds `combineUsageDetails` args_uds
695 (final_uds, mkApps fun' args') }}
697 appSpecial :: OccEnv -> Int -> CtxtTy -> [CoreExpr] -> (UsageDetails, [CoreExpr])
698 appSpecial env n ctxt args
701 go n [] = (emptyDetails, []) -- Too few args
703 go 1 (arg:args) -- The magic arg
704 = case occAnal (setCtxt env ctxt) arg of { (arg_uds, arg') ->
705 case occAnalArgs env args of { (args_uds, args') ->
706 (combineUsageDetails arg_uds args_uds, arg':args') }}
709 = case occAnal env arg of { (arg_uds, arg') ->
710 case go (n-1) args of { (args_uds, args') ->
711 (combineUsageDetails arg_uds args_uds, arg':args') }}
718 occAnalAlt env (con, bndrs, rhs)
719 = case occAnal (env `addNewCands` bndrs) rhs of { (rhs_usage, rhs') ->
721 (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
723 (final_usage, (con, tagged_bndrs, rhs')) }
727 %************************************************************************
729 \subsection[OccurAnal-types]{Data types}
731 %************************************************************************
734 -- We gather inforamtion for variables that are either
739 OccEnv (Id -> Bool) -- Tells whether an Id occurrence is interesting,
740 IdSet -- In-scope Ids
741 CtxtTy -- Tells about linearity
746 -- True:ctxt Analysing a function-valued expression that will be
749 -- False:ctxt Analysing a function-valued expression that may
750 -- be applied many times; but when it is,
751 -- the CtxtTy inside applies
753 isCandidate :: OccEnv -> Id -> Bool
754 isCandidate (OccEnv ifun cands _) id = id `elemVarSet` cands || ifun id
756 addNewCands :: OccEnv -> [Id] -> OccEnv
757 addNewCands (OccEnv ifun cands ctxt) ids
758 = OccEnv ifun (cands `unionVarSet` mkVarSet ids) ctxt
760 addNewCand :: OccEnv -> Id -> OccEnv
761 addNewCand (OccEnv ifun cands ctxt) id
762 = OccEnv ifun (extendVarSet cands id) ctxt
764 setCtxt :: OccEnv -> CtxtTy -> OccEnv
765 setCtxt (OccEnv ifun cands _) ctxt = OccEnv ifun cands ctxt
767 oneShotGroup :: OccEnv -> [CoreBndr] -> (Bool, OccEnv, [CoreBndr])
768 -- True <=> this is a one-shot linear lambda group
769 -- The [CoreBndr] are the binders.
771 -- The result binders have one-shot-ness set that they might not have had originally.
772 -- This happens in (build (\cn -> e)). Here the occurrence analyser
773 -- linearity context knows that c,n are one-shot, and it records that fact in
774 -- the binder. This is useful to guide subsequent float-in/float-out tranformations
776 oneShotGroup (OccEnv ifun cands ctxt) bndrs
777 = case go ctxt bndrs [] of
778 (new_ctxt, new_bndrs) -> (all is_one_shot new_bndrs, OccEnv ifun cands new_ctxt, new_bndrs)
780 is_one_shot b = isId b && isOneShotLambda b
782 go ctxt [] rev_bndrs = (ctxt, reverse rev_bndrs)
784 go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
785 | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
787 bndr' | lin_ctxt = setOneShotLambda bndr
790 go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
793 zapCtxt env@(OccEnv ifun cands []) = env
794 zapCtxt (OccEnv ifun cands _ ) = OccEnv ifun cands []
796 type UsageDetails = IdEnv BinderInfo -- A finite map from ids to their usage
798 combineUsageDetails, combineAltsUsageDetails
799 :: UsageDetails -> UsageDetails -> UsageDetails
801 combineUsageDetails usage1 usage2
802 = plusVarEnv_C addBinderInfo usage1 usage2
804 combineAltsUsageDetails usage1 usage2
805 = plusVarEnv_C orBinderInfo usage1 usage2
807 addOneOcc :: UsageDetails -> Id -> BinderInfo -> UsageDetails
808 addOneOcc usage id info
809 = plusVarEnv_C addBinderInfo usage (unitVarEnv id info)
810 -- ToDo: make this more efficient
812 emptyDetails = (emptyVarEnv :: UsageDetails)
814 unitDetails id info = (unitVarEnv id info :: UsageDetails)
816 usedIn :: Id -> UsageDetails -> Bool
817 v `usedIn` details = isExportedId v || v `elemVarEnv` details
819 tagBinders :: UsageDetails -- Of scope
821 -> (UsageDetails, -- Details with binders removed
822 [IdWithOccInfo]) -- Tagged binders
824 tagBinders usage binders
826 usage' = usage `delVarEnvList` binders
827 uss = map (setBinderOcc usage) binders
829 usage' `seq` (usage', uss)
831 tagBinder :: UsageDetails -- Of scope
833 -> (UsageDetails, -- Details with binders removed
834 IdWithOccInfo) -- Tagged binders
836 tagBinder usage binder
838 usage' = usage `delVarEnv` binder
839 binder' = setBinderOcc usage binder
841 usage' `seq` (usage', binder')
844 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
845 setBinderOcc usage bndr
846 | isTyVar bndr = bndr
848 = -- Don't use local usage info for visible-elsewhere things
849 -- BUT *do* erase any IAmALoopBreaker annotation, because we're
850 -- about to re-generate it and it shouldn't be "sticky"
851 case idOccInfo bndr of
853 other -> setIdOccInfo bndr NoOccInfo
855 | otherwise = setIdOccInfo bndr occ_info
857 occ_info = case lookupVarEnv usage bndr of
859 Just info -> binderInfoToOccInfo info
861 funOccZero = funOccurrence 0