Try harder to avoid making a variable with RULES into a loop-breaker
[ghc-hetmet.git] / compiler / simplCore / OccurAnal.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 %************************************************************************
5 %*                                                                      *
6 \section[OccurAnal]{Occurrence analysis pass}
7 %*                                                                      *
8 %************************************************************************
9
10 The occurrence analyser re-typechecks a core expression, returning a new
11 core expression with (hopefully) improved usage information.
12
13 \begin{code}
14 module OccurAnal (
15         occurAnalysePgm, occurAnalyseExpr
16     ) where
17
18 #include "HsVersions.h"
19
20 import CoreSyn
21 import CoreFVs          ( idRuleVars )
22 import CoreUtils        ( exprIsTrivial, isDefaultAlt )
23 import Id               ( isDataConWorkId, isOneShotBndr, setOneShotLambda, 
24                           idOccInfo, setIdOccInfo, isLocalId,
25                           isExportedId, idArity, idHasRules,
26                           idUnique, Id
27                         )
28 import BasicTypes       ( OccInfo(..), isOneOcc, InterestingCxt )
29
30 import VarSet
31 import VarEnv
32
33 import Maybes           ( orElse )
34 import Digraph          ( stronglyConnCompR, SCC(..) )
35 import PrelNames        ( buildIdKey, foldrIdKey, runSTRepIdKey, augmentIdKey )
36 import Unique           ( Unique )
37 import UniqFM           ( keysUFM, intersectsUFM )  
38 import Util             ( mapAndUnzip, mapAccumL )
39 import Outputable
40 \end{code}
41
42
43 %************************************************************************
44 %*                                                                      *
45 \subsection[OccurAnal-main]{Counting occurrences: main function}
46 %*                                                                      *
47 %************************************************************************
48
49 Here's the externally-callable interface:
50
51 \begin{code}
52 occurAnalysePgm :: [CoreBind] -> [CoreBind]
53 occurAnalysePgm binds
54   = snd (go initOccEnv binds)
55   where
56     go :: OccEnv -> [CoreBind] -> (UsageDetails, [CoreBind])
57     go env [] 
58         = (emptyDetails, [])
59     go env (bind:binds) 
60         = (final_usage, bind' ++ binds')
61         where
62            (bs_usage, binds')   = go env binds
63            (final_usage, bind') = occAnalBind env bind bs_usage
64
65 occurAnalyseExpr :: CoreExpr -> CoreExpr
66         -- Do occurrence analysis, and discard occurence info returned
67 occurAnalyseExpr expr = snd (occAnal initOccEnv expr)
68 \end{code}
69
70
71 %************************************************************************
72 %*                                                                      *
73 \subsection[OccurAnal-main]{Counting occurrences: main function}
74 %*                                                                      *
75 %************************************************************************
76
77 Bindings
78 ~~~~~~~~
79
80 \begin{code}
81 occAnalBind :: OccEnv
82             -> CoreBind
83             -> UsageDetails             -- Usage details of scope
84             -> (UsageDetails,           -- Of the whole let(rec)
85                 [CoreBind])
86
87 occAnalBind env (NonRec binder rhs) body_usage
88   | not (binder `usedIn` body_usage)            -- It's not mentioned
89   = (body_usage, [])
90
91   | otherwise                   -- It's mentioned in the body
92   = (body_usage' +++ addRuleUsage rhs_usage binder,     -- Note [RulesOnly]
93      [NonRec tagged_binder rhs'])
94   where
95     (body_usage', tagged_binder) = tagBinder body_usage binder
96     (rhs_usage, rhs')            = occAnalRhs env tagged_binder rhs
97 \end{code}
98
99 Dropping dead code for recursive bindings is done in a very simple way:
100
101         the entire set of bindings is dropped if none of its binders are
102         mentioned in its body; otherwise none are.
103
104 This seems to miss an obvious improvement.
105 @
106         letrec  f = ...g...
107                 g = ...f...
108         in
109         ...g...
110
111 ===>
112
113         letrec f = ...g...
114                g = ...(...g...)...
115         in
116         ...g...
117 @
118
119 Now @f@ is unused. But dependency analysis will sort this out into a
120 @letrec@ for @g@ and a @let@ for @f@, and then @f@ will get dropped.
121 It isn't easy to do a perfect job in one blow.  Consider
122
123 @
124         letrec f = ...g...
125                g = ...h...
126                h = ...k...
127                k = ...m...
128                m = ...m...
129         in
130         ...m...
131 @
132
133
134 \begin{code}
135 occAnalBind env (Rec pairs) body_usage
136   = foldr (_scc_ "occAnalBind.dofinal" do_final_bind) (body_usage, []) sccs
137   where
138     analysed_pairs :: [Details]
139     analysed_pairs  = [ (bndr, rhs_usage, rhs')
140                       | (bndr, rhs) <- pairs,
141                         let (rhs_usage, rhs') = occAnalRhs env bndr rhs
142                       ]
143
144     sccs :: [SCC (Node Details)]
145     sccs = _scc_ "occAnalBind.scc" stronglyConnCompR edges
146
147
148     ---- stuff for dependency analysis of binds -------------------------------
149     edges :: [Node Details]
150     edges = _scc_ "occAnalBind.assoc"
151             [ (details, idUnique id, edges_from id rhs_usage)
152             | details@(id, rhs_usage, rhs) <- analysed_pairs
153             ]
154
155         -- (a -> b) means a mentions b
156         -- Given the usage details (a UFM that gives occ info for each free var of
157         -- the RHS) we can get the list of free vars -- or rather their Int keys --
158         -- by just extracting the keys from the finite map.  Grimy, but fast.
159         -- Previously we had this:
160         --      [ bndr | bndr <- bndrs,
161         --               maybeToBool (lookupVarEnv rhs_usage bndr)]
162         -- which has n**2 cost, and this meant that edges_from alone 
163         -- consumed 10% of total runtime!
164     edges_from :: Id -> UsageDetails -> [Unique]
165     edges_from bndr rhs_usage = _scc_ "occAnalBind.edges_from"
166                                 keysUFM (addRuleUsage rhs_usage bndr)
167
168     ---- Stuff to "re-constitute" bindings from dependency-analysis info ------
169
170         -- Non-recursive SCC
171     do_final_bind (AcyclicSCC ((bndr, rhs_usage, rhs'), _, _)) (body_usage, binds_so_far)
172       | not (bndr `usedIn` body_usage)
173       = (body_usage, binds_so_far)                      -- Dead code
174       | otherwise
175       = (body_usage' +++ addRuleUsage rhs_usage bndr, new_bind : binds_so_far)  
176       where
177         (body_usage', tagged_bndr) = tagBinder body_usage bndr
178         new_bind                   = NonRec tagged_bndr rhs'
179
180         -- Recursive SCC
181     do_final_bind (CyclicSCC cycle) (body_usage, binds_so_far)
182       | not (any (`usedIn` body_usage) bndrs)           -- NB: look at body_usage, not total_usage
183       = (body_usage, binds_so_far)                      -- Dead code
184       | otherwise                                       -- If any is used, they all are
185       = (final_usage, final_bind : binds_so_far)
186       where
187         details                        = [details | (details, _, _) <- cycle]
188         bndrs                          = [bndr | (bndr, _, _) <- details]
189         bndr_usages                    = [addRuleUsage rhs_usage bndr | (bndr, rhs_usage, _) <- details]
190         total_usage                    = foldr (+++) body_usage bndr_usages
191         (final_usage, tagged_cycle) = mapAccumL tag_bind total_usage cycle
192         tag_bind usg ((bndr,rhs_usg,rhs),k,ks) = (usg', ((bndr',rhs_usg,rhs),k,ks))
193                                            where
194                                              (usg', bndr') = tagBinder usg bndr
195         final_bind = Rec (reOrderCycle (mkVarSet bndrs) tagged_cycle)
196
197 {-      An alternative; rebuild the edges.  No semantic difference, but perf might change
198
199         -- Hopefully 'bndrs' is a relatively small group now
200         -- Now get ready for the loop-breaking phase
201         -- We've done dead-code elimination already, so no worries about un-referenced binders
202         keys = map idUnique bndrs
203         mk_node tagged_bndr (_, rhs_usage, rhs')
204           = ((tagged_bndr, rhs'), idUnique tagged_bndr, used) 
205           where
206             used = [key | key <- keys, used_outside_rule rhs_usage key ]
207
208         used_outside_rule usage uniq = case lookupUFM_Directly usage uniq of
209                                                 Nothing         -> False
210                                                 Just RulesOnly  -> False        -- Ignore rules
211                                                 other           -> True
212 -}
213 \end{code}
214
215 @reOrderRec@ is applied to the list of (binder,rhs) pairs for a cyclic
216 strongly connected component (there's guaranteed to be a cycle).  It returns the
217 same pairs, but 
218         a) in a better order,
219         b) with some of the Ids having a IAmALoopBreaker pragma
220
221 The "loop-breaker" Ids are sufficient to break all cycles in the SCC.  This means
222 that the simplifier can guarantee not to loop provided it never records an inlining
223 for these no-inline guys.
224
225 Furthermore, the order of the binds is such that if we neglect dependencies
226 on the no-inline Ids then the binds are topologically sorted.  This means
227 that the simplifier will generally do a good job if it works from top bottom,
228 recording inlinings for any Ids which aren't marked as "no-inline" as it goes.
229
230 ==============
231 [June 98: I don't understand the following paragraphs, and I've 
232           changed the a=b case again so that it isn't a special case any more.]
233
234 Here's a case that bit me:
235
236         letrec
237                 a = b
238                 b = \x. BIG
239         in
240         ...a...a...a....
241
242 Re-ordering doesn't change the order of bindings, but there was no loop-breaker.
243
244 My solution was to make a=b bindings record b as Many, rather like INLINE bindings.
245 Perhaps something cleverer would suffice.
246 ===============
247
248
249 \begin{code}
250 type Node details = (details, Unique, [Unique]) -- The Ints are gotten from the Unique,
251                                                 -- which is gotten from the Id.
252 type Details      = (Id, UsageDetails, CoreExpr)
253
254 reOrderRec :: IdSet     -- Binders of this group
255            -> SCC (Node Details)
256            -> [(Id,CoreExpr)]
257 -- Sorted into a plausible order.  Enough of the Ids have
258 --      IAmALoopBreaker pragmas that there are no loops left.
259 reOrderRec bndrs (AcyclicSCC ((bndr, _, rhs), _, _)) = [(bndr, rhs)]
260 reOrderRec bndrs (CyclicSCC cycle)                   = reOrderCycle bndrs cycle
261
262 reOrderCycle :: IdSet -> [Node Details] -> [(Id,CoreExpr)]
263 reOrderCycle bndrs []
264   = panic "reOrderCycle"
265 reOrderCycle bndrs [bind]       -- Common case of simple self-recursion
266   = [(makeLoopBreaker bndrs rhs_usg bndr, rhs)]
267   where
268     ((bndr, rhs_usg, rhs), _, _) = bind
269
270 reOrderCycle bndrs (bind : binds)
271   =     -- Choose a loop breaker, mark it no-inline,
272         -- do SCC analysis on the rest, and recursively sort them out
273     concatMap (reOrderRec bndrs) (stronglyConnCompR unchosen) ++
274     [(makeLoopBreaker bndrs rhs_usg bndr, rhs)]
275
276   where
277     (chosen_bind, unchosen) = choose_loop_breaker bind (score bind) [] binds
278     (bndr, rhs_usg, rhs)  = chosen_bind
279
280         -- This loop looks for the bind with the lowest score
281         -- to pick as the loop  breaker.  The rest accumulate in 
282     choose_loop_breaker (details,_,_) loop_sc acc []
283         = (details, acc)        -- Done
284
285     choose_loop_breaker loop_bind loop_sc acc (bind : binds)
286         | sc < loop_sc  -- Lower score so pick this new one
287         = choose_loop_breaker bind sc (loop_bind : acc) binds
288
289         | otherwise     -- No lower so don't pick it
290         = choose_loop_breaker loop_bind loop_sc (bind : acc) binds
291         where
292           sc = score bind
293           
294     score :: Node Details -> Int        -- Higher score => less likely to be picked as loop breaker
295     score ((bndr, _, rhs), _, _)
296         | exprIsTrivial rhs        = 4  -- Practically certain to be inlined
297                 -- Used to have also: && not (isExportedId bndr)
298                 -- But I found this sometimes cost an extra iteration when we have
299                 --      rec { d = (a,b); a = ...df...; b = ...df...; df = d }
300                 -- where df is the exported dictionary. Then df makes a really
301                 -- bad choice for loop breaker
302           
303         | idHasRules bndr = 3
304                 -- Avoid things with specialisations; we'd like
305                 -- to take advantage of them in the subsequent bindings
306                 -- Also vital to avoid risk of divergence:
307                 -- Note [Recursive rules]
308
309         | is_con_app rhs = 2    -- Data types help with cases
310                 -- This used to have a lower score than inlineCandidate, but
311                 -- it's *really* helpful if dictionaries get inlined fast,
312                 -- so I'm experimenting with giving higher priority to data-typed things
313
314         | inlineCandidate bndr rhs = 1  -- Likely to be inlined
315
316         | otherwise = 0
317
318     inlineCandidate :: Id -> CoreExpr -> Bool
319     inlineCandidate id (Note InlineMe _) = True
320     inlineCandidate id rhs               = isOneOcc (idOccInfo id)
321
322         -- Real example (the Enum Ordering instance from PrelBase):
323         --      rec     f = \ x -> case d of (p,q,r) -> p x
324         --              g = \ x -> case d of (p,q,r) -> q x
325         --              d = (v, f, g)
326         --
327         -- Here, f and g occur just once; but we can't inline them into d.
328         -- On the other hand we *could* simplify those case expressions if
329         -- we didn't stupidly choose d as the loop breaker.
330         -- But we won't because constructor args are marked "Many".
331
332         -- Cheap and cheerful; the simplifer moves casts out of the way
333         -- The lambda case is important to spot x = /\a. C (f a)
334         -- which comes up when C is a dictionary constructor and
335         -- f is a default method.  
336         -- Example: the instance for Show (ST s a) in GHC.ST
337         --
338         -- However we *also* treat (\x. C p q) as a con-app-like thing, 
339         --      Note [Closure conversion]
340     is_con_app (Var v)    = isDataConWorkId v
341     is_con_app (App f _)  = is_con_app f
342     is_con_app (Lam b e)  = is_con_app e
343     is_con_app (Note _ e) = is_con_app e
344     is_con_app other      = False
345
346 makeLoopBreaker :: VarSet               -- Binders of this group
347                 -> UsageDetails         -- Usage of this rhs (neglecting rules)
348                 -> Id -> Id
349 -- Set the loop-breaker flag, recording whether the thing occurs only in 
350 -- the RHS of a RULE (in this recursive group)
351 makeLoopBreaker bndrs rhs_usg bndr
352   = setIdOccInfo bndr (IAmALoopBreaker rules_only)
353   where
354     rules_only = bndrs `intersectsUFM` rhs_usg
355 \end{code}
356
357 Note [Recursive rules]
358 ~~~~~~~~~~~~~~~~~~~~~~
359 Consider this group, which is typical of what SpecConstr builds:
360
361    fs a = ....f (C a)....
362    f  x = ....f (C a)....
363    {-# RULE f (C a) = fs a #-}
364
365 So 'f' and 'fs' are mutually recursive.  If we choose 'fs' as the loop breaker,
366 all is well; the RULE is applied, and 'fs' becomes self-recursive.
367
368 But if we choose 'f' as the loop breaker, we may get an infinite loop:
369         - the RULE is applied in f's RHS (see Note [Self-recursive rules] in Simplify
370         - fs is inlined (say it's small)
371         - now there's another opportunity to apply the RULE
372
373 So it's very important to choose the RULE-variable as the loop breaker.
374 This showed up when compiling Control.Concurrent.Chan.getChanContents.
375
376 Note [Closure conversion]
377 ~~~~~~~~~~~~~~~~~~~~~~~~~
378 We treat (\x. C p q) as a high-score candidate in the letrec scoring algorithm.
379 The immediate motivation came from the result of a closure-conversion transformation
380 which generated code like this:
381
382     data Clo a b = forall c. Clo (c -> a -> b) c
383
384     ($:) :: Clo a b -> a -> b
385     Clo f env $: x = f env x
386
387     rec { plus = Clo plus1 ()
388
389         ; plus1 _ n = Clo plus2 n
390
391         ; plus2 Zero     n = n
392         ; plus2 (Succ m) n = Succ (plus $: m $: n) }
393
394 If we inline 'plus' and 'plus1', everything unravels nicely.  But if
395 we choose 'plus1' as the loop breaker (which is entirely possible
396 otherwise), the loop does not unravel nicely.
397
398
399 @occAnalRhs@ deals with the question of bindings where the Id is marked
400 by an INLINE pragma.  For these we record that anything which occurs
401 in its RHS occurs many times.  This pessimistically assumes that ths
402 inlined binder also occurs many times in its scope, but if it doesn't
403 we'll catch it next time round.  At worst this costs an extra simplifier pass.
404 ToDo: try using the occurrence info for the inline'd binder.
405
406 [March 97] We do the same for atomic RHSs.  Reason: see notes with reOrderRec.
407 [June 98, SLPJ]  I've undone this change; I don't understand it.  See notes with reOrderRec.
408
409
410 \begin{code}
411 occAnalRhs :: OccEnv
412            -> Id -> CoreExpr    -- Binder and rhs
413                                 -- For non-recs the binder is alrady tagged
414                                 -- with occurrence info
415            -> (UsageDetails, CoreExpr)
416
417 occAnalRhs env id rhs
418   = occAnal ctxt rhs
419   where
420     ctxt | certainly_inline id = env
421          | otherwise           = rhsCtxt
422         -- Note that we generally use an rhsCtxt.  This tells the occ anal n
423         -- that it's looking at an RHS, which has an effect in occAnalApp
424         --
425         -- But there's a problem.  Consider
426         --      x1 = a0 : []
427         --      x2 = a1 : x1
428         --      x3 = a2 : x2
429         --      g  = f x3
430         -- First time round, it looks as if x1 and x2 occur as an arg of a 
431         -- let-bound constructor ==> give them a many-occurrence.
432         -- But then x3 is inlined (unconditionally as it happens) and
433         -- next time round, x2 will be, and the next time round x1 will be
434         -- Result: multiple simplifier iterations.  Sigh.  
435         -- Crude solution: use rhsCtxt for things that occur just once...
436
437     certainly_inline id = case idOccInfo id of
438                             OneOcc in_lam one_br _ -> not in_lam && one_br
439                             other                  -> False
440 \end{code}
441
442 Note [RulesOnly]
443 ~~~~~~~~~~~~~~~~~~
444 If the binder has RULES inside it then we count the specialised Ids as
445 "extra rhs's".  That way the "parent" keeps the specialised "children"
446 alive.  If the parent dies (because it isn't referenced any more),
447 then the children will die too unless they are already referenced
448 directly.
449
450 That's the basic idea.  However in a recursive situation we want to be a bit
451 cleverer. Example (from GHC.Enum):
452
453   eftInt :: Int# -> Int# -> [Int]
454   eftInt x y = ...(non-recursive)...
455
456   {-# INLINE [0] eftIntFB #-}
457   eftIntFB :: (Int -> r -> r) -> r -> Int# -> Int# -> r
458   eftIntFB c n x y = ...(non-recursive)...
459
460   {-# RULES
461   "eftInt"  [~1] forall x y. eftInt x y = build (\ c n -> eftIntFB c n x y)
462   "eftIntList"  [1] eftIntFB  (:) [] = eftInt
463    #-}
464
465 The two look mutually recursive only because of their RULES; we don't want 
466 that to inhibit inlining!
467
468 So when we identify a LoopBreaker, we mark it to say whether it only mentions 
469 the other binders in its recursive group in a RULE.  If so, we can inline it,
470 because doing so will not expose new occurrences of binders in its group.
471
472
473 \begin{code}
474
475 addRuleUsage :: UsageDetails -> Id -> UsageDetails
476 -- Add the usage from RULES in Id to the usage
477 addRuleUsage usage id
478   = foldVarSet add usage (idRuleVars id)
479   where
480     add v u = addOneOcc u v NoOccInfo           -- Give a non-committal binder info
481                                                 -- (i.e manyOcc) because many copies
482                                                 -- of the specialised thing can appear
483 \end{code}
484
485 Expressions
486 ~~~~~~~~~~~
487 \begin{code}
488 occAnal :: OccEnv
489         -> CoreExpr
490         -> (UsageDetails,       -- Gives info only about the "interesting" Ids
491             CoreExpr)
492
493 occAnal env (Type t)  = (emptyDetails, Type t)
494 occAnal env (Var v)   = (mkOneOcc env v False, Var v)
495     -- At one stage, I gathered the idRuleVars for v here too,
496     -- which in a way is the right thing to do.
497     -- Btu that went wrong right after specialisation, when
498     -- the *occurrences* of the overloaded function didn't have any
499     -- rules in them, so the *specialised* versions looked as if they
500     -- weren't used at all.
501 \end{code}
502
503 We regard variables that occur as constructor arguments as "dangerousToDup":
504
505 \begin{verbatim}
506 module A where
507 f x = let y = expensive x in 
508       let z = (True,y) in 
509       (case z of {(p,q)->q}, case z of {(p,q)->q})
510 \end{verbatim}
511
512 We feel free to duplicate the WHNF (True,y), but that means
513 that y may be duplicated thereby.
514
515 If we aren't careful we duplicate the (expensive x) call!
516 Constructors are rather like lambdas in this way.
517
518 \begin{code}
519 occAnal env expr@(Lit lit) = (emptyDetails, expr)
520 \end{code}
521
522 \begin{code}
523 occAnal env (Note InlineMe body)
524   = case occAnal env body of { (usage, body') -> 
525     (mapVarEnv markMany usage, Note InlineMe body')
526     }
527
528 occAnal env (Note note@(SCC cc) body)
529   = case occAnal env body of { (usage, body') ->
530     (mapVarEnv markInsideSCC usage, Note note body')
531     }
532
533 occAnal env (Note note body)
534   = case occAnal env body of { (usage, body') ->
535     (usage, Note note body')
536     }
537
538 occAnal env (Cast expr co)
539   = case occAnal env expr of { (usage, expr') ->
540     (markRhsUds env True usage, Cast expr' co)
541         -- If we see let x = y `cast` co
542         -- then mark y as 'Many' so that we don't
543         -- immediately inline y again. 
544     }
545 \end{code}
546
547 \begin{code}
548 occAnal env app@(App fun arg)
549   = occAnalApp env (collectArgs app) False
550
551 -- Ignore type variables altogether
552 --   (a) occurrences inside type lambdas only not marked as InsideLam
553 --   (b) type variables not in environment
554
555 occAnal env expr@(Lam x body) | isTyVar x
556   = case occAnal env body of { (body_usage, body') ->
557     (body_usage, Lam x body')
558     }
559
560 -- For value lambdas we do a special hack.  Consider
561 --      (\x. \y. ...x...)
562 -- If we did nothing, x is used inside the \y, so would be marked
563 -- as dangerous to dup.  But in the common case where the abstraction
564 -- is applied to two arguments this is over-pessimistic.
565 -- So instead, we just mark each binder with its occurrence
566 -- info in the *body* of the multiple lambda.
567 -- Then, the simplifier is careful when partially applying lambdas.
568
569 occAnal env expr@(Lam _ _)
570   = case occAnal env_body body of { (body_usage, body') ->
571     let
572         (final_usage, tagged_binders) = tagBinders body_usage binders
573         --      URGH!  Sept 99: we don't seem to be able to use binders' here, because
574         --      we get linear-typed things in the resulting program that we can't handle yet.
575         --      (e.g. PrelShow)  TODO 
576
577         really_final_usage = if linear then
578                                 final_usage
579                              else
580                                 mapVarEnv markInsideLam final_usage
581     in
582     (really_final_usage,
583      mkLams tagged_binders body') }
584   where
585     env_body        = vanillaCtxt                       -- Body is (no longer) an RhsContext
586     (binders, body) = collectBinders expr
587     binders'        = oneShotGroup env binders
588     linear          = all is_one_shot binders'
589     is_one_shot b   = isId b && isOneShotBndr b
590
591 occAnal env (Case scrut bndr ty alts)
592   = case occ_anal_scrut scrut alts                  of { (scrut_usage, scrut') ->
593     case mapAndUnzip (occAnalAlt alt_env bndr) alts of { (alts_usage_s, alts')   -> 
594     let
595         alts_usage  = foldr1 combineAltsUsageDetails alts_usage_s
596         alts_usage' = addCaseBndrUsage alts_usage
597         (alts_usage1, tagged_bndr) = tagBinder alts_usage' bndr
598         total_usage = scrut_usage +++ alts_usage1
599     in
600     total_usage `seq` (total_usage, Case scrut' tagged_bndr ty alts') }}
601   where
602         -- The case binder gets a usage of either "many" or "dead", never "one".
603         -- Reason: we like to inline single occurrences, to eliminate a binding,
604         -- but inlining a case binder *doesn't* eliminate a binding.
605         -- We *don't* want to transform
606         --      case x of w { (p,q) -> f w }
607         -- into
608         --      case x of w { (p,q) -> f (p,q) }
609     addCaseBndrUsage usage = case lookupVarEnv usage bndr of
610                                 Nothing  -> usage
611                                 Just occ -> extendVarEnv usage bndr (markMany occ)
612
613     alt_env = setVanillaCtxt env
614         -- Consider     x = case v of { True -> (p,q); ... }
615         -- Then it's fine to inline p and q
616
617     occ_anal_scrut (Var v) (alt1 : other_alts)
618                                 | not (null other_alts) || not (isDefaultAlt alt1)
619                                 = (mkOneOcc env v True, Var v)
620     occ_anal_scrut scrut alts   = occAnal vanillaCtxt scrut
621                                         -- No need for rhsCtxt
622
623 occAnal env (Let bind body)
624   = case occAnal env body                of { (body_usage, body') ->
625     case occAnalBind env bind body_usage of { (final_usage, new_binds) ->
626        (final_usage, mkLets new_binds body') }}
627
628 occAnalArgs env args
629   = case mapAndUnzip (occAnal arg_env) args of  { (arg_uds_s, args') ->
630     (foldr (+++) emptyDetails arg_uds_s, args')}
631   where
632     arg_env = vanillaCtxt
633 \end{code}
634
635 Applications are dealt with specially because we want
636 the "build hack" to work.
637
638 \begin{code}
639 occAnalApp env (Var fun, args) is_rhs
640   = case args_stuff of { (args_uds, args') ->
641     let
642         final_args_uds = markRhsUds env is_pap args_uds
643     in
644     (fun_uds +++ final_args_uds, mkApps (Var fun) args') }
645   where
646     fun_uniq = idUnique fun
647     fun_uds  = mkOneOcc env fun (valArgCount args > 0)
648     is_pap = isDataConWorkId fun || valArgCount args < idArity fun
649
650                 -- Hack for build, fold, runST
651     args_stuff  | fun_uniq == buildIdKey    = appSpecial env 2 [True,True]  args
652                 | fun_uniq == augmentIdKey  = appSpecial env 2 [True,True]  args
653                 | fun_uniq == foldrIdKey    = appSpecial env 3 [False,True] args
654                 | fun_uniq == runSTRepIdKey = appSpecial env 2 [True]       args
655                         -- (foldr k z xs) may call k many times, but it never
656                         -- shares a partial application of k; hence [False,True]
657                         -- This means we can optimise
658                         --      foldr (\x -> let v = ...x... in \y -> ...v...) z xs
659                         -- by floating in the v
660
661                 | otherwise = occAnalArgs env args
662
663
664 occAnalApp env (fun, args) is_rhs
665   = case occAnal (addAppCtxt env args) fun of   { (fun_uds, fun') ->
666         -- The addAppCtxt is a bit cunning.  One iteration of the simplifier
667         -- often leaves behind beta redexs like
668         --      (\x y -> e) a1 a2
669         -- Here we would like to mark x,y as one-shot, and treat the whole
670         -- thing much like a let.  We do this by pushing some True items
671         -- onto the context stack.
672
673     case occAnalArgs env args of        { (args_uds, args') ->
674     let
675         final_uds = fun_uds +++ args_uds
676     in
677     (final_uds, mkApps fun' args') }}
678     
679
680 markRhsUds :: OccEnv            -- Check if this is a RhsEnv
681            -> Bool              -- and this is true
682            -> UsageDetails      -- The do markMany on this
683            -> UsageDetails
684 -- We mark the free vars of the argument of a constructor or PAP 
685 -- as "many", if it is the RHS of a let(rec).
686 -- This means that nothing gets inlined into a constructor argument
687 -- position, which is what we want.  Typically those constructor
688 -- arguments are just variables, or trivial expressions.
689 --
690 -- This is the *whole point* of the isRhsEnv predicate
691 markRhsUds env is_pap arg_uds
692   | isRhsEnv env && is_pap = mapVarEnv markMany arg_uds
693   | otherwise              = arg_uds
694
695
696 appSpecial :: OccEnv 
697            -> Int -> CtxtTy     -- Argument number, and context to use for it
698            -> [CoreExpr]
699            -> (UsageDetails, [CoreExpr])
700 appSpecial env n ctxt args
701   = go n args
702   where
703     arg_env = vanillaCtxt
704
705     go n [] = (emptyDetails, [])        -- Too few args
706
707     go 1 (arg:args)                     -- The magic arg
708       = case occAnal (setCtxt arg_env ctxt) arg of      { (arg_uds, arg') ->
709         case occAnalArgs env args of                    { (args_uds, args') ->
710         (arg_uds +++ args_uds, arg':args') }}
711     
712     go n (arg:args)
713       = case occAnal arg_env arg of     { (arg_uds, arg') ->
714         case go (n-1) args of           { (args_uds, args') ->
715         (arg_uds +++ args_uds, arg':args') }}
716 \end{code}
717
718     
719 Case alternatives
720 ~~~~~~~~~~~~~~~~~
721 If the case binder occurs at all, the other binders effectively do too.  
722 For example
723         case e of x { (a,b) -> rhs }
724 is rather like
725         let x = (a,b) in rhs
726 If e turns out to be (e1,e2) we indeed get something like
727         let a = e1; b = e2; x = (a,b) in rhs
728
729 Note [Aug 06]: I don't think this is necessary any more, and it helpe
730                to know when binders are unused.  See esp the call to
731                isDeadBinder in Simplify.mkDupableAlt
732
733 \begin{code}
734 occAnalAlt env case_bndr (con, bndrs, rhs)
735   = case occAnal env rhs of { (rhs_usage, rhs') ->
736     let
737         (final_usage, tagged_bndrs) = tagBinders rhs_usage bndrs
738         final_bndrs = tagged_bndrs      -- See Note [Aug06] above
739 {-
740         final_bndrs | case_bndr `elemVarEnv` final_usage = bndrs
741                     | otherwise                         = tagged_bndrs
742                 -- Leave the binders untagged if the case 
743                 -- binder occurs at all; see note above
744 -}
745     in
746     (final_usage, (con, final_bndrs, rhs')) }
747 \end{code}
748
749
750 %************************************************************************
751 %*                                                                      *
752 \subsection[OccurAnal-types]{OccEnv}
753 %*                                                                      *
754 %************************************************************************
755
756 \begin{code}
757 data OccEnv
758   = OccEnv OccEncl      -- Enclosing context information
759            CtxtTy       -- Tells about linearity
760
761 -- OccEncl is used to control whether to inline into constructor arguments
762 -- For example:
763 --      x = (p,q)               -- Don't inline p or q
764 --      y = /\a -> (p a, q a)   -- Still don't inline p or q
765 --      z = f (p,q)             -- Do inline p,q; it may make a rule fire
766 -- So OccEncl tells enought about the context to know what to do when
767 -- we encounter a contructor application or PAP.
768
769 data OccEncl
770   = OccRhs              -- RHS of let(rec), albeit perhaps inside a type lambda
771                         -- Don't inline into constructor args here
772   | OccVanilla          -- Argument of function, body of lambda, scruintee of case etc.
773                         -- Do inline into constructor args here
774
775 type CtxtTy = [Bool]
776         -- []           No info
777         --
778         -- True:ctxt    Analysing a function-valued expression that will be
779         --                      applied just once
780         --
781         -- False:ctxt   Analysing a function-valued expression that may
782         --                      be applied many times; but when it is, 
783         --                      the CtxtTy inside applies
784
785 initOccEnv :: OccEnv
786 initOccEnv = OccEnv OccRhs []
787
788 vanillaCtxt = OccEnv OccVanilla []
789 rhsCtxt     = OccEnv OccRhs     []
790
791 isRhsEnv (OccEnv OccRhs     _) = True
792 isRhsEnv (OccEnv OccVanilla _) = False
793
794 setVanillaCtxt :: OccEnv -> OccEnv
795 setVanillaCtxt (OccEnv OccRhs ctxt_ty) = OccEnv OccVanilla ctxt_ty
796 setVanillaCtxt other_env               = other_env
797
798 setCtxt :: OccEnv -> CtxtTy -> OccEnv
799 setCtxt (OccEnv encl _) ctxt = OccEnv encl ctxt
800
801 oneShotGroup :: OccEnv -> [CoreBndr] -> [CoreBndr]
802         -- The result binders have one-shot-ness set that they might not have had originally.
803         -- This happens in (build (\cn -> e)).  Here the occurrence analyser
804         -- linearity context knows that c,n are one-shot, and it records that fact in
805         -- the binder. This is useful to guide subsequent float-in/float-out tranformations
806
807 oneShotGroup (OccEnv encl ctxt) bndrs 
808   = go ctxt bndrs []
809   where
810     go ctxt [] rev_bndrs = reverse rev_bndrs
811
812     go (lin_ctxt:ctxt) (bndr:bndrs) rev_bndrs
813         | isId bndr = go ctxt bndrs (bndr':rev_bndrs)
814         where
815           bndr' | lin_ctxt  = setOneShotLambda bndr
816                 | otherwise = bndr
817
818     go ctxt (bndr:bndrs) rev_bndrs = go ctxt bndrs (bndr:rev_bndrs)
819
820 addAppCtxt (OccEnv encl ctxt) args 
821   = OccEnv encl (replicate (valArgCount args) True ++ ctxt)
822 \end{code}
823
824 %************************************************************************
825 %*                                                                      *
826 \subsection[OccurAnal-types]{OccEnv}
827 %*                                                                      *
828 %************************************************************************
829
830 \begin{code}
831 type UsageDetails = IdEnv OccInfo       -- A finite map from ids to their usage
832
833 (+++), combineAltsUsageDetails
834         :: UsageDetails -> UsageDetails -> UsageDetails
835
836 (+++) usage1 usage2
837   = plusVarEnv_C addOccInfo usage1 usage2
838
839 combineAltsUsageDetails usage1 usage2
840   = plusVarEnv_C orOccInfo usage1 usage2
841
842 addOneOcc :: UsageDetails -> Id -> OccInfo -> UsageDetails
843 addOneOcc usage id info
844   = plusVarEnv_C addOccInfo usage (unitVarEnv id info)
845         -- ToDo: make this more efficient
846
847 emptyDetails = (emptyVarEnv :: UsageDetails)
848
849 usedIn :: Id -> UsageDetails -> Bool
850 v `usedIn` details =  isExportedId v || v `elemVarEnv` details
851
852 type IdWithOccInfo = Id
853
854 tagBinders :: UsageDetails          -- Of scope
855            -> [Id]                  -- Binders
856            -> (UsageDetails,        -- Details with binders removed
857               [IdWithOccInfo])    -- Tagged binders
858
859 tagBinders usage binders
860  = let
861      usage' = usage `delVarEnvList` binders
862      uss    = map (setBinderOcc usage) binders
863    in
864    usage' `seq` (usage', uss)
865
866 tagBinder :: UsageDetails           -- Of scope
867           -> Id                     -- Binders
868           -> (UsageDetails,         -- Details with binders removed
869               IdWithOccInfo)        -- Tagged binders
870
871 tagBinder usage binder
872  = let
873      usage'  = usage `delVarEnv` binder
874      binder' = setBinderOcc usage binder
875    in
876    usage' `seq` (usage', binder')
877
878 setBinderOcc :: UsageDetails -> CoreBndr -> CoreBndr
879 setBinderOcc usage bndr
880   | isTyVar bndr      = bndr
881   | isExportedId bndr = case idOccInfo bndr of
882                           NoOccInfo -> bndr
883                           other     -> setIdOccInfo bndr NoOccInfo
884             -- Don't use local usage info for visible-elsewhere things
885             -- BUT *do* erase any IAmALoopBreaker annotation, because we're
886             -- about to re-generate it and it shouldn't be "sticky"
887                           
888   | otherwise = setIdOccInfo bndr occ_info
889   where
890     occ_info = lookupVarEnv usage bndr `orElse` IAmDead
891 \end{code}
892
893
894 %************************************************************************
895 %*                                                                      *
896 \subsection{Operations over OccInfo}
897 %*                                                                      *
898 %************************************************************************
899
900 \begin{code}
901 mkOneOcc :: OccEnv -> Id -> InterestingCxt -> UsageDetails
902 mkOneOcc env id int_cxt
903   | isLocalId id = unitVarEnv id (OneOcc False True int_cxt)
904   | otherwise    = emptyDetails
905
906 markMany, markInsideLam, markInsideSCC :: OccInfo -> OccInfo
907
908 markMany IAmDead = IAmDead
909 markMany other   = NoOccInfo
910
911 markInsideSCC occ = markMany occ
912
913 markInsideLam (OneOcc _ one_br int_cxt) = OneOcc True one_br int_cxt
914 markInsideLam occ                       = occ
915
916 addOccInfo, orOccInfo :: OccInfo -> OccInfo -> OccInfo
917
918 addOccInfo IAmDead info2       = info2
919 addOccInfo info1 IAmDead       = info1
920 addOccInfo info1 info2         = NoOccInfo
921
922 -- (orOccInfo orig new) is used
923 -- when combining occurrence info from branches of a case
924
925 orOccInfo IAmDead info2 = info2
926 orOccInfo info1 IAmDead = info1
927 orOccInfo (OneOcc in_lam1 one_branch1 int_cxt1)
928           (OneOcc in_lam2 one_branch2 int_cxt2)
929   = OneOcc (in_lam1 || in_lam2)
930            False        -- False, because it occurs in both branches
931            (int_cxt1 && int_cxt2)
932 orOccInfo info1 info2 = NoOccInfo
933 \end{code}