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 -- XXX This define is a bit of a hack, and should be done more nicely
19 #define FAST_STRING_NOT_NEEDED 1
20 #include "HsVersions.h"
24 import CoreUtils ( exprIsTrivial, isDefaultAlt )
32 import Maybes ( orElse )
33 import Digraph ( stronglyConnCompR, SCC(..) )
34 import PrelNames ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
35 import Unique ( Unique )
36 import LazyUniqFM ( keysUFM, intersectUFM_C, foldUFM_Directly )
37 import Util ( 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 %************************************************************************
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 [Rules are extra RHSs]
94 [NonRec tagged_binder rhs'])
96 (body_usage', tagged_binder) = tagBinder body_usage binder
97 (rhs_usage, rhs') = occAnalRhs env tagged_binder rhs
102 Dropping dead code for recursive bindings is done in a very simple way:
104 the entire set of bindings is dropped if none of its binders are
105 mentioned in its body; otherwise none are.
107 This seems to miss an obvious improvement.
119 Now 'f' is unused! But it's OK! Dependency analysis will sort this
120 out into a letrec for 'g' and a 'let' for 'f', and then 'f' will get
121 dropped. It isn't easy to do a perfect job in one blow. Consider
132 Note [Loop breaking and RULES]
133 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
134 Loop breaking is surprisingly subtle. First read the section 4 of
135 "Secrets of the GHC inliner". This describes our basic plan.
137 However things are made quite a bit more complicated by RULES. Remember
139 * Note [Rules are extra RHSs]
140 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
141 A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
142 keeps the specialised "children" alive. If the parent dies
143 (because it isn't referenced any more), then the children will die
144 too (unless they are already referenced directly).
146 To that end, we build a Rec group for each cyclic strongly
148 *treating f's rules as extra RHSs for 'f'*.
150 When we make the Rec groups we include variables free in *either*
151 LHS *or* RHS of the rule. The former might seems silly, but see
152 Note [Rule dependency info].
154 So in Example [eftInt], eftInt and eftIntFB will be put in the
155 same Rec, even though their 'main' RHSs are both non-recursive.
157 * Note [Rules are visible in their own rec group]
158 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
159 We want the rules for 'f' to be visible in f's right-hand side.
160 And we'd like them to be visible in other functions in f's Rec
161 group. E.g. in Example [Specialisation rules] we want f' rule
162 to be visible in both f's RHS, and fs's RHS.
164 This means that we must simplify the RULEs first, before looking
165 at any of the definitions. This is done by Simplify.simplRecBind,
166 when it calls addLetIdInfo.
168 * Note [Choosing loop breakers]
169 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
170 We avoid infinite inlinings by choosing loop breakers, and
171 ensuring that a loop breaker cuts each loop. But what is a
172 "loop"? In particular, a RULES is like an equation for 'f' that
173 is *always* inlined if it are applicable. We do *not* disable
174 rules for loop-breakers. It's up to whoever makes the rules to
175 make sure that the rules themselves alwasys terminate. See Note
176 [Rules for recursive functions] in Simplify.lhs
179 f's RHS mentions g, and
180 g has a RULE that mentions h, and
181 h has a RULE that mentions f
183 then we *must* choose f to be a loop breaker. In general, take the
184 free variables of f's RHS, and augment it with all the variables
185 reachable by RULES from those starting points. That is the whole
186 reason for computing rule_fv_env in occAnalBind. (Of course we
187 only consider free vars that are also binders in this Rec group.)
189 Note that when we compute this rule_fv_env, we only consider variables
190 free in the *RHS* of the rule, in contrast to the way we build the
191 Rec group in the first place (Note [Rule dependency info])
193 Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
194 chosen as a loop breaker, because their RHSs don't mention each other.
195 And indeed both can be inlined safely.
197 Note that the edges of the graph we use for computing loop breakers
198 are not the same as the edges we use for computing the Rec blocks.
199 That's why we compute
200 rec_edges for the Rec block analysis
201 loop_breaker_edges for the loop breaker analysis
204 * Note [Weak loop breakers]
205 ~~~~~~~~~~~~~~~~~~~~~~~~~
206 There is a last nasty wrinkle. Suppose we have
216 Remmber that we simplify the RULES before any RHS (see Note
217 [Rules are visible in their own rec group] above).
219 So we must *not* postInlineUnconditionally 'g', even though
220 its RHS turns out to be trivial. (I'm assuming that 'g' is
221 not choosen as a loop breaker.)
223 We "solve" this by making g a "weak" or "rules-only" loop breaker,
224 with OccInfo = IAmLoopBreaker True. A normal "strong" loop breaker
225 has IAmLoopBreaker False. So
227 Inline postInlineUnconditinoally
228 IAmLoopBreaker False no no
229 IAmLoopBreaker True yes no
232 The **sole** reason for this kind of loop breaker is so that
233 postInlineUnconditionally does not fire. Ugh.
235 * Note [Rule dependency info]
236 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
237 The VarSet in a SpecInfo is used for dependency analysis in the
238 occurrence analyser. We must track free vars in *both* lhs and rhs. Why both?
242 Then if we substitute y for x, we'd better do so in the
243 rule's LHS too, so we'd better ensure the dependency is respected
248 Example (from GHC.Enum):
250 eftInt :: Int# -> Int# -> [Int]
251 eftInt x y = ...(non-recursive)...
253 {-# INLINE [0] eftIntFB #-}
254 eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
255 eftIntFB c n x y = ...(non-recursive)...
258 "eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
259 "eftIntList" [1] eftIntFB (:) [] = eftInt
262 Example [Specialisation rules]
263 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
264 Consider this group, which is typical of what SpecConstr builds:
266 fs a = ....f (C a)....
267 f x = ....f (C a)....
268 {-# RULE f (C a) = fs a #-}
270 So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
272 But watch out! If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
273 - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
274 - fs is inlined (say it's small)
275 - now there's another opportunity to apply the RULE
277 This showed up when compiling Control.Concurrent.Chan.getChanContents.
281 occAnalBind env (Rec pairs) body_usage
282 | not (any (`usedIn` body_usage) bndrs) -- NB: look at body_usage, not total_usage
283 = (body_usage, []) -- Dead code
285 = (final_usage, map ({-# SCC "occAnalBind.dofinal" #-} do_final_bind) sccs)
287 bndrs = map fst pairs
288 bndr_set = mkVarSet bndrs
290 ---------------------------------------
291 -- See Note [Loop breaking]
292 ---------------------------------------
294 -------------Dependency analysis ------------------------------
295 occ_anald :: [(Id, (UsageDetails, CoreExpr))]
296 -- The UsageDetails here are strictly those arising from the RHS
297 -- *not* from any rules in the Id
298 occ_anald = [(bndr, occAnalRhs env bndr rhs) | (bndr,rhs) <- pairs]
300 total_usage = foldl add_usage body_usage occ_anald
301 add_usage body_usage (bndr, (rhs_usage, _))
302 = body_usage +++ addRuleUsage rhs_usage bndr
304 (final_usage, tagged_bndrs) = tagBinders total_usage bndrs
305 final_bndrs | isEmptyVarSet all_rule_fvs = tagged_bndrs
306 | otherwise = map tag_rule_var tagged_bndrs
308 tag_rule_var bndr | bndr `elemVarSet` all_rule_fvs = makeLoopBreaker True bndr
310 all_rule_fvs = bndr_set `intersectVarSet` foldr (unionVarSet . idRuleVars) emptyVarSet bndrs
311 -- Mark the binder with OccInfo saying "no preInlineUnconditionally" if
312 -- it is used in any rule (lhs or rhs) of the recursive group
314 ---- stuff for dependency analysis of binds -------------------------------
315 sccs :: [SCC (Node Details)]
316 sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompR rec_edges
318 rec_edges :: [Node Details] -- The binders are tagged with correct occ-info
319 rec_edges = {-# SCC "occAnalBind.assoc" #-} zipWith make_node final_bndrs occ_anald
320 make_node tagged_bndr (_bndr, (rhs_usage, rhs))
321 = ((tagged_bndr, rhs, rhs_fvs), idUnique tagged_bndr, out_edges)
323 rhs_fvs = intersectUFM_C (\b _ -> b) bndr_set rhs_usage
324 out_edges = keysUFM (rhs_fvs `unionVarSet` idRuleVars tagged_bndr)
327 -- (a -> b) means a mentions b
328 -- Given the usage details (a UFM that gives occ info for each free var of
329 -- the RHS) we can get the list of free vars -- or rather their Int keys --
330 -- by just extracting the keys from the finite map. Grimy, but fast.
331 -- Previously we had this:
332 -- [ bndr | bndr <- bndrs,
333 -- maybeToBool (lookupVarEnv rhs_usage bndr)]
334 -- which has n**2 cost, and this meant that edges_from alone
335 -- consumed 10% of total runtime!
337 ---- Stuff to "re-constitute" bindings from dependency-analysis info ------
338 do_final_bind (AcyclicSCC ((bndr, rhs, _), _, _)) = NonRec bndr rhs
339 do_final_bind (CyclicSCC cycle)
340 | no_rules = Rec (reOrderCycle cycle)
341 | otherwise = Rec (concatMap reOrderRec (stronglyConnCompR loop_breaker_edges))
342 where -- See Note [Choosing loop breakers] for looop_breker_edges
343 loop_breaker_edges = map mk_node cycle
344 mk_node (details@(_bndr, _rhs, rhs_fvs), k, _) = (details, k, new_ks)
346 new_ks = keysUFM (extendFvs rule_fv_env rhs_fvs rhs_fvs)
349 ------------------------------------
350 rule_fv_env :: IdEnv IdSet -- Variables from this group mentioned in RHS of rules
351 -- Domain is *subset* of bound vars (others have no rule fvs)
352 rule_fv_env = rule_loop init_rule_fvs
354 no_rules = null init_rule_fvs
355 init_rule_fvs = [(b, rule_fvs)
357 , let rule_fvs = idRuleRhsVars b `intersectVarSet` bndr_set
358 , not (isEmptyVarSet rule_fvs)]
360 rule_loop :: [(Id,IdSet)] -> IdEnv IdSet -- Finds fixpoint
363 | otherwise = rule_loop new_fv_list
365 env = mkVarEnv init_rule_fvs
366 (no_change, new_fv_list) = mapAccumL bump True fv_list
367 bump no_change (b,fvs)
368 | new_fvs `subVarSet` fvs = (no_change, (b,fvs))
369 | otherwise = (False, (b,new_fvs `unionVarSet` fvs))
371 new_fvs = extendFvs env emptyVarSet fvs
373 idRuleRhsVars :: Id -> VarSet
374 -- Just the variables free on the *rhs* of a rule
375 -- See Note [Choosing loop breakers]
376 idRuleRhsVars id = foldr (unionVarSet . ruleRhsFreeVars) emptyVarSet (idCoreRules id)
378 extendFvs :: IdEnv IdSet -> IdSet -> IdSet -> IdSet
379 -- (extendFVs env fvs s) returns (fvs `union` env(s))
380 extendFvs env fvs id_set
381 = foldUFM_Directly add fvs id_set
384 = case lookupVarEnv_Directly env uniq of
385 Just fvs' -> fvs' `unionVarSet` fvs
389 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
390 strongly connected component (there's guaranteed to be a cycle). It returns the
392 a) in a better order,
393 b) with some of the Ids having a IAmALoopBreaker pragma
395 The "loop-breaker" Ids are sufficient to break all cycles in the SCC. This means
396 that the simplifier can guarantee not to loop provided it never records an inlining
397 for these no-inline guys.
399 Furthermore, the order of the binds is such that if we neglect dependencies
400 on the no-inline Ids then the binds are topologically sorted. This means
401 that the simplifier will generally do a good job if it works from top bottom,
402 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
405 [June 98: I don't understand the following paragraphs, and I've
406 changed the a=b case again so that it isn't a special case any more.]
408 Here's a case that bit me:
416 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
418 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
419 Perhaps something cleverer would suffice.
424 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
425 -- which is gotten from the Id.
426 type Details = (Id, -- Binder
428 IdSet) -- RHS free vars (*not* include rules)
430 reOrderRec :: SCC (Node Details)
432 -- Sorted into a plausible order. Enough of the Ids have
433 -- IAmALoopBreaker pragmas that there are no loops left.
434 reOrderRec (AcyclicSCC ((bndr, rhs, _), _, _)) = [(bndr, rhs)]
435 reOrderRec (CyclicSCC cycle) = reOrderCycle cycle
437 reOrderCycle :: [Node Details] -> [(Id,CoreExpr)]
439 = panic "reOrderCycle"
440 reOrderCycle [bind] -- Common case of simple self-recursion
441 = [(makeLoopBreaker False bndr, rhs)]
443 ((bndr, rhs, _), _, _) = bind
445 reOrderCycle (bind : binds)
446 = -- Choose a loop breaker, mark it no-inline,
447 -- do SCC analysis on the rest, and recursively sort them out
448 concatMap reOrderRec (stronglyConnCompR unchosen) ++
449 [(makeLoopBreaker False bndr, rhs)]
452 (chosen_bind, unchosen) = choose_loop_breaker bind (score bind) [] binds
453 (bndr, rhs, _) = chosen_bind
455 -- This loop looks for the bind with the lowest score
456 -- to pick as the loop breaker. The rest accumulate in
457 choose_loop_breaker (details,_,_) _loop_sc acc []
458 = (details, acc) -- Done
460 choose_loop_breaker loop_bind loop_sc acc (bind : binds)
461 | sc < loop_sc -- Lower score so pick this new one
462 = choose_loop_breaker bind sc (loop_bind : acc) binds
464 | otherwise -- No lower so don't pick it
465 = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
469 score :: Node Details -> Int -- Higher score => less likely to be picked as loop breaker
470 score ((bndr, rhs, _), _, _)
471 | workerExists (idWorkerInfo bndr) = 10
472 -- Note [Worker inline loop]
474 | exprIsTrivial rhs = 4 -- Practically certain to be inlined
475 -- Used to have also: && not (isExportedId bndr)
476 -- But I found this sometimes cost an extra iteration when we have
477 -- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
478 -- where df is the exported dictionary. Then df makes a really
479 -- bad choice for loop breaker
481 | is_con_app rhs = 2 -- Data types help with cases
484 | inlineCandidate bndr rhs = 1 -- Likely to be inlined
485 -- Note [Inline candidates]
489 inlineCandidate :: Id -> CoreExpr -> Bool
490 inlineCandidate _ (Note InlineMe _) = True
491 inlineCandidate id _ = isOneOcc (idOccInfo id)
495 -- It's really really important to inline dictionaries. Real
496 -- example (the Enum Ordering instance from GHC.Base):
498 -- rec f = \ x -> case d of (p,q,r) -> p x
499 -- g = \ x -> case d of (p,q,r) -> q x
502 -- Here, f and g occur just once; but we can't inline them into d.
503 -- On the other hand we *could* simplify those case expressions if
504 -- we didn't stupidly choose d as the loop breaker.
505 -- But we won't because constructor args are marked "Many".
506 -- Inlining dictionaries is really essential to unravelling
507 -- the loops in static numeric dictionaries, see GHC.Float.
509 -- Cheap and cheerful; the simplifer moves casts out of the way
510 -- The lambda case is important to spot x = /\a. C (f a)
511 -- which comes up when C is a dictionary constructor and
512 -- f is a default method.
513 -- Example: the instance for Show (ST s a) in GHC.ST
515 -- However we *also* treat (\x. C p q) as a con-app-like thing,
516 -- Note [Closure conversion]
517 is_con_app (Var v) = isDataConWorkId v
518 is_con_app (App f _) = is_con_app f
519 is_con_app (Lam _ e) = is_con_app e
520 is_con_app (Note _ e) = is_con_app e
523 makeLoopBreaker :: Bool -> Id -> Id
524 -- Set the loop-breaker flag
525 -- See Note [Weak loop breakers]
526 makeLoopBreaker weak bndr = setIdOccInfo bndr (IAmALoopBreaker weak)
529 Note [Worker inline loop]
530 ~~~~~~~~~~~~~~~~~~~~~~~~
531 Never choose a wrapper as the loop breaker! Because
532 wrappers get auto-generated inlinings when importing, and
533 that can lead to an infinite inlining loop. For example:
535 $wfoo x = ....foo x....
537 {-loop brk-} foo x = ...$wfoo x...
540 The interface file sees the unfolding for $wfoo, and sees that foo is
541 strict (and hence it gets an auto-generated wrapper). Result: an
542 infinite inlining in the importing scope. So be a bit careful if you
543 change this. A good example is Tree.repTree in
544 nofib/spectral/minimax. If the repTree wrapper is chosen as the loop
545 breaker then compiling Game.hs goes into an infinite loop (this
546 happened when we gave is_con_app a lower score than inline candidates).
548 Note [Closure conversion]
549 ~~~~~~~~~~~~~~~~~~~~~~~~~
550 We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
551 The immediate motivation came from the result of a closure-conversion transformation
552 which generated code like this:
554 data Clo a b = forall c. Clo (c -> a -> b) c
556 ($:) :: Clo a b -> a -> b
557 Clo f env $: x = f env x
559 rec { plus = Clo plus1 ()
561 ; plus1 _ n = Clo plus2 n
564 ; plus2 (Succ m) n = Succ (plus $: m $: n) }
566 If we inline 'plus' and 'plus1', everything unravels nicely. But if
567 we choose 'plus1' as the loop breaker (which is entirely possible
568 otherwise), the loop does not unravel nicely.
571 @occAnalRhs@ deals with the question of bindings where the Id is marked
572 by an INLINE pragma. For these we record that anything which occurs
573 in its RHS occurs many times. This pessimistically assumes that ths
574 inlined binder also occurs many times in its scope, but if it doesn't
575 we'll catch it next time round. At worst this costs an extra simplifier pass.
576 ToDo: try using the occurrence info for the inline'd binder.
578 [March 97] We do the same for atomic RHSs. Reason: see notes with reOrderRec.
579 [June 98, SLPJ] I've undone this change; I don't understand it. See notes with reOrderRec.
584 -> Id -> CoreExpr -- Binder and rhs
585 -- For non-recs the binder is alrady tagged
586 -- with occurrence info
587 -> (UsageDetails, CoreExpr)
589 occAnalRhs env id rhs
592 ctxt | certainly_inline id = env
593 | otherwise = rhsCtxt
594 -- Note that we generally use an rhsCtxt. This tells the occ anal n
595 -- that it's looking at an RHS, which has an effect in occAnalApp
597 -- But there's a problem. Consider
602 -- First time round, it looks as if x1 and x2 occur as an arg of a
603 -- let-bound constructor ==> give them a many-occurrence.
604 -- But then x3 is inlined (unconditionally as it happens) and
605 -- next time round, x2 will be, and the next time round x1 will be
606 -- Result: multiple simplifier iterations. Sigh.
607 -- Crude solution: use rhsCtxt for things that occur just once...
609 certainly_inline id = case idOccInfo id of
610 OneOcc in_lam one_br _ -> not in_lam && one_br
617 addRuleUsage :: UsageDetails -> Id -> UsageDetails
618 -- Add the usage from RULES in Id to the usage
619 addRuleUsage usage id
620 = foldVarSet add usage (idRuleVars id)
622 add v u = addOneOcc u v NoOccInfo -- Give a non-committal binder info
623 -- (i.e manyOcc) because many copies
624 -- of the specialised thing can appear
632 -> (UsageDetails, -- Gives info only about the "interesting" Ids
635 occAnal _ (Type t) = (emptyDetails, Type t)
636 occAnal env (Var v) = (mkOneOcc env v False, Var v)
637 -- At one stage, I gathered the idRuleVars for v here too,
638 -- which in a way is the right thing to do.
639 -- Btu that went wrong right after specialisation, when
640 -- the *occurrences* of the overloaded function didn't have any
641 -- rules in them, so the *specialised* versions looked as if they
642 -- weren't used at all.
645 We regard variables that occur as constructor arguments as "dangerousToDup":
649 f x = let y = expensive x in
651 (case z of {(p,q)->q}, case z of {(p,q)->q})
654 We feel free to duplicate the WHNF (True,y), but that means
655 that y may be duplicated thereby.
657 If we aren't careful we duplicate the (expensive x) call!
658 Constructors are rather like lambdas in this way.
661 occAnal _ expr@(Lit _) = (emptyDetails, expr)
665 occAnal env (Note InlineMe body)
666 = case occAnal env body of { (usage, body') ->
667 (mapVarEnv markMany usage, Note InlineMe body')
670 occAnal env (Note note@(SCC _) body)
671 = case occAnal env body of { (usage, body') ->
672 (mapVarEnv markInsideSCC usage, Note note body')
675 occAnal env (Note note body)
676 = case occAnal env body of { (usage, body') ->
677 (usage, Note note body')
680 occAnal env (Cast expr co)
681 = case occAnal env expr of { (usage, expr') ->
682 (markRhsUds env True usage, Cast expr' co)
683 -- If we see let x = y `cast` co
684 -- then mark y as 'Many' so that we don't
685 -- immediately inline y again.
690 occAnal env app@(App _ _)
691 = occAnalApp env (collectArgs app)
693 -- Ignore type variables altogether
694 -- (a) occurrences inside type lambdas only not marked as InsideLam
695 -- (b) type variables not in environment
697 occAnal env (Lam x body) | isTyVar x
698 = case occAnal env body of { (body_usage, body') ->
699 (body_usage, Lam x body')
702 -- For value lambdas we do a special hack. Consider
704 -- If we did nothing, x is used inside the \y, so would be marked
705 -- as dangerous to dup. But in the common case where the abstraction
706 -- is applied to two arguments this is over-pessimistic.
707 -- So instead, we just mark each binder with its occurrence
708 -- info in the *body* of the multiple lambda.
709 -- Then, the simplifier is careful when partially applying lambdas.
711 occAnal env expr@(Lam _ _)
712 = case occAnal env_body body of { (body_usage, body') ->
714 (final_usage, tagged_binders) = tagBinders body_usage binders
715 -- URGH! Sept 99: we don't seem to be able to use binders' here, because
716 -- we get linear-typed things in the resulting program that we can't handle yet.
717 -- (e.g. PrelShow) TODO
719 really_final_usage = if linear then
722 mapVarEnv markInsideLam final_usage
725 mkLams tagged_binders body') }
727 env_body = vanillaCtxt -- Body is (no longer) an RhsContext
728 (binders, body) = collectBinders expr
729 binders' = oneShotGroup env binders
730 linear = all is_one_shot binders'
731 is_one_shot b = isId b && isOneShotBndr b
733 occAnal env (Case scrut bndr ty alts)
734 = case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
735 case mapAndUnzip (occAnalAlt alt_env bndr) alts of { (alts_usage_s, alts') ->
737 alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
738 alts_usage' = addCaseBndrUsage alts_usage
739 (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
740 total_usage = scrut_usage +++ alts_usage1
742 total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
744 -- The case binder gets a usage of either "many" or "dead", never "one".
745 -- Reason: we like to inline single occurrences, to eliminate a binding,
746 -- but inlining a case binder *doesn't* eliminate a binding.
747 -- We *don't* want to transform
748 -- case x of w { (p,q) -> f w }
750 -- case x of w { (p,q) -> f (p,q) }
751 addCaseBndrUsage usage = case lookupVarEnv usage bndr of
753 Just occ -> extendVarEnv usage bndr (markMany occ)
755 alt_env = setVanillaCtxt env
756 -- Consider x = case v of { True -> (p,q); ... }
757 -- Then it's fine to inline p and q
759 occ_anal_scrut (Var v) (alt1 : other_alts)
760 | not (null other_alts) || not (isDefaultAlt alt1)
761 = (mkOneOcc env v True, Var v)
762 occ_anal_scrut scrut _alts = occAnal vanillaCtxt scrut
763 -- No need for rhsCtxt
765 occAnal env (Let bind body)
766 = case occAnal env body of { (body_usage, body') ->
767 case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
768 (final_usage, mkLets new_binds body') }}
770 occAnalArgs :: OccEnv -> [CoreExpr] -> (UsageDetails, [CoreExpr])
771 occAnalArgs _env args
772 = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
773 (foldr (+++) emptyDetails arg_uds_s, args')}
775 arg_env = vanillaCtxt
778 Applications are dealt with specially because we want
779 the "build hack" to work.
783 -> (Expr CoreBndr, [Arg CoreBndr])
784 -> (UsageDetails, Expr CoreBndr)
785 occAnalApp env (Var fun, args)
786 = case args_stuff of { (args_uds, args') ->
788 final_args_uds = markRhsUds env is_pap args_uds
790 (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
792 fun_uniq = idUnique fun
793 fun_uds = mkOneOcc env fun (valArgCount args > 0)
794 is_pap = isDataConWorkId fun || valArgCount args < idArity fun
796 -- Hack for build, fold, runST
797 args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
798 | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
799 | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
800 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
801 -- (foldr k z xs) may call k many times, but it never
802 -- shares a partial application of k; hence [False,True]
803 -- This means we can optimise
804 -- foldr (\x -> let v = ...x... in \y -> ...v...) z xs
805 -- by floating in the v
807 | otherwise = occAnalArgs env args
810 occAnalApp env (fun, args)
811 = case occAnal (addAppCtxt env args) fun of { (fun_uds, fun') ->
812 -- The addAppCtxt is a bit cunning. One iteration of the simplifier
813 -- often leaves behind beta redexs like
815 -- Here we would like to mark x,y as one-shot, and treat the whole
816 -- thing much like a let. We do this by pushing some True items
817 -- onto the context stack.
819 case occAnalArgs env args of { (args_uds, args') ->
821 final_uds = fun_uds +++ args_uds
823 (final_uds, mkApps fun' args') }}
826 markRhsUds :: OccEnv -- Check if this is a RhsEnv
827 -> Bool -- and this is true
828 -> UsageDetails -- The do markMany on this
830 -- We mark the free vars of the argument of a constructor or PAP
831 -- as "many", if it is the RHS of a let(rec).
832 -- This means that nothing gets inlined into a constructor argument
833 -- position, which is what we want. Typically those constructor
834 -- arguments are just variables, or trivial expressions.
836 -- This is the *whole point* of the isRhsEnv predicate
837 markRhsUds env is_pap arg_uds
838 | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
839 | otherwise = arg_uds
843 -> Int -> CtxtTy -- Argument number, and context to use for it
845 -> (UsageDetails, [CoreExpr])
846 appSpecial env n ctxt args
849 arg_env = vanillaCtxt
851 go _ [] = (emptyDetails, []) -- Too few args
853 go 1 (arg:args) -- The magic arg
854 = case occAnal (setCtxt arg_env ctxt) arg of { (arg_uds, arg') ->
855 case occAnalArgs env args of { (args_uds, args') ->
856 (arg_uds +++ args_uds, arg':args') }}
859 = case occAnal arg_env arg of { (arg_uds, arg') ->
860 case go (n-1) args of { (args_uds, args') ->
861 (arg_uds +++ args_uds, arg':args') }}
867 If the case binder occurs at all, the other binders effectively do too.
869 case e of x { (a,b) -> rhs }
872 If e turns out to be (e1,e2) we indeed get something like
873 let a = e1; b = e2; x = (a,b) in rhs
875 Note [Aug 06]: I don't think this is necessary any more, and it helpe
876 to know when binders are unused. See esp the call to
877 isDeadBinder in Simplify.mkDupableAlt
883 -> (UsageDetails, Alt IdWithOccInfo)
884 occAnalAlt env _case_bndr (con, bndrs, rhs)
885 = case occAnal env rhs of { (rhs_usage, rhs') ->
887 (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
888 final_bndrs = tagged_bndrs -- See Note [Aug06] above
890 final_bndrs | case_bndr `elemVarEnv` final_usage = bndrs
891 | otherwise = tagged_bndrs
892 -- Leave the binders untagged if the case
893 -- binder occurs at all; see note above
896 (final_usage, (con, final_bndrs, rhs')) }
900 %************************************************************************
902 \subsection[OccurAnal-types]{OccEnv}
904 %************************************************************************
908 = OccEnv OccEncl -- Enclosing context information
909 CtxtTy -- Tells about linearity
911 -- OccEncl is used to control whether to inline into constructor arguments
913 -- x = (p,q) -- Don't inline p or q
914 -- y = /\a -> (p a, q a) -- Still don't inline p or q
915 -- z = f (p,q) -- Do inline p,q; it may make a rule fire
916 -- So OccEncl tells enought about the context to know what to do when
917 -- we encounter a contructor application or PAP.
920 = OccRhs -- RHS of let(rec), albeit perhaps inside a type lambda
921 -- Don't inline into constructor args here
922 | OccVanilla -- Argument of function, body of lambda, scruintee of case etc.
923 -- Do inline into constructor args here
928 -- True:ctxt Analysing a function-valued expression that will be
931 -- False:ctxt Analysing a function-valued expression that may
932 -- be applied many times; but when it is,
933 -- the CtxtTy inside applies
936 initOccEnv = OccEnv OccRhs []
938 vanillaCtxt :: OccEnv
939 vanillaCtxt = OccEnv OccVanilla []
942 rhsCtxt = OccEnv OccRhs []
944 isRhsEnv :: OccEnv -> Bool
945 isRhsEnv (OccEnv OccRhs _) = True
946 isRhsEnv (OccEnv OccVanilla _) = False
948 setVanillaCtxt :: OccEnv -> OccEnv
949 setVanillaCtxt (OccEnv OccRhs ctxt_ty) = OccEnv OccVanilla ctxt_ty
950 setVanillaCtxt other_env = other_env
952 setCtxt :: OccEnv -> CtxtTy -> OccEnv
953 setCtxt (OccEnv encl _) ctxt = OccEnv encl ctxt
955 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
956 -- The result binders have one-shot-ness set that they might not have had originally.
957 -- This happens in (build (\cn -> e)). Here the occurrence analyser
958 -- linearity context knows that c,n are one-shot, and it records that fact in
959 -- the binder. This is useful to guide subsequent float-in/float-out tranformations
961 oneShotGroup (OccEnv _encl ctxt) bndrs
964 go _ [] rev_bndrs = reverse rev_bndrs
966 go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
967 | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
969 bndr' | lin_ctxt = setOneShotLambda bndr
972 go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
974 addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
975 addAppCtxt (OccEnv encl ctxt) args
976 = OccEnv encl (replicate (valArgCount args) True ++ ctxt)
979 %************************************************************************
981 \subsection[OccurAnal-types]{OccEnv}
983 %************************************************************************
986 type UsageDetails = IdEnv OccInfo -- A finite map from ids to their usage
988 (+++), combineAltsUsageDetails
989 :: UsageDetails -> UsageDetails -> UsageDetails
992 = plusVarEnv_C addOccInfo usage1 usage2
994 combineAltsUsageDetails usage1 usage2
995 = plusVarEnv_C orOccInfo usage1 usage2
997 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
998 addOneOcc usage id info
999 = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
1000 -- ToDo: make this more efficient
1002 emptyDetails :: UsageDetails
1003 emptyDetails = (emptyVarEnv :: UsageDetails)
1005 usedIn :: Id -> UsageDetails -> Bool
1006 v `usedIn` details = isExportedId v || v `elemVarEnv` details
1008 type IdWithOccInfo = Id
1010 tagBinders :: UsageDetails -- Of scope
1012 -> (UsageDetails, -- Details with binders removed
1013 [IdWithOccInfo]) -- Tagged binders
1015 tagBinders usage binders
1017 usage' = usage `delVarEnvList` binders
1018 uss = map (setBinderOcc usage) binders
1020 usage' `seq` (usage', uss)
1022 tagBinder :: UsageDetails -- Of scope
1024 -> (UsageDetails, -- Details with binders removed
1025 IdWithOccInfo) -- Tagged binders
1027 tagBinder usage binder
1029 usage' = usage `delVarEnv` binder
1030 binder' = setBinderOcc usage binder
1032 usage' `seq` (usage', binder')
1034 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
1035 setBinderOcc usage bndr
1036 | isTyVar bndr = bndr
1037 | isExportedId bndr = case idOccInfo bndr of
1039 _ -> setIdOccInfo bndr NoOccInfo
1040 -- Don't use local usage info for visible-elsewhere things
1041 -- BUT *do* erase any IAmALoopBreaker annotation, because we're
1042 -- about to re-generate it and it shouldn't be "sticky"
1044 | otherwise = setIdOccInfo bndr occ_info
1046 occ_info = lookupVarEnv usage bndr `orElse` IAmDead
1050 %************************************************************************
1052 \subsection{Operations over OccInfo}
1054 %************************************************************************
1057 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
1058 mkOneOcc _env id int_cxt
1059 | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
1060 | otherwise = emptyDetails
1062 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
1064 markMany IAmDead = IAmDead
1065 markMany _ = NoOccInfo
1067 markInsideSCC occ = markMany occ
1069 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
1070 markInsideLam occ = occ
1072 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
1074 addOccInfo IAmDead info2 = info2
1075 addOccInfo info1 IAmDead = info1
1076 addOccInfo _ _ = NoOccInfo
1078 -- (orOccInfo orig new) is used
1079 -- when combining occurrence info from branches of a case
1081 orOccInfo IAmDead info2 = info2
1082 orOccInfo info1 IAmDead = info1
1083 orOccInfo (OneOcc in_lam1 _ int_cxt1)
1084 (OneOcc in_lam2 _ int_cxt2)
1085 = OneOcc (in_lam1 || in_lam2)
1086 False -- False, because it occurs in both branches
1087 (int_cxt1 && int_cxt2)
1088 orOccInfo _ _ = NoOccInfo