For a non-recursive let, make sure we extend the value environment
[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 -- The above warning supression flag is a temporary kludge.
8 -- While working on this module you are encouraged to remove it and fix
9 -- any warnings in the module. See
10 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
11 -- for details
12
13 module SpecConstr(
14         specConstrProgram
15 #ifdef GHCI
16         , SpecConstrAnnotation(..)
17 #endif
18     ) where
19
20 #include "HsVersions.h"
21
22 import CoreSyn
23 import CoreSubst
24 import CoreUtils
25 import CoreUnfold       ( couldBeSmallEnoughToInline )
26 import CoreFVs          ( exprsFreeVars )
27 import CoreMonad
28 import HscTypes         ( ModGuts(..) )
29 import WwLib            ( mkWorkerArgs )
30 import DataCon
31 import Coercion 
32 import Rules
33 import Type             hiding( substTy )
34 import Id
35 import MkCore           ( mkImpossibleExpr )
36 import Var
37 import VarEnv
38 import VarSet
39 import Name
40 import BasicTypes
41 import DynFlags         ( DynFlags(..) )
42 import StaticFlags      ( opt_PprStyle_Debug )
43 import Maybes           ( orElse, catMaybes, isJust, isNothing )
44 import Demand
45 import DmdAnal          ( both )
46 import Serialized       ( deserializeWithData )
47 import Util
48 import UniqSupply
49 import Outputable
50 import FastString
51 import UniqFM
52 import MonadUtils
53 import Control.Monad    ( zipWithM )
54 import Data.List
55
56
57 -- See Note [SpecConstrAnnotation]
58 #ifndef GHCI
59 type SpecConstrAnnotation = ()
60 #else
61 import Literal          ( literalType )
62 import TyCon            ( TyCon )
63 import GHC.Exts( SpecConstrAnnotation(..) )
64 #endif
65 \end{code}
66
67 -----------------------------------------------------
68                         Game plan
69 -----------------------------------------------------
70
71 Consider
72         drop n []     = []
73         drop 0 xs     = []
74         drop n (x:xs) = drop (n-1) xs
75
76 After the first time round, we could pass n unboxed.  This happens in
77 numerical code too.  Here's what it looks like in Core:
78
79         drop n xs = case xs of
80                       []     -> []
81                       (y:ys) -> case n of 
82                                   I# n# -> case n# of
83                                              0 -> []
84                                              _ -> drop (I# (n# -# 1#)) xs
85
86 Notice that the recursive call has an explicit constructor as argument.
87 Noticing this, we can make a specialised version of drop
88         
89         RULE: drop (I# n#) xs ==> drop' n# xs
90
91         drop' n# xs = let n = I# n# in ...orig RHS...
92
93 Now the simplifier will apply the specialisation in the rhs of drop', giving
94
95         drop' n# xs = case xs of
96                       []     -> []
97                       (y:ys) -> case n# of
98                                   0 -> []
99                                   _ -> drop (n# -# 1#) xs
100
101 Much better!  
102
103 We'd also like to catch cases where a parameter is carried along unchanged,
104 but evaluated each time round the loop:
105
106         f i n = if i>0 || i>n then i else f (i*2) n
107
108 Here f isn't strict in n, but we'd like to avoid evaluating it each iteration.
109 In Core, by the time we've w/wd (f is strict in i) we get
110
111         f i# n = case i# ># 0 of
112                    False -> I# i#
113                    True  -> case n of n' { I# n# ->
114                             case i# ># n# of
115                                 False -> I# i#
116                                 True  -> f (i# *# 2#) n'
117
118 At the call to f, we see that the argument, n is know to be (I# n#),
119 and n is evaluated elsewhere in the body of f, so we can play the same
120 trick as above.  
121
122
123 Note [Reboxing]
124 ~~~~~~~~~~~~~~~
125 We must be careful not to allocate the same constructor twice.  Consider
126         f p = (...(case p of (a,b) -> e)...p...,
127                ...let t = (r,s) in ...t...(f t)...)
128 At the recursive call to f, we can see that t is a pair.  But we do NOT want
129 to make a specialised copy:
130         f' a b = let p = (a,b) in (..., ...)
131 because now t is allocated by the caller, then r and s are passed to the
132 recursive call, which allocates the (r,s) pair again.
133
134 This happens if
135   (a) the argument p is used in other than a case-scrutinsation way.
136   (b) the argument to the call is not a 'fresh' tuple; you have to
137         look into its unfolding to see that it's a tuple
138
139 Hence the "OR" part of Note [Good arguments] below.
140
141 ALTERNATIVE 2: pass both boxed and unboxed versions.  This no longer saves
142 allocation, but does perhaps save evals. In the RULE we'd have
143 something like
144
145   f (I# x#) = f' (I# x#) x#
146
147 If at the call site the (I# x) was an unfolding, then we'd have to
148 rely on CSE to eliminate the duplicate allocation.... This alternative
149 doesn't look attractive enough to pursue.
150
151 ALTERNATIVE 3: ignore the reboxing problem.  The trouble is that 
152 the conservative reboxing story prevents many useful functions from being
153 specialised.  Example:
154         foo :: Maybe Int -> Int -> Int
155         foo   (Just m) 0 = 0
156         foo x@(Just m) n = foo x (n-m)
157 Here the use of 'x' will clearly not require boxing in the specialised function.
158
159 The strictness analyser has the same problem, in fact.  Example:
160         f p@(a,b) = ...
161 If we pass just 'a' and 'b' to the worker, it might need to rebox the
162 pair to create (a,b).  A more sophisticated analysis might figure out
163 precisely the cases in which this could happen, but the strictness
164 analyser does no such analysis; it just passes 'a' and 'b', and hopes
165 for the best.
166
167 So my current choice is to make SpecConstr similarly aggressive, and
168 ignore the bad potential of reboxing.
169
170
171 Note [Good arguments]
172 ~~~~~~~~~~~~~~~~~~~~~
173 So we look for
174
175 * A self-recursive function.  Ignore mutual recursion for now, 
176   because it's less common, and the code is simpler for self-recursion.
177
178 * EITHER
179
180    a) At a recursive call, one or more parameters is an explicit 
181       constructor application
182         AND
183       That same parameter is scrutinised by a case somewhere in 
184       the RHS of the function
185
186   OR
187
188     b) At a recursive call, one or more parameters has an unfolding
189        that is an explicit constructor application
190         AND
191       That same parameter is scrutinised by a case somewhere in 
192       the RHS of the function
193         AND
194       Those are the only uses of the parameter (see Note [Reboxing])
195
196
197 What to abstract over
198 ~~~~~~~~~~~~~~~~~~~~~
199 There's a bit of a complication with type arguments.  If the call
200 site looks like
201
202         f p = ...f ((:) [a] x xs)...
203
204 then our specialised function look like
205
206         f_spec x xs = let p = (:) [a] x xs in ....as before....
207
208 This only makes sense if either
209   a) the type variable 'a' is in scope at the top of f, or
210   b) the type variable 'a' is an argument to f (and hence fs)
211
212 Actually, (a) may hold for value arguments too, in which case
213 we may not want to pass them.  Supose 'x' is in scope at f's
214 defn, but xs is not.  Then we'd like
215
216         f_spec xs = let p = (:) [a] x xs in ....as before....
217
218 Similarly (b) may hold too.  If x is already an argument at the
219 call, no need to pass it again.
220
221 Finally, if 'a' is not in scope at the call site, we could abstract
222 it as we do the term variables:
223
224         f_spec a x xs = let p = (:) [a] x xs in ...as before...
225
226 So the grand plan is:
227
228         * abstract the call site to a constructor-only pattern
229           e.g.  C x (D (f p) (g q))  ==>  C s1 (D s2 s3)
230
231         * Find the free variables of the abstracted pattern
232
233         * Pass these variables, less any that are in scope at
234           the fn defn.  But see Note [Shadowing] below.
235
236
237 NOTICE that we only abstract over variables that are not in scope,
238 so we're in no danger of shadowing variables used in "higher up"
239 in f_spec's RHS.
240
241
242 Note [Shadowing]
243 ~~~~~~~~~~~~~~~~
244 In this pass we gather up usage information that may mention variables
245 that are bound between the usage site and the definition site; or (more
246 seriously) may be bound to something different at the definition site.
247 For example:
248
249         f x = letrec g y v = let x = ... 
250                              in ...(g (a,b) x)...
251
252 Since 'x' is in scope at the call site, we may make a rewrite rule that 
253 looks like
254         RULE forall a,b. g (a,b) x = ...
255 But this rule will never match, because it's really a different 'x' at 
256 the call site -- and that difference will be manifest by the time the
257 simplifier gets to it.  [A worry: the simplifier doesn't *guarantee*
258 no-shadowing, so perhaps it may not be distinct?]
259
260 Anyway, the rule isn't actually wrong, it's just not useful.  One possibility
261 is to run deShadowBinds before running SpecConstr, but instead we run the
262 simplifier.  That gives the simplest possible program for SpecConstr to
263 chew on; and it virtually guarantees no shadowing.
264
265 Note [Specialising for constant parameters]
266 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
267 This one is about specialising on a *constant* (but not necessarily
268 constructor) argument
269
270     foo :: Int -> (Int -> Int) -> Int
271     foo 0 f = 0
272     foo m f = foo (f m) (+1)
273
274 It produces
275
276     lvl_rmV :: GHC.Base.Int -> GHC.Base.Int
277     lvl_rmV =
278       \ (ds_dlk :: GHC.Base.Int) ->
279         case ds_dlk of wild_alH { GHC.Base.I# x_alG ->
280         GHC.Base.I# (GHC.Prim.+# x_alG 1)
281
282     T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) ->
283     GHC.Prim.Int#
284     T.$wfoo =
285       \ (ww_sme :: GHC.Prim.Int#) (w_smg :: GHC.Base.Int -> GHC.Base.Int) ->
286         case ww_sme of ds_Xlw {
287           __DEFAULT ->
288         case w_smg (GHC.Base.I# ds_Xlw) of w1_Xmo { GHC.Base.I# ww1_Xmz ->
289         T.$wfoo ww1_Xmz lvl_rmV
290         };
291           0 -> 0
292         }
293
294 The recursive call has lvl_rmV as its argument, so we could create a specialised copy
295 with that argument baked in; that is, not passed at all.   Now it can perhaps be inlined.
296
297 When is this worth it?  Call the constant 'lvl'
298 - If 'lvl' has an unfolding that is a constructor, see if the corresponding
299   parameter is scrutinised anywhere in the body.
300
301 - If 'lvl' has an unfolding that is a inlinable function, see if the corresponding
302   parameter is applied (...to enough arguments...?)
303
304   Also do this is if the function has RULES?
305
306 Also    
307
308 Note [Specialising for lambda parameters]
309 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
310     foo :: Int -> (Int -> Int) -> Int
311     foo 0 f = 0
312     foo m f = foo (f m) (\n -> n-m)
313
314 This is subtly different from the previous one in that we get an
315 explicit lambda as the argument:
316
317     T.$wfoo :: GHC.Prim.Int# -> (GHC.Base.Int -> GHC.Base.Int) ->
318     GHC.Prim.Int#
319     T.$wfoo =
320       \ (ww_sm8 :: GHC.Prim.Int#) (w_sma :: GHC.Base.Int -> GHC.Base.Int) ->
321         case ww_sm8 of ds_Xlr {
322           __DEFAULT ->
323         case w_sma (GHC.Base.I# ds_Xlr) of w1_Xmf { GHC.Base.I# ww1_Xmq ->
324         T.$wfoo
325           ww1_Xmq
326           (\ (n_ad3 :: GHC.Base.Int) ->
327              case n_ad3 of wild_alB { GHC.Base.I# x_alA ->
328              GHC.Base.I# (GHC.Prim.-# x_alA ds_Xlr)
329              })
330         };
331           0 -> 0
332         }
333
334 I wonder if SpecConstr couldn't be extended to handle this? After all,
335 lambda is a sort of constructor for functions and perhaps it already
336 has most of the necessary machinery?
337
338 Furthermore, there's an immediate win, because you don't need to allocate the lamda
339 at the call site; and if perchance it's called in the recursive call, then you
340 may avoid allocating it altogether.  Just like for constructors.
341
342 Looks cool, but probably rare...but it might be easy to implement.
343
344
345 Note [SpecConstr for casts]
346 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
347 Consider 
348     data family T a :: *
349     data instance T Int = T Int
350
351     foo n = ...
352        where
353          go (T 0) = 0
354          go (T n) = go (T (n-1))
355
356 The recursive call ends up looking like 
357         go (T (I# ...) `cast` g)
358 So we want to spot the construtor application inside the cast.
359 That's why we have the Cast case in argToPat
360
361 Note [Local recursive groups]
362 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
363 For a *local* recursive group, we can see all the calls to the
364 function, so we seed the specialisation loop from the calls in the
365 body, not from the calls in the RHS.  Consider:
366
367   bar m n = foo n (n,n) (n,n) (n,n) (n,n)
368    where
369      foo n p q r s
370        | n == 0    = m
371        | n > 3000  = case p of { (p1,p2) -> foo (n-1) (p2,p1) q r s }
372        | n > 2000  = case q of { (q1,q2) -> foo (n-1) p (q2,q1) r s }
373        | n > 1000  = case r of { (r1,r2) -> foo (n-1) p q (r2,r1) s }
374        | otherwise = case s of { (s1,s2) -> foo (n-1) p q r (s2,s1) }
375
376 If we start with the RHSs of 'foo', we get lots and lots of specialisations,
377 most of which are not needed.  But if we start with the (single) call
378 in the rhs of 'bar' we get exactly one fully-specialised copy, and all
379 the recursive calls go to this fully-specialised copy. Indeed, the original
380 function is later collected as dead code.  This is very important in 
381 specialising the loops arising from stream fusion, for example in NDP where
382 we were getting literally hundreds of (mostly unused) specialisations of
383 a local function.
384
385 Note [Do not specialise diverging functions]
386 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
387 Specialising a function that just diverges is a waste of code.
388 Furthermore, it broke GHC (simpl014) thus:
389    {-# STR Sb #-}
390    f = \x. case x of (a,b) -> f x
391 If we specialise f we get
392    f = \x. case x of (a,b) -> fspec a b
393 But fspec doesn't have decent strictnes info.  As it happened,
394 (f x) :: IO t, so the state hack applied and we eta expanded fspec,
395 and hence f.  But now f's strictness is less than its arity, which
396 breaks an invariant.
397
398 Note [SpecConstrAnnotation]
399 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
400 SpecConstrAnnotation is defined in GHC.Exts, and is only guaranteed to
401 be available in stage 2 (well, until the bootstrap compiler can be
402 guaranteed to have it)
403
404 So we define it to be () in stage1 (ie when GHCI is undefined), and
405 '#ifdef' out the code that uses it.
406
407 See also Note [Forcing specialisation]
408
409 Note [Forcing specialisation]
410 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
411 With stream fusion and in other similar cases, we want to fully specialise
412 some (but not necessarily all!) loops regardless of their size and the
413 number of specialisations. We allow a library to specify this by annotating
414 a type with ForceSpecConstr and then adding a parameter of that type to the
415 loop. Here is a (simplified) example from the vector library:
416
417   data SPEC = SPEC | SPEC2
418   {-# ANN type SPEC ForceSpecConstr #-}
419
420   foldl :: (a -> b -> a) -> a -> Stream b -> a
421   {-# INLINE foldl #-}
422   foldl f z (Stream step s _) = foldl_loop SPEC z s
423     where
424       foldl_loop SPEC z s = case step s of
425                               Yield x s' -> foldl_loop SPEC (f z x) s'
426                               Skip       -> foldl_loop SPEC z s'
427                               Done       -> z
428
429 SpecConstr will spot the SPEC parameter and always fully specialise
430 foldl_loop. Note that we can't just annotate foldl_loop since it isn't a
431 top-level function but even if we could, inlining etc. could easily drop the
432 annotation. We also have to prevent the SPEC argument from being removed by
433 w/w which is why SPEC is a sum type. This is all quite ugly; we ought to come
434 up with a better design.
435
436 ForceSpecConstr arguments are spotted in scExpr' and scTopBinds which then set
437 force_spec to True when calling specLoop. This flag makes specLoop and
438 specialise ignore specConstrCount and specConstrThreshold when deciding
439 whether to specialise a function.
440
441 -----------------------------------------------------
442                 Stuff not yet handled
443 -----------------------------------------------------
444
445 Here are notes arising from Roman's work that I don't want to lose.
446
447 Example 1
448 ~~~~~~~~~
449     data T a = T !a
450
451     foo :: Int -> T Int -> Int
452     foo 0 t = 0
453     foo x t | even x    = case t of { T n -> foo (x-n) t }
454             | otherwise = foo (x-1) t
455
456 SpecConstr does no specialisation, because the second recursive call
457 looks like a boxed use of the argument.  A pity.
458
459     $wfoo_sFw :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
460     $wfoo_sFw =
461       \ (ww_sFo [Just L] :: GHC.Prim.Int#) (w_sFq [Just L] :: T.T GHC.Base.Int) ->
462          case ww_sFo of ds_Xw6 [Just L] {
463            __DEFAULT ->
464                 case GHC.Prim.remInt# ds_Xw6 2 of wild1_aEF [Dead Just A] {
465                   __DEFAULT -> $wfoo_sFw (GHC.Prim.-# ds_Xw6 1) w_sFq;
466                   0 ->
467                     case w_sFq of wild_Xy [Just L] { T.T n_ad5 [Just U(L)] ->
468                     case n_ad5 of wild1_aET [Just A] { GHC.Base.I# y_aES [Just L] ->
469                     $wfoo_sFw (GHC.Prim.-# ds_Xw6 y_aES) wild_Xy
470                     } } };
471            0 -> 0
472
473 Example 2
474 ~~~~~~~~~
475     data a :*: b = !a :*: !b
476     data T a = T !a
477
478     foo :: (Int :*: T Int) -> Int
479     foo (0 :*: t) = 0
480     foo (x :*: t) | even x    = case t of { T n -> foo ((x-n) :*: t) }
481                   | otherwise = foo ((x-1) :*: t)
482
483 Very similar to the previous one, except that the parameters are now in
484 a strict tuple. Before SpecConstr, we have
485
486     $wfoo_sG3 :: GHC.Prim.Int# -> T.T GHC.Base.Int -> GHC.Prim.Int#
487     $wfoo_sG3 =
488       \ (ww_sFU [Just L] :: GHC.Prim.Int#) (ww_sFW [Just L] :: T.T
489     GHC.Base.Int) ->
490         case ww_sFU of ds_Xws [Just L] {
491           __DEFAULT ->
492         case GHC.Prim.remInt# ds_Xws 2 of wild1_aEZ [Dead Just A] {
493           __DEFAULT ->
494             case ww_sFW of tpl_B2 [Just L] { T.T a_sFo [Just A] ->
495             $wfoo_sG3 (GHC.Prim.-# ds_Xws 1) tpl_B2             -- $wfoo1
496             };
497           0 ->
498             case ww_sFW of wild_XB [Just A] { T.T n_ad7 [Just S(L)] ->
499             case n_ad7 of wild1_aFd [Just L] { GHC.Base.I# y_aFc [Just L] ->
500             $wfoo_sG3 (GHC.Prim.-# ds_Xws y_aFc) wild_XB        -- $wfoo2
501             } } };
502           0 -> 0 }
503
504 We get two specialisations:
505 "SC:$wfoo1" [0] __forall {a_sFB :: GHC.Base.Int sc_sGC :: GHC.Prim.Int#}
506                   Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int a_sFB)
507                   = Foo.$s$wfoo1 a_sFB sc_sGC ;
508 "SC:$wfoo2" [0] __forall {y_aFp :: GHC.Prim.Int# sc_sGC :: GHC.Prim.Int#}
509                   Foo.$wfoo sc_sGC (Foo.T @ GHC.Base.Int (GHC.Base.I# y_aFp))
510                   = Foo.$s$wfoo y_aFp sc_sGC ;
511
512 But perhaps the first one isn't good.  After all, we know that tpl_B2 is
513 a T (I# x) really, because T is strict and Int has one constructor.  (We can't
514 unbox the strict fields, becuase T is polymorphic!)
515
516 %************************************************************************
517 %*                                                                      *
518 \subsection{Top level wrapper stuff}
519 %*                                                                      *
520 %************************************************************************
521
522 \begin{code}
523 specConstrProgram :: ModGuts -> CoreM ModGuts
524 specConstrProgram guts
525   = do
526       dflags <- getDynFlags
527       us     <- getUniqueSupplyM
528       annos  <- getFirstAnnotations deserializeWithData guts
529       let binds' = fst $ initUs us (go (initScEnv dflags annos) (mg_binds guts))
530       return (guts { mg_binds = binds' })
531   where
532     go _   []           = return []
533     go env (bind:binds) = do (env', bind') <- scTopBind env bind
534                              binds' <- go env' binds
535                              return (bind' : binds')
536 \end{code}
537
538
539 %************************************************************************
540 %*                                                                      *
541 \subsection{Environment: goes downwards}
542 %*                                                                      *
543 %************************************************************************
544
545 \begin{code}
546 data ScEnv = SCE { sc_size  :: Maybe Int,       -- Size threshold
547                    sc_count :: Maybe Int,       -- Max # of specialisations for any one fn
548                                                 -- See Note [Avoiding exponential blowup]
549
550                    sc_subst :: Subst,           -- Current substitution
551                                                 -- Maps InIds to OutExprs
552
553                    sc_how_bound :: HowBoundEnv,
554                         -- Binds interesting non-top-level variables
555                         -- Domain is OutVars (*after* applying the substitution)
556
557                    sc_vals  :: ValueEnv,
558                         -- Domain is OutIds (*after* applying the substitution)
559                         -- Used even for top-level bindings (but not imported ones)
560
561                    sc_annotations :: UniqFM SpecConstrAnnotation
562              }
563
564 ---------------------
565 -- As we go, we apply a substitution (sc_subst) to the current term
566 type InExpr = CoreExpr          -- _Before_ applying the subst
567 type InVar  = Var
568
569 type OutExpr = CoreExpr         -- _After_ applying the subst
570 type OutId   = Id
571 type OutVar  = Var
572
573 ---------------------
574 type HowBoundEnv = VarEnv HowBound      -- Domain is OutVars
575
576 ---------------------
577 type ValueEnv = IdEnv Value             -- Domain is OutIds
578 data Value    = ConVal AltCon [CoreArg] -- _Saturated_ constructors
579                                         --   The AltCon is never DEFAULT
580               | LambdaVal               -- Inlinable lambdas or PAPs
581
582 instance Outputable Value where
583    ppr (ConVal con args) = ppr con <+> interpp'SP args
584    ppr LambdaVal         = ptext (sLit "<Lambda>")
585
586 ---------------------
587 initScEnv :: DynFlags -> UniqFM SpecConstrAnnotation -> ScEnv
588 initScEnv dflags anns
589   = SCE { sc_size = specConstrThreshold dflags,
590           sc_count = specConstrCount dflags,
591           sc_subst = emptySubst, 
592           sc_how_bound = emptyVarEnv, 
593           sc_vals = emptyVarEnv,
594           sc_annotations = anns }
595
596 data HowBound = RecFun  -- These are the recursive functions for which 
597                         -- we seek interesting call patterns
598
599               | RecArg  -- These are those functions' arguments, or their sub-components; 
600                         -- we gather occurrence information for these
601
602 instance Outputable HowBound where
603   ppr RecFun = text "RecFun"
604   ppr RecArg = text "RecArg"
605
606 lookupHowBound :: ScEnv -> Id -> Maybe HowBound
607 lookupHowBound env id = lookupVarEnv (sc_how_bound env) id
608
609 scSubstId :: ScEnv -> Id -> CoreExpr
610 scSubstId env v = lookupIdSubst (text "scSubstId") (sc_subst env) v
611
612 scSubstTy :: ScEnv -> Type -> Type
613 scSubstTy env ty = substTy (sc_subst env) ty
614
615 zapScSubst :: ScEnv -> ScEnv
616 zapScSubst env = env { sc_subst = zapSubstEnv (sc_subst env) }
617
618 extendScInScope :: ScEnv -> [Var] -> ScEnv
619         -- Bring the quantified variables into scope
620 extendScInScope env qvars = env { sc_subst = extendInScopeList (sc_subst env) qvars }
621
622         -- Extend the substitution
623 extendScSubst :: ScEnv -> Var -> OutExpr -> ScEnv
624 extendScSubst env var expr = env { sc_subst = extendSubst (sc_subst env) var expr }
625
626 extendScSubstList :: ScEnv -> [(Var,OutExpr)] -> ScEnv
627 extendScSubstList env prs = env { sc_subst = extendSubstList (sc_subst env) prs }
628
629 extendHowBound :: ScEnv -> [Var] -> HowBound -> ScEnv
630 extendHowBound env bndrs how_bound
631   = env { sc_how_bound = extendVarEnvList (sc_how_bound env)
632                             [(bndr,how_bound) | bndr <- bndrs] }
633
634 extendBndrsWith :: HowBound -> ScEnv -> [Var] -> (ScEnv, [Var])
635 extendBndrsWith how_bound env bndrs 
636   = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndrs')
637   where
638     (subst', bndrs') = substBndrs (sc_subst env) bndrs
639     hb_env' = sc_how_bound env `extendVarEnvList` 
640                     [(bndr,how_bound) | bndr <- bndrs']
641
642 extendBndrWith :: HowBound -> ScEnv -> Var -> (ScEnv, Var)
643 extendBndrWith how_bound env bndr 
644   = (env { sc_subst = subst', sc_how_bound = hb_env' }, bndr')
645   where
646     (subst', bndr') = substBndr (sc_subst env) bndr
647     hb_env' = extendVarEnv (sc_how_bound env) bndr' how_bound
648
649 extendRecBndrs :: ScEnv -> [Var] -> (ScEnv, [Var])
650 extendRecBndrs env bndrs  = (env { sc_subst = subst' }, bndrs')
651                       where
652                         (subst', bndrs') = substRecBndrs (sc_subst env) bndrs
653
654 extendBndr :: ScEnv -> Var -> (ScEnv, Var)
655 extendBndr  env bndr  = (env { sc_subst = subst' }, bndr')
656                       where
657                         (subst', bndr') = substBndr (sc_subst env) bndr
658
659 extendValEnv :: ScEnv -> Id -> Maybe Value -> ScEnv
660 extendValEnv env _  Nothing   = env
661 extendValEnv env id (Just cv) = env { sc_vals = extendVarEnv (sc_vals env) id cv }
662
663 extendCaseBndrs :: ScEnv -> Id -> AltCon -> [Var] -> (ScEnv, [Var])
664 -- When we encounter
665 --      case scrut of b
666 --          C x y -> ...
667 -- we want to bind b, to (C x y)
668 -- NB1: Extends only the sc_vals part of the envt
669 -- NB2: Kill the dead-ness info on the pattern binders x,y, since
670 --      they are potentially made alive by the [b -> C x y] binding
671 extendCaseBndrs env case_bndr con alt_bndrs
672   | isDeadBinder case_bndr
673   = (env, alt_bndrs)
674   | otherwise
675   = (env1, map zap alt_bndrs)
676         -- NB: We used to bind v too, if scrut = (Var v); but
677         --     the simplifer has already done this so it seems
678         --     redundant to do so here
679         -- case scrut of
680         --      Var v  -> extendValEnv env1 v cval
681         --      _other -> env1
682  where
683    zap v | isTyCoVar v = v              -- See NB2 above
684          | otherwise = zapIdOccInfo v
685    env1 = extendValEnv env case_bndr cval
686    cval = case con of
687                 DEFAULT    -> Nothing
688                 LitAlt {}  -> Just (ConVal con [])
689                 DataAlt {} -> Just (ConVal con vanilla_args)
690                       where
691                         vanilla_args = map Type (tyConAppArgs (idType case_bndr)) ++
692                                        varsToCoreExprs alt_bndrs
693
694
695 decreaseSpecCount :: ScEnv -> Int -> ScEnv
696 -- See Note [Avoiding exponential blowup]
697 decreaseSpecCount env n_specs 
698   = env { sc_count = case sc_count env of
699                        Nothing -> Nothing
700                        Just n  -> Just (n `div` (n_specs + 1)) }
701         -- The "+1" takes account of the original function; 
702         -- See Note [Avoiding exponential blowup]
703
704 ---------------------------------------------------
705 -- See Note [SpecConstrAnnotation]
706 ignoreType    :: ScEnv -> Type   -> Bool
707 ignoreAltCon  :: ScEnv -> AltCon -> Bool
708 forceSpecBndr :: ScEnv -> Var    -> Bool
709 #ifndef GHCI
710 ignoreType    _ _ = False
711 ignoreAltCon  _ _ = False
712 forceSpecBndr _ _ = False
713
714 #else /* GHCI */
715
716 ignoreAltCon env (DataAlt dc) = ignoreTyCon env (dataConTyCon dc)
717 ignoreAltCon env (LitAlt lit) = ignoreType env (literalType lit)
718 ignoreAltCon _   DEFAULT      = panic "ignoreAltCon"  -- DEFAULT cannot be in a ConVal
719
720 ignoreType env ty
721   = case splitTyConApp_maybe ty of
722       Just (tycon, _) -> ignoreTyCon env tycon
723       _               -> False
724
725 ignoreTyCon :: ScEnv -> TyCon -> Bool
726 ignoreTyCon env tycon
727   = lookupUFM (sc_annotations env) tycon == Just NoSpecConstr
728
729 forceSpecBndr env var = forceSpecFunTy env . snd . splitForAllTys . varType $ var
730
731 forceSpecFunTy :: ScEnv -> Type -> Bool
732 forceSpecFunTy env = any (forceSpecArgTy env) . fst . splitFunTys
733
734 forceSpecArgTy :: ScEnv -> Type -> Bool
735 forceSpecArgTy env ty
736   | Just ty' <- coreView ty = forceSpecArgTy env ty'
737
738 forceSpecArgTy env ty
739   | Just (tycon, tys) <- splitTyConApp_maybe ty
740   , tycon /= funTyCon
741       = lookupUFM (sc_annotations env) tycon == Just ForceSpecConstr
742         || any (forceSpecArgTy env) tys
743
744 forceSpecArgTy _ _ = False
745 #endif /* GHCI */
746 \end{code}
747
748 Note [Avoiding exponential blowup]
749 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
750 The sc_count field of the ScEnv says how many times we are prepared to
751 duplicate a single function.  But we must take care with recursive
752 specialiations.  Consider
753
754         let $j1 = let $j2 = let $j3 = ...
755                             in 
756                             ...$j3...
757                   in 
758                   ...$j2...
759         in 
760         ...$j1...
761
762 If we specialise $j1 then in each specialisation (as well as the original)
763 we can specialise $j2, and similarly $j3.  Even if we make just *one*
764 specialisation of each, becuase we also have the original we'll get 2^n
765 copies of $j3, which is not good.
766
767 So when recursively specialising we divide the sc_count by the number of
768 copies we are making at this level, including the original.
769
770
771 %************************************************************************
772 %*                                                                      *
773 \subsection{Usage information: flows upwards}
774 %*                                                                      *
775 %************************************************************************
776
777 \begin{code}
778 data ScUsage
779    = SCU {
780         scu_calls :: CallEnv,           -- Calls
781                                         -- The functions are a subset of the 
782                                         --      RecFuns in the ScEnv
783
784         scu_occs :: !(IdEnv ArgOcc)     -- Information on argument occurrences
785      }                                  -- The domain is OutIds
786
787 type CallEnv = IdEnv [Call]
788 type Call = (ValueEnv, [CoreArg])
789         -- The arguments of the call, together with the
790         -- env giving the constructor bindings at the call site
791
792 nullUsage :: ScUsage
793 nullUsage = SCU { scu_calls = emptyVarEnv, scu_occs = emptyVarEnv }
794
795 combineCalls :: CallEnv -> CallEnv -> CallEnv
796 combineCalls = plusVarEnv_C (++)
797
798 combineUsage :: ScUsage -> ScUsage -> ScUsage
799 combineUsage u1 u2 = SCU { scu_calls = combineCalls (scu_calls u1) (scu_calls u2),
800                            scu_occs  = plusVarEnv_C combineOcc (scu_occs u1) (scu_occs u2) }
801
802 combineUsages :: [ScUsage] -> ScUsage
803 combineUsages [] = nullUsage
804 combineUsages us = foldr1 combineUsage us
805
806 lookupOcc :: ScUsage -> OutVar -> (ScUsage, ArgOcc)
807 lookupOcc (SCU { scu_calls = sc_calls, scu_occs = sc_occs }) bndr
808   = (SCU {scu_calls = sc_calls, scu_occs = delVarEnv sc_occs bndr},
809      lookupVarEnv sc_occs bndr `orElse` NoOcc)
810
811 lookupOccs :: ScUsage -> [OutVar] -> (ScUsage, [ArgOcc])
812 lookupOccs (SCU { scu_calls = sc_calls, scu_occs = sc_occs }) bndrs
813   = (SCU {scu_calls = sc_calls, scu_occs = delVarEnvList sc_occs bndrs},
814      [lookupVarEnv sc_occs b `orElse` NoOcc | b <- bndrs])
815
816 data ArgOcc = NoOcc     -- Doesn't occur at all; or a type argument
817             | UnkOcc    -- Used in some unknown way
818
819             | ScrutOcc (UniqFM [ArgOcc])        -- See Note [ScrutOcc]
820
821             | BothOcc   -- Definitely taken apart, *and* perhaps used in some other way
822
823 {-      Note  [ScrutOcc]
824
825 An occurrence of ScrutOcc indicates that the thing, or a `cast` version of the thing,
826 is *only* taken apart or applied.
827
828   Functions, literal: ScrutOcc emptyUFM
829   Data constructors:  ScrutOcc subs,
830
831 where (subs :: UniqFM [ArgOcc]) gives usage of the *pattern-bound* components,
832 The domain of the UniqFM is the Unique of the data constructor
833
834 The [ArgOcc] is the occurrences of the *pattern-bound* components 
835 of the data structure.  E.g.
836         data T a = forall b. MkT a b (b->a)
837 A pattern binds b, x::a, y::b, z::b->a, but not 'a'!
838
839 -}
840
841 instance Outputable ArgOcc where
842   ppr (ScrutOcc xs) = ptext (sLit "scrut-occ") <> ppr xs
843   ppr UnkOcc        = ptext (sLit "unk-occ")
844   ppr BothOcc       = ptext (sLit "both-occ")
845   ppr NoOcc         = ptext (sLit "no-occ")
846
847 -- Experimentally, this vesion of combineOcc makes ScrutOcc "win", so
848 -- that if the thing is scrutinised anywhere then we get to see that
849 -- in the overall result, even if it's also used in a boxed way
850 -- This might be too agressive; see Note [Reboxing] Alternative 3
851 combineOcc :: ArgOcc -> ArgOcc -> ArgOcc
852 combineOcc NoOcc         occ           = occ
853 combineOcc occ           NoOcc         = occ
854 combineOcc (ScrutOcc xs) (ScrutOcc ys) = ScrutOcc (plusUFM_C combineOccs xs ys)
855 combineOcc _occ          (ScrutOcc ys) = ScrutOcc ys
856 combineOcc (ScrutOcc xs) _occ          = ScrutOcc xs
857 combineOcc UnkOcc        UnkOcc        = UnkOcc
858 combineOcc _        _                  = BothOcc
859
860 combineOccs :: [ArgOcc] -> [ArgOcc] -> [ArgOcc]
861 combineOccs xs ys = zipWithEqual "combineOccs" combineOcc xs ys
862
863 setScrutOcc :: ScEnv -> ScUsage -> OutExpr -> ArgOcc -> ScUsage
864 -- _Overwrite_ the occurrence info for the scrutinee, if the scrutinee
865 -- is a variable, and an interesting variable
866 setScrutOcc env usg (Cast e _) occ = setScrutOcc env usg e occ
867 setScrutOcc env usg (Note _ e) occ = setScrutOcc env usg e occ
868 setScrutOcc env usg (Var v)    occ
869   | Just RecArg <- lookupHowBound env v = usg { scu_occs = extendVarEnv (scu_occs usg) v occ }
870   | otherwise                           = usg
871 setScrutOcc _env usg _other _occ        -- Catch-all
872   = usg 
873
874 conArgOccs :: ArgOcc -> AltCon -> [ArgOcc]
875 -- Find usage of components of data con; returns [UnkOcc...] if unknown
876 -- See Note [ScrutOcc] for the extra UnkOccs in the vanilla datacon case
877
878 conArgOccs (ScrutOcc fm) (DataAlt dc) 
879   | Just pat_arg_occs <- lookupUFM fm dc
880   = [UnkOcc | _ <- dataConUnivTyVars dc] ++ pat_arg_occs
881
882 conArgOccs _other _con = repeat UnkOcc
883 \end{code}
884
885 %************************************************************************
886 %*                                                                      *
887 \subsection{The main recursive function}
888 %*                                                                      *
889 %************************************************************************
890
891 The main recursive function gathers up usage information, and
892 creates specialised versions of functions.
893
894 \begin{code}
895 scExpr, scExpr' :: ScEnv -> CoreExpr -> UniqSM (ScUsage, CoreExpr)
896         -- The unique supply is needed when we invent
897         -- a new name for the specialised function and its args
898
899 scExpr env e = scExpr' env e
900
901
902 scExpr' env (Var v)     = case scSubstId env v of
903                             Var v' -> return (varUsage env v' UnkOcc, Var v')
904                             e'     -> scExpr (zapScSubst env) e'
905
906 scExpr' env (Type t)    = return (nullUsage, Type (scSubstTy env t))
907 scExpr' _   e@(Lit {})  = return (nullUsage, e)
908 scExpr' env (Note n e)  = do (usg,e') <- scExpr env e
909                              return (usg, Note n e')
910 scExpr' env (Cast e co) = do (usg, e') <- scExpr env e
911                              return (usg, Cast e' (scSubstTy env co))
912 scExpr' env e@(App _ _) = scApp env (collectArgs e)
913 scExpr' env (Lam b e)   = do let (env', b') = extendBndr env b
914                              (usg, e') <- scExpr env' e
915                              return (usg, Lam b' e')
916
917 scExpr' env (Case scrut b ty alts) 
918   = do  { (scrut_usg, scrut') <- scExpr env scrut
919         ; case isValue (sc_vals env) scrut' of
920                 Just (ConVal con args) -> sc_con_app con args scrut'
921                 _other                 -> sc_vanilla scrut_usg scrut'
922         }
923   where
924     sc_con_app con args scrut'  -- Known constructor; simplify
925         = do { let (_, bs, rhs) = findAlt con alts
926                                   `orElse` (DEFAULT, [], mkImpossibleExpr (coreAltsType alts))
927                    alt_env'  = extendScSubstList env ((b,scrut') : bs `zip` trimConArgs con args)
928              ; scExpr alt_env' rhs }
929                                 
930     sc_vanilla scrut_usg scrut' -- Normal case
931      = do { let (alt_env,b') = extendBndrWith RecArg env b
932                         -- Record RecArg for the components
933
934           ; (alt_usgs, alt_occs, alts')
935                 <- mapAndUnzip3M (sc_alt alt_env scrut' b') alts
936
937           ; let (alt_usg, b_occ) = lookupOcc (combineUsages alt_usgs) b'
938                 scrut_occ        = foldr combineOcc b_occ alt_occs
939                 scrut_usg'       = setScrutOcc env scrut_usg scrut' scrut_occ
940                 -- The combined usage of the scrutinee is given
941                 -- by scrut_occ, which is passed to scScrut, which
942                 -- in turn treats a bare-variable scrutinee specially
943
944           ; return (alt_usg `combineUsage` scrut_usg',
945                     Case scrut' b' (scSubstTy env ty) alts') }
946
947     sc_alt env _scrut' b' (con,bs,rhs)
948       = do { let (env1, bs1)  = extendBndrsWith RecArg env bs
949                  (env2, bs2) = extendCaseBndrs env1 b' con bs1
950            ; (usg,rhs') <- scExpr env2 rhs
951            ; let (usg', arg_occs) = lookupOccs usg bs2
952                  scrut_occ = case con of
953                                 DataAlt dc -> ScrutOcc (unitUFM dc arg_occs)
954                                 _          -> ScrutOcc emptyUFM
955            ; return (usg', scrut_occ, (con, bs2, rhs')) }
956
957 scExpr' env (Let (NonRec bndr rhs) body)
958   | isTyCoVar bndr      -- Type-lets may be created by doBeta
959   = scExpr' (extendScSubst env bndr rhs) body
960
961   | otherwise   
962   = do  { let (body_env, bndr') = extendBndr env bndr
963         ; (rhs_usg, rhs_info) <- scRecRhs env (bndr',rhs)
964
965         ; let body_env2 = extendHowBound body_env [bndr'] RecFun
966                                    -- Note [Local let bindings]
967               RI _ rhs' _ _ _ = rhs_info
968               body_env3 = extendValEnv body_env2 bndr' (isValue (sc_vals env) rhs')
969
970         ; (body_usg, body') <- scExpr body_env3 body
971
972           -- NB: We don't use the ForceSpecConstr mechanism (see
973           -- Note [Forcing specialisation]) for non-recursive bindings
974           -- at the moment. I'm not sure if this is the right thing to do.
975         ; let force_spec = False
976         ; (spec_usg, specs) <- specialise env force_spec 
977                                           (scu_calls body_usg) 
978                                           rhs_info
979                                           (SI [] 0 (Just rhs_usg))
980
981         ; return (body_usg { scu_calls = scu_calls body_usg `delVarEnv` bndr' } 
982                     `combineUsage` spec_usg,
983                   mkLets [NonRec b r | (b,r) <- specInfoBinds rhs_info specs] body')
984         }
985
986
987 -- A *local* recursive group: see Note [Local recursive groups]
988 scExpr' env (Let (Rec prs) body)
989   = do  { let (bndrs,rhss) = unzip prs
990               (rhs_env1,bndrs') = extendRecBndrs env bndrs
991               rhs_env2 = extendHowBound rhs_env1 bndrs' RecFun
992               force_spec = any (forceSpecBndr env) bndrs'
993                 -- Note [Forcing specialisation]
994
995         ; (rhs_usgs, rhs_infos) <- mapAndUnzipM (scRecRhs rhs_env2) (bndrs' `zip` rhss)
996         ; (body_usg, body')     <- scExpr rhs_env2 body
997
998         -- NB: start specLoop from body_usg
999         ; (spec_usg, specs) <- specLoop rhs_env2 force_spec
1000                                         (scu_calls body_usg) rhs_infos nullUsage
1001                                         [SI [] 0 (Just usg) | usg <- rhs_usgs]
1002                 -- Do not unconditionally use rhs_usgs. 
1003                 -- Instead use them only if we find an unspecialised call
1004                 -- See Note [Local recursive groups]
1005
1006         ; let all_usg = spec_usg `combineUsage` body_usg
1007               bind'   = Rec (concat (zipWith specInfoBinds rhs_infos specs))
1008
1009         ; return (all_usg { scu_calls = scu_calls all_usg `delVarEnvList` bndrs' },
1010                   Let bind' body') }
1011 \end{code}
1012
1013 Note [Local let bindings]
1014 ~~~~~~~~~~~~~~~~~~~~~~~~~
1015 It is not uncommon to find this
1016
1017    let $j = \x. <blah> in ...$j True...$j True...
1018
1019 Here $j is an arbitrary let-bound function, but it often comes up for
1020 join points.  We might like to specialise $j for its call patterns.
1021 Notice the difference from a letrec, where we look for call patterns
1022 in the *RHS* of the function.  Here we look for call patterns in the
1023 *body* of the let.
1024
1025 At one point I predicated this on the RHS mentioning the outer
1026 recursive function, but that's not essential and might even be
1027 harmful.  I'm not sure.
1028
1029
1030 \begin{code}
1031 scApp :: ScEnv -> (InExpr, [InExpr]) -> UniqSM (ScUsage, CoreExpr)
1032
1033 scApp env (Var fn, args)        -- Function is a variable
1034   = ASSERT( not (null args) )
1035     do  { args_w_usgs <- mapM (scExpr env) args
1036         ; let (arg_usgs, args') = unzip args_w_usgs
1037               arg_usg = combineUsages arg_usgs
1038         ; case scSubstId env fn of
1039             fn'@(Lam {}) -> scExpr (zapScSubst env) (doBeta fn' args')
1040                         -- Do beta-reduction and try again
1041
1042             Var fn' -> return (arg_usg `combineUsage` fn_usg, mkApps (Var fn') args')
1043                 where
1044                   fn_usg = case lookupHowBound env fn' of
1045                                 Just RecFun -> SCU { scu_calls = unitVarEnv fn' [(sc_vals env, args')], 
1046                                                      scu_occs  = emptyVarEnv }
1047                                 Just RecArg -> SCU { scu_calls = emptyVarEnv,
1048                                                      scu_occs  = unitVarEnv fn' (ScrutOcc emptyUFM) }
1049                                 Nothing     -> nullUsage
1050
1051
1052             other_fn' -> return (arg_usg, mkApps other_fn' args') }
1053                 -- NB: doing this ignores any usage info from the substituted
1054                 --     function, but I don't think that matters.  If it does
1055                 --     we can fix it.
1056   where
1057     doBeta :: OutExpr -> [OutExpr] -> OutExpr
1058     -- ToDo: adjust for System IF
1059     doBeta (Lam bndr body) (arg : args) = Let (NonRec bndr arg) (doBeta body args)
1060     doBeta fn              args         = mkApps fn args
1061
1062 -- The function is almost always a variable, but not always.  
1063 -- In particular, if this pass follows float-in,
1064 -- which it may, we can get 
1065 --      (let f = ...f... in f) arg1 arg2
1066 scApp env (other_fn, args)
1067   = do  { (fn_usg,   fn')   <- scExpr env other_fn
1068         ; (arg_usgs, args') <- mapAndUnzipM (scExpr env) args
1069         ; return (combineUsages arg_usgs `combineUsage` fn_usg, mkApps fn' args') }
1070
1071 ----------------------
1072 scTopBind :: ScEnv -> CoreBind -> UniqSM (ScEnv, CoreBind)
1073 scTopBind env (Rec prs)
1074   | Just threshold <- sc_size env
1075   , not force_spec
1076   , not (all (couldBeSmallEnoughToInline threshold) rhss)
1077                 -- No specialisation
1078   = do  { let (rhs_env,bndrs') = extendRecBndrs env bndrs
1079         ; (_, rhss') <- mapAndUnzipM (scExpr rhs_env) rhss
1080         ; return (rhs_env, Rec (bndrs' `zip` rhss')) }
1081   | otherwise   -- Do specialisation
1082   = do  { let (rhs_env1,bndrs') = extendRecBndrs env bndrs
1083               rhs_env2 = extendHowBound rhs_env1 bndrs' RecFun
1084
1085         ; (rhs_usgs, rhs_infos) <- mapAndUnzipM (scRecRhs rhs_env2) (bndrs' `zip` rhss)
1086         ; let rhs_usg = combineUsages rhs_usgs
1087
1088         ; (_, specs) <- specLoop rhs_env2 force_spec
1089                                  (scu_calls rhs_usg) rhs_infos nullUsage
1090                                  [SI [] 0 Nothing | _ <- bndrs]
1091
1092         ; return (rhs_env1,  -- For the body of the letrec, delete the RecFun business
1093                   Rec (concat (zipWith specInfoBinds rhs_infos specs))) }
1094   where
1095     (bndrs,rhss) = unzip prs
1096     force_spec = any (forceSpecBndr env) bndrs
1097       -- Note [Forcing specialisation]
1098
1099 scTopBind env (NonRec bndr rhs)
1100   = do  { (_, rhs') <- scExpr env rhs
1101         ; let (env1, bndr') = extendBndr env bndr
1102               env2 = extendValEnv env1 bndr' (isValue (sc_vals env) rhs')
1103         ; return (env2, NonRec bndr' rhs') }
1104
1105 ----------------------
1106 scRecRhs :: ScEnv -> (OutId, InExpr) -> UniqSM (ScUsage, RhsInfo)
1107 scRecRhs env (bndr,rhs)
1108   = do  { let (arg_bndrs,body) = collectBinders rhs
1109               (body_env, arg_bndrs') = extendBndrsWith RecArg env arg_bndrs
1110         ; (body_usg, body') <- scExpr body_env body
1111         ; let (rhs_usg, arg_occs) = lookupOccs body_usg arg_bndrs'
1112         ; return (rhs_usg, RI bndr (mkLams arg_bndrs' body')
1113                                    arg_bndrs body arg_occs) }
1114                 -- The arg_occs says how the visible,
1115                 -- lambda-bound binders of the RHS are used
1116                 -- (including the TyVar binders)
1117                 -- Two pats are the same if they match both ways
1118
1119 ----------------------
1120 specInfoBinds :: RhsInfo -> SpecInfo -> [(Id,CoreExpr)]
1121 specInfoBinds (RI fn new_rhs _ _ _) (SI specs _ _)
1122   = [(id,rhs) | OS _ _ id rhs <- specs] ++ 
1123     [(fn `addIdSpecialisations` rules, new_rhs)]
1124   where
1125     rules = [r | OS _ r _ _ <- specs]
1126
1127 ----------------------
1128 varUsage :: ScEnv -> OutVar -> ArgOcc -> ScUsage
1129 varUsage env v use 
1130   | Just RecArg <- lookupHowBound env v = SCU { scu_calls = emptyVarEnv 
1131                                               , scu_occs = unitVarEnv v use }
1132   | otherwise                           = nullUsage
1133 \end{code}
1134
1135
1136 %************************************************************************
1137 %*                                                                      *
1138                 The specialiser itself
1139 %*                                                                      *
1140 %************************************************************************
1141
1142 \begin{code}
1143 data RhsInfo = RI OutId                 -- The binder
1144                   OutExpr               -- The new RHS
1145                   [InVar] InExpr        -- The *original* RHS (\xs.body)
1146                                         --   Note [Specialise original body]
1147                   [ArgOcc]              -- Info on how the xs occur in body
1148
1149 data SpecInfo = SI [OneSpec]            -- The specialisations we have generated
1150
1151                    Int                  -- Length of specs; used for numbering them
1152
1153                    (Maybe ScUsage)      -- Nothing => we have generated specialisations
1154                                         --            from calls in the *original* RHS
1155                                         -- Just cs => we haven't, and this is the usage
1156                                         --            of the original RHS
1157                                         -- See Note [Local recursive groups]
1158
1159         -- One specialisation: Rule plus definition
1160 data OneSpec  = OS CallPat              -- Call pattern that generated this specialisation
1161                    CoreRule             -- Rule connecting original id with the specialisation
1162                    OutId OutExpr        -- Spec id + its rhs
1163
1164
1165 specLoop :: ScEnv
1166          -> Bool                                -- force specialisation?
1167                                                 -- Note [Forcing specialisation]
1168          -> CallEnv
1169          -> [RhsInfo]
1170          -> ScUsage -> [SpecInfo]               -- One per binder; acccumulating parameter
1171          -> UniqSM (ScUsage, [SpecInfo])        -- ...ditto...
1172 specLoop env force_spec all_calls rhs_infos usg_so_far specs_so_far
1173   = do  { specs_w_usg <- zipWithM (specialise env force_spec all_calls) rhs_infos specs_so_far
1174         ; let (new_usg_s, all_specs) = unzip specs_w_usg
1175               new_usg   = combineUsages new_usg_s
1176               new_calls = scu_calls new_usg
1177               all_usg   = usg_so_far `combineUsage` new_usg
1178         ; if isEmptyVarEnv new_calls then
1179                 return (all_usg, all_specs) 
1180           else 
1181                 specLoop env force_spec new_calls rhs_infos all_usg all_specs }
1182
1183 specialise 
1184    :: ScEnv
1185    -> Bool                              -- force specialisation?
1186                                         --   Note [Forcing specialisation]
1187    -> CallEnv                           -- Info on calls
1188    -> RhsInfo
1189    -> SpecInfo                          -- Original RHS plus patterns dealt with
1190    -> UniqSM (ScUsage, SpecInfo)        -- New specialised versions and their usage
1191
1192 -- Note: the rhs here is the optimised version of the original rhs
1193 -- So when we make a specialised copy of the RHS, we're starting
1194 -- from an RHS whose nested functions have been optimised already.
1195
1196 specialise env force_spec bind_calls (RI fn _ arg_bndrs body arg_occs) 
1197                           spec_info@(SI specs spec_count mb_unspec)
1198   | not (isBottomingId fn)      -- Note [Do not specialise diverging functions]
1199   , not (isNeverActive (idInlineActivation fn)) -- See Note [Transfer activation]
1200   , notNull arg_bndrs           -- Only specialise functions
1201   , Just all_calls <- lookupVarEnv bind_calls fn
1202   = do  { (boring_call, pats) <- callsToPats env specs arg_occs all_calls
1203 --      ; pprTrace "specialise" (vcat [ ppr fn <+> text "with" <+> int (length pats) <+> text "good patterns"
1204 --                                      , text "arg_occs" <+> ppr arg_occs
1205 --                                    , text "calls" <+> ppr all_calls
1206 --                                    , text "good pats" <+> ppr pats])  $
1207 --        return ()
1208
1209                 -- Bale out if too many specialisations
1210         ; let n_pats      = length pats
1211               spec_count' = n_pats + spec_count
1212         ; case sc_count env of
1213             Just max | not force_spec && spec_count' > max
1214                 -> pprTrace "SpecConstr" msg $  
1215                    return (nullUsage, spec_info)
1216                 where
1217                    msg = vcat [ sep [ ptext (sLit "Function") <+> quotes (ppr fn)
1218                                     , nest 2 (ptext (sLit "has") <+> 
1219                                               speakNOf spec_count' (ptext (sLit "call pattern")) <> comma <+>
1220                                               ptext (sLit "but the limit is") <+> int max) ]
1221                               , ptext (sLit "Use -fspec-constr-count=n to set the bound")
1222                               , extra ]
1223                    extra | not opt_PprStyle_Debug = ptext (sLit "Use -dppr-debug to see specialisations")
1224                          | otherwise = ptext (sLit "Specialisations:") <+> ppr (pats ++ [p | OS p _ _ _ <- specs])
1225
1226             _normal_case -> do {
1227
1228           let spec_env = decreaseSpecCount env n_pats
1229         ; (spec_usgs, new_specs) <- mapAndUnzipM (spec_one spec_env fn arg_bndrs body)
1230                                                  (pats `zip` [spec_count..])
1231                 -- See Note [Specialise original body]
1232
1233         ; let spec_usg = combineUsages spec_usgs
1234               (new_usg, mb_unspec')
1235                   = case mb_unspec of
1236                       Just rhs_usg | boring_call -> (spec_usg `combineUsage` rhs_usg, Nothing)
1237                       _                          -> (spec_usg,                      mb_unspec)
1238             
1239         ; return (new_usg, SI (new_specs ++ specs) spec_count' mb_unspec') } }
1240   | otherwise
1241   = return (nullUsage, spec_info)               -- The boring case
1242
1243
1244 ---------------------
1245 spec_one :: ScEnv
1246          -> OutId       -- Function
1247          -> [InVar]     -- Lambda-binders of RHS; should match patterns
1248          -> InExpr      -- Body of the original function
1249          -> (CallPat, Int)
1250          -> UniqSM (ScUsage, OneSpec)   -- Rule and binding
1251
1252 -- spec_one creates a specialised copy of the function, together
1253 -- with a rule for using it.  I'm very proud of how short this
1254 -- function is, considering what it does :-).
1255
1256 {- 
1257   Example
1258   
1259      In-scope: a, x::a   
1260      f = /\b \y::[(a,b)] -> ....f (b,c) ((:) (a,(b,c)) (x,v) (h w))...
1261           [c::*, v::(b,c) are presumably bound by the (...) part]
1262   ==>
1263      f_spec = /\ b c \ v::(b,c) hw::[(a,(b,c))] ->
1264                   (...entire body of f...) [b -> (b,c), 
1265                                             y -> ((:) (a,(b,c)) (x,v) hw)]
1266   
1267      RULE:  forall b::* c::*,           -- Note, *not* forall a, x
1268                    v::(b,c),
1269                    hw::[(a,(b,c))] .
1270   
1271             f (b,c) ((:) (a,(b,c)) (x,v) hw) = f_spec b c v hw
1272 -}
1273
1274 spec_one env fn arg_bndrs body (call_pat@(qvars, pats), rule_number)
1275   = do  { spec_uniq <- getUniqueUs
1276         ; let spec_env = extendScSubstList (extendScInScope env qvars)
1277                                            (arg_bndrs `zip` pats)
1278               fn_name    = idName fn
1279               fn_loc     = nameSrcSpan fn_name
1280               spec_occ   = mkSpecOcc (nameOccName fn_name)
1281               rule_name  = mkFastString ("SC:" ++ showSDoc (ppr fn <> int rule_number))
1282               spec_name  = mkInternalName spec_uniq spec_occ fn_loc
1283 --      ; pprTrace "{spec_one" (ppr (sc_count env) <+> ppr fn <+> ppr pats <+> text "-->" <+> ppr spec_name) $ 
1284 --        return ()
1285
1286         -- Specialise the body
1287         ; (spec_usg, spec_body) <- scExpr spec_env body
1288
1289 --      ; pprTrace "done spec_one}" (ppr fn) $ 
1290 --        return ()
1291
1292                 -- And build the results
1293         ; let spec_id = mkLocalId spec_name (mkPiTypes spec_lam_args body_ty) 
1294                              `setIdStrictness` spec_str         -- See Note [Transfer strictness]
1295                              `setIdArity` count isId spec_lam_args
1296               spec_str   = calcSpecStrictness fn spec_lam_args pats
1297               (spec_lam_args, spec_call_args) = mkWorkerArgs qvars body_ty
1298                 -- Usual w/w hack to avoid generating 
1299                 -- a spec_rhs of unlifted type and no args
1300
1301               spec_rhs   = mkLams spec_lam_args spec_body
1302               body_ty    = exprType spec_body
1303               rule_rhs   = mkVarApps (Var spec_id) spec_call_args
1304               inline_act = idInlineActivation fn
1305               rule       = mkRule True {- Auto -} True {- Local -}
1306                                   rule_name inline_act fn_name qvars pats rule_rhs
1307                            -- See Note [Transfer activation]
1308         ; return (spec_usg, OS call_pat rule spec_id spec_rhs) }
1309
1310 calcSpecStrictness :: Id                     -- The original function
1311                    -> [Var] -> [CoreExpr]    -- Call pattern
1312                    -> StrictSig              -- Strictness of specialised thing
1313 -- See Note [Transfer strictness]
1314 calcSpecStrictness fn qvars pats
1315   = StrictSig (mkTopDmdType spec_dmds TopRes)
1316   where
1317     spec_dmds = [ lookupVarEnv dmd_env qv `orElse` lazyDmd | qv <- qvars, isId qv ]
1318     StrictSig (DmdType _ dmds _) = idStrictness fn
1319
1320     dmd_env = go emptyVarEnv dmds pats
1321
1322     go env ds (Type {} : pats) = go env ds pats
1323     go env (d:ds) (pat : pats) = go (go_one env d pat) ds pats
1324     go env _      _            = env
1325
1326     go_one env d   (Var v) = extendVarEnv_C both env v d
1327     go_one env (Box d)   e = go_one env d e
1328     go_one env (Eval (Prod ds)) e 
1329            | (Var _, args) <- collectArgs e = go env ds args
1330     go_one env _         _ = env
1331
1332 \end{code}
1333
1334 Note [Specialise original body]
1335 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1336 The RhsInfo for a binding keeps the *original* body of the binding.  We
1337 must specialise that, *not* the result of applying specExpr to the RHS
1338 (which is also kept in RhsInfo). Otherwise we end up specialising a
1339 specialised RHS, and that can lead directly to exponential behaviour.
1340
1341 Note [Transfer activation]
1342 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1343   This note is for SpecConstr, but exactly the same thing
1344   happens in the overloading specialiser; see
1345   Note [Auto-specialisation and RULES] in Specialise.
1346
1347 In which phase should the specialise-constructor rules be active?
1348 Originally I made them always-active, but Manuel found that this
1349 defeated some clever user-written rules.  Then I made them active only
1350 in Phase 0; after all, currently, the specConstr transformation is
1351 only run after the simplifier has reached Phase 0, but that meant
1352 that specialisations didn't fire inside wrappers; see test
1353 simplCore/should_compile/spec-inline.
1354
1355 So now I just use the inline-activation of the parent Id, as the
1356 activation for the specialiation RULE, just like the main specialiser;
1357
1358 This in turn means there is no point in specialising NOINLINE things,
1359 so we test for that.
1360
1361 Note [Transfer strictness]
1362 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1363 We must transfer strictness information from the original function to
1364 the specialised one.  Suppose, for example
1365
1366   f has strictness     SS
1367         and a RULE     f (a:as) b = f_spec a as b
1368
1369 Now we want f_spec to have strictess  LLS, otherwise we'll use call-by-need
1370 when calling f_spec instead of call-by-value.  And that can result in 
1371 unbounded worsening in space (cf the classic foldl vs foldl')
1372
1373 See Trac #3437 for a good example.
1374
1375 The function calcSpecStrictness performs the calculation.
1376
1377
1378 %************************************************************************
1379 %*                                                                      *
1380 \subsection{Argument analysis}
1381 %*                                                                      *
1382 %************************************************************************
1383
1384 This code deals with analysing call-site arguments to see whether
1385 they are constructor applications.
1386
1387
1388 \begin{code}
1389 type CallPat = ([Var], [CoreExpr])      -- Quantified variables and arguments
1390
1391
1392 callsToPats :: ScEnv -> [OneSpec] -> [ArgOcc] -> [Call] -> UniqSM (Bool, [CallPat])
1393         -- Result has no duplicate patterns, 
1394         -- nor ones mentioned in done_pats
1395         -- Bool indicates that there was at least one boring pattern
1396 callsToPats env done_specs bndr_occs calls
1397   = do  { mb_pats <- mapM (callToPats env bndr_occs) calls
1398
1399         ; let good_pats :: [([Var], [CoreArg])]
1400               good_pats = catMaybes mb_pats
1401               done_pats = [p | OS p _ _ _ <- done_specs] 
1402               is_done p = any (samePat p) done_pats
1403
1404         ; return (any isNothing mb_pats, 
1405                   filterOut is_done (nubBy samePat good_pats)) }
1406
1407 callToPats :: ScEnv -> [ArgOcc] -> Call -> UniqSM (Maybe CallPat)
1408         -- The [Var] is the variables to quantify over in the rule
1409         --      Type variables come first, since they may scope 
1410         --      over the following term variables
1411         -- The [CoreExpr] are the argument patterns for the rule
1412 callToPats env bndr_occs (con_env, args)
1413   | length args < length bndr_occs      -- Check saturated
1414   = return Nothing
1415   | otherwise
1416   = do  { let in_scope = substInScope (sc_subst env)
1417         ; prs <- argsToPats env in_scope con_env (args `zip` bndr_occs)
1418         ; let (interesting_s, pats) = unzip prs
1419               pat_fvs = varSetElems (exprsFreeVars pats)
1420               qvars   = filterOut (`elemInScopeSet` in_scope) pat_fvs
1421                 -- Quantify over variables that are not in sccpe
1422                 -- at the call site
1423                 -- See Note [Shadowing] at the top
1424                 
1425               (tvs, ids) = partition isTyCoVar qvars
1426               qvars'     = tvs ++ ids
1427                 -- Put the type variables first; the type of a term
1428                 -- variable may mention a type variable
1429
1430         ; -- pprTrace "callToPats"  (ppr args $$ ppr prs $$ ppr bndr_occs) $
1431           if or interesting_s
1432           then return (Just (qvars', pats))
1433           else return Nothing }
1434
1435     -- argToPat takes an actual argument, and returns an abstracted
1436     -- version, consisting of just the "constructor skeleton" of the
1437     -- argument, with non-constructor sub-expression replaced by new
1438     -- placeholder variables.  For example:
1439     --    C a (D (f x) (g y))  ==>  C p1 (D p2 p3)
1440
1441 argToPat :: ScEnv
1442          -> InScopeSet                  -- What's in scope at the fn defn site
1443          -> ValueEnv                    -- ValueEnv at the call site
1444          -> CoreArg                     -- A call arg (or component thereof)
1445          -> ArgOcc
1446          -> UniqSM (Bool, CoreArg)
1447 -- Returns (interesting, pat), 
1448 -- where pat is the pattern derived from the argument
1449 --            intersting=True if the pattern is non-trivial (not a variable or type)
1450 -- E.g.         x:xs         --> (True, x:xs)
1451 --              f xs         --> (False, w)        where w is a fresh wildcard
1452 --              (f xs, 'c')  --> (True, (w, 'c'))  where w is a fresh wildcard
1453 --              \x. x+y      --> (True, \x. x+y)
1454 --              lvl7         --> (True, lvl7)      if lvl7 is bound 
1455 --                                                 somewhere further out
1456
1457 argToPat _env _in_scope _val_env arg@(Type {}) _arg_occ
1458   = return (False, arg)
1459
1460 argToPat env in_scope val_env (Note _ arg) arg_occ
1461   = argToPat env in_scope val_env arg arg_occ
1462         -- Note [Notes in call patterns]
1463         -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1464         -- Ignore Notes.  In particular, we want to ignore any InlineMe notes
1465         -- Perhaps we should not ignore profiling notes, but I'm going to
1466         -- ride roughshod over them all for now.
1467         --- See Note [Notes in RULE matching] in Rules
1468
1469 argToPat env in_scope val_env (Let _ arg) arg_occ
1470   = argToPat env in_scope val_env arg arg_occ
1471         -- See Note [Matching lets] in Rule.lhs
1472         -- Look through let expressions
1473         -- e.g.         f (let v = rhs in (v,w))
1474         -- Here we can specialise for f (v,w)
1475         -- because the rule-matcher will look through the let.
1476
1477 {- Disabled; see Note [Matching cases] in Rule.lhs
1478 argToPat env in_scope val_env (Case scrut _ _ [(_, _, rhs)]) arg_occ
1479   | exprOkForSpeculation scrut  -- See Note [Matching cases] in Rule.hhs
1480   = argToPat env in_scope val_env rhs arg_occ
1481 -}
1482
1483 argToPat env in_scope val_env (Cast arg co) arg_occ
1484   | not (ignoreType env ty2)
1485   = do  { (interesting, arg') <- argToPat env in_scope val_env arg arg_occ
1486         ; if not interesting then 
1487                 wildCardPat ty2
1488           else do
1489         { -- Make a wild-card pattern for the coercion
1490           uniq <- getUniqueUs
1491         ; let co_name = mkSysTvName uniq (fsLit "sg")
1492               co_var = mkCoVar co_name (mkCoKind ty1 ty2)
1493         ; return (interesting, Cast arg' (mkTyVarTy co_var)) } }
1494   where
1495     (ty1, ty2) = coercionKind co
1496
1497     
1498
1499 {-      Disabling lambda specialisation for now
1500         It's fragile, and the spec_loop can be infinite
1501 argToPat in_scope val_env arg arg_occ
1502   | is_value_lam arg
1503   = return (True, arg)
1504   where
1505     is_value_lam (Lam v e)      -- Spot a value lambda, even if 
1506         | isId v = True         -- it is inside a type lambda
1507         | otherwise = is_value_lam e
1508     is_value_lam other = False
1509 -}
1510
1511   -- Check for a constructor application
1512   -- NB: this *precedes* the Var case, so that we catch nullary constrs
1513 argToPat env in_scope val_env arg arg_occ
1514   | Just (ConVal dc args) <- isValue val_env arg
1515   , not (ignoreAltCon env dc)
1516   , case arg_occ of
1517         ScrutOcc _ -> True              -- Used only by case scrutinee
1518         BothOcc    -> case arg of       -- Used elsewhere
1519                         App {} -> True  --     see Note [Reboxing]
1520                         _other -> False
1521         _other     -> False     -- No point; the arg is not decomposed
1522   = do  { args' <- argsToPats env in_scope val_env (args `zip` conArgOccs arg_occ dc)
1523         ; return (True, mk_con_app dc (map snd args')) }
1524
1525   -- Check if the argument is a variable that 
1526   -- is in scope at the function definition site
1527   -- It's worth specialising on this if
1528   --    (a) it's used in an interesting way in the body
1529   --    (b) we know what its value is
1530 argToPat env in_scope val_env (Var v) arg_occ
1531   | case arg_occ of { UnkOcc -> False; _other -> True },        -- (a)
1532     is_value,                                                   -- (b)
1533     not (ignoreType env (varType v))
1534   = return (True, Var v)
1535   where
1536     is_value 
1537         | isLocalId v = v `elemInScopeSet` in_scope 
1538                         && isJust (lookupVarEnv val_env v)
1539                 -- Local variables have values in val_env
1540         | otherwise   = isValueUnfolding (idUnfolding v)
1541                 -- Imports have unfoldings
1542
1543 --      I'm really not sure what this comment means
1544 --      And by not wild-carding we tend to get forall'd 
1545 --      variables that are in soope, which in turn can
1546 --      expose the weakness in let-matching
1547 --      See Note [Matching lets] in Rules
1548
1549   -- Check for a variable bound inside the function. 
1550   -- Don't make a wild-card, because we may usefully share
1551   --    e.g.  f a = let x = ... in f (x,x)
1552   -- NB: this case follows the lambda and con-app cases!!
1553 -- argToPat _in_scope _val_env (Var v) _arg_occ
1554 --   = return (False, Var v)
1555         -- SLPJ : disabling this to avoid proliferation of versions
1556         -- also works badly when thinking about seeding the loop
1557         -- from the body of the let
1558         --       f x y = letrec g z = ... in g (x,y)
1559         -- We don't want to specialise for that *particular* x,y
1560
1561   -- The default case: make a wild-card
1562 argToPat _env _in_scope _val_env arg _arg_occ
1563   = wildCardPat (exprType arg)
1564
1565 wildCardPat :: Type -> UniqSM (Bool, CoreArg)
1566 wildCardPat ty = do { uniq <- getUniqueUs
1567                     ; let id = mkSysLocal (fsLit "sc") uniq ty
1568                     ; return (False, Var id) }
1569
1570 argsToPats :: ScEnv -> InScopeSet -> ValueEnv
1571            -> [(CoreArg, ArgOcc)]
1572            -> UniqSM [(Bool, CoreArg)]
1573 argsToPats env in_scope val_env args
1574   = mapM do_one args
1575   where
1576     do_one (arg,occ) = argToPat env in_scope val_env arg occ
1577 \end{code}
1578
1579
1580 \begin{code}
1581 isValue :: ValueEnv -> CoreExpr -> Maybe Value
1582 isValue _env (Lit lit)
1583   = Just (ConVal (LitAlt lit) [])
1584
1585 isValue env (Var v)
1586   | Just stuff <- lookupVarEnv env v
1587   = Just stuff  -- You might think we could look in the idUnfolding here
1588                 -- but that doesn't take account of which branch of a 
1589                 -- case we are in, which is the whole point
1590
1591   | not (isLocalId v) && isCheapUnfolding unf
1592   = isValue env (unfoldingTemplate unf)
1593   where
1594     unf = idUnfolding v
1595         -- However we do want to consult the unfolding 
1596         -- as well, for let-bound constructors!
1597
1598 isValue env (Lam b e)
1599   | isTyCoVar b = case isValue env e of
1600                   Just _  -> Just LambdaVal
1601                   Nothing -> Nothing
1602   | otherwise = Just LambdaVal
1603
1604 isValue _env expr       -- Maybe it's a constructor application
1605   | (Var fun, args) <- collectArgs expr
1606   = case isDataConWorkId_maybe fun of
1607
1608         Just con | args `lengthAtLeast` dataConRepArity con 
1609                 -- Check saturated; might be > because the 
1610                 --                  arity excludes type args
1611                 -> Just (ConVal (DataAlt con) args)
1612
1613         _other | valArgCount args < idArity fun
1614                 -- Under-applied function
1615                -> Just LambdaVal        -- Partial application
1616
1617         _other -> Nothing
1618
1619 isValue _env _expr = Nothing
1620
1621 mk_con_app :: AltCon -> [CoreArg] -> CoreExpr
1622 mk_con_app (LitAlt lit)  []   = Lit lit
1623 mk_con_app (DataAlt con) args = mkConApp con args
1624 mk_con_app _other _args = panic "SpecConstr.mk_con_app"
1625
1626 samePat :: CallPat -> CallPat -> Bool
1627 samePat (vs1, as1) (vs2, as2)
1628   = all2 same as1 as2
1629   where
1630     same (Var v1) (Var v2) 
1631         | v1 `elem` vs1 = v2 `elem` vs2
1632         | v2 `elem` vs2 = False
1633         | otherwise     = v1 == v2
1634
1635     same (Lit l1)    (Lit l2)    = l1==l2
1636     same (App f1 a1) (App f2 a2) = same f1 f2 && same a1 a2
1637
1638     same (Type {}) (Type {}) = True     -- Note [Ignore type differences]
1639     same (Note _ e1) e2 = same e1 e2    -- Ignore casts and notes
1640     same (Cast e1 _) e2 = same e1 e2
1641     same e1 (Note _ e2) = same e1 e2
1642     same e1 (Cast e2 _) = same e1 e2
1643
1644     same e1 e2 = WARN( bad e1 || bad e2, ppr e1 $$ ppr e2) 
1645                  False  -- Let, lambda, case should not occur
1646     bad (Case {}) = True
1647     bad (Let {})  = True
1648     bad (Lam {})  = True
1649     bad _other    = False
1650 \end{code}
1651
1652 Note [Ignore type differences]
1653 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1654 We do not want to generate specialisations where the call patterns
1655 differ only in their type arguments!  Not only is it utterly useless,
1656 but it also means that (with polymorphic recursion) we can generate
1657 an infinite number of specialisations. Example is Data.Sequence.adjustTree, 
1658 I think.
1659