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"
22 import CoreUtils ( exprIsTrivial, isDefaultAlt )
23 import Coercion ( mkSymCoercion )
31 import Maybes ( orElse )
32 import Digraph ( SCC(..), stronglyConnCompFromEdgedVerticesR )
33 import PrelNames ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
34 import Unique ( Unique )
35 import UniqFM ( keysUFM, intersectUFM_C, foldUFM_Directly )
36 import Util ( mapAndUnzip )
43 %************************************************************************
45 \subsection[OccurAnal-main]{Counting occurrences: main function}
47 %************************************************************************
49 Here's the externally-callable interface:
52 occurAnalysePgm :: [CoreBind] -> [CoreBind]
54 = snd (go initOccEnv binds)
56 go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
60 = (final_usage, bind' ++ binds')
62 (bs_usage, binds') = go env binds
63 (final_usage, bind') = occAnalBind env bind bs_usage
65 occurAnalyseExpr :: CoreExpr -> CoreExpr
66 -- Do occurrence analysis, and discard occurence info returned
67 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
71 %************************************************************************
73 \subsection[OccurAnal-main]{Counting occurrences: main function}
75 %************************************************************************
83 -> UsageDetails -- Usage details of scope
84 -> (UsageDetails, -- Of the whole let(rec)
87 occAnalBind env (NonRec binder rhs) body_usage
88 | isTyVar binder -- A type let; we don't gather usage info
89 = (body_usage, [NonRec binder rhs])
91 | not (binder `usedIn` body_usage) -- It's not mentioned
94 | otherwise -- It's mentioned in the body
95 = (body_usage' +++ addRuleUsage rhs_usage binder, -- Note [Rules are extra RHSs]
96 [NonRec tagged_binder rhs'])
98 (body_usage', tagged_binder) = tagBinder body_usage binder
99 (rhs_usage, rhs') = occAnalRhs env tagged_binder rhs
104 Dropping dead code for recursive bindings is done in a very simple way:
106 the entire set of bindings is dropped if none of its binders are
107 mentioned in its body; otherwise none are.
109 This seems to miss an obvious improvement.
121 Now 'f' is unused! But it's OK! Dependency analysis will sort this
122 out into a letrec for 'g' and a 'let' for 'f', and then 'f' will get
123 dropped. It isn't easy to do a perfect job in one blow. Consider
134 Note [Loop breaking and RULES]
135 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136 Loop breaking is surprisingly subtle. First read the section 4 of
137 "Secrets of the GHC inliner". This describes our basic plan.
139 However things are made quite a bit more complicated by RULES. Remember
141 * Note [Rules are extra RHSs]
142 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
143 A RULE for 'f' is like an extra RHS for 'f'. That way the "parent"
144 keeps the specialised "children" alive. If the parent dies
145 (because it isn't referenced any more), then the children will die
146 too (unless they are already referenced directly).
148 To that end, we build a Rec group for each cyclic strongly
150 *treating f's rules as extra RHSs for 'f'*.
152 When we make the Rec groups we include variables free in *either*
153 LHS *or* RHS of the rule. The former might seems silly, but see
154 Note [Rule dependency info].
156 So in Example [eftInt], eftInt and eftIntFB will be put in the
157 same Rec, even though their 'main' RHSs are both non-recursive.
159 * Note [Rules are visible in their own rec group]
160 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
161 We want the rules for 'f' to be visible in f's right-hand side.
162 And we'd like them to be visible in other functions in f's Rec
163 group. E.g. in Example [Specialisation rules] we want f' rule
164 to be visible in both f's RHS, and fs's RHS.
166 This means that we must simplify the RULEs first, before looking
167 at any of the definitions. This is done by Simplify.simplRecBind,
168 when it calls addLetIdInfo.
170 * Note [Choosing loop breakers]
171 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
172 We avoid infinite inlinings by choosing loop breakers, and
173 ensuring that a loop breaker cuts each loop. But what is a
174 "loop"? In particular, a RULE is like an equation for 'f' that
175 is *always* inlined if it is applicable. We do *not* disable
176 rules for loop-breakers. It's up to whoever makes the rules to
177 make sure that the rules themselves alwasys terminate. See Note
178 [Rules for recursive functions] in Simplify.lhs
181 f's RHS mentions g, and
182 g has a RULE that mentions h, and
183 h has a RULE that mentions f
185 then we *must* choose f to be a loop breaker. In general, take the
186 free variables of f's RHS, and augment it with all the variables
187 reachable by RULES from those starting points. That is the whole
188 reason for computing rule_fv_env in occAnalBind. (Of course we
189 only consider free vars that are also binders in this Rec group.)
191 Note that when we compute this rule_fv_env, we only consider variables
192 free in the *RHS* of the rule, in contrast to the way we build the
193 Rec group in the first place (Note [Rule dependency info])
195 Note that in Example [eftInt], *neither* eftInt *nor* eftIntFB is
196 chosen as a loop breaker, because their RHSs don't mention each other.
197 And indeed both can be inlined safely.
199 Note that the edges of the graph we use for computing loop breakers
200 are not the same as the edges we use for computing the Rec blocks.
201 That's why we compute
202 rec_edges for the Rec block analysis
203 loop_breaker_edges for the loop breaker analysis
206 * Note [Weak loop breakers]
207 ~~~~~~~~~~~~~~~~~~~~~~~~~
208 There is a last nasty wrinkle. Suppose we have
218 Remmber that we simplify the RULES before any RHS (see Note
219 [Rules are visible in their own rec group] above).
221 So we must *not* postInlineUnconditionally 'g', even though
222 its RHS turns out to be trivial. (I'm assuming that 'g' is
223 not choosen as a loop breaker.)
225 We "solve" this by making g a "weak" or "rules-only" loop breaker,
226 with OccInfo = IAmLoopBreaker True. A normal "strong" loop breaker
227 has IAmLoopBreaker False. So
229 Inline postInlineUnconditinoally
230 IAmLoopBreaker False no no
231 IAmLoopBreaker True yes no
234 The **sole** reason for this kind of loop breaker is so that
235 postInlineUnconditionally does not fire. Ugh.
237 * Note [Rule dependency info]
238 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
239 The VarSet in a SpecInfo is used for dependency analysis in the
240 occurrence analyser. We must track free vars in *both* lhs and rhs.
241 Hence use of idRuleVars, rather than idRuleRhsVars in addRuleUsage.
245 Then if we substitute y for x, we'd better do so in the
246 rule's LHS too, so we'd better ensure the dependency is respected
251 Example (from GHC.Enum):
253 eftInt :: Int# -> Int# -> [Int]
254 eftInt x y = ...(non-recursive)...
256 {-# INLINE [0] eftIntFB #-}
257 eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
258 eftIntFB c n x y = ...(non-recursive)...
261 "eftInt" [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
262 "eftIntList" [1] eftIntFB (:) [] = eftInt
265 Example [Specialisation rules]
266 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
267 Consider this group, which is typical of what SpecConstr builds:
269 fs a = ....f (C a)....
270 f x = ....f (C a)....
271 {-# RULE f (C a) = fs a #-}
273 So 'f' and 'fs' are in the same Rec group (since f refers to fs via its RULE).
275 But watch out! If 'fs' is not chosen as a loop breaker, we may get an infinite loop:
276 - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
277 - fs is inlined (say it's small)
278 - now there's another opportunity to apply the RULE
280 This showed up when compiling Control.Concurrent.Chan.getChanContents.
284 occAnalBind env (Rec pairs) body_usage
285 = foldr occAnalRec (body_usage, []) sccs
286 -- For a recursive group, we
287 -- * occ-analyse all the RHSs
288 -- * compute strongly-connected components
289 -- * feed those components to occAnalRec
291 -------------Dependency analysis ------------------------------
292 bndr_set = mkVarSet (map fst pairs)
294 sccs :: [SCC (Node Details)]
295 sccs = {-# SCC "occAnalBind.scc" #-} stronglyConnCompFromEdgedVerticesR rec_edges
297 rec_edges :: [Node Details]
298 rec_edges = {-# SCC "occAnalBind.assoc" #-} map make_node pairs
300 make_node (bndr, rhs)
301 = (ND bndr rhs' rhs_usage rhs_fvs, idUnique bndr, out_edges)
303 (rhs_usage, rhs') = occAnalRhs env bndr rhs
304 rhs_fvs = intersectUFM_C (\b _ -> b) bndr_set rhs_usage
305 out_edges = keysUFM (rhs_fvs `unionVarSet` idRuleVars bndr)
306 -- (a -> b) means a mentions b
307 -- Given the usage details (a UFM that gives occ info for each free var of
308 -- the RHS) we can get the list of free vars -- or rather their Int keys --
309 -- by just extracting the keys from the finite map. Grimy, but fast.
310 -- Previously we had this:
311 -- [ bndr | bndr <- bndrs,
312 -- maybeToBool (lookupVarEnv rhs_usage bndr)]
313 -- which has n**2 cost, and this meant that edges_from alone
314 -- consumed 10% of total runtime!
316 -----------------------------
317 occAnalRec :: SCC (Node Details) -> (UsageDetails, [CoreBind])
318 -> (UsageDetails, [CoreBind])
320 -- The NonRec case is just like a Let (NonRec ...) above
321 occAnalRec (AcyclicSCC (ND bndr rhs rhs_usage _, _, _)) (body_usage, binds)
322 | not (bndr `usedIn` body_usage)
323 = (body_usage, binds)
325 | otherwise -- It's mentioned in the body
326 = (body_usage' +++ addRuleUsage rhs_usage bndr, -- Note [Rules are extra RHSs]
327 NonRec tagged_bndr rhs : binds)
329 (body_usage', tagged_bndr) = tagBinder body_usage bndr
332 -- The Rec case is the interesting one
333 -- See Note [Loop breaking]
334 occAnalRec (CyclicSCC nodes) (body_usage, binds)
335 | not (any (`usedIn` body_usage) bndrs) -- NB: look at body_usage, not total_usage
336 = (body_usage, binds) -- Dead code
338 | otherwise -- At this point we always build a single Rec
339 = (final_usage, Rec pairs : binds)
342 bndrs = [b | (ND b _ _ _, _, _) <- nodes]
343 bndr_set = mkVarSet bndrs
345 ----------------------------
346 -- Tag the binders with their occurrence info
347 total_usage = foldl add_usage body_usage nodes
348 add_usage body_usage (ND bndr _ rhs_usage _, _, _)
349 = body_usage +++ addRuleUsage rhs_usage bndr
350 (final_usage, tagged_nodes) = mapAccumL tag_node total_usage nodes
352 tag_node :: UsageDetails -> Node Details -> (UsageDetails, Node Details)
353 -- (a) Tag the binders in the details with occ info
354 -- (b) Mark the binder with "weak loop-breaker" OccInfo
355 -- saying "no preInlineUnconditionally" if it is used
356 -- in any rule (lhs or rhs) of the recursive group
357 -- See Note [Weak loop breakers]
358 tag_node usage (ND bndr rhs rhs_usage rhs_fvs, k, ks)
359 = (usage `delVarEnv` bndr, (ND bndr2 rhs rhs_usage rhs_fvs, k, ks))
361 bndr2 | bndr `elemVarSet` all_rule_fvs = makeLoopBreaker True bndr1
363 bndr1 = setBinderOcc usage bndr
364 all_rule_fvs = bndr_set `intersectVarSet` foldr (unionVarSet . idRuleVars)
367 ----------------------------
368 -- Now reconstruct the cycle
369 pairs | no_rules = reOrderCycle tagged_nodes
370 | otherwise = concatMap reOrderRec (stronglyConnCompFromEdgedVerticesR loop_breaker_edges)
372 -- See Note [Choosing loop breakers] for looop_breaker_edges
373 loop_breaker_edges = map mk_node tagged_nodes
374 mk_node (details@(ND _ _ _ rhs_fvs), k, _) = (details, k, new_ks)
376 new_ks = keysUFM (extendFvs rule_fv_env rhs_fvs rhs_fvs)
378 ------------------------------------
379 rule_fv_env :: IdEnv IdSet -- Variables from this group mentioned in RHS of rules
380 -- Domain is *subset* of bound vars (others have no rule fvs)
381 rule_fv_env = rule_loop init_rule_fvs
383 no_rules = null init_rule_fvs
384 init_rule_fvs = [(b, rule_fvs)
386 , let rule_fvs = idRuleRhsVars b `intersectVarSet` bndr_set
387 , not (isEmptyVarSet rule_fvs)]
389 rule_loop :: [(Id,IdSet)] -> IdEnv IdSet -- Finds fixpoint
392 | otherwise = rule_loop new_fv_list
394 env = mkVarEnv init_rule_fvs
395 (no_change, new_fv_list) = mapAccumL bump True fv_list
396 bump no_change (b,fvs)
397 | new_fvs `subVarSet` fvs = (no_change, (b,fvs))
398 | otherwise = (False, (b,new_fvs `unionVarSet` fvs))
400 new_fvs = extendFvs env emptyVarSet fvs
402 idRuleRhsVars :: Id -> VarSet
403 -- Just the variables free on the *rhs* of a rule
404 -- See Note [Choosing loop breakers]
405 idRuleRhsVars id = foldr (unionVarSet . ruleRhsFreeVars) emptyVarSet (idCoreRules id)
407 extendFvs :: IdEnv IdSet -> IdSet -> IdSet -> IdSet
408 -- (extendFVs env fvs s) returns (fvs `union` env(s))
409 extendFvs env fvs id_set
410 = foldUFM_Directly add fvs id_set
413 = case lookupVarEnv_Directly env uniq of
414 Just fvs' -> fvs' `unionVarSet` fvs
418 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
419 strongly connected component (there's guaranteed to be a cycle). It returns the
421 a) in a better order,
422 b) with some of the Ids having a IAmALoopBreaker pragma
424 The "loop-breaker" Ids are sufficient to break all cycles in the SCC. This means
425 that the simplifier can guarantee not to loop provided it never records an inlining
426 for these no-inline guys.
428 Furthermore, the order of the binds is such that if we neglect dependencies
429 on the no-inline Ids then the binds are topologically sorted. This means
430 that the simplifier will generally do a good job if it works from top bottom,
431 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
434 [June 98: I don't understand the following paragraphs, and I've
435 changed the a=b case again so that it isn't a special case any more.]
437 Here's a case that bit me:
445 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
447 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
448 Perhaps something cleverer would suffice.
453 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
454 -- which is gotten from the Id.
455 data Details = ND Id -- Binder
457 UsageDetails -- Full usage from RHS (*not* including rules)
458 IdSet -- Other binders from this Rec group mentioned on RHS
459 -- (derivable from UsageDetails but cached here)
461 reOrderRec :: SCC (Node Details)
463 -- Sorted into a plausible order. Enough of the Ids have
464 -- IAmALoopBreaker pragmas that there are no loops left.
465 reOrderRec (AcyclicSCC (ND bndr rhs _ _, _, _)) = [(bndr, rhs)]
466 reOrderRec (CyclicSCC cycle) = reOrderCycle cycle
468 reOrderCycle :: [Node Details] -> [(Id,CoreExpr)]
470 = panic "reOrderCycle"
471 reOrderCycle [bind] -- Common case of simple self-recursion
472 = [(makeLoopBreaker False bndr, rhs)]
474 (ND bndr rhs _ _, _, _) = bind
476 reOrderCycle (bind : binds)
477 = -- Choose a loop breaker, mark it no-inline,
478 -- do SCC analysis on the rest, and recursively sort them out
479 concatMap reOrderRec (stronglyConnCompFromEdgedVerticesR unchosen) ++
480 [(makeLoopBreaker False bndr, rhs)]
483 (chosen_bind, unchosen) = choose_loop_breaker bind (score bind) [] binds
484 ND bndr rhs _ _ = chosen_bind
486 -- This loop looks for the bind with the lowest score
487 -- to pick as the loop breaker. The rest accumulate in
488 choose_loop_breaker (details,_,_) _loop_sc acc []
489 = (details, acc) -- Done
491 choose_loop_breaker loop_bind loop_sc acc (bind : binds)
492 | sc < loop_sc -- Lower score so pick this new one
493 = choose_loop_breaker bind sc (loop_bind : acc) binds
495 | otherwise -- No lower so don't pick it
496 = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
500 score :: Node Details -> Int -- Higher score => less likely to be picked as loop breaker
501 score (ND bndr rhs _ _, _, _)
502 | workerExists (idWorkerInfo bndr) = 10
503 -- Note [Worker inline loop]
505 | exprIsTrivial rhs = 5 -- Practically certain to be inlined
506 -- Used to have also: && not (isExportedId bndr)
507 -- But I found this sometimes cost an extra iteration when we have
508 -- rec { d = (a,b); a = ...df...; b = ...df...; df = d }
509 -- where df is the exported dictionary. Then df makes a really
510 -- bad choice for loop breaker
512 | is_con_app rhs = 3 -- Data types help with cases
513 -- Note [Constructor applictions]
515 -- If an Id is marked "never inline" then it makes a great loop breaker
516 -- The only reason for not checking that here is that it is rare
517 -- and I've never seen a situation where it makes a difference,
518 -- so it probably isn't worth the time to test on every binder
519 -- | isNeverActive (idInlinePragma bndr) = -10
521 | inlineCandidate bndr rhs = 2 -- Likely to be inlined
522 -- Note [Inline candidates]
524 | not (neverUnfold (idUnfolding bndr)) = 1
525 -- the Id has some kind of unfolding
529 inlineCandidate :: Id -> CoreExpr -> Bool
530 inlineCandidate _ (Note InlineMe _) = True
531 inlineCandidate id _ = isOneOcc (idOccInfo id)
535 -- It's really really important to inline dictionaries. Real
536 -- example (the Enum Ordering instance from GHC.Base):
538 -- rec f = \ x -> case d of (p,q,r) -> p x
539 -- g = \ x -> case d of (p,q,r) -> q x
542 -- Here, f and g occur just once; but we can't inline them into d.
543 -- On the other hand we *could* simplify those case expressions if
544 -- we didn't stupidly choose d as the loop breaker.
545 -- But we won't because constructor args are marked "Many".
546 -- Inlining dictionaries is really essential to unravelling
547 -- the loops in static numeric dictionaries, see GHC.Float.
549 -- Cheap and cheerful; the simplifer moves casts out of the way
550 -- The lambda case is important to spot x = /\a. C (f a)
551 -- which comes up when C is a dictionary constructor and
552 -- f is a default method.
553 -- Example: the instance for Show (ST s a) in GHC.ST
555 -- However we *also* treat (\x. C p q) as a con-app-like thing,
556 -- Note [Closure conversion]
557 is_con_app (Var v) = isDataConWorkId v
558 is_con_app (App f _) = is_con_app f
559 is_con_app (Lam _ e) = is_con_app e
560 is_con_app (Note _ e) = is_con_app e
563 makeLoopBreaker :: Bool -> Id -> Id
564 -- Set the loop-breaker flag: see Note [Weak loop breakers]
565 makeLoopBreaker weak bndr = setIdOccInfo bndr (IAmALoopBreaker weak)
568 Note [INLINE pragmas]
569 ~~~~~~~~~~~~~~~~~~~~~
570 Never choose a function with an INLINE pramga as the loop breaker!
571 If such a function is mutually-recursive with a non-INLINE thing,
572 then the latter should be the loop-breaker.
574 A particular case is wrappers generated by the demand analyser.
575 If you make then into a loop breaker you may get an infinite
576 inlining loop. For example:
578 $wfoo x = ....foo x....
580 {-loop brk-} foo x = ...$wfoo x...
582 The interface file sees the unfolding for $wfoo, and sees that foo is
583 strict (and hence it gets an auto-generated wrapper). Result: an
584 infinite inlining in the importing scope. So be a bit careful if you
585 change this. A good example is Tree.repTree in
586 nofib/spectral/minimax. If the repTree wrapper is chosen as the loop
587 breaker then compiling Game.hs goes into an infinite loop (this
588 happened when we gave is_con_app a lower score than inline candidates).
590 Note [Constructor applications]
591 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
592 It's really really important to inline dictionaries. Real
593 example (the Enum Ordering instance from GHC.Base):
595 rec f = \ x -> case d of (p,q,r) -> p x
596 g = \ x -> case d of (p,q,r) -> q x
599 Here, f and g occur just once; but we can't inline them into d.
600 On the other hand we *could* simplify those case expressions if
601 we didn't stupidly choose d as the loop breaker.
602 But we won't because constructor args are marked "Many".
603 Inlining dictionaries is really essential to unravelling
604 the loops in static numeric dictionaries, see GHC.Float.
606 Note [Closure conversion]
607 ~~~~~~~~~~~~~~~~~~~~~~~~~
608 We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
609 The immediate motivation came from the result of a closure-conversion transformation
610 which generated code like this:
612 data Clo a b = forall c. Clo (c -> a -> b) c
614 ($:) :: Clo a b -> a -> b
615 Clo f env $: x = f env x
617 rec { plus = Clo plus1 ()
619 ; plus1 _ n = Clo plus2 n
622 ; plus2 (Succ m) n = Succ (plus $: m $: n) }
624 If we inline 'plus' and 'plus1', everything unravels nicely. But if
625 we choose 'plus1' as the loop breaker (which is entirely possible
626 otherwise), the loop does not unravel nicely.
629 @occAnalRhs@ deals with the question of bindings where the Id is marked
630 by an INLINE pragma. For these we record that anything which occurs
631 in its RHS occurs many times. This pessimistically assumes that ths
632 inlined binder also occurs many times in its scope, but if it doesn't
633 we'll catch it next time round. At worst this costs an extra simplifier pass.
634 ToDo: try using the occurrence info for the inline'd binder.
636 [March 97] We do the same for atomic RHSs. Reason: see notes with reOrderRec.
637 [June 98, SLPJ] I've undone this change; I don't understand it. See notes with reOrderRec.
642 -> Id -> CoreExpr -- Binder and rhs
643 -- For non-recs the binder is alrady tagged
644 -- with occurrence info
645 -> (UsageDetails, CoreExpr)
647 occAnalRhs env id rhs
650 ctxt | certainly_inline id = env
651 | otherwise = rhsCtxt env
652 -- Note that we generally use an rhsCtxt. This tells the occ anal n
653 -- that it's looking at an RHS, which has an effect in occAnalApp
655 -- But there's a problem. Consider
660 -- First time round, it looks as if x1 and x2 occur as an arg of a
661 -- let-bound constructor ==> give them a many-occurrence.
662 -- But then x3 is inlined (unconditionally as it happens) and
663 -- next time round, x2 will be, and the next time round x1 will be
664 -- Result: multiple simplifier iterations. Sigh.
665 -- Crude solution: use rhsCtxt for things that occur just once...
667 certainly_inline id = case idOccInfo id of
668 OneOcc in_lam one_br _ -> not in_lam && one_br
675 addRuleUsage :: UsageDetails -> Id -> UsageDetails
676 -- Add the usage from RULES in Id to the usage
677 addRuleUsage usage id
678 = foldVarSet add usage (idRuleVars id)
679 -- idRuleVars here: see Note [Rule dependency info]
681 add v u = addOneOcc u v NoOccInfo
682 -- Give a non-committal binder info (i.e manyOcc) because
683 -- a) Many copies of the specialised thing can appear
684 -- b) We don't want to substitute a BIG expression inside a RULE
685 -- even if that's the only occurrence of the thing
686 -- (Same goes for INLINE.)
694 -> (UsageDetails, -- Gives info only about the "interesting" Ids
697 occAnal _ (Type t) = (emptyDetails, Type t)
698 occAnal env (Var v) = (mkOneOcc env v False, Var v)
699 -- At one stage, I gathered the idRuleVars for v here too,
700 -- which in a way is the right thing to do.
701 -- But that went wrong right after specialisation, when
702 -- the *occurrences* of the overloaded function didn't have any
703 -- rules in them, so the *specialised* versions looked as if they
704 -- weren't used at all.
707 We regard variables that occur as constructor arguments as "dangerousToDup":
711 f x = let y = expensive x in
713 (case z of {(p,q)->q}, case z of {(p,q)->q})
716 We feel free to duplicate the WHNF (True,y), but that means
717 that y may be duplicated thereby.
719 If we aren't careful we duplicate the (expensive x) call!
720 Constructors are rather like lambdas in this way.
723 occAnal _ expr@(Lit _) = (emptyDetails, expr)
727 occAnal env (Note InlineMe body)
728 = case occAnal env body of { (usage, body') ->
729 (mapVarEnv markMany usage, Note InlineMe body')
732 occAnal env (Note note@(SCC _) body)
733 = case occAnal env body of { (usage, body') ->
734 (mapVarEnv markInsideSCC usage, Note note body')
737 occAnal env (Note note body)
738 = case occAnal env body of { (usage, body') ->
739 (usage, Note note body')
742 occAnal env (Cast expr co)
743 = case occAnal env expr of { (usage, expr') ->
744 (markRhsUds env True usage, Cast expr' co)
745 -- If we see let x = y `cast` co
746 -- then mark y as 'Many' so that we don't
747 -- immediately inline y again.
752 occAnal env app@(App _ _)
753 = occAnalApp env (collectArgs app)
755 -- Ignore type variables altogether
756 -- (a) occurrences inside type lambdas only not marked as InsideLam
757 -- (b) type variables not in environment
759 occAnal env (Lam x body) | isTyVar x
760 = case occAnal env body of { (body_usage, body') ->
761 (body_usage, Lam x body')
764 -- For value lambdas we do a special hack. Consider
766 -- If we did nothing, x is used inside the \y, so would be marked
767 -- as dangerous to dup. But in the common case where the abstraction
768 -- is applied to two arguments this is over-pessimistic.
769 -- So instead, we just mark each binder with its occurrence
770 -- info in the *body* of the multiple lambda.
771 -- Then, the simplifier is careful when partially applying lambdas.
773 occAnal env expr@(Lam _ _)
774 = case occAnal env_body body of { (body_usage, body') ->
776 (final_usage, tagged_binders) = tagBinders body_usage binders
777 -- URGH! Sept 99: we don't seem to be able to use binders' here, because
778 -- we get linear-typed things in the resulting program that we can't handle yet.
779 -- (e.g. PrelShow) TODO
781 really_final_usage = if linear then
784 mapVarEnv markInsideLam final_usage
787 mkLams tagged_binders body') }
789 env_body = vanillaCtxt env -- Body is (no longer) an RhsContext
790 (binders, body) = collectBinders expr
791 binders' = oneShotGroup env binders
792 linear = all is_one_shot binders'
793 is_one_shot b = isId b && isOneShotBndr b
795 occAnal env (Case scrut bndr ty alts)
796 = case occ_anal_scrut scrut alts of { (scrut_usage, scrut') ->
797 case mapAndUnzip occ_anal_alt alts of { (alts_usage_s, alts') ->
799 alts_usage = foldr1 combineAltsUsageDetails alts_usage_s
800 alts_usage' = addCaseBndrUsage alts_usage
801 (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
802 total_usage = scrut_usage +++ alts_usage1
804 total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
806 -- Note [Case binder usage]
807 -- ~~~~~~~~~~~~~~~~~~~~~~~~
808 -- The case binder gets a usage of either "many" or "dead", never "one".
809 -- Reason: we like to inline single occurrences, to eliminate a binding,
810 -- but inlining a case binder *doesn't* eliminate a binding.
811 -- We *don't* want to transform
812 -- case x of w { (p,q) -> f w }
814 -- case x of w { (p,q) -> f (p,q) }
815 addCaseBndrUsage usage = case lookupVarEnv usage bndr of
817 Just _ -> extendVarEnv usage bndr NoOccInfo
819 alt_env = mkAltEnv env bndr_swap
820 -- Consider x = case v of { True -> (p,q); ... }
821 -- Then it's fine to inline p and q
823 bndr_swap = case scrut of
824 Var v -> Just (v, Var bndr)
825 Cast (Var v) co -> Just (v, Cast (Var bndr) (mkSymCoercion co))
828 occ_anal_alt = occAnalAlt alt_env bndr bndr_swap
830 occ_anal_scrut (Var v) (alt1 : other_alts)
831 | not (null other_alts) || not (isDefaultAlt alt1)
832 = (mkOneOcc env v True, Var v) -- The 'True' says that the variable occurs
833 -- in an interesting context; the case has
834 -- at least one non-default alternative
835 occ_anal_scrut scrut _alts
836 = occAnal (vanillaCtxt env) scrut -- No need for rhsCtxt
838 occAnal env (Let bind body)
839 = case occAnal env body of { (body_usage, body') ->
840 case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
841 (final_usage, mkLets new_binds body') }}
843 occAnalArgs :: OccEnv -> [CoreExpr] -> (UsageDetails, [CoreExpr])
845 = case mapAndUnzip (occAnal arg_env) args of { (arg_uds_s, args') ->
846 (foldr (+++) emptyDetails arg_uds_s, args')}
848 arg_env = vanillaCtxt env
851 Applications are dealt with specially because we want
852 the "build hack" to work.
856 -> (Expr CoreBndr, [Arg CoreBndr])
857 -> (UsageDetails, Expr CoreBndr)
858 occAnalApp env (Var fun, args)
859 = case args_stuff of { (args_uds, args') ->
861 final_args_uds = markRhsUds env is_pap args_uds
863 (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
865 fun_uniq = idUnique fun
866 fun_uds = mkOneOcc env fun (valArgCount args > 0)
867 is_pap = isDataConWorkId fun || valArgCount args < idArity fun
869 -- Hack for build, fold, runST
870 args_stuff | fun_uniq == buildIdKey = appSpecial env 2 [True,True] args
871 | fun_uniq == augmentIdKey = appSpecial env 2 [True,True] args
872 | fun_uniq == foldrIdKey = appSpecial env 3 [False,True] args
873 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True] args
874 -- (foldr k z xs) may call k many times, but it never
875 -- shares a partial application of k; hence [False,True]
876 -- This means we can optimise
877 -- foldr (\x -> let v = ...x... in \y -> ...v...) z xs
878 -- by floating in the v
880 | otherwise = occAnalArgs env args
883 occAnalApp env (fun, args)
884 = case occAnal (addAppCtxt env args) fun of { (fun_uds, fun') ->
885 -- The addAppCtxt is a bit cunning. One iteration of the simplifier
886 -- often leaves behind beta redexs like
888 -- Here we would like to mark x,y as one-shot, and treat the whole
889 -- thing much like a let. We do this by pushing some True items
890 -- onto the context stack.
892 case occAnalArgs env args of { (args_uds, args') ->
894 final_uds = fun_uds +++ args_uds
896 (final_uds, mkApps fun' args') }}
899 markRhsUds :: OccEnv -- Check if this is a RhsEnv
900 -> Bool -- and this is true
901 -> UsageDetails -- The do markMany on this
903 -- We mark the free vars of the argument of a constructor or PAP
904 -- as "many", if it is the RHS of a let(rec).
905 -- This means that nothing gets inlined into a constructor argument
906 -- position, which is what we want. Typically those constructor
907 -- arguments are just variables, or trivial expressions.
909 -- This is the *whole point* of the isRhsEnv predicate
910 markRhsUds env is_pap arg_uds
911 | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
912 | otherwise = arg_uds
916 -> Int -> CtxtTy -- Argument number, and context to use for it
918 -> (UsageDetails, [CoreExpr])
919 appSpecial env n ctxt args
922 arg_env = vanillaCtxt env
924 go _ [] = (emptyDetails, []) -- Too few args
926 go 1 (arg:args) -- The magic arg
927 = case occAnal (setCtxtTy arg_env ctxt) arg of { (arg_uds, arg') ->
928 case occAnalArgs env args of { (args_uds, args') ->
929 (arg_uds +++ args_uds, arg':args') }}
932 = case occAnal arg_env arg of { (arg_uds, arg') ->
933 case go (n-1) args of { (args_uds, args') ->
934 (arg_uds +++ args_uds, arg':args') }}
940 We do these two transformations right here:
942 (1) case x of b { pi -> ri }
944 case x of b { pi -> let x=b in ri }
946 (2) case (x |> co) of b { pi -> ri }
948 case (x |> co) of b { pi -> let x = b |> sym co in ri }
950 Why (2)? See Note [Case of cast]
952 In both cases, in a particular alternative (pi -> ri), we only
954 (a) x occurs free in (pi -> ri)
955 (ie it occurs in ri, but is not bound in pi)
956 (b) the pi does not bind b (or the free vars of co)
957 We need (a) and (b) for the inserted binding to be correct.
959 For the alternatives where we inject the binding, we can transfer
960 all x's OccInfo to b. And that is the point.
963 * The deliberate shadowing of 'x'.
964 * That (a) rapidly becomes false, so no bindings are injected.
966 The reason for doing these transformations here is because it allows
967 us to adjust the OccInfo for 'x' and 'b' as we go.
969 * Suppose the only occurrences of 'x' are the scrutinee and in the
970 ri; then this transformation makes it occur just once, and hence
971 get inlined right away.
973 * If we do this in the Simplifier, we don't know whether 'x' is used
974 in ri, so we are forced to pessimistically zap b's OccInfo even
975 though it is typically dead (ie neither it nor x appear in the
976 ri). There's nothing actually wrong with zapping it, except that
977 it's kind of nice to know which variables are dead. My nose
978 tells me to keep this information as robustly as possible.
980 The Maybe (Id,CoreExpr) passed to occAnalAlt is the extra let-binding
981 {x=b}; it's Nothing if the binder-swap doesn't happen.
983 Note [Binder swap on GlobalId scrutinees]
984 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
985 When the scrutinee is a GlobalId we must take care in two ways
987 i) In order to *know* whether 'x' occurs free in the RHS, we need its
988 occurrence info. BUT, we don't gather occurrence info for
989 GlobalIds. That's what the (small) occ_scrut_ids set in OccEnv is
990 for: it says "gather occurrence info for these.
992 ii) We must call localiseId on 'x' first, in case it's a GlobalId, or
993 has an External Name. See, for example, SimplEnv Note [Global Ids in
998 Consider case (x `cast` co) of b { I# ->
999 ... (case (x `cast` co) of {...}) ...
1000 We'd like to eliminate the inner case. That is the motivation for
1001 equation (2) in Note [Binder swap]. When we get to the inner case, we
1002 inline x, cancel the casts, and away we go.
1004 Note [Binders in case alternatives]
1005 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1007 case x of y { (a,b) -> f y }
1008 We treat 'a', 'b' as dead, because they don't physically occur in the
1009 case alternative. (Indeed, a variable is dead iff it doesn't occur in
1010 its scope in the output of OccAnal.) This invariant is It really
1011 helpe to know when binders are unused. See esp the call to
1012 isDeadBinder in Simplify.mkDupableAlt
1014 In this example, though, the Simplifier will bring 'a' and 'b' back to
1015 life, beause it binds 'y' to (a,b) (imagine got inlined and
1019 occAnalAlt :: OccEnv
1021 -> Maybe (Id, CoreExpr) -- Note [Binder swap]
1023 -> (UsageDetails, Alt IdWithOccInfo)
1024 occAnalAlt env case_bndr mb_scrut_var (con, bndrs, rhs)
1025 = case occAnal env rhs of { (rhs_usage, rhs') ->
1027 (alt_usg, tagged_bndrs) = tagBinders rhs_usage bndrs
1028 bndrs' = tagged_bndrs -- See Note [Binders in case alternatives]
1030 case mb_scrut_var of
1031 Just (scrut_var, scrut_rhs) -- See Note [Binder swap]
1032 | scrut_var `localUsedIn` alt_usg -- (a) Fast path, usually false
1033 , not (any shadowing bndrs) -- (b)
1034 -> (addOneOcc usg_wo_scrut case_bndr NoOccInfo,
1035 -- See Note [Case binder usage] for the NoOccInfo
1036 (con, bndrs', Let (NonRec scrut_var' scrut_rhs) rhs'))
1038 (usg_wo_scrut, scrut_var') = tagBinder alt_usg (localiseId scrut_var)
1039 -- Note the localiseId; we're making a new binding
1040 -- for it, and it might have an External Name, or
1041 -- even be a GlobalId; Note [Binder swap on GlobalId scrutinees]
1042 shadowing bndr = bndr `elemVarSet` rhs_fvs
1043 rhs_fvs = exprFreeVars scrut_rhs
1045 _other -> (alt_usg, (con, bndrs', rhs')) }
1049 %************************************************************************
1051 \subsection[OccurAnal-types]{OccEnv}
1053 %************************************************************************
1057 = OccEnv { occ_encl :: !OccEncl -- Enclosing context information
1058 , occ_ctxt :: !CtxtTy -- Tells about linearity
1059 , occ_scrut_ids :: !GblScrutIds }
1061 type GblScrutIds = IdSet -- GlobalIds that are scrutinised, and for which
1062 -- we want to gather occurence info; see
1063 -- Note [Binder swap for GlobalId scrutinee]
1064 -- No need to prune this if there's a shadowing binding
1065 -- because it's OK for it to be too big
1067 -- OccEncl is used to control whether to inline into constructor arguments
1069 -- x = (p,q) -- Don't inline p or q
1070 -- y = /\a -> (p a, q a) -- Still don't inline p or q
1071 -- z = f (p,q) -- Do inline p,q; it may make a rule fire
1072 -- So OccEncl tells enought about the context to know what to do when
1073 -- we encounter a contructor application or PAP.
1076 = OccRhs -- RHS of let(rec), albeit perhaps inside a type lambda
1077 -- Don't inline into constructor args here
1078 | OccVanilla -- Argument of function, body of lambda, scruintee of case etc.
1079 -- Do inline into constructor args here
1081 type CtxtTy = [Bool]
1084 -- True:ctxt Analysing a function-valued expression that will be
1085 -- applied just once
1087 -- False:ctxt Analysing a function-valued expression that may
1088 -- be applied many times; but when it is,
1089 -- the CtxtTy inside applies
1091 initOccEnv :: OccEnv
1092 initOccEnv = OccEnv { occ_encl = OccRhs
1094 , occ_scrut_ids = emptyVarSet }
1096 vanillaCtxt :: OccEnv -> OccEnv
1097 vanillaCtxt env = OccEnv { occ_encl = OccVanilla, occ_ctxt = []
1098 , occ_scrut_ids = occ_scrut_ids env }
1100 rhsCtxt :: OccEnv -> OccEnv
1101 rhsCtxt env = OccEnv { occ_encl = OccRhs, occ_ctxt = []
1102 , occ_scrut_ids = occ_scrut_ids env }
1104 mkAltEnv :: OccEnv -> Maybe (Id, CoreExpr) -> OccEnv
1105 -- Does two things: a) makes the occ_ctxt = OccVanilla
1106 -- b) extends the scrut_ids if necessary
1107 mkAltEnv env (Just (scrut_id, _))
1108 | not (isLocalId scrut_id)
1109 = OccEnv { occ_encl = OccVanilla
1110 , occ_scrut_ids = extendVarSet (occ_scrut_ids env) scrut_id
1111 , occ_ctxt = occ_ctxt env }
1113 | isRhsEnv env = env { occ_encl = OccVanilla }
1116 setCtxtTy :: OccEnv -> CtxtTy -> OccEnv
1117 setCtxtTy env ctxt = env { occ_ctxt = ctxt }
1119 isRhsEnv :: OccEnv -> Bool
1120 isRhsEnv (OccEnv { occ_encl = OccRhs }) = True
1121 isRhsEnv (OccEnv { occ_encl = OccVanilla }) = False
1123 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
1124 -- The result binders have one-shot-ness set that they might not have had originally.
1125 -- This happens in (build (\cn -> e)). Here the occurrence analyser
1126 -- linearity context knows that c,n are one-shot, and it records that fact in
1127 -- the binder. This is useful to guide subsequent float-in/float-out tranformations
1129 oneShotGroup (OccEnv { occ_ctxt = ctxt }) bndrs
1132 go _ [] rev_bndrs = reverse rev_bndrs
1134 go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
1135 | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
1137 bndr' | lin_ctxt = setOneShotLambda bndr
1140 go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
1142 addAppCtxt :: OccEnv -> [Arg CoreBndr] -> OccEnv
1143 addAppCtxt env@(OccEnv { occ_ctxt = ctxt }) args
1144 = env { occ_ctxt = replicate (valArgCount args) True ++ ctxt }
1147 %************************************************************************
1149 \subsection[OccurAnal-types]{OccEnv}
1151 %************************************************************************
1154 type UsageDetails = IdEnv OccInfo -- A finite map from ids to their usage
1155 -- INVARIANT: never IAmDead
1156 -- (Deadness is signalled by not being in the map at all)
1158 (+++), combineAltsUsageDetails
1159 :: UsageDetails -> UsageDetails -> UsageDetails
1162 = plusVarEnv_C addOccInfo usage1 usage2
1164 combineAltsUsageDetails usage1 usage2
1165 = plusVarEnv_C orOccInfo usage1 usage2
1167 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
1168 addOneOcc usage id info
1169 = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
1170 -- ToDo: make this more efficient
1172 emptyDetails :: UsageDetails
1173 emptyDetails = (emptyVarEnv :: UsageDetails)
1175 localUsedIn, usedIn :: Id -> UsageDetails -> Bool
1176 v `localUsedIn` details = v `elemVarEnv` details
1177 v `usedIn` details = isExportedId v || v `localUsedIn` details
1179 type IdWithOccInfo = Id
1181 tagBinders :: UsageDetails -- Of scope
1183 -> (UsageDetails, -- Details with binders removed
1184 [IdWithOccInfo]) -- Tagged binders
1186 tagBinders usage binders
1188 usage' = usage `delVarEnvList` binders
1189 uss = map (setBinderOcc usage) binders
1191 usage' `seq` (usage', uss)
1193 tagBinder :: UsageDetails -- Of scope
1195 -> (UsageDetails, -- Details with binders removed
1196 IdWithOccInfo) -- Tagged binders
1198 tagBinder usage binder
1200 usage' = usage `delVarEnv` binder
1201 binder' = setBinderOcc usage binder
1203 usage' `seq` (usage', binder')
1205 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
1206 setBinderOcc usage bndr
1207 | isTyVar bndr = bndr
1208 | isExportedId bndr = case idOccInfo bndr of
1210 _ -> setIdOccInfo bndr NoOccInfo
1211 -- Don't use local usage info for visible-elsewhere things
1212 -- BUT *do* erase any IAmALoopBreaker annotation, because we're
1213 -- about to re-generate it and it shouldn't be "sticky"
1215 | otherwise = setIdOccInfo bndr occ_info
1217 occ_info = lookupVarEnv usage bndr `orElse` IAmDead
1221 %************************************************************************
1223 \subsection{Operations over OccInfo}
1225 %************************************************************************
1228 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
1229 mkOneOcc env id int_cxt
1230 | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
1231 | id `elemVarSet` occ_scrut_ids env = unitVarEnv id NoOccInfo
1232 | otherwise = emptyDetails
1234 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
1236 markMany _ = NoOccInfo
1238 markInsideSCC occ = markMany occ
1240 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
1241 markInsideLam occ = occ
1243 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
1245 addOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )
1246 NoOccInfo -- Both branches are at least One
1247 -- (Argument is never IAmDead)
1249 -- (orOccInfo orig new) is used
1250 -- when combining occurrence info from branches of a case
1252 orOccInfo (OneOcc in_lam1 _ int_cxt1)
1253 (OneOcc in_lam2 _ int_cxt2)
1254 = OneOcc (in_lam1 || in_lam2)
1255 False -- False, because it occurs in both branches
1256 (int_cxt1 && int_cxt2)
1257 orOccInfo a1 a2 = ASSERT( not (isDeadOcc a1 || isDeadOcc a2) )