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 (markRhsUds env True usage, Cast expr' co)
486 -- If we see let x = y `cast` co
487 -- then mark y as 'Many' so that we don't
488 -- immediately inline y again.
493 occAnal env app@(App fun arg)
494 = occAnalApp env (collectArgs app) False
496 -- Ignore type variables altogether
497 -- (a) occurrences inside type lambdas only not marked as InsideLam
498 -- (b) type variables not in environment
500 occAnal env expr@(Lam x body) | isTyVar x
501 = case occAnal env body of { (body_usage, body') ->
502 (body_usage, Lam x body')
505 -- For value lambdas we do a special hack. Consider
507 -- If we did nothing, x is used inside the \y, so would be marked
508 -- as dangerous to dup. But in the common case where the abstraction
509 -- is applied to two arguments this is over-pessimistic.
510 -- So instead, we just mark each binder with its occurrence
511 -- info in the *body* of the multiple lambda.
512 -- Then, the simplifier is careful when partially applying lambdas.
514 occAnal env expr@(Lam _ _)
515 = case occAnal env_body body of { (body_usage, body') ->
517 (final_usage, tagged_binders) = tagBinders body_usage binders
518 -- URGH! Sept 99: we don't seem to be able to use binders' here, because
519 -- we get linear-typed things in the resulting program that we can't handle yet.
520 -- (e.g. PrelShow) TODO
522 really_final_usage = if linear then
525 mapVarEnv markInsideLam final_usage
528 mkLams tagged_binders body') }
530 env_body = vanillaCtxt -- Body is (no longer) an RhsContext
531 (binders, body) = collectBinders expr
532 binders' = oneShotGroup env binders
533 linear = all is_one_shot binders'
534 is_one_shot b = isId b && isOneShotBndr b
536 occAnal env (Case scrut bndr ty alts)
537 = case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
538 case mapAndUnzip (occAnalAlt alt_env bndr) alts of { (alts_usage_s, alts') ->
540 alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
541 alts_usage' = addCaseBndrUsage alts_usage
542 (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
543 total_usage = scrut_usage +++ alts_usage1
545 total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
547 -- The case binder gets a usage of either "many" or "dead", never "one".
548 -- Reason: we like to inline single occurrences, to eliminate a binding,
549 -- but inlining a case binder *doesn't* eliminate a binding.
550 -- We *don't* want to transform
551 -- case x of w { (p,q) -> f w }
553 -- case x of w { (p,q) -> f (p,q) }
554 addCaseBndrUsage usage = case lookupVarEnv usage bndr of
556 Just occ -> extendVarEnv usage bndr (markMany occ)
558 alt_env = setVanillaCtxt env
559 -- Consider x = case v of { True -> (p,q); ... }
560 -- Then it's fine to inline p and q
562 occ_anal_scrut (Var v) (alt1 : other_alts)
563 | not (null other_alts) || not (isDefaultAlt alt1)
564 = (mkOneOcc env v True, Var v)
565 occ_anal_scrut scrut alts = occAnal vanillaCtxt scrut
566 -- No need for rhsCtxt
568 occAnal env (Let bind body)
569 = case occAnal env body of { (body_usage, body') ->
570 case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
571 (final_usage, mkLets new_binds body') }}
574 = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
575 (foldr (+++) emptyDetails arg_uds_s, args')}
577 arg_env = vanillaCtxt
580 Applications are dealt with specially because we want
581 the "build hack" to work.
584 occAnalApp env (Var fun, args) is_rhs
585 = case args_stuff of { (args_uds, args') ->
587 final_args_uds = markRhsUds env is_pap args_uds
589 (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
591 fun_uniq = idUnique fun
592 fun_uds = mkOneOcc env fun (valArgCount args > 0)
593 is_pap = isDataConWorkId fun || valArgCount args < idArity fun
595 -- Hack for build, fold, runST
596 args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
597 | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
598 | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
599 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
600 -- (foldr k z xs) may call k many times, but it never
601 -- shares a partial application of k; hence [False,True]
602 -- This means we can optimise
603 -- foldr (\x -> let v = ...x... in \y -> ...v...) z xs
604 -- by floating in the v
606 | otherwise = occAnalArgs env args
609 occAnalApp env (fun, args) is_rhs
610 = case occAnal (addAppCtxt env args) fun of { (fun_uds, fun') ->
611 -- The addAppCtxt is a bit cunning. One iteration of the simplifier
612 -- often leaves behind beta redexs like
614 -- Here we would like to mark x,y as one-shot, and treat the whole
615 -- thing much like a let. We do this by pushing some True items
616 -- onto the context stack.
618 case occAnalArgs env args of { (args_uds, args') ->
620 final_uds = fun_uds +++ args_uds
622 (final_uds, mkApps fun' args') }}
625 markRhsUds :: OccEnv -- Check if this is a RhsEnv
626 -> Bool -- and this is true
627 -> UsageDetails -- The do markMany on this
629 -- We mark the free vars of the argument of a constructor or PAP
630 -- as "many", if it is the RHS of a let(rec).
631 -- This means that nothing gets inlined into a constructor argument
632 -- position, which is what we want. Typically those constructor
633 -- arguments are just variables, or trivial expressions.
635 -- This is the *whole point* of the isRhsEnv predicate
636 markRhsUds env is_pap arg_uds
637 | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
638 | otherwise = arg_uds
642 -> Int -> CtxtTy -- Argument number, and context to use for it
644 -> (UsageDetails, [CoreExpr])
645 appSpecial env n ctxt args
648 arg_env = vanillaCtxt
650 go n [] = (emptyDetails, []) -- Too few args
652 go 1 (arg:args) -- The magic arg
653 = case occAnal (setCtxt arg_env ctxt) arg of { (arg_uds, arg') ->
654 case occAnalArgs env args of { (args_uds, args') ->
655 (arg_uds +++ args_uds, arg':args') }}
658 = case occAnal arg_env arg of { (arg_uds, arg') ->
659 case go (n-1) args of { (args_uds, args') ->
660 (arg_uds +++ args_uds, arg':args') }}
666 If the case binder occurs at all, the other binders effectively do too.
668 case e of x { (a,b) -> rhs }
671 If e turns out to be (e1,e2) we indeed get something like
672 let a = e1; b = e2; x = (a,b) in rhs
674 Note [Aug 06]: I don't think this is necessary any more, and it helpe
675 to know when binders are unused. See esp the call to
676 isDeadBinder in Simplify.mkDupableAlt
679 occAnalAlt env case_bndr (con, bndrs, rhs)
680 = case occAnal env rhs of { (rhs_usage, rhs') ->
682 (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
683 final_bndrs = tagged_bndrs -- See Note [Aug06] above
685 final_bndrs | case_bndr `elemVarEnv` final_usage = bndrs
686 | otherwise = tagged_bndrs
687 -- Leave the binders untagged if the case
688 -- binder occurs at all; see note above
691 (final_usage, (con, final_bndrs, rhs')) }
695 %************************************************************************
697 \subsection[OccurAnal-types]{OccEnv}
699 %************************************************************************
703 = OccEnv OccEncl -- Enclosing context information
704 CtxtTy -- Tells about linearity
706 -- OccEncl is used to control whether to inline into constructor arguments
708 -- x = (p,q) -- Don't inline p or q
709 -- y = /\a -> (p a, q a) -- Still don't inline p or q
710 -- z = f (p,q) -- Do inline p,q; it may make a rule fire
711 -- So OccEncl tells enought about the context to know what to do when
712 -- we encounter a contructor application or PAP.
715 = OccRhs -- RHS of let(rec), albeit perhaps inside a type lambda
716 -- Don't inline into constructor args here
717 | OccVanilla -- Argument of function, body of lambda, scruintee of case etc.
718 -- Do inline into constructor args here
723 -- True:ctxt Analysing a function-valued expression that will be
726 -- False:ctxt Analysing a function-valued expression that may
727 -- be applied many times; but when it is,
728 -- the CtxtTy inside applies
731 initOccEnv = OccEnv OccRhs []
733 vanillaCtxt = OccEnv OccVanilla []
734 rhsCtxt = OccEnv OccRhs []
736 isRhsEnv (OccEnv OccRhs _) = True
737 isRhsEnv (OccEnv OccVanilla _) = False
739 setVanillaCtxt :: OccEnv -> OccEnv
740 setVanillaCtxt (OccEnv OccRhs ctxt_ty) = OccEnv OccVanilla ctxt_ty
741 setVanillaCtxt other_env = other_env
743 setCtxt :: OccEnv -> CtxtTy -> OccEnv
744 setCtxt (OccEnv encl _) ctxt = OccEnv encl ctxt
746 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
747 -- The result binders have one-shot-ness set that they might not have had originally.
748 -- This happens in (build (\cn -> e)). Here the occurrence analyser
749 -- linearity context knows that c,n are one-shot, and it records that fact in
750 -- the binder. This is useful to guide subsequent float-in/float-out tranformations
752 oneShotGroup (OccEnv encl ctxt) bndrs
755 go ctxt [] rev_bndrs = reverse rev_bndrs
757 go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
758 | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
760 bndr' | lin_ctxt = setOneShotLambda bndr
763 go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
765 addAppCtxt (OccEnv encl ctxt) args
766 = OccEnv encl (replicate (valArgCount args) True ++ ctxt)
769 %************************************************************************
771 \subsection[OccurAnal-types]{OccEnv}
773 %************************************************************************
776 type UsageDetails = IdEnv OccInfo -- A finite map from ids to their usage
778 (+++), combineAltsUsageDetails
779 :: UsageDetails -> UsageDetails -> UsageDetails
782 = plusVarEnv_C addOccInfo usage1 usage2
784 combineAltsUsageDetails usage1 usage2
785 = plusVarEnv_C orOccInfo usage1 usage2
787 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
788 addOneOcc usage id info
789 = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
790 -- ToDo: make this more efficient
792 emptyDetails = (emptyVarEnv :: UsageDetails)
794 usedIn :: Id -> UsageDetails -> Bool
795 v `usedIn` details = isExportedId v || v `elemVarEnv` details
797 type IdWithOccInfo = Id
799 tagBinders :: UsageDetails -- Of scope
801 -> (UsageDetails, -- Details with binders removed
802 [IdWithOccInfo]) -- Tagged binders
804 tagBinders usage binders
806 usage' = usage `delVarEnvList` binders
807 uss = map (setBinderOcc usage) binders
809 usage' `seq` (usage', uss)
811 tagBinder :: UsageDetails -- Of scope
813 -> (UsageDetails, -- Details with binders removed
814 IdWithOccInfo) -- Tagged binders
816 tagBinder usage binder
818 usage' = usage `delVarEnv` binder
819 binder' = setBinderOcc usage binder
821 usage' `seq` (usage', binder')
823 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
824 setBinderOcc usage bndr
825 | isTyVar bndr = bndr
826 | isExportedId bndr = case idOccInfo bndr of
828 other -> setIdOccInfo bndr NoOccInfo
829 -- Don't use local usage info for visible-elsewhere things
830 -- BUT *do* erase any IAmALoopBreaker annotation, because we're
831 -- about to re-generate it and it shouldn't be "sticky"
833 | otherwise = setIdOccInfo bndr occ_info
835 occ_info = lookupVarEnv usage bndr `orElse` IAmDead
839 %************************************************************************
841 \subsection{Operations over OccInfo}
843 %************************************************************************
846 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
847 mkOneOcc env id int_cxt
848 | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
849 | otherwise = emptyDetails
851 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
853 markMany IAmDead = IAmDead
854 markMany other = NoOccInfo
856 markInsideSCC occ = markMany occ
858 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
859 markInsideLam occ = occ
861 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
863 addOccInfo IAmDead info2 = info2
864 addOccInfo info1 IAmDead = info1
865 addOccInfo info1 info2 = NoOccInfo
867 -- (orOccInfo orig new) is used
868 -- when combining occurrence info from branches of a case
870 orOccInfo IAmDead info2 = info2
871 orOccInfo info1 IAmDead = info1
872 orOccInfo (OneOcc in_lam1 one_branch1 int_cxt1)
873 (OneOcc in_lam2 one_branch2 int_cxt2)
874 = OneOcc (in_lam1 || in_lam2)
875 False -- False, because it occurs in both branches
876 (int_cxt1 && int_cxt2)
877 orOccInfo info1 info2 = NoOccInfo