f18c8f950aeb6dead2fd16c78555f45f47aff101
[ghc-hetmet.git] / compiler / specialise / Specialise.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[Specialise]{Stamping out overloading, and (optionally) polymorphism}
5
6 \begin{code}
7 module Specialise ( specProgram ) where
8
9 #include "HsVersions.h"
10
11 import Id
12 import TcType
13 import CoreSubst 
14 import CoreUnfold       ( mkUnfolding, mkInlineRule )
15 import VarSet
16 import VarEnv
17 import CoreSyn
18 import Rules
19 import CoreUtils        ( exprIsTrivial, applyTypeToArgs, mkPiTypes )
20 import CoreFVs          ( exprFreeVars, exprsFreeVars, idFreeVars )
21 import UniqSupply       ( UniqSupply, UniqSM, initUs_, MonadUnique(..) )
22 import Name
23 import MkId             ( voidArgId, realWorldPrimId )
24 import FiniteMap
25 import Maybes           ( catMaybes, isJust )
26 import BasicTypes       ( isNeverActive, inlinePragmaActivation )
27 import Bag
28 import Util
29 import Outputable
30 import FastString
31
32 \end{code}
33
34 %************************************************************************
35 %*                                                                      *
36 \subsection[notes-Specialise]{Implementation notes [SLPJ, Aug 18 1993]}
37 %*                                                                      *
38 %************************************************************************
39
40 These notes describe how we implement specialisation to eliminate
41 overloading.
42
43 The specialisation pass works on Core
44 syntax, complete with all the explicit dictionary application,
45 abstraction and construction as added by the type checker.  The
46 existing type checker remains largely as it is.
47
48 One important thought: the {\em types} passed to an overloaded
49 function, and the {\em dictionaries} passed are mutually redundant.
50 If the same function is applied to the same type(s) then it is sure to
51 be applied to the same dictionary(s)---or rather to the same {\em
52 values}.  (The arguments might look different but they will evaluate
53 to the same value.)
54
55 Second important thought: we know that we can make progress by
56 treating dictionary arguments as static and worth specialising on.  So
57 we can do without binding-time analysis, and instead specialise on
58 dictionary arguments and no others.
59
60 The basic idea
61 ~~~~~~~~~~~~~~
62 Suppose we have
63
64         let f = <f_rhs>
65         in <body>
66
67 and suppose f is overloaded.
68
69 STEP 1: CALL-INSTANCE COLLECTION
70
71 We traverse <body>, accumulating all applications of f to types and
72 dictionaries.
73
74 (Might there be partial applications, to just some of its types and
75 dictionaries?  In principle yes, but in practice the type checker only
76 builds applications of f to all its types and dictionaries, so partial
77 applications could only arise as a result of transformation, and even
78 then I think it's unlikely.  In any case, we simply don't accumulate such
79 partial applications.)
80
81
82 STEP 2: EQUIVALENCES
83
84 So now we have a collection of calls to f:
85         f t1 t2 d1 d2
86         f t3 t4 d3 d4
87         ...
88 Notice that f may take several type arguments.  To avoid ambiguity, we
89 say that f is called at type t1/t2 and t3/t4.
90
91 We take equivalence classes using equality of the *types* (ignoring
92 the dictionary args, which as mentioned previously are redundant).
93
94 STEP 3: SPECIALISATION
95
96 For each equivalence class, choose a representative (f t1 t2 d1 d2),
97 and create a local instance of f, defined thus:
98
99         f@t1/t2 = <f_rhs> t1 t2 d1 d2
100
101 f_rhs presumably has some big lambdas and dictionary lambdas, so lots
102 of simplification will now result.  However we don't actually *do* that
103 simplification.  Rather, we leave it for the simplifier to do.  If we
104 *did* do it, though, we'd get more call instances from the specialised
105 RHS.  We can work out what they are by instantiating the call-instance
106 set from f's RHS with the types t1, t2.
107
108 Add this new id to f's IdInfo, to record that f has a specialised version.
109
110 Before doing any of this, check that f's IdInfo doesn't already
111 tell us about an existing instance of f at the required type/s.
112 (This might happen if specialisation was applied more than once, or
113 it might arise from user SPECIALIZE pragmas.)
114
115 Recursion
116 ~~~~~~~~~
117 Wait a minute!  What if f is recursive?  Then we can't just plug in
118 its right-hand side, can we?
119
120 But it's ok.  The type checker *always* creates non-recursive definitions
121 for overloaded recursive functions.  For example:
122
123         f x = f (x+x)           -- Yes I know its silly
124
125 becomes
126
127         f a (d::Num a) = let p = +.sel a d
128                          in
129                          letrec fl (y::a) = fl (p y y)
130                          in
131                          fl
132
133 We still have recusion for non-overloaded functions which we
134 speciailise, but the recursive call should get specialised to the
135 same recursive version.
136
137
138 Polymorphism 1
139 ~~~~~~~~~~~~~~
140
141 All this is crystal clear when the function is applied to *constant
142 types*; that is, types which have no type variables inside.  But what if
143 it is applied to non-constant types?  Suppose we find a call of f at type
144 t1/t2.  There are two possibilities:
145
146 (a) The free type variables of t1, t2 are in scope at the definition point
147 of f.  In this case there's no problem, we proceed just as before.  A common
148 example is as follows.  Here's the Haskell:
149
150         g y = let f x = x+x
151               in f y + f y
152
153 After typechecking we have
154
155         g a (d::Num a) (y::a) = let f b (d'::Num b) (x::b) = +.sel b d' x x
156                                 in +.sel a d (f a d y) (f a d y)
157
158 Notice that the call to f is at type type "a"; a non-constant type.
159 Both calls to f are at the same type, so we can specialise to give:
160
161         g a (d::Num a) (y::a) = let f@a (x::a) = +.sel a d x x
162                                 in +.sel a d (f@a y) (f@a y)
163
164
165 (b) The other case is when the type variables in the instance types
166 are *not* in scope at the definition point of f.  The example we are
167 working with above is a good case.  There are two instances of (+.sel a d),
168 but "a" is not in scope at the definition of +.sel.  Can we do anything?
169 Yes, we can "common them up", a sort of limited common sub-expression deal.
170 This would give:
171
172         g a (d::Num a) (y::a) = let +.sel@a = +.sel a d
173                                     f@a (x::a) = +.sel@a x x
174                                 in +.sel@a (f@a y) (f@a y)
175
176 This can save work, and can't be spotted by the type checker, because
177 the two instances of +.sel weren't originally at the same type.
178
179 Further notes on (b)
180
181 * There are quite a few variations here.  For example, the defn of
182   +.sel could be floated ouside the \y, to attempt to gain laziness.
183   It certainly mustn't be floated outside the \d because the d has to
184   be in scope too.
185
186 * We don't want to inline f_rhs in this case, because
187 that will duplicate code.  Just commoning up the call is the point.
188
189 * Nothing gets added to +.sel's IdInfo.
190
191 * Don't bother unless the equivalence class has more than one item!
192
193 Not clear whether this is all worth it.  It is of course OK to
194 simply discard call-instances when passing a big lambda.
195
196 Polymorphism 2 -- Overloading
197 ~~~~~~~~~~~~~~
198 Consider a function whose most general type is
199
200         f :: forall a b. Ord a => [a] -> b -> b
201
202 There is really no point in making a version of g at Int/Int and another
203 at Int/Bool, because it's only instancing the type variable "a" which
204 buys us any efficiency. Since g is completely polymorphic in b there
205 ain't much point in making separate versions of g for the different
206 b types.
207
208 That suggests that we should identify which of g's type variables
209 are constrained (like "a") and which are unconstrained (like "b").
210 Then when taking equivalence classes in STEP 2, we ignore the type args
211 corresponding to unconstrained type variable.  In STEP 3 we make
212 polymorphic versions.  Thus:
213
214         f@t1/ = /\b -> <f_rhs> t1 b d1 d2
215
216 We do this.
217
218
219 Dictionary floating
220 ~~~~~~~~~~~~~~~~~~~
221 Consider this
222
223         f a (d::Num a) = let g = ...
224                          in
225                          ...(let d1::Ord a = Num.Ord.sel a d in g a d1)...
226
227 Here, g is only called at one type, but the dictionary isn't in scope at the
228 definition point for g.  Usually the type checker would build a
229 definition for d1 which enclosed g, but the transformation system
230 might have moved d1's defn inward.  Solution: float dictionary bindings
231 outwards along with call instances.
232
233 Consider
234
235         f x = let g p q = p==q
236                   h r s = (r+s, g r s)
237               in
238               h x x
239
240
241 Before specialisation, leaving out type abstractions we have
242
243         f df x = let g :: Eq a => a -> a -> Bool
244                      g dg p q = == dg p q
245                      h :: Num a => a -> a -> (a, Bool)
246                      h dh r s = let deq = eqFromNum dh
247                                 in (+ dh r s, g deq r s)
248               in
249               h df x x
250
251 After specialising h we get a specialised version of h, like this:
252
253                     h' r s = let deq = eqFromNum df
254                              in (+ df r s, g deq r s)
255
256 But we can't naively make an instance for g from this, because deq is not in scope
257 at the defn of g.  Instead, we have to float out the (new) defn of deq
258 to widen its scope.  Notice that this floating can't be done in advance -- it only
259 shows up when specialisation is done.
260
261 User SPECIALIZE pragmas
262 ~~~~~~~~~~~~~~~~~~~~~~~
263 Specialisation pragmas can be digested by the type checker, and implemented
264 by adding extra definitions along with that of f, in the same way as before
265
266         f@t1/t2 = <f_rhs> t1 t2 d1 d2
267
268 Indeed the pragmas *have* to be dealt with by the type checker, because
269 only it knows how to build the dictionaries d1 and d2!  For example
270
271         g :: Ord a => [a] -> [a]
272         {-# SPECIALIZE f :: [Tree Int] -> [Tree Int] #-}
273
274 Here, the specialised version of g is an application of g's rhs to the
275 Ord dictionary for (Tree Int), which only the type checker can conjure
276 up.  There might not even *be* one, if (Tree Int) is not an instance of
277 Ord!  (All the other specialision has suitable dictionaries to hand
278 from actual calls.)
279
280 Problem.  The type checker doesn't have to hand a convenient <f_rhs>, because
281 it is buried in a complex (as-yet-un-desugared) binding group.
282 Maybe we should say
283
284         f@t1/t2 = f* t1 t2 d1 d2
285
286 where f* is the Id f with an IdInfo which says "inline me regardless!".
287 Indeed all the specialisation could be done in this way.
288 That in turn means that the simplifier has to be prepared to inline absolutely
289 any in-scope let-bound thing.
290
291
292 Again, the pragma should permit polymorphism in unconstrained variables:
293
294         h :: Ord a => [a] -> b -> b
295         {-# SPECIALIZE h :: [Int] -> b -> b #-}
296
297 We *insist* that all overloaded type variables are specialised to ground types,
298 (and hence there can be no context inside a SPECIALIZE pragma).
299 We *permit* unconstrained type variables to be specialised to
300         - a ground type
301         - or left as a polymorphic type variable
302 but nothing in between.  So
303
304         {-# SPECIALIZE h :: [Int] -> [c] -> [c] #-}
305
306 is *illegal*.  (It can be handled, but it adds complication, and gains the
307 programmer nothing.)
308
309
310 SPECIALISING INSTANCE DECLARATIONS
311 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
312 Consider
313
314         instance Foo a => Foo [a] where
315                 ...
316         {-# SPECIALIZE instance Foo [Int] #-}
317
318 The original instance decl creates a dictionary-function
319 definition:
320
321         dfun.Foo.List :: forall a. Foo a -> Foo [a]
322
323 The SPECIALIZE pragma just makes a specialised copy, just as for
324 ordinary function definitions:
325
326         dfun.Foo.List@Int :: Foo [Int]
327         dfun.Foo.List@Int = dfun.Foo.List Int dFooInt
328
329 The information about what instance of the dfun exist gets added to
330 the dfun's IdInfo in the same way as a user-defined function too.
331
332
333 Automatic instance decl specialisation?
334 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
335 Can instance decls be specialised automatically?  It's tricky.
336 We could collect call-instance information for each dfun, but
337 then when we specialised their bodies we'd get new call-instances
338 for ordinary functions; and when we specialised their bodies, we might get
339 new call-instances of the dfuns, and so on.  This all arises because of
340 the unrestricted mutual recursion between instance decls and value decls.
341
342 Still, there's no actual problem; it just means that we may not do all
343 the specialisation we could theoretically do.
344
345 Furthermore, instance decls are usually exported and used non-locally,
346 so we'll want to compile enough to get those specialisations done.
347
348 Lastly, there's no such thing as a local instance decl, so we can
349 survive solely by spitting out *usage* information, and then reading that
350 back in as a pragma when next compiling the file.  So for now,
351 we only specialise instance decls in response to pragmas.
352
353
354 SPITTING OUT USAGE INFORMATION
355 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
356
357 To spit out usage information we need to traverse the code collecting
358 call-instance information for all imported (non-prelude?) functions
359 and data types. Then we equivalence-class it and spit it out.
360
361 This is done at the top-level when all the call instances which escape
362 must be for imported functions and data types.
363
364 *** Not currently done ***
365
366
367 Partial specialisation by pragmas
368 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
369 What about partial specialisation:
370
371         k :: (Ord a, Eq b) => [a] -> b -> b -> [a]
372         {-# SPECIALIZE k :: Eq b => [Int] -> b -> b -> [a] #-}
373
374 or even
375
376         {-# SPECIALIZE k :: Eq b => [Int] -> [b] -> [b] -> [a] #-}
377
378 Seems quite reasonable.  Similar things could be done with instance decls:
379
380         instance (Foo a, Foo b) => Foo (a,b) where
381                 ...
382         {-# SPECIALIZE instance Foo a => Foo (a,Int) #-}
383         {-# SPECIALIZE instance Foo b => Foo (Int,b) #-}
384
385 Ho hum.  Things are complex enough without this.  I pass.
386
387
388 Requirements for the simplifer
389 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
390 The simplifier has to be able to take advantage of the specialisation.
391
392 * When the simplifier finds an application of a polymorphic f, it looks in
393 f's IdInfo in case there is a suitable instance to call instead.  This converts
394
395         f t1 t2 d1 d2   ===>   f_t1_t2
396
397 Note that the dictionaries get eaten up too!
398
399 * Dictionary selection operations on constant dictionaries must be
400   short-circuited:
401
402         +.sel Int d     ===>  +Int
403
404 The obvious way to do this is in the same way as other specialised
405 calls: +.sel has inside it some IdInfo which tells that if it's applied
406 to the type Int then it should eat a dictionary and transform to +Int.
407
408 In short, dictionary selectors need IdInfo inside them for constant
409 methods.
410
411 * Exactly the same applies if a superclass dictionary is being
412   extracted:
413
414         Eq.sel Int d   ===>   dEqInt
415
416 * Something similar applies to dictionary construction too.  Suppose
417 dfun.Eq.List is the function taking a dictionary for (Eq a) to
418 one for (Eq [a]).  Then we want
419
420         dfun.Eq.List Int d      ===> dEq.List_Int
421
422 Where does the Eq [Int] dictionary come from?  It is built in
423 response to a SPECIALIZE pragma on the Eq [a] instance decl.
424
425 In short, dfun Ids need IdInfo with a specialisation for each
426 constant instance of their instance declaration.
427
428 All this uses a single mechanism: the SpecEnv inside an Id
429
430
431 What does the specialisation IdInfo look like?
432 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
433
434 The SpecEnv of an Id maps a list of types (the template) to an expression
435
436         [Type]  |->  Expr
437
438 For example, if f has this SpecInfo:
439
440         [Int, a]  ->  \d:Ord Int. f' a
441
442 it means that we can replace the call
443
444         f Int t  ===>  (\d. f' t)
445
446 This chucks one dictionary away and proceeds with the
447 specialised version of f, namely f'.
448
449
450 What can't be done this way?
451 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
452 There is no way, post-typechecker, to get a dictionary for (say)
453 Eq a from a dictionary for Eq [a].  So if we find
454
455         ==.sel [t] d
456
457 we can't transform to
458
459         eqList (==.sel t d')
460
461 where
462         eqList :: (a->a->Bool) -> [a] -> [a] -> Bool
463
464 Of course, we currently have no way to automatically derive
465 eqList, nor to connect it to the Eq [a] instance decl, but you
466 can imagine that it might somehow be possible.  Taking advantage
467 of this is permanently ruled out.
468
469 Still, this is no great hardship, because we intend to eliminate
470 overloading altogether anyway!
471
472 A note about non-tyvar dictionaries
473 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
474 Some Ids have types like
475
476         forall a,b,c. Eq a -> Ord [a] -> tau
477
478 This seems curious at first, because we usually only have dictionary
479 args whose types are of the form (C a) where a is a type variable.
480 But this doesn't hold for the functions arising from instance decls,
481 which sometimes get arguements with types of form (C (T a)) for some
482 type constructor T.
483
484 Should we specialise wrt this compound-type dictionary?  We used to say
485 "no", saying:
486         "This is a heuristic judgement, as indeed is the fact that we 
487         specialise wrt only dictionaries.  We choose *not* to specialise
488         wrt compound dictionaries because at the moment the only place
489         they show up is in instance decls, where they are simply plugged
490         into a returned dictionary.  So nothing is gained by specialising
491         wrt them."
492
493 But it is simpler and more uniform to specialise wrt these dicts too;
494 and in future GHC is likely to support full fledged type signatures 
495 like
496         f :: Eq [(a,b)] => ...
497
498
499 %************************************************************************
500 %*                                                                      *
501 \subsubsection{The new specialiser}
502 %*                                                                      *
503 %************************************************************************
504
505 Our basic game plan is this.  For let(rec) bound function
506         f :: (C a, D c) => (a,b,c,d) -> Bool
507
508 * Find any specialised calls of f, (f ts ds), where 
509   ts are the type arguments t1 .. t4, and
510   ds are the dictionary arguments d1 .. d2.
511
512 * Add a new definition for f1 (say):
513
514         f1 = /\ b d -> (..body of f..) t1 b t3 d d1 d2
515
516   Note that we abstract over the unconstrained type arguments.
517
518 * Add the mapping
519
520         [t1,b,t3,d]  |->  \d1 d2 -> f1 b d
521
522   to the specialisations of f.  This will be used by the
523   simplifier to replace calls 
524                 (f t1 t2 t3 t4) da db
525   by
526                 (\d1 d1 -> f1 t2 t4) da db
527
528   All the stuff about how many dictionaries to discard, and what types
529   to apply the specialised function to, are handled by the fact that the
530   SpecEnv contains a template for the result of the specialisation.
531
532 We don't build *partial* specialisations for f.  For example:
533
534   f :: Eq a => a -> a -> Bool
535   {-# SPECIALISE f :: (Eq b, Eq c) => (b,c) -> (b,c) -> Bool #-}
536
537 Here, little is gained by making a specialised copy of f.
538 There's a distinct danger that the specialised version would
539 first build a dictionary for (Eq b, Eq c), and then select the (==) 
540 method from it!  Even if it didn't, not a great deal is saved.
541
542 We do, however, generate polymorphic, but not overloaded, specialisations:
543
544   f :: Eq a => [a] -> b -> b -> b
545   {#- SPECIALISE f :: [Int] -> b -> b -> b #-}
546
547 Hence, the invariant is this: 
548
549         *** no specialised version is overloaded ***
550
551
552 %************************************************************************
553 %*                                                                      *
554 \subsubsection{The exported function}
555 %*                                                                      *
556 %************************************************************************
557
558 \begin{code}
559 specProgram :: UniqSupply -> [CoreBind] -> [CoreBind]
560 specProgram us binds = initSM us $
561                        do { (binds', uds') <- go binds
562                           ; return (wrapDictBinds (ud_binds uds') binds') }
563   where
564         -- We need to start with a Subst that knows all the things
565         -- that are in scope, so that the substitution engine doesn't
566         -- accidentally re-use a unique that's already in use
567         -- Easiest thing is to do it all at once, as if all the top-level
568         -- decls were mutually recursive
569     top_subst       = mkEmptySubst (mkInScopeSet (mkVarSet (bindersOfBinds binds)))
570
571     go []           = return ([], emptyUDs)
572     go (bind:binds) = do (binds', uds) <- go binds
573                          (bind', uds') <- specBind top_subst bind uds
574                          return (bind' ++ binds', uds')
575 \end{code}
576
577 %************************************************************************
578 %*                                                                      *
579 \subsubsection{@specExpr@: the main function}
580 %*                                                                      *
581 %************************************************************************
582
583 \begin{code}
584 specVar :: Subst -> Id -> CoreExpr
585 specVar subst v = lookupIdSubst (text "specVar") subst v
586
587 specExpr :: Subst -> CoreExpr -> SpecM (CoreExpr, UsageDetails)
588 -- We carry a substitution down:
589 --      a) we must clone any binding that might float outwards,
590 --         to avoid name clashes
591 --      b) we carry a type substitution to use when analysing
592 --         the RHS of specialised bindings (no type-let!)
593
594 ---------------- First the easy cases --------------------
595 specExpr subst (Type ty) = return (Type (CoreSubst.substTy subst ty), emptyUDs)
596 specExpr subst (Var v)   = return (specVar subst v,         emptyUDs)
597 specExpr _     (Lit lit) = return (Lit lit,                 emptyUDs)
598 specExpr subst (Cast e co) = do
599     (e', uds) <- specExpr subst e
600     return ((Cast e' (CoreSubst.substTy subst co)), uds)
601 specExpr subst (Note note body) = do
602     (body', uds) <- specExpr subst body
603     return (Note (specNote subst note) body', uds)
604
605
606 ---------------- Applications might generate a call instance --------------------
607 specExpr subst expr@(App {})
608   = go expr []
609   where
610     go (App fun arg) args = do (arg', uds_arg) <- specExpr subst arg
611                                (fun', uds_app) <- go fun (arg':args)
612                                return (App fun' arg', uds_arg `plusUDs` uds_app)
613
614     go (Var f)       args = case specVar subst f of
615                                 Var f' -> return (Var f', mkCallUDs f' args)
616                                 e'     -> return (e', emptyUDs) -- I don't expect this!
617     go other         _    = specExpr subst other
618
619 ---------------- Lambda/case require dumping of usage details --------------------
620 specExpr subst e@(Lam _ _) = do
621     (body', uds) <- specExpr subst' body
622     let (free_uds, dumped_dbs) = dumpUDs bndrs' uds 
623     return (mkLams bndrs' (wrapDictBindsE dumped_dbs body'), free_uds)
624   where
625     (bndrs, body) = collectBinders e
626     (subst', bndrs') = substBndrs subst bndrs
627         -- More efficient to collect a group of binders together all at once
628         -- and we don't want to split a lambda group with dumped bindings
629
630 specExpr subst (Case scrut case_bndr ty alts) 
631   = do { (scrut', scrut_uds) <- specExpr subst scrut
632        ; (scrut'', case_bndr', alts', alts_uds) 
633              <- specCase subst scrut' case_bndr alts 
634        ; return (Case scrut'' case_bndr' (CoreSubst.substTy subst ty) alts'
635                 , scrut_uds `plusUDs` alts_uds) }
636
637 ---------------- Finally, let is the interesting case --------------------
638 specExpr subst (Let bind body) = do
639         -- Clone binders
640     (rhs_subst, body_subst, bind') <- cloneBindSM subst bind
641
642         -- Deal with the body
643     (body', body_uds) <- specExpr body_subst body
644
645         -- Deal with the bindings
646     (binds', uds) <- specBind rhs_subst bind' body_uds
647
648         -- All done
649     return (foldr Let body' binds', uds)
650
651 -- Must apply the type substitution to coerceions
652 specNote :: Subst -> Note -> Note
653 specNote _ note = note
654
655
656 specCase :: Subst 
657          -> CoreExpr            -- Scrutinee, already done
658          -> Id -> [CoreAlt]
659          -> SpecM ( CoreExpr    -- New scrutinee
660                   , Id
661                   , [CoreAlt]
662                   , UsageDetails)
663 specCase subst scrut' case_bndr [(con, args, rhs)]
664   | isDictId case_bndr           -- See Note [Floating dictionaries out of cases]
665   , interestingDict scrut'
666   , not (isDeadBinder case_bndr && null sc_args')
667   = do { (case_bndr_flt : sc_args_flt) <- mapM clone_me (case_bndr' : sc_args')
668
669        ; let sc_rhss = [ Case (Var case_bndr_flt) case_bndr' (idType sc_arg')
670                               [(con, args', Var sc_arg')]
671                        | sc_arg' <- sc_args' ]
672
673              -- Extend the substitution for RHS to map the *original* binders
674              -- to their floated verions.  Attach an unfolding to these floated
675              -- binders so they look interesting to interestingDict
676              mb_sc_flts :: [Maybe DictId]
677              mb_sc_flts = map (lookupVarEnv clone_env) args'
678              clone_env  = zipVarEnv sc_args' (zipWith add_unf sc_args_flt sc_rhss)
679              subst_prs  = (case_bndr, Var (add_unf case_bndr_flt scrut'))
680                         : [ (arg, Var sc_flt) 
681                           | (arg, Just sc_flt) <- args `zip` mb_sc_flts ]
682              subst_rhs' = extendIdSubstList subst_rhs subst_prs
683                                                       
684        ; (rhs',   rhs_uds)   <- specExpr subst_rhs' rhs
685        ; let scrut_bind    = mkDB (NonRec case_bndr_flt scrut')
686              case_bndr_set = unitVarSet case_bndr_flt
687              sc_binds      = [(NonRec sc_arg_flt sc_rhs, case_bndr_set)
688                              | (sc_arg_flt, sc_rhs) <- sc_args_flt `zip` sc_rhss ]
689              flt_binds     = scrut_bind : sc_binds
690              (free_uds, dumped_dbs) = dumpUDs (case_bndr':args') rhs_uds
691              all_uds = flt_binds `addDictBinds` free_uds
692              alt'    = (con, args', wrapDictBindsE dumped_dbs rhs')
693        ; return (Var case_bndr_flt, case_bndr', [alt'], all_uds) }
694   where
695     (subst_rhs, (case_bndr':args')) = substBndrs subst (case_bndr:args)
696     sc_args' = filter is_flt_sc_arg args'
697              
698     clone_me bndr = do { uniq <- getUniqueM
699                        ; return (mkUserLocal occ uniq ty loc) }
700        where
701          name = idName bndr
702          ty   = idType bndr
703          occ  = nameOccName name
704          loc  = getSrcSpan name
705
706     add_unf sc_flt sc_rhs  -- Sole purpose: make sc_flt respond True to interestingDictId
707       = setIdUnfolding sc_flt (mkUnfolding False False sc_rhs)
708
709     arg_set = mkVarSet args'
710     is_flt_sc_arg var =  isId var
711                       && not (isDeadBinder var)
712                       && isDictTy var_ty
713                       && not (tyVarsOfType var_ty `intersectsVarSet` arg_set)
714        where
715          var_ty = idType var
716
717
718 specCase subst scrut case_bndr alts
719   = do { (alts', uds_alts) <- mapAndCombineSM spec_alt alts
720        ; return (scrut, case_bndr', alts', uds_alts) }
721   where
722     (subst_alt, case_bndr') = substBndr subst case_bndr
723     spec_alt (con, args, rhs) = do
724           (rhs', uds) <- specExpr subst_rhs rhs
725           let (free_uds, dumped_dbs) = dumpUDs (case_bndr' : args') uds
726           return ((con, args', wrapDictBindsE dumped_dbs rhs'), free_uds)
727         where
728           (subst_rhs, args') = substBndrs subst_alt args
729 \end{code}
730
731 Note [Floating dictionaries out of cases]
732 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
733 Consider
734    g = \d. case d of { MkD sc ... -> ...(f sc)... }
735 Naively we can't float d2's binding out of the case expression,
736 because 'sc' is bound by the case, and that in turn means we can't
737 specialise f, which seems a pity.  
738
739 So we invert the case, by floating out a binding 
740 for 'sc_flt' thus:
741     sc_flt = case d of { MkD sc ... -> sc }
742 Now we can float the call instance for 'f'.  Indeed this is just
743 what'll happen if 'sc' was originally bound with a let binding,
744 but case is more efficient, and necessary with equalities. So it's
745 good to work with both.
746
747 You might think that this won't make any difference, because the
748 call instance will only get nuked by the \d.  BUT if 'g' itself is 
749 specialised, then transitively we should be able to specialise f.
750
751 In general, given
752    case e of cb { MkD sc ... -> ...(f sc)... }
753 we transform to
754    let cb_flt = e
755        sc_flt = case cb_flt of { MkD sc ... -> sc }
756    in
757    case cb_flt of bg { MkD sc ... -> ....(f sc_flt)... }
758
759 The "_flt" things are the floated binds; we use the current substitution
760 to substitute sc -> sc_flt in the RHS
761
762 %************************************************************************
763 %*                                                                      *
764 \subsubsection{Dealing with a binding}
765 %*                                                                      *
766 %************************************************************************
767
768 \begin{code}
769 specBind :: Subst                       -- Use this for RHSs
770          -> CoreBind
771          -> UsageDetails                -- Info on how the scope of the binding
772          -> SpecM ([CoreBind],          -- New bindings
773                    UsageDetails)        -- And info to pass upstream
774
775 -- Returned UsageDetails:
776 --    No calls for binders of this bind
777 specBind rhs_subst (NonRec fn rhs) body_uds
778   = do { (rhs', rhs_uds) <- specExpr rhs_subst rhs
779        ; (fn', spec_defns, body_uds1) <- specDefn rhs_subst body_uds fn rhs
780
781        ; let pairs = spec_defns ++ [(fn', rhs')]
782                         -- fn' mentions the spec_defns in its rules, 
783                         -- so put the latter first
784
785              combined_uds = body_uds1 `plusUDs` rhs_uds
786                 -- This way round a call in rhs_uds of a function f
787                 -- at type T will override a call of f at T in body_uds1; and
788                 -- that is good because it'll tend to keep "earlier" calls
789                 -- See Note [Specialisation of dictionary functions]
790
791              (free_uds, dump_dbs, float_all) = dumpBindUDs [fn] combined_uds
792                 -- See Note [From non-recursive to recursive]
793
794              final_binds | isEmptyBag dump_dbs = [NonRec b r | (b,r) <- pairs]
795                          | otherwise = [Rec (flattenDictBinds dump_dbs pairs)]
796
797          ; if float_all then
798              -- Rather than discard the calls mentioning the bound variables
799              -- we float this binding along with the others
800               return ([], free_uds `snocDictBinds` final_binds)
801            else
802              -- No call in final_uds mentions bound variables, 
803              -- so we can just leave the binding here
804               return (final_binds, free_uds) }
805
806
807 specBind rhs_subst (Rec pairs) body_uds
808        -- Note [Specialising a recursive group]
809   = do { let (bndrs,rhss) = unzip pairs
810        ; (rhss', rhs_uds) <- mapAndCombineSM (specExpr rhs_subst) rhss
811        ; let scope_uds = body_uds `plusUDs` rhs_uds
812                        -- Includes binds and calls arising from rhss
813
814        ; (bndrs1, spec_defns1, uds1) <- specDefns rhs_subst scope_uds pairs
815
816        ; (bndrs3, spec_defns3, uds3)
817              <- if null spec_defns1  -- Common case: no specialisation
818                 then return (bndrs1, [], uds1)
819                 else do {            -- Specialisation occurred; do it again
820                           (bndrs2, spec_defns2, uds2)
821                               <- specDefns rhs_subst uds1 (bndrs1 `zip` rhss)
822                         ; return (bndrs2, spec_defns2 ++ spec_defns1, uds2) }
823
824        ; let (final_uds, dumped_dbs, float_all) = dumpBindUDs bndrs uds3
825              bind = Rec (flattenDictBinds dumped_dbs $
826                          spec_defns3 ++ zip bndrs3 rhss')
827              
828        ; if float_all then
829               return ([], final_uds `snocDictBind` bind)
830            else
831               return ([bind], final_uds) }
832
833
834 ---------------------------
835 specDefns :: Subst
836           -> UsageDetails               -- Info on how it is used in its scope
837           -> [(Id,CoreExpr)]            -- The things being bound and their un-processed RHS
838           -> SpecM ([Id],               -- Original Ids with RULES added
839                     [(Id,CoreExpr)],    -- Extra, specialised bindings
840                     UsageDetails)       -- Stuff to fling upwards from the specialised versions
841
842 -- Specialise a list of bindings (the contents of a Rec), but flowing usages
843 -- upwards binding by binding.  Example: { f = ...g ...; g = ...f .... }
844 -- Then if the input CallDetails has a specialised call for 'g', whose specialisation
845 -- in turn generates a specialised call for 'f', we catch that in this one sweep.
846 -- But not vice versa (it's a fixpoint problem).
847
848 specDefns _subst uds []
849   = return ([], [], uds)
850 specDefns subst uds ((bndr,rhs):pairs)
851   = do { (bndrs1, spec_defns1, uds1) <- specDefns subst uds pairs
852        ; (bndr1, spec_defns2, uds2)  <- specDefn subst uds1 bndr rhs
853        ; return (bndr1 : bndrs1, spec_defns1 ++ spec_defns2, uds2) }
854
855 ---------------------------
856 specDefn :: Subst
857          -> UsageDetails                -- Info on how it is used in its scope
858          -> Id -> CoreExpr              -- The thing being bound and its un-processed RHS
859          -> SpecM (Id,                  -- Original Id with added RULES
860                    [(Id,CoreExpr)],     -- Extra, specialised bindings
861                    UsageDetails)        -- Stuff to fling upwards from the specialised versions
862
863 specDefn subst body_uds fn rhs
864         -- The first case is the interesting one
865   |  rhs_tyvars `lengthIs`     n_tyvars -- Rhs of fn's defn has right number of big lambdas
866   && rhs_ids    `lengthAtLeast` n_dicts -- and enough dict args
867   && notNull calls_for_me               -- And there are some calls to specialise
868   && not (isNeverActive (idInlineActivation fn))
869         -- Don't specialise NOINLINE things
870         -- See Note [Auto-specialisation and RULES]
871
872 --   && not (certainlyWillInline (idUnfolding fn))      -- And it's not small
873 --      See Note [Inline specialisation] for why we do not 
874 --      switch off specialisation for inline functions
875
876   = -- pprTrace "specDefn: some" (ppr fn $$ ppr calls_for_me) $
877     do {       -- Make a specialised version for each call in calls_for_me
878          stuff <- mapM spec_call calls_for_me
879        ; let (spec_defns, spec_uds, spec_rules) = unzip3 (catMaybes stuff)
880              fn' = addIdSpecialisations fn spec_rules
881              final_uds = body_uds_without_me `plusUDs` plusUDList spec_uds 
882                 -- It's important that the `plusUDs` is this way
883                 -- round, because body_uds_without_me may bind
884                 -- dictionaries that are used in calls_for_me passed
885                 -- to specDefn.  So the dictionary bindings in
886                 -- spec_uds may mention dictionaries bound in
887                 -- body_uds_without_me
888
889        ; return (fn', spec_defns, final_uds) }
890
891   | otherwise   -- No calls or RHS doesn't fit our preconceptions
892   = WARN( notNull calls_for_me, ptext (sLit "Missed specialisation opportunity for") <+> ppr fn )
893           -- Note [Specialisation shape]
894     -- pprTrace "specDefn: none" (ppr fn $$ ppr calls_for_me) $
895     return (fn, [], body_uds_without_me)
896   
897   where
898     fn_type            = idType fn
899     fn_arity           = idArity fn
900     fn_unf             = realIdUnfolding fn     -- Ignore loop-breaker-ness here
901     (tyvars, theta, _) = tcSplitSigmaTy fn_type
902     n_tyvars           = length tyvars
903     n_dicts            = length theta
904     inl_act            = inlinePragmaActivation (idInlinePragma fn)
905
906         -- Figure out whether the function has an INLINE pragma
907         -- See Note [Inline specialisations]
908     fn_has_inline_rule :: Maybe Bool    -- Derive sat-flag from existing thing
909     fn_has_inline_rule = case isInlineRule_maybe fn_unf of
910                            Just (_,sat) -> Just sat
911                            Nothing      -> Nothing
912
913     spec_arity = unfoldingArity fn_unf - n_dicts  -- Arity of the *specialised* inline rule
914
915     (rhs_tyvars, rhs_ids, rhs_body) = collectTyAndValBinders rhs
916
917     (body_uds_without_me, calls_for_me) = callsForMe fn body_uds
918
919     rhs_dict_ids = take n_dicts rhs_ids
920     body         = mkLams (drop n_dicts rhs_ids) rhs_body
921                 -- Glue back on the non-dict lambdas
922
923     already_covered :: [CoreExpr] -> Bool
924     already_covered args          -- Note [Specialisations already covered]
925        = isJust (lookupRule (const True) realIdUnfolding 
926                             (substInScope subst) 
927                             fn args (idCoreRules fn))
928
929     mk_ty_args :: [Maybe Type] -> [CoreExpr]
930     mk_ty_args call_ts = zipWithEqual "spec_call" mk_ty_arg rhs_tyvars call_ts
931                where
932                   mk_ty_arg rhs_tyvar Nothing   = Type (mkTyVarTy rhs_tyvar)
933                   mk_ty_arg _         (Just ty) = Type ty
934
935     ----------------------------------------------------------
936         -- Specialise to one particular call pattern
937     spec_call :: CallInfo                         -- Call instance
938               -> SpecM (Maybe ((Id,CoreExpr),     -- Specialised definition
939                                UsageDetails,      -- Usage details from specialised body
940                                CoreRule))         -- Info for the Id's SpecEnv
941     spec_call (CallKey call_ts, (call_ds, _))
942       = ASSERT( call_ts `lengthIs` n_tyvars  && call_ds `lengthIs` n_dicts )
943         
944         -- Suppose f's defn is  f = /\ a b c -> \ d1 d2 -> rhs  
945         -- Supppose the call is for f [Just t1, Nothing, Just t3] [dx1, dx2]
946
947         -- Construct the new binding
948         --      f1 = SUBST[a->t1,c->t3, d1->d1', d2->d2'] (/\ b -> rhs)
949         -- PLUS the usage-details
950         --      { d1' = dx1; d2' = dx2 }
951         -- where d1', d2' are cloned versions of d1,d2, with the type substitution
952         -- applied.  These auxiliary bindings just avoid duplication of dx1, dx2
953         --
954         -- Note that the substitution is applied to the whole thing.
955         -- This is convenient, but just slightly fragile.  Notably:
956         --      * There had better be no name clashes in a/b/c
957         do { let
958                 -- poly_tyvars = [b] in the example above
959                 -- spec_tyvars = [a,c] 
960                 -- ty_args     = [t1,b,t3]
961                 poly_tyvars   = [tv | (tv, Nothing) <- rhs_tyvars `zip` call_ts]
962                 spec_tv_binds = [(tv,ty) | (tv, Just ty) <- rhs_tyvars `zip` call_ts]
963                 spec_ty_args  = map snd spec_tv_binds
964                 ty_args       = mk_ty_args call_ts
965                 rhs_subst     = CoreSubst.extendTvSubstList subst spec_tv_binds
966
967            ; (rhs_subst1, inst_dict_ids) <- newDictBndrs rhs_subst rhs_dict_ids
968                           -- Clone rhs_dicts, including instantiating their types
969
970            ; let (rhs_subst2, dx_binds) = bindAuxiliaryDicts rhs_subst1 $
971                                           (my_zipEqual rhs_dict_ids inst_dict_ids call_ds)
972                  inst_args = ty_args ++ map Var inst_dict_ids
973
974            ; if already_covered inst_args then
975                 return Nothing
976              else do
977            {    -- Figure out the type of the specialised function
978              let body_ty = applyTypeToArgs rhs fn_type inst_args
979                  (lam_args, app_args)           -- Add a dummy argument if body_ty is unlifted
980                    | isUnLiftedType body_ty     -- C.f. WwLib.mkWorkerArgs
981                    = (poly_tyvars ++ [voidArgId], poly_tyvars ++ [realWorldPrimId])
982                    | otherwise = (poly_tyvars, poly_tyvars)
983                  spec_id_ty = mkPiTypes lam_args body_ty
984         
985            ; spec_f <- newSpecIdSM fn spec_id_ty
986            ; (spec_rhs, rhs_uds) <- specExpr rhs_subst2 (mkLams lam_args body)
987            ; let
988                 -- The rule to put in the function's specialisation is:
989                 --      forall b, d1',d2'.  f t1 b t3 d1' d2' = f1 b  
990                 rule_name = mkFastString ("SPEC " ++ showSDoc (ppr fn <+> ppr spec_ty_args))
991                 spec_env_rule = mkLocalRule
992                                   rule_name
993                                   inl_act       -- Note [Auto-specialisation and RULES]
994                                   (idName fn)
995                                   (poly_tyvars ++ inst_dict_ids)
996                                   inst_args 
997                                   (mkVarApps (Var spec_f) app_args)
998
999                 -- Add the { d1' = dx1; d2' = dx2 } usage stuff
1000                 final_uds = foldr consDictBind rhs_uds dx_binds
1001
1002                 -- Adding arity information just propagates it a bit faster
1003                 --      See Note [Arity decrease] in Simplify
1004                 -- Copy InlinePragma information from the parent Id.
1005                 -- So if f has INLINE[1] so does spec_f
1006                 spec_f_w_arity = spec_f `setIdArity`          max 0 (fn_arity - n_dicts)
1007                                         `setInlineActivation` inl_act
1008
1009                 -- Add an InlineRule if the parent has one
1010                 -- See Note [Inline specialisations]
1011                 final_spec_f 
1012                   | Just sat <- fn_has_inline_rule
1013                   = let 
1014                        mb_spec_arity = if sat then Just spec_arity else Nothing
1015                     in 
1016                     spec_f_w_arity `setIdUnfolding` mkInlineRule spec_rhs mb_spec_arity
1017                   | otherwise 
1018                   = spec_f_w_arity
1019
1020            ; return (Just ((final_spec_f, spec_rhs), final_uds, spec_env_rule)) } }
1021       where
1022         my_zipEqual xs ys zs
1023          | debugIsOn && not (equalLength xs ys && equalLength ys zs)
1024              = pprPanic "my_zipEqual" (vcat [ ppr xs, ppr ys
1025                                             , ppr fn <+> ppr call_ts
1026                                             , ppr (idType fn), ppr theta
1027                                             , ppr n_dicts, ppr rhs_dict_ids 
1028                                             , ppr rhs])
1029          | otherwise = zip3 xs ys zs
1030
1031 bindAuxiliaryDicts
1032         :: Subst
1033         -> [(DictId,DictId,CoreExpr)]   -- (orig_dict, inst_dict, dx)
1034         -> (Subst,                      -- Substitute for all orig_dicts
1035             [CoreBind])                 -- Auxiliary bindings
1036 -- Bind any dictionary arguments to fresh names, to preserve sharing
1037 -- Substitution already substitutes orig_dict -> inst_dict
1038 bindAuxiliaryDicts subst triples = go subst [] triples
1039   where
1040     go subst binds []    = (subst, binds)
1041     go subst binds ((d, dx_id, dx) : pairs)
1042       | exprIsTrivial dx = go (extendIdSubst subst d dx) binds pairs
1043              -- No auxiliary binding necessary
1044              -- Note that we bind the *original* dict in the substitution,
1045              -- overriding any d->dx_id binding put there by substBndrs
1046
1047       | otherwise        = go subst_w_unf (NonRec dx_id dx : binds) pairs
1048       where
1049         dx_id1 = dx_id `setIdUnfolding` mkUnfolding False False dx
1050         subst_w_unf = extendIdSubst subst d (Var dx_id1)
1051              -- Important!  We're going to substitute dx_id1 for d
1052              -- and we want it to look "interesting", else we won't gather *any*
1053              -- consequential calls. E.g.
1054              --     f d = ...g d....
1055              -- If we specialise f for a call (f (dfun dNumInt)), we'll get 
1056              -- a consequent call (g d') with an auxiliary definition
1057              --     d' = df dNumInt
1058              -- We want that consequent call to look interesting
1059              --
1060              -- Again, note that we bind the *original* dict in the substitution,
1061              -- overriding any d->dx_id binding put there by substBndrs
1062 \end{code}
1063
1064 Note [From non-recursive to recursive]
1065 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1066 Even in the non-recursive case, if any dict-binds depend on 'fn' we might 
1067 have built a recursive knot
1068
1069       f a d x = <blah>
1070       MkUD { ud_binds = d7 = MkD ..f..
1071            , ud_calls = ...(f T d7)... }
1072
1073 The we generate
1074
1075       Rec { fs x = <blah>[T/a, d7/d]
1076             f a d x = <blah>
1077                RULE f T _ = fs
1078             d7 = ...f... }
1079
1080 Here the recursion is only through the RULE.
1081
1082  
1083 Note [Specialisation of dictionary functions]
1084 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1085 Here is a nasty example that bit us badly: see Trac #3591
1086
1087      dfun a d = MkD a d (meth d)
1088      d4 = <blah>
1089      d2 = dfun T d4
1090      d1 = $p1 d2
1091      d3 = dfun T d1
1092
1093 None of these definitions is recursive. What happened was that we 
1094 generated a specialisation:
1095
1096      RULE forall d. dfun T d = dT
1097      dT = (MkD a d (meth d)) [T/a, d1/d]
1098         = MkD T d1 (meth d1)
1099
1100 But now we use the RULE on the RHS of d2, to get
1101
1102     d2 = dT = MkD d1 (meth d1)
1103     d1 = $p1 d2
1104
1105 and now d1 is bottom!  The problem is that when specialising 'dfun' we
1106 should first dump "below" the binding all floated dictionary bindings
1107 that mention 'dfun' itself.  So d2 and d3 (and hence d1) must be
1108 placed below 'dfun', and thus unavailable to it when specialising
1109 'dfun'.  That in turn means that the call (dfun T d1) must be
1110 discarded.  On the other hand, the call (dfun T d4) is fine, assuming
1111 d4 doesn't mention dfun.
1112
1113 But look at this:
1114
1115   class C a where { foo,bar :: [a] -> [a] }
1116
1117   instance C Int where 
1118      foo x = r_bar x    
1119      bar xs = reverse xs
1120
1121   r_bar :: C a => [a] -> [a]
1122   r_bar xs = bar (xs ++ xs)
1123
1124 That translates to:
1125
1126     r_bar a (c::C a) (xs::[a]) = bar a d (xs ++ xs)
1127
1128     Rec { $fCInt :: C Int = MkC foo_help reverse
1129           foo_help (xs::[Int]) = r_bar Int $fCInt xs }
1130
1131 The call (r_bar $fCInt) mentions $fCInt, 
1132                         which mentions foo_help, 
1133                         which mentions r_bar
1134 But we DO want to specialise r_bar at Int:
1135
1136     Rec { $fCInt :: C Int = MkC foo_help reverse
1137           foo_help (xs::[Int]) = r_bar Int $fCInt xs
1138
1139           r_bar a (c::C a) (xs::[a]) = bar a d (xs ++ xs)
1140             RULE r_bar Int _ = r_bar_Int
1141
1142           r_bar_Int xs = bar Int $fCInt (xs ++ xs)
1143            }
1144    
1145 Note that, because of its RULE, r_bar joins the recursive
1146 group.  (In this case it'll unravel a short moment later.)
1147
1148
1149 Conclusion: we catch the nasty case using filter_dfuns in
1150 callsForMe To be honest I'm not 100% certain that this is 100%
1151 right, but it works.  Sigh.
1152
1153
1154 Note [Specialising a recursive group]
1155 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1156 Consider
1157     let rec { f x = ...g x'...
1158             ; g y = ...f y'.... }
1159     in f 'a'
1160 Here we specialise 'f' at Char; but that is very likely to lead to 
1161 a specialisation of 'g' at Char.  We must do the latter, else the
1162 whole point of specialisation is lost.
1163
1164 But we do not want to keep iterating to a fixpoint, because in the
1165 presence of polymorphic recursion we might generate an infinite number
1166 of specialisations.
1167
1168 So we use the following heuristic:
1169   * Arrange the rec block in dependency order, so far as possible
1170     (the occurrence analyser already does this)
1171
1172   * Specialise it much like a sequence of lets
1173
1174   * Then go through the block a second time, feeding call-info from
1175     the RHSs back in the bottom, as it were
1176
1177 In effect, the ordering maxmimises the effectiveness of each sweep,
1178 and we do just two sweeps.   This should catch almost every case of 
1179 monomorphic recursion -- the exception could be a very knotted-up
1180 recursion with multiple cycles tied up together.
1181
1182 This plan is implemented in the Rec case of specBindItself.
1183  
1184 Note [Specialisations already covered]
1185 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1186 We obviously don't want to generate two specialisations for the same
1187 argument pattern.  There are two wrinkles
1188
1189 1. We do the already-covered test in specDefn, not when we generate
1190 the CallInfo in mkCallUDs.  We used to test in the latter place, but
1191 we now iterate the specialiser somewhat, and the Id at the call site
1192 might therefore not have all the RULES that we can see in specDefn
1193
1194 2. What about two specialisations where the second is an *instance*
1195 of the first?  If the more specific one shows up first, we'll generate
1196 specialisations for both.  If the *less* specific one shows up first,
1197 we *don't* currently generate a specialisation for the more specific
1198 one.  (See the call to lookupRule in already_covered.)  Reasons:
1199   (a) lookupRule doesn't say which matches are exact (bad reason)
1200   (b) if the earlier specialisation is user-provided, it's
1201       far from clear that we should auto-specialise further
1202
1203 Note [Auto-specialisation and RULES]
1204 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1205 Consider:
1206    g :: Num a => a -> a
1207    g = ...
1208
1209    f :: (Int -> Int) -> Int
1210    f w = ...
1211    {-# RULE f g = 0 #-}
1212
1213 Suppose that auto-specialisation makes a specialised version of
1214 g::Int->Int That version won't appear in the LHS of the RULE for f.
1215 So if the specialisation rule fires too early, the rule for f may
1216 never fire. 
1217
1218 It might be possible to add new rules, to "complete" the rewrite system.
1219 Thus when adding
1220         RULE forall d. g Int d = g_spec
1221 also add
1222         RULE f g_spec = 0
1223
1224 But that's a bit complicated.  For now we ask the programmer's help,
1225 by *copying the INLINE activation pragma* to the auto-specialised
1226 rule.  So if g says {-# NOINLINE[2] g #-}, then the auto-spec rule
1227 will also not be active until phase 2.  And that's what programmers
1228 should jolly well do anyway, even aside from specialisation, to ensure
1229 that g doesn't inline too early.
1230
1231 This in turn means that the RULE would never fire for a NOINLINE
1232 thing so not much point in generating a specialisation at all.
1233
1234 Note [Specialisation shape]
1235 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1236 We only specialise a function if it has visible top-level lambdas
1237 corresponding to its overloading.  E.g. if
1238         f :: forall a. Eq a => ....
1239 then its body must look like
1240         f = /\a. \d. ...
1241
1242 Reason: when specialising the body for a call (f ty dexp), we want to
1243 substitute dexp for d, and pick up specialised calls in the body of f.
1244
1245 This doesn't always work.  One example I came across was this:
1246         newtype Gen a = MkGen{ unGen :: Int -> a }
1247
1248         choose :: Eq a => a -> Gen a
1249         choose n = MkGen (\r -> n)
1250
1251         oneof = choose (1::Int)
1252
1253 It's a silly exapmle, but we get
1254         choose = /\a. g `cast` co
1255 where choose doesn't have any dict arguments.  Thus far I have not
1256 tried to fix this (wait till there's a real example).
1257
1258 Note [Inline specialisations]
1259 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1260 We transfer to the specialised function any INLINE stuff from the
1261 original.  This means 
1262    (a) the Activation for its inlining (from its InlinePragma)
1263    (b) any InlineRule
1264
1265 This is a change (Jun06).  Previously the idea is that the point of
1266 inlining was precisely to specialise the function at its call site,
1267 and that's not so important for the specialised copies.  But
1268 *pragma-directed* specialisation now takes place in the
1269 typechecker/desugarer, with manually specified INLINEs.  The
1270 specialiation here is automatic.  It'd be very odd if a function
1271 marked INLINE was specialised (because of some local use), and then
1272 forever after (including importing modules) the specialised version
1273 wasn't INLINEd.  After all, the programmer said INLINE!
1274
1275 You might wonder why we don't just not specialise INLINE functions.
1276 It's because even INLINE functions are sometimes not inlined, when 
1277 they aren't applied to interesting arguments.  But perhaps the type
1278 arguments alone are enough to specialise (even though the args are too
1279 boring to trigger inlining), and it's certainly better to call the 
1280 specialised version.
1281
1282
1283 %************************************************************************
1284 %*                                                                      *
1285 \subsubsection{UsageDetails and suchlike}
1286 %*                                                                      *
1287 %************************************************************************
1288
1289 \begin{code}
1290 data UsageDetails 
1291   = MkUD {
1292         ud_binds :: !(Bag DictBind),
1293                         -- Floated dictionary bindings
1294                         -- The order is important; 
1295                         -- in ds1 `union` ds2, bindings in ds2 can depend on those in ds1
1296                         -- (Remember, Bags preserve order in GHC.)
1297
1298         ud_calls :: !CallDetails  
1299
1300         -- INVARIANT: suppose bs = bindersOf ud_binds
1301         -- Then 'calls' may *mention* 'bs', 
1302         -- but there should be no calls *for* bs
1303     }
1304
1305 instance Outputable UsageDetails where
1306   ppr (MkUD { ud_binds = dbs, ud_calls = calls })
1307         = ptext (sLit "MkUD") <+> braces (sep (punctuate comma 
1308                 [ptext (sLit "binds") <+> equals <+> ppr dbs,
1309                  ptext (sLit "calls") <+> equals <+> ppr calls]))
1310
1311 type DictBind = (CoreBind, VarSet)
1312         -- The set is the free vars of the binding
1313         -- both tyvars and dicts
1314
1315 type DictExpr = CoreExpr
1316
1317 emptyUDs :: UsageDetails
1318 emptyUDs = MkUD { ud_binds = emptyBag, ud_calls = emptyVarEnv }
1319
1320 ------------------------------------------------------------                    
1321 type CallDetails  = IdEnv CallInfoSet
1322 newtype CallKey   = CallKey [Maybe Type]                        -- Nothing => unconstrained type argument
1323
1324 -- CallInfo uses a FiniteMap, thereby ensuring that
1325 -- we record only one call instance for any key
1326 --
1327 -- The list of types and dictionaries is guaranteed to
1328 -- match the type of f
1329 type CallInfoSet = FiniteMap CallKey ([DictExpr], VarSet)
1330                         -- Range is dict args and the vars of the whole
1331                         -- call (including tyvars)
1332                         -- [*not* include the main id itself, of course]
1333
1334 type CallInfo = (CallKey, ([DictExpr], VarSet))
1335
1336 instance Outputable CallKey where
1337   ppr (CallKey ts) = ppr ts
1338
1339 -- Type isn't an instance of Ord, so that we can control which
1340 -- instance we use.  That's tiresome here.  Oh well
1341 instance Eq CallKey where
1342   k1 == k2 = case k1 `compare` k2 of { EQ -> True; _ -> False }
1343
1344 instance Ord CallKey where
1345   compare (CallKey k1) (CallKey k2) = cmpList cmp k1 k2
1346                 where
1347                   cmp Nothing   Nothing   = EQ
1348                   cmp Nothing   (Just _)  = LT
1349                   cmp (Just _)  Nothing   = GT
1350                   cmp (Just t1) (Just t2) = tcCmpType t1 t2
1351
1352 unionCalls :: CallDetails -> CallDetails -> CallDetails
1353 unionCalls c1 c2 = plusVarEnv_C plusFM c1 c2
1354
1355 -- plusCalls :: UsageDetails -> CallDetails -> UsageDetails
1356 -- plusCalls uds call_ds = uds { ud_calls = ud_calls uds `unionCalls` call_ds }
1357
1358 callDetailsFVs :: CallDetails -> VarSet
1359 callDetailsFVs calls = foldVarEnv (unionVarSet . callInfoFVs) emptyVarSet calls
1360
1361 callInfoFVs :: CallInfoSet -> VarSet
1362 callInfoFVs call_info = foldFM (\_ (_,fv) vs -> unionVarSet fv vs) emptyVarSet call_info
1363
1364 ------------------------------------------------------------                    
1365 singleCall :: Id -> [Maybe Type] -> [DictExpr] -> UsageDetails
1366 singleCall id tys dicts 
1367   = MkUD {ud_binds = emptyBag, 
1368           ud_calls = unitVarEnv id (unitFM (CallKey tys) (dicts, call_fvs)) }
1369   where
1370     call_fvs = exprsFreeVars dicts `unionVarSet` tys_fvs
1371     tys_fvs  = tyVarsOfTypes (catMaybes tys)
1372         -- The type args (tys) are guaranteed to be part of the dictionary
1373         -- types, because they are just the constrained types,
1374         -- and the dictionary is therefore sure to be bound
1375         -- inside the binding for any type variables free in the type;
1376         -- hence it's safe to neglect tyvars free in tys when making
1377         -- the free-var set for this call
1378         -- BUT I don't trust this reasoning; play safe and include tys_fvs
1379         --
1380         -- We don't include the 'id' itself.
1381
1382 mkCallUDs :: Id -> [CoreExpr] -> UsageDetails
1383 mkCallUDs f args 
1384   | not (isLocalId f)   -- Imported from elsewhere
1385   || null theta         -- Not overloaded
1386   || not (all isClassPred theta)        
1387         -- Only specialise if all overloading is on class params. 
1388         -- In ptic, with implicit params, the type args
1389         --  *don't* say what the value of the implicit param is!
1390   || not (spec_tys `lengthIs` n_tyvars)
1391   || not ( dicts   `lengthIs` n_dicts)
1392   || not (any interestingDict dicts)    -- Note [Interesting dictionary arguments]
1393   -- See also Note [Specialisations already covered]
1394   = -- pprTrace "mkCallUDs: discarding" (vcat [ppr f, ppr args, ppr n_tyvars, ppr n_dicts, ppr (map interestingDict dicts)]) 
1395     emptyUDs    -- Not overloaded, or no specialisation wanted
1396
1397   | otherwise
1398   = -- pprTrace "mkCallUDs: keeping" (vcat [ppr f, ppr args, ppr n_tyvars, ppr n_dicts, ppr (map interestingDict dicts)]) 
1399     singleCall f spec_tys dicts
1400   where
1401     (tyvars, theta, _) = tcSplitSigmaTy (idType f)
1402     constrained_tyvars = tyVarsOfTheta theta 
1403     n_tyvars           = length tyvars
1404     n_dicts            = length theta
1405
1406     spec_tys = [mk_spec_ty tv ty | (tv, Type ty) <- tyvars `zip` args]
1407     dicts    = [dict_expr | (_, dict_expr) <- theta `zip` (drop n_tyvars args)]
1408     
1409     mk_spec_ty tyvar ty 
1410         | tyvar `elemVarSet` constrained_tyvars = Just ty
1411         | otherwise                             = Nothing
1412 \end{code}
1413
1414 Note [Interesting dictionary arguments]
1415 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1416 Consider this
1417          \a.\d:Eq a.  let f = ... in ...(f d)...
1418 There really is not much point in specialising f wrt the dictionary d,
1419 because the code for the specialised f is not improved at all, because
1420 d is lambda-bound.  We simply get junk specialisations.
1421
1422 What is "interesting"?  Just that it has *some* structure.  
1423
1424 \begin{code}
1425 interestingDict :: CoreExpr -> Bool
1426 -- A dictionary argument is interesting if it has *some* structure
1427 interestingDict (Var v) =  hasSomeUnfolding (idUnfolding v)
1428                         || isDataConWorkId v
1429 interestingDict (Type _)          = False
1430 interestingDict (App fn (Type _)) = interestingDict fn
1431 interestingDict (Note _ a)        = interestingDict a
1432 interestingDict (Cast e _)        = interestingDict e
1433 interestingDict _                 = True
1434 \end{code}
1435
1436 \begin{code}
1437 plusUDs :: UsageDetails -> UsageDetails -> UsageDetails
1438 plusUDs (MkUD {ud_binds = db1, ud_calls = calls1})
1439         (MkUD {ud_binds = db2, ud_calls = calls2})
1440   = MkUD { ud_binds = db1    `unionBags`   db2 
1441          , ud_calls = calls1 `unionCalls`  calls2 }
1442
1443 plusUDList :: [UsageDetails] -> UsageDetails
1444 plusUDList = foldr plusUDs emptyUDs
1445
1446 -----------------------------
1447 _dictBindBndrs :: Bag DictBind -> [Id]
1448 _dictBindBndrs dbs = foldrBag ((++) . bindersOf . fst) [] dbs
1449
1450 mkDB :: CoreBind -> DictBind
1451 mkDB bind = (bind, bind_fvs bind)
1452
1453 bind_fvs :: CoreBind -> VarSet
1454 bind_fvs (NonRec bndr rhs) = pair_fvs (bndr,rhs)
1455 bind_fvs (Rec prs)         = foldl delVarSet rhs_fvs bndrs
1456                            where
1457                              bndrs = map fst prs
1458                              rhs_fvs = unionVarSets (map pair_fvs prs)
1459
1460 pair_fvs :: (Id, CoreExpr) -> VarSet
1461 pair_fvs (bndr, rhs) = exprFreeVars rhs `unionVarSet` idFreeVars bndr
1462         -- Don't forget variables mentioned in the
1463         -- rules of the bndr.  C.f. OccAnal.addRuleUsage
1464         -- Also tyvars mentioned in its type; they may not appear in the RHS
1465         --      type T a = Int
1466         --      x :: T a = 3
1467
1468 flattenDictBinds :: Bag DictBind -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
1469 flattenDictBinds dbs pairs
1470   = foldrBag add pairs dbs
1471   where
1472     add (NonRec b r,_) pairs = (b,r) : pairs
1473     add (Rec prs1, _)  pairs = prs1 ++ pairs
1474
1475 snocDictBinds :: UsageDetails -> [CoreBind] -> UsageDetails
1476 -- Add ud_binds to the tail end of the bindings in uds
1477 snocDictBinds uds dbs
1478   = uds { ud_binds = ud_binds uds `unionBags` 
1479                      foldr (consBag . mkDB) emptyBag dbs }
1480
1481 consDictBind :: CoreBind -> UsageDetails -> UsageDetails
1482 consDictBind bind uds = uds { ud_binds = mkDB bind `consBag` ud_binds uds }
1483
1484 addDictBinds :: [DictBind] -> UsageDetails -> UsageDetails
1485 addDictBinds binds uds = uds { ud_binds = listToBag binds `unionBags` ud_binds uds }
1486
1487 snocDictBind :: UsageDetails -> CoreBind -> UsageDetails
1488 snocDictBind uds bind = uds { ud_binds = ud_binds uds `snocBag` mkDB bind }
1489
1490 wrapDictBinds :: Bag DictBind -> [CoreBind] -> [CoreBind]
1491 wrapDictBinds dbs binds
1492   = foldrBag add binds dbs
1493   where
1494     add (bind,_) binds = bind : binds
1495
1496 wrapDictBindsE :: Bag DictBind -> CoreExpr -> CoreExpr
1497 wrapDictBindsE dbs expr
1498   = foldrBag add expr dbs
1499   where
1500     add (bind,_) expr = Let bind expr
1501
1502 ----------------------
1503 dumpUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, Bag DictBind)
1504 -- Used at a lambda or case binder; just dump anything mentioning the binder
1505 dumpUDs bndrs uds@(MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })
1506   | null bndrs = (uds, emptyBag)  -- Common in case alternatives
1507   | otherwise  = -- pprTrace "dumpUDs" (ppr bndrs $$ ppr free_uds $$ ppr dump_dbs) $
1508                  (free_uds, dump_dbs)
1509   where
1510     free_uds = MkUD { ud_binds = free_dbs, ud_calls = free_calls }
1511     bndr_set = mkVarSet bndrs
1512     (free_dbs, dump_dbs, dump_set) = splitDictBinds orig_dbs bndr_set
1513     free_calls = deleteCallsMentioning dump_set $   -- Drop calls mentioning bndr_set on the floor
1514                  deleteCallsFor bndrs orig_calls    -- Discard calls for bndr_set; there should be 
1515                                                     -- no calls for any of the dicts in dump_dbs
1516
1517 dumpBindUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, Bag DictBind, Bool)
1518 -- Used at a lambda or case binder; just dump anything mentioning the binder
1519 dumpBindUDs bndrs (MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })
1520   = -- pprTrace "dumpBindUDs" (ppr bndrs $$ ppr free_uds $$ ppr dump_dbs) $
1521     (free_uds, dump_dbs, float_all)
1522   where
1523     free_uds = MkUD { ud_binds = free_dbs, ud_calls = free_calls }
1524     bndr_set = mkVarSet bndrs
1525     (free_dbs, dump_dbs, dump_set) = splitDictBinds orig_dbs bndr_set
1526     free_calls = deleteCallsFor bndrs orig_calls
1527     float_all = dump_set `intersectsVarSet` callDetailsFVs free_calls
1528
1529 callsForMe :: Id -> UsageDetails -> (UsageDetails, [CallInfo])
1530 callsForMe fn (MkUD { ud_binds = orig_dbs, ud_calls = orig_calls })
1531   = -- pprTrace ("callsForMe")
1532     --         (vcat [ppr fn, 
1533     --                text "Orig dbs ="     <+> ppr (_dictBindBndrs orig_dbs), 
1534     --                text "Orig calls ="   <+> ppr orig_calls,
1535     --                text "Dep set ="      <+> ppr dep_set, 
1536     --                text "Calls for me =" <+> ppr calls_for_me]) $
1537     (uds_without_me, calls_for_me)
1538   where
1539     uds_without_me = MkUD { ud_binds = orig_dbs, ud_calls = delVarEnv orig_calls fn }
1540     calls_for_me = case lookupVarEnv orig_calls fn of
1541                         Nothing -> []
1542                         Just cs -> filter_dfuns (fmToList cs)
1543
1544     dep_set = foldlBag go (unitVarSet fn) orig_dbs
1545     go dep_set (db,fvs) | fvs `intersectsVarSet` dep_set
1546                         = extendVarSetList dep_set (bindersOf db)
1547                         | otherwise = dep_set
1548
1549         -- Note [Specialisation of dictionary functions]
1550     filter_dfuns | isDFunId fn = filter ok_call
1551                  | otherwise   = \cs -> cs
1552
1553     ok_call (_, (_,fvs)) = not (fvs `intersectsVarSet` dep_set)
1554
1555 ----------------------
1556 splitDictBinds :: Bag DictBind -> IdSet -> (Bag DictBind, Bag DictBind, IdSet)
1557 -- Returns (free_dbs, dump_dbs, dump_set)
1558 splitDictBinds dbs bndr_set
1559    = foldlBag split_db (emptyBag, emptyBag, bndr_set) dbs
1560                 -- Important that it's foldl not foldr;
1561                 -- we're accumulating the set of dumped ids in dump_set
1562    where
1563     split_db (free_dbs, dump_dbs, dump_idset) db@(bind, fvs)
1564         | dump_idset `intersectsVarSet` fvs     -- Dump it
1565         = (free_dbs, dump_dbs `snocBag` db,
1566            extendVarSetList dump_idset (bindersOf bind))
1567
1568         | otherwise     -- Don't dump it
1569         = (free_dbs `snocBag` db, dump_dbs, dump_idset)
1570
1571
1572 ----------------------
1573 deleteCallsMentioning :: VarSet -> CallDetails -> CallDetails
1574 -- Remove calls *mentioning* bs 
1575 deleteCallsMentioning bs calls
1576   = mapVarEnv filter_calls calls
1577   where
1578     filter_calls :: CallInfoSet -> CallInfoSet
1579     filter_calls = filterFM (\_ (_, fvs) -> not (fvs `intersectsVarSet` bs))
1580
1581 deleteCallsFor :: [Id] -> CallDetails -> CallDetails
1582 -- Remove calls *for* bs
1583 deleteCallsFor bs calls = delVarEnvList calls bs
1584 \end{code}
1585
1586
1587 %************************************************************************
1588 %*                                                                      *
1589 \subsubsection{Boring helper functions}
1590 %*                                                                      *
1591 %************************************************************************
1592
1593 \begin{code}
1594 type SpecM a = UniqSM a
1595
1596 initSM :: UniqSupply -> SpecM a -> a
1597 initSM    = initUs_
1598
1599 mapAndCombineSM :: (a -> SpecM (b, UsageDetails)) -> [a] -> SpecM ([b], UsageDetails)
1600 mapAndCombineSM _ []     = return ([], emptyUDs)
1601 mapAndCombineSM f (x:xs) = do (y, uds1) <- f x
1602                               (ys, uds2) <- mapAndCombineSM f xs
1603                               return (y:ys, uds1 `plusUDs` uds2)
1604
1605 cloneBindSM :: Subst -> CoreBind -> SpecM (Subst, Subst, CoreBind)
1606 -- Clone the binders of the bind; return new bind with the cloned binders
1607 -- Return the substitution to use for RHSs, and the one to use for the body
1608 cloneBindSM subst (NonRec bndr rhs) = do
1609     us <- getUniqueSupplyM
1610     let (subst', bndr') = cloneIdBndr subst us bndr
1611     return (subst, subst', NonRec bndr' rhs)
1612
1613 cloneBindSM subst (Rec pairs) = do
1614     us <- getUniqueSupplyM
1615     let (subst', bndrs') = cloneRecIdBndrs subst us (map fst pairs)
1616     return (subst', subst', Rec (bndrs' `zip` map snd pairs))
1617
1618 newDictBndrs :: Subst -> [CoreBndr] -> SpecM (Subst, [CoreBndr])
1619 -- Make up completely fresh binders for the dictionaries
1620 -- Their bindings are going to float outwards
1621 newDictBndrs subst bndrs 
1622   = do { bndrs' <- mapM new bndrs
1623        ; let subst' = extendIdSubstList subst 
1624                         [(d, Var d') | (d,d') <- bndrs `zip` bndrs']
1625        ; return (subst', bndrs' ) }
1626   where
1627     new b = do { uniq <- getUniqueM
1628                ; let n   = idName b
1629                      ty' = CoreSubst.substTy subst (idType b)
1630                ; return (mkUserLocal (nameOccName n) uniq ty' (getSrcSpan n)) }
1631
1632 newSpecIdSM :: Id -> Type -> SpecM Id
1633     -- Give the new Id a similar occurrence name to the old one
1634 newSpecIdSM old_id new_ty
1635   = do  { uniq <- getUniqueM
1636         ; let name    = idName old_id
1637               new_occ = mkSpecOcc (nameOccName name)
1638               new_id  = mkUserLocal new_occ uniq new_ty (getSrcSpan name)
1639         ; return new_id }
1640 \end{code}
1641
1642
1643                 Old (but interesting) stuff about unboxed bindings
1644                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1645
1646 What should we do when a value is specialised to a *strict* unboxed value?
1647
1648         map_*_* f (x:xs) = let h = f x
1649                                t = map f xs
1650                            in h:t
1651
1652 Could convert let to case:
1653
1654         map_*_Int# f (x:xs) = case f x of h# ->
1655                               let t = map f xs
1656                               in h#:t
1657
1658 This may be undesirable since it forces evaluation here, but the value
1659 may not be used in all branches of the body. In the general case this
1660 transformation is impossible since the mutual recursion in a letrec
1661 cannot be expressed as a case.
1662
1663 There is also a problem with top-level unboxed values, since our
1664 implementation cannot handle unboxed values at the top level.
1665
1666 Solution: Lift the binding of the unboxed value and extract it when it
1667 is used:
1668
1669         map_*_Int# f (x:xs) = let h = case (f x) of h# -> _Lift h#
1670                                   t = map f xs
1671                               in case h of
1672                                  _Lift h# -> h#:t
1673
1674 Now give it to the simplifier and the _Lifting will be optimised away.
1675
1676 The benfit is that we have given the specialised "unboxed" values a
1677 very simplep lifted semantics and then leave it up to the simplifier to
1678 optimise it --- knowing that the overheads will be removed in nearly
1679 all cases.
1680
1681 In particular, the value will only be evaluted in the branches of the
1682 program which use it, rather than being forced at the point where the
1683 value is bound. For example:
1684
1685         filtermap_*_* p f (x:xs)
1686           = let h = f x
1687                 t = ...
1688             in case p x of
1689                 True  -> h:t
1690                 False -> t
1691    ==>
1692         filtermap_*_Int# p f (x:xs)
1693           = let h = case (f x) of h# -> _Lift h#
1694                 t = ...
1695             in case p x of
1696                 True  -> case h of _Lift h#
1697                            -> h#:t
1698                 False -> t
1699
1700 The binding for h can still be inlined in the one branch and the
1701 _Lifting eliminated.
1702
1703
1704 Question: When won't the _Lifting be eliminated?
1705
1706 Answer: When they at the top-level (where it is necessary) or when
1707 inlining would duplicate work (or possibly code depending on
1708 options). However, the _Lifting will still be eliminated if the
1709 strictness analyser deems the lifted binding strict.
1710