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