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