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