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 occurAnalysePgm, occurAnalyseExpr
18 #include "HsVersions.h"
21 import CoreFVs ( idRuleVars )
22 import CoreUtils ( exprIsTrivial, isDefaultAlt )
23 import Id ( isDataConWorkId, isOneShotBndr, setOneShotLambda,
24 idOccInfo, setIdOccInfo, isLocalId,
25 isExportedId, idArity, idHasRules,
28 import BasicTypes ( OccInfo(..), isOneOcc, InterestingCxt )
33 import Type ( isFunTy, dropForAlls )
34 import Maybes ( orElse )
35 import Digraph ( stronglyConnCompR, SCC(..) )
36 import PrelNames ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
37 import Unique ( Unique )
38 import UniqFM ( keysUFM )
39 import Util ( zipWithEqual, mapAndUnzip )
44 %************************************************************************
46 \subsection[OccurAnal-main]{Counting occurrences: main function}
48 %************************************************************************
50 Here's the externally-callable interface:
53 occurAnalysePgm :: [CoreBind] -> [CoreBind]
55 = snd (go initOccEnv binds)
57 go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
61 = (final_usage, bind' ++ binds')
63 (bs_usage, binds') = go env binds
64 (final_usage, bind') = occAnalBind env bind bs_usage
66 occurAnalyseExpr :: CoreExpr -> CoreExpr
67 -- Do occurrence analysis, and discard occurence info returned
68 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
72 %************************************************************************
74 \subsection[OccurAnal-main]{Counting occurrences: main function}
76 %************************************************************************
82 type IdWithOccInfo = Id -- An Id with fresh PragmaInfo attached
84 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
85 -- which is gotten from the Id.
86 type Details1 = (Id, UsageDetails, CoreExpr)
87 type Details2 = (IdWithOccInfo, CoreExpr)
92 -> UsageDetails -- Usage details of scope
93 -> (UsageDetails, -- Of the whole let(rec)
96 occAnalBind env (NonRec binder rhs) body_usage
97 | not (binder `usedIn` body_usage) -- It's not mentioned
100 | otherwise -- It's mentioned in the body
101 = (final_body_usage `combineUsageDetails` rhs_usage,
102 [NonRec tagged_binder rhs'])
105 (final_body_usage, tagged_binder) = tagBinder body_usage binder
106 (rhs_usage, rhs') = occAnalRhs env tagged_binder rhs
109 Dropping dead code for recursive bindings is done in a very simple way:
111 the entire set of bindings is dropped if none of its binders are
112 mentioned in its body; otherwise none are.
114 This seems to miss an obvious improvement.
129 Now @f@ is unused. But dependency analysis will sort this out into a
130 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
131 It isn't easy to do a perfect job in one blow. Consider
145 occAnalBind env (Rec pairs) body_usage
146 = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
148 analysed_pairs :: [Details1]
149 analysed_pairs = [ (bndr, rhs_usage, rhs')
150 | (bndr, rhs) <- pairs,
151 let (rhs_usage, rhs') = occAnalRhs env bndr rhs
154 sccs :: [SCC (Node Details1)]
155 sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
158 ---- stuff for dependency analysis of binds -------------------------------
159 edges :: [Node Details1]
160 edges = _scc_ "occAnalBind.assoc"
161 [ (details, idUnique id, edges_from rhs_usage)
162 | details@(id, rhs_usage, rhs) <- analysed_pairs
165 -- (a -> b) means a mentions b
166 -- Given the usage details (a UFM that gives occ info for each free var of
167 -- the RHS) we can get the list of free vars -- or rather their Int keys --
168 -- by just extracting the keys from the finite map. Grimy, but fast.
169 -- Previously we had this:
170 -- [ bndr | bndr <- bndrs,
171 -- maybeToBool (lookupVarEnv rhs_usage bndr)]
172 -- which has n**2 cost, and this meant that edges_from alone
173 -- consumed 10% of total runtime!
174 edges_from :: UsageDetails -> [Unique]
175 edges_from rhs_usage = _scc_ "occAnalBind.edges_from"
178 ---- stuff to "re-constitute" bindings from dependency-analysis info ------
181 do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
182 | not (bndr `usedIn` body_usage)
183 = (body_usage, binds_so_far) -- Dead code
185 = (combined_usage, new_bind : binds_so_far)
187 total_usage = combineUsageDetails body_usage rhs_usage
188 (combined_usage, tagged_bndr) = tagBinder total_usage bndr
189 new_bind = NonRec tagged_bndr rhs'
192 do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
193 | not (any (`usedIn` body_usage) bndrs) -- NB: look at body_usage, not total_usage
194 = (body_usage, binds_so_far) -- Dead code
196 = (combined_usage, final_bind:binds_so_far)
198 details = [details | (details, _, _) <- cycle]
199 bndrs = [bndr | (bndr, _, _) <- details]
200 rhs_usages = [rhs_usage | (_, rhs_usage, _) <- details]
201 total_usage = foldr combineUsageDetails body_usage rhs_usages
202 (combined_usage, tagged_bndrs) = tagBinders total_usage bndrs
203 final_bind = Rec (reOrderRec env new_cycle)
205 new_cycle = CyclicSCC (zipWithEqual "occAnalBind" mk_new_bind tagged_bndrs cycle)
206 mk_new_bind tagged_bndr ((_, _, rhs'), key, keys) = ((tagged_bndr, rhs'), key, keys)
209 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
210 strongly connected component (there's guaranteed to be a cycle). It returns the
212 a) in a better order,
213 b) with some of the Ids having a IMustNotBeINLINEd pragma
215 The "no-inline" Ids are sufficient to break all cycles in the SCC. This means
216 that the simplifier can guarantee not to loop provided it never records an inlining
217 for these no-inline guys.
219 Furthermore, the order of the binds is such that if we neglect dependencies
220 on the no-inline Ids then the binds are topologically sorted. This means
221 that the simplifier will generally do a good job if it works from top bottom,
222 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
225 [June 98: I don't understand the following paragraphs, and I've
226 changed the a=b case again so that it isn't a special case any more.]
228 Here's a case that bit me:
236 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
238 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
239 Perhaps something cleverer would suffice.
242 You might think that you can prevent non-termination simply by making
243 sure that we simplify a recursive binding's RHS in an environment that
244 simply clones the recursive Id. But no. Consider
246 letrec f = \x -> let z = f x' in ...
253 We bind n to its *simplified* RHS, we then *re-simplify* it when
254 we inline n. Then we may well inline f; and then the same thing
257 I don't think it's possible to prevent non-termination by environment
258 manipulation in this way. Apart from anything else, successive
259 iterations of the simplifier may unroll recursive loops in cases like
260 that above. The idea of beaking every recursive loop with an
261 IMustNotBeINLINEd pragma is much much better.
267 -> SCC (Node Details2)
269 -- Sorted into a plausible order. Enough of the Ids have
270 -- dontINLINE pragmas that there are no loops left.
272 -- Non-recursive case
273 reOrderRec env (AcyclicSCC (bind, _, _)) = [bind]
275 -- Common case of simple self-recursion
276 reOrderRec env (CyclicSCC [bind])
277 = [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
279 ((tagged_bndr, rhs), _, _) = bind
281 reOrderRec env (CyclicSCC (bind : binds))
282 = -- Choose a loop breaker, mark it no-inline,
283 -- do SCC analysis on the rest, and recursively sort them out
284 concat (map (reOrderRec env) (stronglyConnCompR unchosen))
286 [(setIdOccInfo tagged_bndr IAmALoopBreaker, rhs)]
289 (chosen_pair, unchosen) = choose_loop_breaker bind (score bind) [] binds
290 (tagged_bndr, rhs) = chosen_pair
292 -- This loop looks for the bind with the lowest score
293 -- to pick as the loop breaker. The rest accumulate in
294 choose_loop_breaker (details,_,_) loop_sc acc []
295 = (details, acc) -- Done
297 choose_loop_breaker loop_bind loop_sc acc (bind : binds)
298 | sc < loop_sc -- Lower score so pick this new one
299 = choose_loop_breaker bind sc (loop_bind : acc) binds
301 | otherwise -- No lower so don't pick it
302 = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
306 score :: Node Details2 -> Int -- Higher score => less likely to be picked as loop breaker
307 score ((bndr, rhs), _, _)
308 | exprIsTrivial rhs = 4 -- Practically certain to be inlined
309 -- Used to have also: && not (isExportedId bndr)
310 -- But I found this sometimes cost an extra iteration when we have
311 -- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
312 -- where df is the exported dictionary. Then df makes a really
313 -- bad choice for loop breaker
315 | not_fun_ty (idType bndr) = 3 -- Data types help with cases
316 -- This used to have a lower score than inlineCandidate, but
317 -- it's *really* helpful if dictionaries get inlined fast,
318 -- so I'm experimenting with giving higher priority to data-typed things
320 | inlineCandidate bndr rhs = 2 -- Likely to be inlined
322 | idHasRules bndr = 1
323 -- Avoid things with specialisations; we'd like
324 -- to take advantage of them in the subsequent bindings
328 inlineCandidate :: Id -> CoreExpr -> Bool
329 inlineCandidate id (Note InlineMe _) = True
330 inlineCandidate id rhs = isOneOcc (idOccInfo id)
332 -- Real example (the Enum Ordering instance from PrelBase):
333 -- rec f = \ x -> case d of (p,q,r) -> p x
334 -- g = \ x -> case d of (p,q,r) -> q x
337 -- Here, f and g occur just once; but we can't inline them into d.
338 -- On the other hand we *could* simplify those case expressions if
339 -- we didn't stupidly choose d as the loop breaker.
340 -- But we won't because constructor args are marked "Many".
342 not_fun_ty ty = not (isFunTy (dropForAlls ty))
345 @occAnalRhs@ deals with the question of bindings where the Id is marked
346 by an INLINE pragma. For these we record that anything which occurs
347 in its RHS occurs many times. This pessimistically assumes that ths
348 inlined binder also occurs many times in its scope, but if it doesn't
349 we'll catch it next time round. At worst this costs an extra simplifier pass.
350 ToDo: try using the occurrence info for the inline'd binder.
352 [March 97] We do the same for atomic RHSs. Reason: see notes with reOrderRec.
353 [June 98, SLPJ] I've undone this change; I don't understand it. See notes with reOrderRec.
358 -> Id -> CoreExpr -- Binder and rhs
359 -- For non-recs the binder is alrady tagged
360 -- with occurrence info
361 -> (UsageDetails, CoreExpr)
363 occAnalRhs env id rhs
364 = (final_usage, rhs')
366 (rhs_usage, rhs') = occAnal ctxt rhs
367 ctxt | certainly_inline id = env
368 | otherwise = rhsCtxt
369 -- Note that we generally use an rhsCtxt. This tells the occ anal n
370 -- that it's looking at an RHS, which has an effect in occAnalApp
372 -- But there's a problem. Consider
377 -- First time round, it looks as if x1 and x2 occur as an arg of a
378 -- let-bound constructor ==> give them a many-occurrence.
379 -- But then x3 is inlined (unconditionally as it happens) and
380 -- next time round, x2 will be, and the next time round x1 will be
381 -- Result: multiple simplifier iterations. Sigh.
382 -- Crude solution: use rhsCtxt for things that occur just once...
384 certainly_inline id = case idOccInfo id of
385 OneOcc in_lam one_br _ -> not in_lam && one_br
388 -- [March 98] A new wrinkle is that if the binder has specialisations inside
389 -- it then we count the specialised Ids as "extra rhs's". That way
390 -- the "parent" keeps the specialised "children" alive. If the parent
391 -- dies (because it isn't referenced any more), then the children will
392 -- die too unless they are already referenced directly.
394 final_usage = addRuleUsage rhs_usage id
396 addRuleUsage :: UsageDetails -> Id -> UsageDetails
397 -- Add the usage from RULES in Id to the usage
398 addRuleUsage usage id
399 = foldVarSet add usage (idRuleVars id)
401 add v u = addOneOcc u v NoOccInfo -- Give a non-committal binder info
402 -- (i.e manyOcc) because many copies
403 -- of the specialised thing can appear
411 -> (UsageDetails, -- Gives info only about the "interesting" Ids
414 occAnal env (Type t) = (emptyDetails, Type t)
415 occAnal env (Var v) = (mkOneOcc env v False, Var v)
416 -- At one stage, I gathered the idRuleVars for v here too,
417 -- which in a way is the right thing to do.
418 -- Btu that went wrong right after specialisation, when
419 -- the *occurrences* of the overloaded function didn't have any
420 -- rules in them, so the *specialised* versions looked as if they
421 -- weren't used at all.
424 We regard variables that occur as constructor arguments as "dangerousToDup":
428 f x = let y = expensive x in
430 (case z of {(p,q)->q}, case z of {(p,q)->q})
433 We feel free to duplicate the WHNF (True,y), but that means
434 that y may be duplicated thereby.
436 If we aren't careful we duplicate the (expensive x) call!
437 Constructors are rather like lambdas in this way.
440 occAnal env expr@(Lit lit) = (emptyDetails, expr)
444 occAnal env (Note InlineMe body)
445 = case occAnal env body of { (usage, body') ->
446 (mapVarEnv markMany usage, Note InlineMe body')
449 occAnal env (Note note@(SCC cc) body)
450 = case occAnal env body of { (usage, body') ->
451 (mapVarEnv markInsideSCC usage, Note note body')
454 occAnal env (Note note body)
455 = case occAnal env body of { (usage, body') ->
456 (usage, Note note body')
459 occAnal env (Cast expr co)
460 = case occAnal env expr of { (usage, expr') ->
461 (usage, Cast expr' co)
466 occAnal env app@(App fun arg)
467 = occAnalApp env (collectArgs app) False
469 -- Ignore type variables altogether
470 -- (a) occurrences inside type lambdas only not marked as InsideLam
471 -- (b) type variables not in environment
473 occAnal env expr@(Lam x body) | isTyVar x
474 = case occAnal env body of { (body_usage, body') ->
475 (body_usage, Lam x body')
478 -- For value lambdas we do a special hack. Consider
480 -- If we did nothing, x is used inside the \y, so would be marked
481 -- as dangerous to dup. But in the common case where the abstraction
482 -- is applied to two arguments this is over-pessimistic.
483 -- So instead, we just mark each binder with its occurrence
484 -- info in the *body* of the multiple lambda.
485 -- Then, the simplifier is careful when partially applying lambdas.
487 occAnal env expr@(Lam _ _)
488 = case occAnal env_body body of { (body_usage, body') ->
490 (final_usage, tagged_binders) = tagBinders body_usage binders
491 -- URGH! Sept 99: we don't seem to be able to use binders' here, because
492 -- we get linear-typed things in the resulting program that we can't handle yet.
493 -- (e.g. PrelShow) TODO
495 really_final_usage = if linear then
498 mapVarEnv markInsideLam final_usage
501 mkLams tagged_binders body') }
503 env_body = vanillaCtxt -- Body is (no longer) an RhsContext
504 (binders, body) = collectBinders expr
505 binders' = oneShotGroup env binders
506 linear = all is_one_shot binders'
507 is_one_shot b = isId b && isOneShotBndr b
509 occAnal env (Case scrut bndr ty alts)
510 = case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
511 case mapAndUnzip (occAnalAlt alt_env bndr) alts of { (alts_usage_s, alts') ->
513 alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
514 alts_usage' = addCaseBndrUsage alts_usage
515 (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
516 total_usage = scrut_usage `combineUsageDetails` alts_usage1
518 total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
520 -- The case binder gets a usage of either "many" or "dead", never "one".
521 -- Reason: we like to inline single occurrences, to eliminate a binding,
522 -- but inlining a case binder *doesn't* eliminate a binding.
523 -- We *don't* want to transform
524 -- case x of w { (p,q) -> f w }
526 -- case x of w { (p,q) -> f (p,q) }
527 addCaseBndrUsage usage = case lookupVarEnv usage bndr of
529 Just occ -> extendVarEnv usage bndr (markMany occ)
531 alt_env = setVanillaCtxt env
532 -- Consider x = case v of { True -> (p,q); ... }
533 -- Then it's fine to inline p and q
535 occ_anal_scrut (Var v) (alt1 : other_alts)
536 | not (null other_alts) || not (isDefaultAlt alt1)
537 = (mkOneOcc env v True, Var v)
538 occ_anal_scrut scrut alts = occAnal vanillaCtxt scrut
539 -- No need for rhsCtxt
541 occAnal env (Let bind body)
542 = case occAnal env body of { (body_usage, body') ->
543 case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
544 (final_usage, mkLets new_binds body') }}
547 = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
548 (foldr combineUsageDetails emptyDetails arg_uds_s, args')}
550 arg_env = vanillaCtxt
553 Applications are dealt with specially because we want
554 the "build hack" to work.
557 occAnalApp env (Var fun, args) is_rhs
558 = case args_stuff of { (args_uds, args') ->
560 -- We mark the free vars of the argument of a constructor or PAP
561 -- as "many", if it is the RHS of a let(rec).
562 -- This means that nothing gets inlined into a constructor argument
563 -- position, which is what we want. Typically those constructor
564 -- arguments are just variables, or trivial expressions.
566 -- This is the *whole point* of the isRhsEnv predicate
569 isDataConWorkId fun || valArgCount args < idArity fun
570 = mapVarEnv markMany args_uds
571 | otherwise = args_uds
573 (fun_uds `combineUsageDetails` final_args_uds, mkApps (Var fun) args') }
575 fun_uniq = idUnique fun
576 fun_uds = mkOneOcc env fun (valArgCount args > 0)
578 -- Hack for build, fold, runST
579 args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
580 | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
581 | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
582 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
583 -- (foldr k z xs) may call k many times, but it never
584 -- shares a partial application of k; hence [False,True]
585 -- This means we can optimise
586 -- foldr (\x -> let v = ...x... in \y -> ...v...) z xs
587 -- by floating in the v
589 | otherwise = occAnalArgs env args
592 occAnalApp env (fun, args) is_rhs
593 = case occAnal (addAppCtxt env args) fun of { (fun_uds, fun') ->
594 -- The addAppCtxt is a bit cunning. One iteration of the simplifier
595 -- often leaves behind beta redexs like
597 -- Here we would like to mark x,y as one-shot, and treat the whole
598 -- thing much like a let. We do this by pushing some True items
599 -- onto the context stack.
601 case occAnalArgs env args of { (args_uds, args') ->
603 final_uds = fun_uds `combineUsageDetails` args_uds
605 (final_uds, mkApps fun' args') }}
608 -> Int -> CtxtTy -- Argument number, and context to use for it
610 -> (UsageDetails, [CoreExpr])
611 appSpecial env n ctxt args
614 arg_env = vanillaCtxt
616 go n [] = (emptyDetails, []) -- Too few args
618 go 1 (arg:args) -- The magic arg
619 = case occAnal (setCtxt arg_env ctxt) arg of { (arg_uds, arg') ->
620 case occAnalArgs env args of { (args_uds, args') ->
621 (combineUsageDetails arg_uds args_uds, arg':args') }}
624 = case occAnal arg_env arg of { (arg_uds, arg') ->
625 case go (n-1) args of { (args_uds, args') ->
626 (combineUsageDetails arg_uds args_uds, arg':args') }}
632 If the case binder occurs at all, the other binders effectively do too.
634 case e of x { (a,b) -> rhs }
637 If e turns out to be (e1,e2) we indeed get something like
638 let a = e1; b = e2; x = (a,b) in rhs
640 Note [Aug 06]: I don't think this is necessary any more, and it helpe
641 to know when binders are unused. See esp the call to
642 isDeadBinder in Simplify.mkDupableAlt
645 occAnalAlt env case_bndr (con, bndrs, rhs)
646 = case occAnal env rhs of { (rhs_usage, rhs') ->
648 (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
649 final_bndrs = tagged_bndrs -- See Note [Aug06] above
651 final_bndrs | case_bndr `elemVarEnv` final_usage = bndrs
652 | otherwise = tagged_bndrs
653 -- Leave the binders untagged if the case
654 -- binder occurs at all; see note above
657 (final_usage, (con, final_bndrs, rhs')) }
661 %************************************************************************
663 \subsection[OccurAnal-types]{OccEnv}
665 %************************************************************************
669 = OccEnv OccEncl -- Enclosing context information
670 CtxtTy -- Tells about linearity
672 -- OccEncl is used to control whether to inline into constructor arguments
674 -- x = (p,q) -- Don't inline p or q
675 -- y = /\a -> (p a, q a) -- Still don't inline p or q
676 -- z = f (p,q) -- Do inline p,q; it may make a rule fire
677 -- So OccEncl tells enought about the context to know what to do when
678 -- we encounter a contructor application or PAP.
681 = OccRhs -- RHS of let(rec), albeit perhaps inside a type lambda
682 -- Don't inline into constructor args here
683 | OccVanilla -- Argument of function, body of lambda, scruintee of case etc.
684 -- Do inline into constructor args here
689 -- True:ctxt Analysing a function-valued expression that will be
692 -- False:ctxt Analysing a function-valued expression that may
693 -- be applied many times; but when it is,
694 -- the CtxtTy inside applies
697 initOccEnv = OccEnv OccRhs []
699 vanillaCtxt = OccEnv OccVanilla []
700 rhsCtxt = OccEnv OccRhs []
702 isRhsEnv (OccEnv OccRhs _) = True
703 isRhsEnv (OccEnv OccVanilla _) = False
705 setVanillaCtxt :: OccEnv -> OccEnv
706 setVanillaCtxt (OccEnv OccRhs ctxt_ty) = OccEnv OccVanilla ctxt_ty
707 setVanillaCtxt other_env = other_env
709 setCtxt :: OccEnv -> CtxtTy -> OccEnv
710 setCtxt (OccEnv encl _) ctxt = OccEnv encl ctxt
712 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
713 -- The result binders have one-shot-ness set that they might not have had originally.
714 -- This happens in (build (\cn -> e)). Here the occurrence analyser
715 -- linearity context knows that c,n are one-shot, and it records that fact in
716 -- the binder. This is useful to guide subsequent float-in/float-out tranformations
718 oneShotGroup (OccEnv encl ctxt) bndrs
721 go ctxt [] rev_bndrs = reverse rev_bndrs
723 go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
724 | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
726 bndr' | lin_ctxt = setOneShotLambda bndr
729 go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
731 addAppCtxt (OccEnv encl ctxt) args
732 = OccEnv encl (replicate (valArgCount args) True ++ ctxt)
735 %************************************************************************
737 \subsection[OccurAnal-types]{OccEnv}
739 %************************************************************************
742 type UsageDetails = IdEnv OccInfo -- A finite map from ids to their usage
744 combineUsageDetails, combineAltsUsageDetails
745 :: UsageDetails -> UsageDetails -> UsageDetails
747 combineUsageDetails usage1 usage2
748 = plusVarEnv_C addOccInfo usage1 usage2
750 combineAltsUsageDetails usage1 usage2
751 = plusVarEnv_C orOccInfo usage1 usage2
753 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
754 addOneOcc usage id info
755 = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
756 -- ToDo: make this more efficient
758 emptyDetails = (emptyVarEnv :: UsageDetails)
760 usedIn :: Id -> UsageDetails -> Bool
761 v `usedIn` details = isExportedId v || v `elemVarEnv` details
763 tagBinders :: UsageDetails -- Of scope
765 -> (UsageDetails, -- Details with binders removed
766 [IdWithOccInfo]) -- Tagged binders
768 tagBinders usage binders
770 usage' = usage `delVarEnvList` binders
771 uss = map (setBinderOcc usage) binders
773 usage' `seq` (usage', uss)
775 tagBinder :: UsageDetails -- Of scope
777 -> (UsageDetails, -- Details with binders removed
778 IdWithOccInfo) -- Tagged binders
780 tagBinder usage binder
782 usage' = usage `delVarEnv` binder
783 binder' = setBinderOcc usage binder
785 usage' `seq` (usage', binder')
787 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
788 setBinderOcc usage bndr
789 | isTyVar bndr = bndr
790 | isExportedId bndr = case idOccInfo bndr of
792 other -> setIdOccInfo bndr NoOccInfo
793 -- Don't use local usage info for visible-elsewhere things
794 -- BUT *do* erase any IAmALoopBreaker annotation, because we're
795 -- about to re-generate it and it shouldn't be "sticky"
797 | otherwise = setIdOccInfo bndr occ_info
799 occ_info = lookupVarEnv usage bndr `orElse` IAmDead
803 %************************************************************************
805 \subsection{Operations over OccInfo}
807 %************************************************************************
810 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
811 mkOneOcc env id int_cxt
812 | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
813 | otherwise = emptyDetails
815 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
817 markMany IAmDead = IAmDead
818 markMany other = NoOccInfo
820 markInsideSCC occ = markMany occ
822 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
823 markInsideLam occ = occ
825 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
827 addOccInfo IAmDead info2 = info2
828 addOccInfo info1 IAmDead = info1
829 addOccInfo info1 info2 = NoOccInfo
831 -- (orOccInfo orig new) is used
832 -- when combining occurrence info from branches of a case
834 orOccInfo IAmDead info2 = info2
835 orOccInfo info1 IAmDead = info1
836 orOccInfo (OneOcc in_lam1 one_branch1 int_cxt1)
837 (OneOcc in_lam2 one_branch2 int_cxt2)
838 = OneOcc (in_lam1 || in_lam2)
839 False -- False, because it occurs in both branches
840 (int_cxt1 && int_cxt2)
842 orOccInfo info1 info2 = NoOccInfo