Record constructor arg occs correctly (bug-fix)
[ghc-hetmet.git] / compiler / specialise / SpecConstr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[SpecConstr]{Specialise over constructors}
5
6 \begin{code}
7 module SpecConstr(
8         specConstrProgram       
9     ) where
10
11 #include "HsVersions.h"
12
13 import CoreSyn
14 import CoreLint         ( showPass, endPass )
15 import CoreUtils        ( exprType, mkPiTypes )
16 import CoreFVs          ( exprsFreeVars )
17 import CoreSubst        ( Subst, mkSubst, substExpr )
18 import CoreTidy         ( tidyRules )
19 import PprCore          ( pprRules )
20 import WwLib            ( mkWorkerArgs )
21 import DataCon          ( dataConRepArity, isVanillaDataCon, dataConTyVars )
22 import Type             ( tyConAppArgs, tyVarsOfTypes )
23 import Rules            ( matchN )
24 import Unify            ( coreRefineTys )
25 import Id               ( Id, idName, idType, isDataConWorkId_maybe, 
26                           mkUserLocal, mkSysLocal, idUnfolding, isLocalId )
27 import Var              ( Var )
28 import VarEnv
29 import VarSet
30 import Name             ( nameOccName, nameSrcLoc )
31 import Rules            ( addIdSpecialisations, mkLocalRule, rulesOfBinds )
32 import OccName          ( mkSpecOcc )
33 import ErrUtils         ( dumpIfSet_dyn )
34 import DynFlags         ( DynFlags, DynFlag(..) )
35 import BasicTypes       ( Activation(..) )
36 import Maybes           ( orElse, catMaybes, isJust )
37 import Util             ( zipWithEqual, lengthAtLeast, notNull )
38 import List             ( nubBy, partition )
39 import UniqSupply
40 import Outputable
41 import FastString
42 import UniqFM
43 \end{code}
44
45 -----------------------------------------------------
46                         Game plan
47 -----------------------------------------------------
48
49 Consider
50         drop n []     = []
51         drop 0 xs     = []
52         drop n (x:xs) = drop (n-1) xs
53
54 After the first time round, we could pass n unboxed.  This happens in
55 numerical code too.  Here's what it looks like in Core:
56
57         drop n xs = case xs of
58                       []     -> []
59                       (y:ys) -> case n of 
60                                   I# n# -> case n# of
61                                              0 -> []
62                                              _ -> drop (I# (n# -# 1#)) xs
63
64 Notice that the recursive call has an explicit constructor as argument.
65 Noticing this, we can make a specialised version of drop
66         
67         RULE: drop (I# n#) xs ==> drop' n# xs
68
69         drop' n# xs = let n = I# n# in ...orig RHS...
70
71 Now the simplifier will apply the specialisation in the rhs of drop', giving
72
73         drop' n# xs = case xs of
74                       []     -> []
75                       (y:ys) -> case n# of
76                                   0 -> []
77                                   _ -> drop (n# -# 1#) xs
78
79 Much better!  
80
81 We'd also like to catch cases where a parameter is carried along unchanged,
82 but evaluated each time round the loop:
83
84         f i n = if i>0 || i>n then i else f (i*2) n
85
86 Here f isn't strict in n, but we'd like to avoid evaluating it each iteration.
87 In Core, by the time we've w/wd (f is strict in i) we get
88
89         f i# n = case i# ># 0 of
90                    False -> I# i#
91                    True  -> case n of n' { I# n# ->
92                             case i# ># n# of
93                                 False -> I# i#
94                                 True  -> f (i# *# 2#) n'
95
96 At the call to f, we see that the argument, n is know to be (I# n#),
97 and n is evaluated elsewhere in the body of f, so we can play the same
98 trick as above.  
99
100
101 Note [Reboxing]
102 ~~~~~~~~~~~~~~~
103 We must be careful not to allocate the same constructor twice.  Consider
104         f p = (...(case p of (a,b) -> e)...p...,
105                ...let t = (r,s) in ...t...(f t)...)
106 At the recursive call to f, we can see that t is a pair.  But we do NOT want
107 to make a specialised copy:
108         f' a b = let p = (a,b) in (..., ...)
109 because now t is allocated by the caller, then r and s are passed to the
110 recursive call, which allocates the (r,s) pair again.
111
112 This happens if
113   (a) the argument p is used in other than a case-scrutinsation way.
114   (b) the argument to the call is not a 'fresh' tuple; you have to
115         look into its unfolding to see that it's a tuple
116
117 Hence the "OR" part of Note [Good arguments] below.
118
119 ALTERNATIVE: pass both boxed and unboxed versions.  This no longer saves
120 allocation, but does perhaps save evals. In the RULE we'd have
121 something like
122
123   f (I# x#) = f' (I# x#) x#
124
125 If at the call site the (I# x) was an unfolding, then we'd have to
126 rely on CSE to eliminate the duplicate allocation.... This alternative
127 doesn't look attractive enough to pursue.
128
129
130 Note [Good arguments]
131 ~~~~~~~~~~~~~~~~~~~~~
132 So we look for
133
134 * A self-recursive function.  Ignore mutual recursion for now, 
135   because it's less common, and the code is simpler for self-recursion.
136
137 * EITHER
138
139    a) At a recursive call, one or more parameters is an explicit 
140       constructor application
141         AND
142       That same parameter is scrutinised by a case somewhere in 
143       the RHS of the function
144
145   OR
146
147     b) At a recursive call, one or more parameters has an unfolding
148        that is an explicit constructor application
149         AND
150       That same parameter is scrutinised by a case somewhere in 
151       the RHS of the function
152         AND
153       Those are the only uses of the parameter (see Note [Reboxing])
154
155
156 What to abstract over
157 ~~~~~~~~~~~~~~~~~~~~~
158 There's a bit of a complication with type arguments.  If the call
159 site looks like
160
161         f p = ...f ((:) [a] x xs)...
162
163 then our specialised function look like
164
165         f_spec x xs = let p = (:) [a] x xs in ....as before....
166
167 This only makes sense if either
168   a) the type variable 'a' is in scope at the top of f, or
169   b) the type variable 'a' is an argument to f (and hence fs)
170
171 Actually, (a) may hold for value arguments too, in which case
172 we may not want to pass them.  Supose 'x' is in scope at f's
173 defn, but xs is not.  Then we'd like
174
175         f_spec xs = let p = (:) [a] x xs in ....as before....
176
177 Similarly (b) may hold too.  If x is already an argument at the
178 call, no need to pass it again.
179
180 Finally, if 'a' is not in scope at the call site, we could abstract
181 it as we do the term variables:
182
183         f_spec a x xs = let p = (:) [a] x xs in ...as before...
184
185 So the grand plan is:
186
187         * abstract the call site to a constructor-only pattern
188           e.g.  C x (D (f p) (g q))  ==>  C s1 (D s2 s3)
189
190         * Find the free variables of the abstracted pattern
191
192         * Pass these variables, less any that are in scope at
193           the fn defn.  But see Note [Shadowing] below.
194
195
196 NOTICE that we only abstract over variables that are not in scope,
197 so we're in no danger of shadowing variables used in "higher up"
198 in f_spec's RHS.
199
200
201 Note [Shadowing]
202 ~~~~~~~~~~~~~~~~
203 In this pass we gather up usage information that may mention variables
204 that are bound between the usage site and the definition site; or (more
205 seriously) may be bound to something different at the definition site.
206 For example:
207
208         f x = letrec g y v = let x = ... 
209                              in ...(g (a,b) x)...
210
211 Since 'x' is in scope at the call site, we may make a rewrite rule that 
212 looks like
213         RULE forall a,b. g (a,b) x = ...
214 But this rule will never match, because it's really a different 'x' at 
215 the call site -- and that difference will be manifest by the time the
216 simplifier gets to it.  [A worry: the simplifier doesn't *guarantee*
217 no-shadowing, so perhaps it may not be distinct?]
218
219 Anyway, the rule isn't actually wrong, it's just not useful.  One possibility
220 is to run deShadowBinds before running SpecConstr, but instead we run the
221 simplifier.  That gives the simplest possible program for SpecConstr to
222 chew on; and it virtually guarantees no shadowing.
223
224 Note [Specialising for constant parameters]
225 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
226 This one is about specialising on a *constant* (but not necessarily
227 constructor) argument
228
229     foo :: Int -> (Int -> Int) -> Int
230     foo 0 f = 0
231     foo m f = foo (f m) (+1)
232
233 It produces
234
235     lvl_rmV :: GHC.Base.Int -> GHC.Base.Int
236     lvl_rmV =
237       \ (ds_dlk :: GHC.Base.Int) ->
238         case ds_dlk of wild_alH { GHC.Base.I# x_alG ->
239         GHC.Base.I# (GHC.Prim.+# x_alG 1)
240
241     T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) ->
242     GHC.Prim.Int#
243     T.$wfoo =
244       \ (ww_sme :: GHC.Prim.Int#) (w_smg :: GHC.Base.Int -> GHC.Base.Int) ->
245         case ww_sme of ds_Xlw {
246           __DEFAULT ->
247         case w_smg (GHC.Base.I# ds_Xlw) of w1_Xmo { GHC.Base.I# ww1_Xmz ->
248         T.$wfoo ww1_Xmz lvl_rmV
249         };
250           0 -> 0
251         }
252
253 The recursive call has lvl_rmV as its argument, so we could create a specialised copy
254 with that argument baked in; that is, not passed at all.   Now it can perhaps be inlined.
255
256 When is this worth it?  Call the constant 'lvl'
257 - If 'lvl' has an unfolding that is a constructor, see if the corresponding
258   parameter is scrutinised anywhere in the body.
259
260 - If 'lvl' has an unfolding that is a inlinable function, see if the corresponding
261   parameter is applied (...to enough arguments...?)
262
263   Also do this is if the function has RULES?
264
265 Also    
266
267 Note [Specialising for lambda parameters]
268 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
269     foo :: Int -> (Int -> Int) -> Int
270     foo 0 f = 0
271     foo m f = foo (f m) (\n -> n-m)
272
273 This is subtly different from the previous one in that we get an
274 explicit lambda as the argument:
275
276     T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) ->
277     GHC.Prim.Int#
278     T.$wfoo =
279       \ (ww_sm8 :: GHC.Prim.Int#) (w_sma :: GHC.Base.Int -> GHC.Base.Int) ->
280         case ww_sm8 of ds_Xlr {
281           __DEFAULT ->
282         case w_sma (GHC.Base.I# ds_Xlr) of w1_Xmf { GHC.Base.I# ww1_Xmq ->
283         T.$wfoo
284           ww1_Xmq
285           (\ (n_ad3 :: GHC.Base.Int) ->
286              case n_ad3 of wild_alB { GHC.Base.I# x_alA ->
287              GHC.Base.I# (GHC.Prim.-# x_alA ds_Xlr)
288              })
289         };
290           0 -> 0
291         }
292
293 I wonder if SpecConstr couldn't be extended to handle this? After all,
294 lambda is a sort of constructor for functions and perhaps it already
295 has most of the necessary machinery?
296
297 Furthermore, there's an immediate win, because you don't need to allocate the lamda
298 at the call site; and if perchance it's called in the recursive call, then you
299 may avoid allocating it altogether.  Just like for constructors.
300
301 Looks cool, but probably rare...but it might be easy to implement.
302
303 -----------------------------------------------------
304                 Stuff not yet handled
305 -----------------------------------------------------
306
307 Here are notes arising from Roman's work that I don't want to lose.
308
309 Example 1
310 ~~~~~~~~~
311     data T a = T !a
312
313     foo :: Int -> T Int -> Int
314     foo 0 t = 0
315     foo x t | even x    = case t of { T n -> foo (x-n) t }
316             | otherwise = foo (x-1) t
317
318 SpecConstr does no specialisation, because the second recursive call
319 looks like a boxed use of the argument.  A pity.
320
321     $wfoo_sFw :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
322     $wfoo_sFw =
323       \ (ww_sFo [Just L] :: GHC.Prim.Int#) (w_sFq [Just L] :: T.T GHC.Base.Int) ->
324          case ww_sFo of ds_Xw6 [Just L] {
325            __DEFAULT ->
326                 case GHC.Prim.remInt# ds_Xw6 2 of wild1_aEF [Dead Just A] {
327                   __DEFAULT -> $wfoo_sFw (GHC.Prim.-# ds_Xw6 1) w_sFq;
328                   0 ->
329                     case w_sFq of wild_Xy [Just L] { T.T n_ad5 [Just U(L)] ->
330                     case n_ad5 of wild1_aET [Just A] { GHC.Base.I# y_aES [Just L] ->
331                     $wfoo_sFw (GHC.Prim.-# ds_Xw6 y_aES) wild_Xy
332                     } } };
333            0 -> 0
334
335 Example 2
336 ~~~~~~~~~
337     data a :*: b = !a :*: !b
338     data T a = T !a
339
340     foo :: (Int :*: T Int) -> Int
341     foo (0 :*: t) = 0
342     foo (x :*: t) | even x    = case t of { T n -> foo ((x-n) :*: t) }
343                   | otherwise = foo ((x-1) :*: t)
344
345 Very similar to the previous one, except that the parameters are now in
346 a strict tuple. Before SpecConstr, we have
347
348     $wfoo_sG3 :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
349     $wfoo_sG3 =
350       \ (ww_sFU [Just L] :: GHC.Prim.Int#) (ww_sFW [Just L] :: T.T
351     GHC.Base.Int) ->
352         case ww_sFU of ds_Xws [Just L] {
353           __DEFAULT ->
354         case GHC.Prim.remInt# ds_Xws 2 of wild1_aEZ [Dead Just A] {
355           __DEFAULT ->
356             case ww_sFW of tpl_B2 [Just L] { T.T a_sFo [Just A] ->
357             $wfoo_sG3 (GHC.Prim.-# ds_Xws 1) tpl_B2             -- $wfoo1
358             };
359           0 ->
360             case ww_sFW of wild_XB [Just A] { T.T n_ad7 [Just S(L)] ->
361             case n_ad7 of wild1_aFd [Just L] { GHC.Base.I# y_aFc [Just L] ->
362             $wfoo_sG3 (GHC.Prim.-# ds_Xws y_aFc) wild_XB        -- $wfoo2
363             } } };
364           0 -> 0 }
365
366 We get two specialisations:
367 "SC:$wfoo1" [0] __forall {a_sFB :: GHC.Base.Int sc_sGC :: GHC.Prim.Int#}
368                   Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int a_sFB)
369                   = Foo.$s$wfoo1 a_sFB sc_sGC ;
370 "SC:$wfoo2" [0] __forall {y_aFp :: GHC.Prim.Int# sc_sGC :: GHC.Prim.Int#}
371                   Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int (GHC.Base.I# y_aFp))
372                   = Foo.$s$wfoo y_aFp sc_sGC ;
373
374 But perhaps the first one isn't good.  After all, we know that tpl_B2 is
375 a T (I# x) really, because T is strict and Int has one constructor.  (We can't
376 unbox the strict fields, becuase T is polymorphic!)
377
378
379
380 %************************************************************************
381 %*                                                                      *
382 \subsection{Top level wrapper stuff}
383 %*                                                                      *
384 %************************************************************************
385
386 \begin{code}
387 specConstrProgram :: DynFlags -> UniqSupply -> [CoreBind] -> IO [CoreBind]
388 specConstrProgram dflags us binds
389   = do
390         showPass dflags "SpecConstr"
391
392         let (binds', _) = initUs us (go emptyScEnv binds)
393
394         endPass dflags "SpecConstr" Opt_D_dump_spec binds'
395
396         dumpIfSet_dyn dflags Opt_D_dump_rules "Top-level specialisations"
397                   (pprRules (tidyRules emptyTidyEnv (rulesOfBinds binds')))
398
399         return binds'
400   where
401     go env []           = returnUs []
402     go env (bind:binds) = scBind env bind       `thenUs` \ (env', _, bind') ->
403                           go env' binds         `thenUs` \ binds' ->
404                           returnUs (bind' : binds')
405 \end{code}
406
407
408 %************************************************************************
409 %*                                                                      *
410 \subsection{Environment: goes downwards}
411 %*                                                                      *
412 %************************************************************************
413
414 \begin{code}
415 data ScEnv = SCE { scope :: InScopeEnv,
416                         -- Binds all non-top-level variables in scope
417
418                    cons  :: ConstrEnv
419              }
420
421 type InScopeEnv = VarEnv HowBound
422
423 type ConstrEnv = IdEnv ConValue
424 data ConValue  = CV AltCon [CoreArg]
425         -- Variables known to be bound to a constructor
426         -- in a particular case alternative
427
428
429 instance Outputable ConValue where
430    ppr (CV con args) = ppr con <+> interpp'SP args
431
432 refineConstrEnv :: Subst -> ConstrEnv -> ConstrEnv
433 -- The substitution is a type substitution only
434 refineConstrEnv subst env = mapVarEnv refine_con_value env
435   where
436     refine_con_value (CV con args) = CV con (map (substExpr subst) args)
437
438 emptyScEnv = SCE { scope = emptyVarEnv, cons = emptyVarEnv }
439
440 data HowBound = RecFun          -- These are the recursive functions for which 
441                                 -- we seek interesting call patterns
442
443               | RecArg          -- These are those functions' arguments; we are
444                                 -- interested to see if those arguments are scrutinised
445
446               | Other           -- We track all others so we know what's in scope
447                                 -- This is used in spec_one to check what needs to be
448                                 -- passed as a parameter and what is in scope at the 
449                                 -- function definition site
450
451 instance Outputable HowBound where
452   ppr RecFun = text "RecFun"
453   ppr RecArg = text "RecArg"
454   ppr Other = text "Other"
455
456 lookupScopeEnv env v = lookupVarEnv (scope env) v
457
458 extendBndrs env bndrs = env { scope = extendVarEnvList (scope env) [(b,Other) | b <- bndrs] }
459 extendBndr  env bndr  = env { scope = extendVarEnv (scope env) bndr Other }
460
461     -- When we encounter
462     --  case scrut of b
463     --      C x y -> ...
464     -- we want to bind b, and perhaps scrut too, to (C x y)
465 extendCaseBndrs :: ScEnv -> Id -> CoreExpr -> AltCon -> [Var] -> ScEnv
466 extendCaseBndrs env case_bndr scrut DEFAULT alt_bndrs
467   = extendBndrs env (case_bndr : alt_bndrs)
468
469 extendCaseBndrs env case_bndr scrut con@(LitAlt lit) alt_bndrs
470   = ASSERT( null alt_bndrs ) extendAlt env case_bndr scrut (CV con []) []
471
472 extendCaseBndrs env case_bndr scrut con@(DataAlt data_con) alt_bndrs
473   | isVanillaDataCon data_con
474   = extendAlt env case_bndr scrut (CV con vanilla_args) alt_bndrs
475     
476   | otherwise   -- GADT
477   = extendAlt env1 case_bndr scrut (CV con gadt_args) alt_bndrs
478   where
479     vanilla_args = map Type (tyConAppArgs (idType case_bndr)) ++
480                    map varToCoreExpr alt_bndrs
481
482     gadt_args = map (substExpr subst . varToCoreExpr) alt_bndrs
483         -- This call generates some bogus warnings from substExpr,
484         -- because it's inconvenient to put all the Ids in scope
485         -- Will be fixed when we move to FC
486
487     (alt_tvs, _) = span isTyVar alt_bndrs
488     Just (tv_subst, is_local) = coreRefineTys data_con alt_tvs (idType case_bndr)
489     subst = mkSubst in_scope tv_subst emptyVarEnv       -- No Id substitition
490     in_scope = mkInScopeSet (tyVarsOfTypes (varEnvElts tv_subst))
491
492     env1 | is_local  = env
493          | otherwise = env { cons = refineConstrEnv subst (cons env) }
494
495
496 extendAlt :: ScEnv -> Id -> CoreExpr -> ConValue -> [Var] -> ScEnv
497 extendAlt env case_bndr scrut val alt_bndrs
498   = let 
499        env1 = SCE { scope = extendVarEnvList (scope env) [(b,Other) | b <- case_bndr : alt_bndrs],
500                     cons  = extendVarEnv     (cons  env) case_bndr val }
501     in
502     case scrut of
503         Var v ->   -- Bind the scrutinee in the ConstrEnv if it's a variable
504                    -- Also forget if the scrutinee is a RecArg, because we're
505                    -- now in the branch of a case, and we don't want to
506                    -- record a non-scrutinee use of v if we have
507                    --   case v of { (a,b) -> ...(f v)... }
508                  SCE { scope = extendVarEnv (scope env1) v Other,
509                        cons  = extendVarEnv (cons env1)  v val }
510         other -> env1
511
512     -- When we encounter a recursive function binding
513     --  f = \x y -> ...
514     -- we want to extend the scope env with bindings 
515     -- that record that f is a RecFn and x,y are RecArgs
516 extendRecBndr env fn bndrs
517   =  env { scope = scope env `extendVarEnvList` 
518                    ((fn,RecFun): [(bndr,RecArg) | bndr <- bndrs]) }
519 \end{code}
520
521
522 %************************************************************************
523 %*                                                                      *
524 \subsection{Usage information: flows upwards}
525 %*                                                                      *
526 %************************************************************************
527
528 \begin{code}
529 data ScUsage
530    = SCU {
531         calls :: !(IdEnv ([Call])),     -- Calls
532                                         -- The functions are a subset of the 
533                                         --      RecFuns in the ScEnv
534
535         occs :: !(IdEnv ArgOcc)         -- Information on argument occurrences
536      }                                  -- The variables are a subset of the 
537                                         --      RecArg in the ScEnv
538
539 type Call = (ConstrEnv, [CoreArg])
540         -- The arguments of the call, together with the
541         -- env giving the constructor bindings at the call site
542
543 nullUsage = SCU { calls = emptyVarEnv, occs = emptyVarEnv }
544
545 combineUsage u1 u2 = SCU { calls = plusVarEnv_C (++) (calls u1) (calls u2),
546                            occs  = plusVarEnv_C combineOcc (occs u1) (occs u2) }
547
548 combineUsages [] = nullUsage
549 combineUsages us = foldr1 combineUsage us
550
551 lookupOcc :: ScUsage -> Var -> (ScUsage, ArgOcc)
552 lookupOcc (SCU { calls = sc_calls, occs = sc_occs }) bndr
553   = (SCU {calls = sc_calls, occs = delVarEnv sc_occs bndr},
554      lookupVarEnv sc_occs bndr `orElse` NoOcc)
555
556 lookupOccs :: ScUsage -> [Var] -> (ScUsage, [ArgOcc])
557 lookupOccs (SCU { calls = sc_calls, occs = sc_occs }) bndrs
558   = (SCU {calls = sc_calls, occs = delVarEnvList sc_occs bndrs},
559      [lookupVarEnv sc_occs b `orElse` NoOcc | b <- bndrs])
560
561 data ArgOcc = NoOcc     -- Doesn't occur at all; or a type argument
562             | UnkOcc    -- Used in some unknown way
563
564             | ScrutOcc (UniqFM [ArgOcc])        -- See Note [ScrutOcc]
565
566             | BothOcc   -- Definitely taken apart, *and* perhaps used in some other way
567
568 {-      Note  [ScrutOcc]
569
570 An occurrence of ScrutOcc indicates that the thing is *only* taken apart or applied.
571
572   Functions, litersl: ScrutOcc emptyUFM
573   Data constructors:  ScrutOcc subs,
574
575 where (subs :: UniqFM [ArgOcc]) gives usage of the *pattern-bound* components,
576 The domain of the UniqFM is the Unique of the data constructor
577
578 The [ArgOcc] is the occurrences of the *pattern-bound* components 
579 of the data structure.  E.g.
580         data T a = forall b. MkT a b (b->a)
581 A pattern binds b, x::a, y::b, z::b->a, but not 'a'!
582
583 -}
584
585 instance Outputable ArgOcc where
586   ppr (ScrutOcc xs) = ptext SLIT("scrut-occ") <+> ppr xs
587   ppr UnkOcc        = ptext SLIT("unk-occ")
588   ppr BothOcc       = ptext SLIT("both-occ")
589   ppr NoOcc         = ptext SLIT("no-occ")
590
591 combineOcc NoOcc         occ           = occ
592 combineOcc occ           NoOcc         = occ
593 combineOcc (ScrutOcc xs) (ScrutOcc ys) = ScrutOcc (plusUFM_C combineOccs xs ys)
594 combineOcc UnkOcc        UnkOcc        = UnkOcc
595 combineOcc _        _                  = BothOcc
596
597 combineOccs :: [ArgOcc] -> [ArgOcc] -> [ArgOcc]
598 combineOccs xs ys = zipWithEqual "combineOccs" combineOcc xs ys
599
600 conArgOccs :: ArgOcc -> AltCon -> [ArgOcc]
601 -- Find usage of components of data con; returns [UnkOcc...] if unknown
602 -- See Note [ScrutOcc] for the extra UnkOccs in the vanilla datacon case
603
604 conArgOccs (ScrutOcc fm) (DataAlt dc) 
605   | Just pat_arg_occs <- lookupUFM fm dc
606   = tyvar_unks ++ pat_arg_occs
607   where
608     tyvar_unks | isVanillaDataCon dc = [UnkOcc | tv <- dataConTyVars dc]
609                | otherwise           = []
610
611 conArgOccs other con = repeat UnkOcc
612 \end{code}
613
614
615 %************************************************************************
616 %*                                                                      *
617 \subsection{The main recursive function}
618 %*                                                                      *
619 %************************************************************************
620
621 The main recursive function gathers up usage information, and
622 creates specialised versions of functions.
623
624 \begin{code}
625 scExpr :: ScEnv -> CoreExpr -> UniqSM (ScUsage, CoreExpr)
626         -- The unique supply is needed when we invent
627         -- a new name for the specialised function and its args
628
629 scExpr env e@(Type t) = returnUs (nullUsage, e)
630 scExpr env e@(Lit l)  = returnUs (nullUsage, e)
631 scExpr env e@(Var v)  = returnUs (varUsage env v UnkOcc, e)
632 scExpr env (Note n e) = scExpr env e    `thenUs` \ (usg,e') ->
633                         returnUs (usg, Note n e')
634 scExpr env (Lam b e)  = scExpr (extendBndr env b) e     `thenUs` \ (usg,e') ->
635                         returnUs (usg, Lam b e')
636
637 scExpr env (Case scrut b ty alts) 
638   = do  { (alt_usgs, alt_occs, alts') <- mapAndUnzip3Us sc_alt alts
639         ; let (alt_usg, b_occ) = lookupOcc (combineUsages alt_usgs) b
640               scrut_occ = foldr combineOcc b_occ alt_occs
641                 -- The combined usage of the scrutinee is given
642                 -- by scrut_occ, which is passed to scScrut, which
643                 -- in turn treats a bare-variable scrutinee specially
644         ; (scrut_usg, scrut') <- scScrut env scrut scrut_occ
645         ; return (alt_usg `combineUsage` scrut_usg,
646                   Case scrut' b ty alts') }
647   where
648     sc_alt (con,bs,rhs)
649       = do { let env1 = extendCaseBndrs env b scrut con bs
650            ; (usg,rhs') <- scExpr env1 rhs
651            ; let (usg', arg_occs) = lookupOccs usg bs
652                  scrut_occ = case con of
653                                 DataAlt dc -> ScrutOcc (unitUFM dc arg_occs)
654                                 other      -> ScrutOcc emptyUFM
655            ; return (usg', scrut_occ, (con,bs,rhs')) }
656
657 scExpr env (Let bind body)
658   = scBind env bind     `thenUs` \ (env', bind_usg, bind') ->
659     scExpr env' body    `thenUs` \ (body_usg, body') ->
660     returnUs (bind_usg `combineUsage` body_usg, Let bind' body')
661
662 scExpr env e@(App _ _) 
663   = do  { let (fn, args) = collectArgs e
664         ; (fn_usg, fn') <- scScrut env fn (ScrutOcc emptyUFM)
665         -- Process the function too.   It's almost always a variable,
666         -- but not always.  In particular, if this pass follows float-in,
667         -- which it may, we can get 
668         --      (let f = ...f... in f) arg1 arg2
669         -- We use scScrut to record the fact that the function is called
670         -- Perhpas we should check that it has at least one value arg, 
671         -- but currently we don't bother
672
673         ; (arg_usgs, args') <- mapAndUnzipUs (scExpr env) args
674         ; let call_usg = case fn of
675                            Var f | Just RecFun <- lookupScopeEnv env f
676                                  -> SCU { calls = unitVarEnv f [(cons env, args)], 
677                                           occs  = emptyVarEnv }
678                            other -> nullUsage
679         ; return (combineUsages arg_usgs `combineUsage` fn_usg 
680                                          `combineUsage` call_usg,
681                   mkApps fn' args') }
682
683
684 ----------------------
685 scScrut :: ScEnv -> CoreExpr -> ArgOcc -> UniqSM (ScUsage, CoreExpr)
686 -- Used for the scrutinee of a case, 
687 -- or the function of an application
688 scScrut env e@(Var v) occ = returnUs (varUsage env v occ, e)
689 scScrut env e         occ = scExpr env e
690
691
692 ----------------------
693 scBind :: ScEnv -> CoreBind -> UniqSM (ScEnv, ScUsage, CoreBind)
694 scBind env (Rec [(fn,rhs)])
695   | notNull val_bndrs
696   = scExpr env_fn_body body             `thenUs` \ (usg, body') ->
697     specialise env fn bndrs body' usg   `thenUs` \ (rules, spec_prs) ->
698         -- Note body': the specialised copies should be based on the 
699         --             optimised version of the body, in case there were
700         --             nested functions inside.
701     let
702         SCU { calls = calls, occs = occs } = usg
703     in
704     returnUs (extendBndr env fn,        -- For the body of the letrec, just
705                                         -- extend the env with Other to record 
706                                         -- that it's in scope; no funny RecFun business
707               SCU { calls = calls `delVarEnv` fn, occs = occs `delVarEnvList` val_bndrs},
708               Rec ((fn `addIdSpecialisations` rules, mkLams bndrs body') : spec_prs))
709   where
710     (bndrs,body) = collectBinders rhs
711     val_bndrs    = filter isId bndrs
712     env_fn_body  = extendRecBndr env fn bndrs
713
714 scBind env (Rec prs)
715   = mapAndUnzipUs do_one prs    `thenUs` \ (usgs, prs') ->
716     returnUs (extendBndrs env (map fst prs), combineUsages usgs, Rec prs')
717   where
718     do_one (bndr,rhs) = scExpr env rhs  `thenUs` \ (usg, rhs') ->
719                         returnUs (usg, (bndr,rhs'))
720
721 scBind env (NonRec bndr rhs)
722   = scExpr env rhs      `thenUs` \ (usg, rhs') ->
723     returnUs (extendBndr env bndr, usg, NonRec bndr rhs')
724
725 ----------------------
726 varUsage env v use 
727   | Just RecArg <- lookupScopeEnv env v = SCU { calls = emptyVarEnv, 
728                                                 occs = unitVarEnv v use }
729   | otherwise                           = nullUsage
730 \end{code}
731
732
733 %************************************************************************
734 %*                                                                      *
735 \subsection{The specialiser}
736 %*                                                                      *
737 %************************************************************************
738
739 \begin{code}
740 specialise :: ScEnv
741            -> Id                        -- Functionn
742            -> [CoreBndr] -> CoreExpr    -- Its RHS
743            -> ScUsage                   -- Info on usage
744            -> UniqSM ([CoreRule],       -- Rules
745                       [(Id,CoreExpr)])  -- Bindings
746
747 specialise env fn bndrs body body_usg
748   = do  { let (_, bndr_occs) = lookupOccs body_usg bndrs
749
750         ; mb_calls <- mapM (callToPats (scope env) bndr_occs)
751                            (lookupVarEnv (calls body_usg) fn `orElse` [])
752
753         ; let good_calls :: [([Var], [CoreArg])]
754               good_calls = catMaybes mb_calls
755               in_scope = mkInScopeSet $ unionVarSets $
756                          [ exprsFreeVars pats `delVarSetList` vs 
757                          | (vs,pats) <- good_calls ]
758               uniq_calls = nubBy (same_call in_scope) good_calls
759     in
760     mapAndUnzipUs (spec_one env fn (mkLams bndrs body)) 
761                   (uniq_calls `zip` [1..]) }
762   where
763         -- Two calls are the same if they match both ways
764     same_call in_scope (vs1,as1)(vs2,as2)
765          =  isJust (matchN in_scope vs1 as1 as2)
766          && isJust (matchN in_scope vs2 as2 as1)
767
768 callToPats :: InScopeEnv -> [ArgOcc] -> Call
769            -> UniqSM (Maybe ([Var], [CoreExpr]))
770         -- The VarSet is the variables to quantify over in the rule
771         -- The [CoreExpr] are the argument patterns for the rule
772 callToPats in_scope bndr_occs (con_env, args)
773   | length args < length bndr_occs      -- Check saturated
774   = return Nothing
775   | otherwise
776   = do  { prs <- argsToPats in_scope con_env (args `zip` bndr_occs)
777         ; let (good_pats, pats) = unzip prs
778               pat_fvs = varSetElems (exprsFreeVars pats)
779               qvars   = filter (not . (`elemVarEnv` in_scope)) pat_fvs
780                 -- Quantify over variables that are not in sccpe
781                 -- See Note [Shadowing] at the top
782                 
783         ; if or good_pats 
784           then return (Just (qvars, pats))
785           else return Nothing }
786
787 ---------------------
788 spec_one :: ScEnv
789          -> Id                                  -- Function
790          -> CoreExpr                            -- Rhs of the original function
791          -> (([Var], [CoreArg]), Int)
792          -> UniqSM (CoreRule, (Id,CoreExpr))    -- Rule and binding
793
794 -- spec_one creates a specialised copy of the function, together
795 -- with a rule for using it.  I'm very proud of how short this
796 -- function is, considering what it does :-).
797
798 {- 
799   Example
800   
801      In-scope: a, x::a   
802      f = /\b \y::[(a,b)] -> ....f (b,c) ((:) (a,(b,c)) (x,v) (h w))...
803           [c::*, v::(b,c) are presumably bound by the (...) part]
804   ==>
805      f_spec = /\ b c \ v::(b,c) hw::[(a,(b,c))] ->
806                   (...entire RHS of f...) (b,c) ((:) (a,(b,c)) (x,v) hw)
807   
808      RULE:  forall b::* c::*,           -- Note, *not* forall a, x
809                    v::(b,c),
810                    hw::[(a,(b,c))] .
811   
812             f (b,c) ((:) (a,(b,c)) (x,v) hw) = f_spec b c v hw
813 -}
814
815 spec_one env fn rhs ((vars_to_bind, pats), rule_number)
816   = getUniqueUs                 `thenUs` \ spec_uniq ->
817     let 
818         fn_name      = idName fn
819         fn_loc       = nameSrcLoc fn_name
820         spec_occ     = mkSpecOcc (nameOccName fn_name)
821
822                 -- Put the type variables first; the type of a term
823                 -- variable may mention a type variable
824         (tvs, ids)   = partition isTyVar vars_to_bind
825         bndrs        = tvs ++ ids
826         spec_body    = mkApps rhs pats
827         body_ty      = exprType spec_body
828         
829         (spec_lam_args, spec_call_args) = mkWorkerArgs bndrs body_ty
830                 -- Usual w/w hack to avoid generating 
831                 -- a spec_rhs of unlifted type and no args
832         
833         rule_name = mkFastString ("SC:" ++ showSDoc (ppr fn <> int rule_number))
834         spec_rhs  = mkLams spec_lam_args spec_body
835         spec_id   = mkUserLocal spec_occ spec_uniq (mkPiTypes spec_lam_args body_ty) fn_loc
836         rule_rhs  = mkVarApps (Var spec_id) spec_call_args
837         rule      = mkLocalRule rule_name specConstrActivation fn_name bndrs pats rule_rhs
838     in
839     returnUs (rule, (spec_id, spec_rhs))
840
841 -- In which phase should the specialise-constructor rules be active?
842 -- Originally I made them always-active, but Manuel found that
843 -- this defeated some clever user-written rules.  So Plan B
844 -- is to make them active only in Phase 0; after all, currently,
845 -- the specConstr transformation is only run after the simplifier
846 -- has reached Phase 0.  In general one would want it to be 
847 -- flag-controllable, but for now I'm leaving it baked in
848 --                                      [SLPJ Oct 01]
849 specConstrActivation :: Activation
850 specConstrActivation = ActiveAfter 0    -- Baked in; see comments above
851 \end{code}
852
853 %************************************************************************
854 %*                                                                      *
855 \subsection{Argument analysis}
856 %*                                                                      *
857 %************************************************************************
858
859 This code deals with analysing call-site arguments to see whether
860 they are constructor applications.
861
862 ---------------------
863 good_arg :: ConstrEnv -> IdEnv ArgOcc -> (CoreBndr, CoreArg) -> Bool
864 -- See Note [Good arguments] above
865 good_arg con_env arg_occs (bndr, arg)
866   = case is_con_app_maybe con_env arg of        
867         Just _ ->  bndr_usg_ok arg_occs bndr arg
868         other   -> False
869
870 bndr_usg_ok :: IdEnv ArgOcc -> Var -> CoreArg -> Bool
871 bndr_usg_ok arg_occs bndr arg
872   = case lookupVarEnv arg_occs bndr of
873         Just ScrutOcc -> True                   -- Used only by case scrutiny
874         Just Both     -> case arg of            -- Used by case and elsewhere
875                             App _ _ -> True     -- so the arg should be an explicit con app
876                             other   -> False
877         other -> False                          -- Not used, or used wonkily
878     
879
880 \begin{code}
881     -- argToPat takes an actual argument, and returns an abstracted
882     -- version, consisting of just the "constructor skeleton" of the
883     -- argument, with non-constructor sub-expression replaced by new
884     -- placeholder variables.  For example:
885     --    C a (D (f x) (g y))  ==>  C p1 (D p2 p3)
886
887 argToPat :: InScopeEnv                  -- What's in scope at the fn defn site
888          -> ConstrEnv                   -- ConstrEnv at the call site
889          -> CoreArg                     -- A call arg (or component thereof)
890          -> ArgOcc
891          -> UniqSM (Bool, CoreArg)
892 -- Returns (interesting, pat), 
893 -- where pat is the pattern derived from the argument
894 --            intersting=True if the pattern is non-trivial (not a variable or type)
895 -- E.g.         x:xs         --> (True, x:xs)
896 --              f xs         --> (False, w)        where w is a fresh wildcard
897 --              (f xs, 'c')  --> (True, (w, 'c'))  where w is a fresh wildcard
898 --              \x. x+y      --> (True, \x. x+y)
899 --              lvl7         --> (True, lvl7)      if lvl7 is bound 
900 --                                                 somewhere further out
901
902 argToPat in_scope con_env arg@(Type ty) arg_occ
903   = return (False, arg)
904
905 argToPat in_scope con_env (Var v) arg_occ       -- Don't uniqify existing vars,
906   = return (interesting, Var v) -- so that we can spot when we pass them twice
907   where
908     interesting = not (isLocalId v) || v `elemVarEnv` in_scope
909
910 argToPat in_scope con_env arg arg_occ
911   | is_value_lam arg
912   = return (True, arg)
913   where
914     is_value_lam (Lam v e)      -- Spot a value lambda, even if 
915         | isId v = True         -- it is inside a type lambda
916         | otherwise = is_value_lam e
917     is_value_lam other = False
918
919 argToPat in_scope con_env arg arg_occ
920   | Just (CV dc args) <- is_con_app_maybe con_env arg
921   , case arg_occ of
922         ScrutOcc _ -> True              -- Used only by case scrutinee
923         BothOcc    -> case arg of       -- Used by case scrut
924                         App {} -> True  -- ...and elsewhere...
925                         other  -> False
926         other      -> False     -- No point; the arg is not decomposed
927   = do  { args' <- argsToPats in_scope con_env (args `zip` conArgOccs arg_occ dc)
928         ; return (True, mk_con_app dc (map snd args')) }
929
930 argToPat in_scope con_env arg arg_occ
931   = do  { uniq <- getUniqueUs
932         ; let id = mkSysLocal FSLIT("sc") uniq (exprType arg)
933         ; return (False, Var id) }
934
935 argsToPats :: InScopeEnv -> ConstrEnv
936            -> [(CoreArg, ArgOcc)]
937            -> UniqSM [(Bool, CoreArg)]
938 argsToPats in_scope con_env args
939   = mapUs do_one args
940   where
941     do_one (arg,occ) = argToPat in_scope con_env arg occ
942 \end{code}
943
944
945 \begin{code}
946 is_con_app_maybe :: ConstrEnv -> CoreExpr -> Maybe ConValue
947 is_con_app_maybe env (Var v)
948   = case lookupVarEnv env v of
949         Just stuff -> Just stuff
950                 -- You might think we could look in the idUnfolding here
951                 -- but that doesn't take account of which branch of a 
952                 -- case we are in, which is the whole point
953
954         Nothing | isCheapUnfolding unf
955                 -> is_con_app_maybe env (unfoldingTemplate unf)
956                 where
957                   unf = idUnfolding v
958                 -- However we do want to consult the unfolding 
959                 -- as well, for let-bound constructors!
960
961         other  -> Nothing
962
963 is_con_app_maybe env (Lit lit)
964   = Just (CV (LitAlt lit) [])
965
966 is_con_app_maybe env expr
967   = case collectArgs expr of
968         (Var fun, args) | Just con <- isDataConWorkId_maybe fun,
969                           args `lengthAtLeast` dataConRepArity con
970                 -- Might be > because the arity excludes type args
971                         -> Just (CV (DataAlt con) args)
972
973         other -> Nothing
974
975 mk_con_app :: AltCon -> [CoreArg] -> CoreExpr
976 mk_con_app (LitAlt lit)  []   = Lit lit
977 mk_con_app (DataAlt con) args = mkConApp con args
978 \end{code}