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, intersectsUFM )
39 import Util ( mapAndUnzip, mapAccumL )
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 %************************************************************************
84 -> UsageDetails -- Usage details of scope
85 -> (UsageDetails, -- Of the whole let(rec)
88 occAnalBind env (NonRec binder rhs) body_usage
89 | not (binder `usedIn` body_usage) -- It's not mentioned
92 | otherwise -- It's mentioned in the body
93 = (body_usage' +++ addRuleUsage rhs_usage binder, -- Note [RulesOnly]
94 [NonRec tagged_binder rhs'])
96 (body_usage', tagged_binder) = tagBinder body_usage binder
97 (rhs_usage, rhs') = occAnalRhs env tagged_binder rhs
100 Dropping dead code for recursive bindings is done in a very simple way:
102 the entire set of bindings is dropped if none of its binders are
103 mentioned in its body; otherwise none are.
105 This seems to miss an obvious improvement.
120 Now @f@ is unused. But dependency analysis will sort this out into a
121 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
122 It isn't easy to do a perfect job in one blow. Consider
136 occAnalBind env (Rec pairs) body_usage
137 = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
139 analysed_pairs :: [Details]
140 analysed_pairs = [ (bndr, rhs_usage, rhs')
141 | (bndr, rhs) <- pairs,
142 let (rhs_usage, rhs') = occAnalRhs env bndr rhs
145 sccs :: [SCC (Node Details)]
146 sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
149 ---- stuff for dependency analysis of binds -------------------------------
150 edges :: [Node Details]
151 edges = _scc_ "occAnalBind.assoc"
152 [ (details, idUnique id, edges_from id rhs_usage)
153 | details@(id, rhs_usage, rhs) <- analysed_pairs
156 -- (a -> b) means a mentions b
157 -- Given the usage details (a UFM that gives occ info for each free var of
158 -- the RHS) we can get the list of free vars -- or rather their Int keys --
159 -- by just extracting the keys from the finite map. Grimy, but fast.
160 -- Previously we had this:
161 -- [ bndr | bndr <- bndrs,
162 -- maybeToBool (lookupVarEnv rhs_usage bndr)]
163 -- which has n**2 cost, and this meant that edges_from alone
164 -- consumed 10% of total runtime!
165 edges_from :: Id -> UsageDetails -> [Unique]
166 edges_from bndr rhs_usage = _scc_ "occAnalBind.edges_from"
167 keysUFM (addRuleUsage rhs_usage bndr)
169 ---- Stuff to "re-constitute" bindings from dependency-analysis info ------
172 do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
173 | not (bndr `usedIn` body_usage)
174 = (body_usage, binds_so_far) -- Dead code
176 = (body_usage' +++ addRuleUsage rhs_usage bndr, new_bind : binds_so_far)
178 (body_usage', tagged_bndr) = tagBinder body_usage bndr
179 new_bind = NonRec tagged_bndr rhs'
182 do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
183 | not (any (`usedIn` body_usage) bndrs) -- NB: look at body_usage, not total_usage
184 = (body_usage, binds_so_far) -- Dead code
185 | otherwise -- If any is used, they all are
186 = (final_usage, final_bind : binds_so_far)
188 details = [details | (details, _, _) <- cycle]
189 bndrs = [bndr | (bndr, _, _) <- details]
190 bndr_usages = [addRuleUsage rhs_usage bndr | (bndr, rhs_usage, _) <- details]
191 total_usage = foldr (+++) body_usage bndr_usages
192 (final_usage, tagged_cycle) = mapAccumL tag_bind total_usage cycle
193 tag_bind usg ((bndr,rhs_usg,rhs),k,ks) = (usg', ((bndr',rhs_usg,rhs),k,ks))
195 (usg', bndr') = tagBinder usg bndr
196 final_bind = Rec (reOrderCycle (mkVarSet bndrs) tagged_cycle)
198 {- An alternative; rebuild the edges. No semantic difference, but perf might change
200 -- Hopefully 'bndrs' is a relatively small group now
201 -- Now get ready for the loop-breaking phase
202 -- We've done dead-code elimination already, so no worries about un-referenced binders
203 keys = map idUnique bndrs
204 mk_node tagged_bndr (_, rhs_usage, rhs')
205 = ((tagged_bndr, rhs'), idUnique tagged_bndr, used)
207 used = [key | key <- keys, used_outside_rule rhs_usage key ]
209 used_outside_rule usage uniq = case lookupUFM_Directly usage uniq of
211 Just RulesOnly -> False -- Ignore rules
216 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
217 strongly connected component (there's guaranteed to be a cycle). It returns the
219 a) in a better order,
220 b) with some of the Ids having a IAmALoopBreaker pragma
222 The "loop-breaker" Ids are sufficient to break all cycles in the SCC. This means
223 that the simplifier can guarantee not to loop provided it never records an inlining
224 for these no-inline guys.
226 Furthermore, the order of the binds is such that if we neglect dependencies
227 on the no-inline Ids then the binds are topologically sorted. This means
228 that the simplifier will generally do a good job if it works from top bottom,
229 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
232 [June 98: I don't understand the following paragraphs, and I've
233 changed the a=b case again so that it isn't a special case any more.]
235 Here's a case that bit me:
243 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
245 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
246 Perhaps something cleverer would suffice.
251 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
252 -- which is gotten from the Id.
253 type Details = (Id, UsageDetails, CoreExpr)
255 reOrderRec :: IdSet -- Binders of this group
256 -> SCC (Node Details)
258 -- Sorted into a plausible order. Enough of the Ids have
259 -- IAmALoopBreaker pragmas that there are no loops left.
260 reOrderRec bndrs (AcyclicSCC ((bndr, _, rhs), _, _)) = [(bndr, rhs)]
261 reOrderRec bndrs (CyclicSCC cycle) = reOrderCycle bndrs cycle
263 reOrderCycle :: IdSet -> [Node Details] -> [(Id,CoreExpr)]
264 reOrderCycle bndrs []
265 = panic "reOrderCycle"
266 reOrderCycle bndrs [bind] -- Common case of simple self-recursion
267 = [(makeLoopBreaker bndrs rhs_usg bndr, rhs)]
269 ((bndr, rhs_usg, rhs), _, _) = bind
271 reOrderCycle bndrs (bind : binds)
272 = -- Choose a loop breaker, mark it no-inline,
273 -- do SCC analysis on the rest, and recursively sort them out
274 concatMap (reOrderRec bndrs) (stronglyConnCompR unchosen) ++
275 [(makeLoopBreaker bndrs rhs_usg bndr, rhs)]
278 (chosen_bind, unchosen) = choose_loop_breaker bind (score bind) [] binds
279 (bndr, rhs_usg, rhs) = chosen_bind
281 -- This loop looks for the bind with the lowest score
282 -- to pick as the loop breaker. The rest accumulate in
283 choose_loop_breaker (details,_,_) loop_sc acc []
284 = (details, acc) -- Done
286 choose_loop_breaker loop_bind loop_sc acc (bind : binds)
287 | sc < loop_sc -- Lower score so pick this new one
288 = choose_loop_breaker bind sc (loop_bind : acc) binds
290 | otherwise -- No lower so don't pick it
291 = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
295 score :: Node Details -> Int -- Higher score => less likely to be picked as loop breaker
296 score ((bndr, _, rhs), _, _)
297 | exprIsTrivial rhs = 4 -- Practically certain to be inlined
298 -- Used to have also: && not (isExportedId bndr)
299 -- But I found this sometimes cost an extra iteration when we have
300 -- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
301 -- where df is the exported dictionary. Then df makes a really
302 -- bad choice for loop breaker
304 | not_fun_ty (idType bndr) = 3 -- Data types help with cases
305 -- This used to have a lower score than inlineCandidate, but
306 -- it's *really* helpful if dictionaries get inlined fast,
307 -- so I'm experimenting with giving higher priority to data-typed things
309 | inlineCandidate bndr rhs = 2 -- Likely to be inlined
311 | idHasRules bndr = 1
312 -- Avoid things with specialisations; we'd like
313 -- to take advantage of them in the subsequent bindings
317 inlineCandidate :: Id -> CoreExpr -> Bool
318 inlineCandidate id (Note InlineMe _) = True
319 inlineCandidate id rhs = isOneOcc (idOccInfo id)
321 -- Real example (the Enum Ordering instance from PrelBase):
322 -- rec f = \ x -> case d of (p,q,r) -> p x
323 -- g = \ x -> case d of (p,q,r) -> q x
326 -- Here, f and g occur just once; but we can't inline them into d.
327 -- On the other hand we *could* simplify those case expressions if
328 -- we didn't stupidly choose d as the loop breaker.
329 -- But we won't because constructor args are marked "Many".
331 not_fun_ty ty = not (isFunTy (dropForAlls ty))
333 makeLoopBreaker :: VarSet -- Binders of this group
334 -> UsageDetails -- Usage of this rhs (neglecting rules)
336 -- Set the loop-breaker flag, recording whether the thing occurs only in
337 -- the RHS of a RULE (in this recursive group)
338 makeLoopBreaker bndrs rhs_usg bndr
339 = setIdOccInfo bndr (IAmALoopBreaker rules_only)
341 rules_only = bndrs `intersectsUFM` rhs_usg
344 @occAnalRhs@ deals with the question of bindings where the Id is marked
345 by an INLINE pragma. For these we record that anything which occurs
346 in its RHS occurs many times. This pessimistically assumes that ths
347 inlined binder also occurs many times in its scope, but if it doesn't
348 we'll catch it next time round. At worst this costs an extra simplifier pass.
349 ToDo: try using the occurrence info for the inline'd binder.
351 [March 97] We do the same for atomic RHSs. Reason: see notes with reOrderRec.
352 [June 98, SLPJ] I've undone this change; I don't understand it. See notes with reOrderRec.
357 -> Id -> CoreExpr -- Binder and rhs
358 -- For non-recs the binder is alrady tagged
359 -- with occurrence info
360 -> (UsageDetails, CoreExpr)
362 occAnalRhs env id rhs
365 ctxt | certainly_inline id = env
366 | otherwise = rhsCtxt
367 -- Note that we generally use an rhsCtxt. This tells the occ anal n
368 -- that it's looking at an RHS, which has an effect in occAnalApp
370 -- But there's a problem. Consider
375 -- First time round, it looks as if x1 and x2 occur as an arg of a
376 -- let-bound constructor ==> give them a many-occurrence.
377 -- But then x3 is inlined (unconditionally as it happens) and
378 -- next time round, x2 will be, and the next time round x1 will be
379 -- Result: multiple simplifier iterations. Sigh.
380 -- Crude solution: use rhsCtxt for things that occur just once...
382 certainly_inline id = case idOccInfo id of
383 OneOcc in_lam one_br _ -> not in_lam && one_br
389 If the binder has RULES inside it then we count the specialised Ids as
390 "extra rhs's". That way the "parent" keeps the specialised "children"
391 alive. If the parent dies (because it isn't referenced any more),
392 then the children will die too unless they are already referenced
395 That's the basic idea. However in a recursive situation we want to be a bit
396 cleverer. Example (from GHC.Enum):
398 eftInt :: Int# -> Int# -> [Int]
399 eftInt x y = ...(non-recursive)...
401 {-# INLINE [0] eftIntFB #-}
402 eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
403 eftIntFB c n x y = ...(non-recursive)...
406 "eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
407 "eftIntList" [1] eftIntFB (:) [] = eftInt
410 The two look mutually recursive only because of their RULES; we don't want
411 that to inhibit inlining!
413 So when we identify a LoopBreaker, we mark it to say whether it only mentions
414 the other binders in its recursive group in a RULE. If so, we can inline it,
415 because doing so will not expose new occurrences of binders in its group.
420 addRuleUsage :: UsageDetails -> Id -> UsageDetails
421 -- Add the usage from RULES in Id to the usage
422 addRuleUsage usage id
423 = foldVarSet add usage (idRuleVars id)
425 add v u = addOneOcc u v NoOccInfo -- Give a non-committal binder info
426 -- (i.e manyOcc) because many copies
427 -- of the specialised thing can appear
435 -> (UsageDetails, -- Gives info only about the "interesting" Ids
438 occAnal env (Type t) = (emptyDetails, Type t)
439 occAnal env (Var v) = (mkOneOcc env v False, Var v)
440 -- At one stage, I gathered the idRuleVars for v here too,
441 -- which in a way is the right thing to do.
442 -- Btu that went wrong right after specialisation, when
443 -- the *occurrences* of the overloaded function didn't have any
444 -- rules in them, so the *specialised* versions looked as if they
445 -- weren't used at all.
448 We regard variables that occur as constructor arguments as "dangerousToDup":
452 f x = let y = expensive x in
454 (case z of {(p,q)->q}, case z of {(p,q)->q})
457 We feel free to duplicate the WHNF (True,y), but that means
458 that y may be duplicated thereby.
460 If we aren't careful we duplicate the (expensive x) call!
461 Constructors are rather like lambdas in this way.
464 occAnal env expr@(Lit lit) = (emptyDetails, expr)
468 occAnal env (Note InlineMe body)
469 = case occAnal env body of { (usage, body') ->
470 (mapVarEnv markMany usage, Note InlineMe body')
473 occAnal env (Note note@(SCC cc) body)
474 = case occAnal env body of { (usage, body') ->
475 (mapVarEnv markInsideSCC usage, Note note body')
478 occAnal env (Note note body)
479 = case occAnal env body of { (usage, body') ->
480 (usage, Note note body')
483 occAnal env (Cast expr co)
484 = case occAnal env expr of { (usage, expr') ->
485 (usage, Cast expr' co)
490 occAnal env app@(App fun arg)
491 = occAnalApp env (collectArgs app) False
493 -- Ignore type variables altogether
494 -- (a) occurrences inside type lambdas only not marked as InsideLam
495 -- (b) type variables not in environment
497 occAnal env expr@(Lam x body) | isTyVar x
498 = case occAnal env body of { (body_usage, body') ->
499 (body_usage, Lam x body')
502 -- For value lambdas we do a special hack. Consider
504 -- If we did nothing, x is used inside the \y, so would be marked
505 -- as dangerous to dup. But in the common case where the abstraction
506 -- is applied to two arguments this is over-pessimistic.
507 -- So instead, we just mark each binder with its occurrence
508 -- info in the *body* of the multiple lambda.
509 -- Then, the simplifier is careful when partially applying lambdas.
511 occAnal env expr@(Lam _ _)
512 = case occAnal env_body body of { (body_usage, body') ->
514 (final_usage, tagged_binders) = tagBinders body_usage binders
515 -- URGH! Sept 99: we don't seem to be able to use binders' here, because
516 -- we get linear-typed things in the resulting program that we can't handle yet.
517 -- (e.g. PrelShow) TODO
519 really_final_usage = if linear then
522 mapVarEnv markInsideLam final_usage
525 mkLams tagged_binders body') }
527 env_body = vanillaCtxt -- Body is (no longer) an RhsContext
528 (binders, body) = collectBinders expr
529 binders' = oneShotGroup env binders
530 linear = all is_one_shot binders'
531 is_one_shot b = isId b && isOneShotBndr b
533 occAnal env (Case scrut bndr ty alts)
534 = case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
535 case mapAndUnzip (occAnalAlt alt_env bndr) alts of { (alts_usage_s, alts') ->
537 alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
538 alts_usage' = addCaseBndrUsage alts_usage
539 (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
540 total_usage = scrut_usage +++ alts_usage1
542 total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
544 -- The case binder gets a usage of either "many" or "dead", never "one".
545 -- Reason: we like to inline single occurrences, to eliminate a binding,
546 -- but inlining a case binder *doesn't* eliminate a binding.
547 -- We *don't* want to transform
548 -- case x of w { (p,q) -> f w }
550 -- case x of w { (p,q) -> f (p,q) }
551 addCaseBndrUsage usage = case lookupVarEnv usage bndr of
553 Just occ -> extendVarEnv usage bndr (markMany occ)
555 alt_env = setVanillaCtxt env
556 -- Consider x = case v of { True -> (p,q); ... }
557 -- Then it's fine to inline p and q
559 occ_anal_scrut (Var v) (alt1 : other_alts)
560 | not (null other_alts) || not (isDefaultAlt alt1)
561 = (mkOneOcc env v True, Var v)
562 occ_anal_scrut scrut alts = occAnal vanillaCtxt scrut
563 -- No need for rhsCtxt
565 occAnal env (Let bind body)
566 = case occAnal env body of { (body_usage, body') ->
567 case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
568 (final_usage, mkLets new_binds body') }}
571 = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
572 (foldr (+++) emptyDetails arg_uds_s, args')}
574 arg_env = vanillaCtxt
577 Applications are dealt with specially because we want
578 the "build hack" to work.
581 occAnalApp env (Var fun, args) is_rhs
582 = case args_stuff of { (args_uds, args') ->
584 -- We mark the free vars of the argument of a constructor or PAP
585 -- as "many", if it is the RHS of a let(rec).
586 -- This means that nothing gets inlined into a constructor argument
587 -- position, which is what we want. Typically those constructor
588 -- arguments are just variables, or trivial expressions.
590 -- This is the *whole point* of the isRhsEnv predicate
593 isDataConWorkId fun || valArgCount args < idArity fun
594 = mapVarEnv markMany args_uds
595 | otherwise = args_uds
597 (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
599 fun_uniq = idUnique fun
600 fun_uds = mkOneOcc env fun (valArgCount args > 0)
602 -- Hack for build, fold, runST
603 args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
604 | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
605 | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
606 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
607 -- (foldr k z xs) may call k many times, but it never
608 -- shares a partial application of k; hence [False,True]
609 -- This means we can optimise
610 -- foldr (\x -> let v = ...x... in \y -> ...v...) z xs
611 -- by floating in the v
613 | otherwise = occAnalArgs env args
616 occAnalApp env (fun, args) is_rhs
617 = case occAnal (addAppCtxt env args) fun of { (fun_uds, fun') ->
618 -- The addAppCtxt is a bit cunning. One iteration of the simplifier
619 -- often leaves behind beta redexs like
621 -- Here we would like to mark x,y as one-shot, and treat the whole
622 -- thing much like a let. We do this by pushing some True items
623 -- onto the context stack.
625 case occAnalArgs env args of { (args_uds, args') ->
627 final_uds = fun_uds +++ args_uds
629 (final_uds, mkApps fun' args') }}
632 -> Int -> CtxtTy -- Argument number, and context to use for it
634 -> (UsageDetails, [CoreExpr])
635 appSpecial env n ctxt args
638 arg_env = vanillaCtxt
640 go n [] = (emptyDetails, []) -- Too few args
642 go 1 (arg:args) -- The magic arg
643 = case occAnal (setCtxt arg_env ctxt) arg of { (arg_uds, arg') ->
644 case occAnalArgs env args of { (args_uds, args') ->
645 (arg_uds +++ args_uds, arg':args') }}
648 = case occAnal arg_env arg of { (arg_uds, arg') ->
649 case go (n-1) args of { (args_uds, args') ->
650 (arg_uds +++ args_uds, arg':args') }}
656 If the case binder occurs at all, the other binders effectively do too.
658 case e of x { (a,b) -> rhs }
661 If e turns out to be (e1,e2) we indeed get something like
662 let a = e1; b = e2; x = (a,b) in rhs
664 Note [Aug 06]: I don't think this is necessary any more, and it helpe
665 to know when binders are unused. See esp the call to
666 isDeadBinder in Simplify.mkDupableAlt
669 occAnalAlt env case_bndr (con, bndrs, rhs)
670 = case occAnal env rhs of { (rhs_usage, rhs') ->
672 (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
673 final_bndrs = tagged_bndrs -- See Note [Aug06] above
675 final_bndrs | case_bndr `elemVarEnv` final_usage = bndrs
676 | otherwise = tagged_bndrs
677 -- Leave the binders untagged if the case
678 -- binder occurs at all; see note above
681 (final_usage, (con, final_bndrs, rhs')) }
685 %************************************************************************
687 \subsection[OccurAnal-types]{OccEnv}
689 %************************************************************************
693 = OccEnv OccEncl -- Enclosing context information
694 CtxtTy -- Tells about linearity
696 -- OccEncl is used to control whether to inline into constructor arguments
698 -- x = (p,q) -- Don't inline p or q
699 -- y = /\a -> (p a, q a) -- Still don't inline p or q
700 -- z = f (p,q) -- Do inline p,q; it may make a rule fire
701 -- So OccEncl tells enought about the context to know what to do when
702 -- we encounter a contructor application or PAP.
705 = OccRhs -- RHS of let(rec), albeit perhaps inside a type lambda
706 -- Don't inline into constructor args here
707 | OccVanilla -- Argument of function, body of lambda, scruintee of case etc.
708 -- Do inline into constructor args here
713 -- True:ctxt Analysing a function-valued expression that will be
716 -- False:ctxt Analysing a function-valued expression that may
717 -- be applied many times; but when it is,
718 -- the CtxtTy inside applies
721 initOccEnv = OccEnv OccRhs []
723 vanillaCtxt = OccEnv OccVanilla []
724 rhsCtxt = OccEnv OccRhs []
726 isRhsEnv (OccEnv OccRhs _) = True
727 isRhsEnv (OccEnv OccVanilla _) = False
729 setVanillaCtxt :: OccEnv -> OccEnv
730 setVanillaCtxt (OccEnv OccRhs ctxt_ty) = OccEnv OccVanilla ctxt_ty
731 setVanillaCtxt other_env = other_env
733 setCtxt :: OccEnv -> CtxtTy -> OccEnv
734 setCtxt (OccEnv encl _) ctxt = OccEnv encl ctxt
736 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
737 -- The result binders have one-shot-ness set that they might not have had originally.
738 -- This happens in (build (\cn -> e)). Here the occurrence analyser
739 -- linearity context knows that c,n are one-shot, and it records that fact in
740 -- the binder. This is useful to guide subsequent float-in/float-out tranformations
742 oneShotGroup (OccEnv encl ctxt) bndrs
745 go ctxt [] rev_bndrs = reverse rev_bndrs
747 go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
748 | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
750 bndr' | lin_ctxt = setOneShotLambda bndr
753 go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
755 addAppCtxt (OccEnv encl ctxt) args
756 = OccEnv encl (replicate (valArgCount args) True ++ ctxt)
759 %************************************************************************
761 \subsection[OccurAnal-types]{OccEnv}
763 %************************************************************************
766 type UsageDetails = IdEnv OccInfo -- A finite map from ids to their usage
768 (+++), combineAltsUsageDetails
769 :: UsageDetails -> UsageDetails -> UsageDetails
772 = plusVarEnv_C addOccInfo usage1 usage2
774 combineAltsUsageDetails usage1 usage2
775 = plusVarEnv_C orOccInfo usage1 usage2
777 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
778 addOneOcc usage id info
779 = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
780 -- ToDo: make this more efficient
782 emptyDetails = (emptyVarEnv :: UsageDetails)
784 usedIn :: Id -> UsageDetails -> Bool
785 v `usedIn` details = isExportedId v || v `elemVarEnv` details
787 type IdWithOccInfo = Id
789 tagBinders :: UsageDetails -- Of scope
791 -> (UsageDetails, -- Details with binders removed
792 [IdWithOccInfo]) -- Tagged binders
794 tagBinders usage binders
796 usage' = usage `delVarEnvList` binders
797 uss = map (setBinderOcc usage) binders
799 usage' `seq` (usage', uss)
801 tagBinder :: UsageDetails -- Of scope
803 -> (UsageDetails, -- Details with binders removed
804 IdWithOccInfo) -- Tagged binders
806 tagBinder usage binder
808 usage' = usage `delVarEnv` binder
809 binder' = setBinderOcc usage binder
811 usage' `seq` (usage', binder')
813 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
814 setBinderOcc usage bndr
815 | isTyVar bndr = bndr
816 | isExportedId bndr = case idOccInfo bndr of
818 other -> setIdOccInfo bndr NoOccInfo
819 -- Don't use local usage info for visible-elsewhere things
820 -- BUT *do* erase any IAmALoopBreaker annotation, because we're
821 -- about to re-generate it and it shouldn't be "sticky"
823 | otherwise = setIdOccInfo bndr occ_info
825 occ_info = lookupVarEnv usage bndr `orElse` IAmDead
829 %************************************************************************
831 \subsection{Operations over OccInfo}
833 %************************************************************************
836 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
837 mkOneOcc env id int_cxt
838 | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
839 | otherwise = emptyDetails
841 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
843 markMany IAmDead = IAmDead
844 markMany other = NoOccInfo
846 markInsideSCC occ = markMany occ
848 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
849 markInsideLam occ = occ
851 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
853 addOccInfo IAmDead info2 = info2
854 addOccInfo info1 IAmDead = info1
855 addOccInfo info1 info2 = NoOccInfo
857 -- (orOccInfo orig new) is used
858 -- when combining occurrence info from branches of a case
860 orOccInfo IAmDead info2 = info2
861 orOccInfo info1 IAmDead = info1
862 orOccInfo (OneOcc in_lam1 one_branch1 int_cxt1)
863 (OneOcc in_lam2 one_branch2 int_cxt2)
864 = OneOcc (in_lam1 || in_lam2)
865 False -- False, because it occurs in both branches
866 (int_cxt1 && int_cxt2)
867 orOccInfo info1 info2 = NoOccInfo