[project @ 1998-04-07 16:40:08 by simonpj]
[ghc-hetmet.git] / ghc / compiler / specialise / Specialise.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
3 %
4 \section[Specialise]{Stamping out overloading, and (optionally) polymorphism}
5
6 \begin{code}
7 module Specialise (
8         specProgram, 
9         idSpecVars
10     ) where
11
12 #include "HsVersions.h"
13
14 import MkId             ( mkUserLocal )
15 import Id               ( Id, DictVar, idType, mkTemplateLocals,
16
17                           getIdSpecialisation, setIdSpecialisation, isSpecPragmaId,
18
19                           IdSet, mkIdSet, addOneToIdSet, intersectIdSets, isEmptyIdSet, 
20                                  emptyIdSet, unionIdSets, minusIdSet, unitIdSet, elementOfIdSet,
21
22                           IdEnv, mkIdEnv, lookupIdEnv, addOneToIdEnv, delOneFromIdEnv
23                         )
24
25 import Type             ( Type, mkTyVarTy, splitSigmaTy, instantiateTy, isDictTy,
26                           tyVarsOfType, tyVarsOfTypes, applyTys, mkForAllTys
27                         )
28 import TyCon            ( TyCon )
29 import TyVar            ( TyVar, alphaTyVars,
30                           TyVarSet, mkTyVarSet, isEmptyTyVarSet, intersectTyVarSets,
31                                     elementOfTyVarSet, unionTyVarSets, emptyTyVarSet,
32                           TyVarEnv, mkTyVarEnv, delFromTyVarEnv
33                         )
34 import CoreSyn
35 import PprCore          ()      -- Instances 
36 import Name             ( NamedThing(..), getSrcLoc )
37 import SpecEnv          ( addToSpecEnv, lookupSpecEnv, specEnvValues )
38
39 import UniqSupply       ( UniqSupply,
40                           UniqSM, initUs, thenUs, returnUs, getUnique, mapUs
41                         )
42
43 import FiniteMap
44 import Maybes           ( MaybeErr(..), maybeToBool )
45 import Bag
46 import List             ( partition )
47 import Util             ( zipEqual )
48 import Outputable
49
50
51 infixr 9 `thenSM`
52 \end{code}
53
54 %************************************************************************
55 %*                                                                      *
56 \subsection[notes-Specialise]{Implementation notes [SLPJ, Aug 18 1993]}
57 %*                                                                      *
58 %************************************************************************
59
60 These notes describe how we implement specialisation to eliminate
61 overloading.
62
63 The specialisation pass works on Core
64 syntax, complete with all the explicit dictionary application,
65 abstraction and construction as added by the type checker.  The
66 existing type checker remains largely as it is.
67
68 One important thought: the {\em types} passed to an overloaded
69 function, and the {\em dictionaries} passed are mutually redundant.
70 If the same function is applied to the same type(s) then it is sure to
71 be applied to the same dictionary(s)---or rather to the same {\em
72 values}.  (The arguments might look different but they will evaluate
73 to the same value.)
74
75 Second important thought: we know that we can make progress by
76 treating dictionary arguments as static and worth specialising on.  So
77 we can do without binding-time analysis, and instead specialise on
78 dictionary arguments and no others.
79
80 The basic idea
81 ~~~~~~~~~~~~~~
82 Suppose we have
83
84         let f = <f_rhs>
85         in <body>
86
87 and suppose f is overloaded.
88
89 STEP 1: CALL-INSTANCE COLLECTION
90
91 We traverse <body>, accumulating all applications of f to types and
92 dictionaries.
93
94 (Might there be partial applications, to just some of its types and
95 dictionaries?  In principle yes, but in practice the type checker only
96 builds applications of f to all its types and dictionaries, so partial
97 applications could only arise as a result of transformation, and even
98 then I think it's unlikely.  In any case, we simply don't accumulate such
99 partial applications.)
100
101 There's a choice of whether to collect details of all *polymorphic* functions
102 or simply all *overloaded* ones.  How to sort this out?
103   Pass in a predicate on the function to say if it is "interesting"?
104   This is dependent on the user flags: SpecialiseOverloaded
105                                        SpecialiseUnboxed
106                                        SpecialiseAll
107
108 STEP 2: EQUIVALENCES
109
110 So now we have a collection of calls to f:
111         f t1 t2 d1 d2
112         f t3 t4 d3 d4
113         ...
114 Notice that f may take several type arguments.  To avoid ambiguity, we
115 say that f is called at type t1/t2 and t3/t4.
116
117 We take equivalence classes using equality of the *types* (ignoring
118 the dictionary args, which as mentioned previously are redundant).
119
120 STEP 3: SPECIALISATION
121
122 For each equivalence class, choose a representative (f t1 t2 d1 d2),
123 and create a local instance of f, defined thus:
124
125         f@t1/t2 = <f_rhs> t1 t2 d1 d2
126
127 f_rhs presumably has some big lambdas and dictionary lambdas, so lots
128 of simplification will now result.  However we don't actually *do* that
129 simplification.  Rather, we leave it for the simplifier to do.  If we
130 *did* do it, though, we'd get more call instances from the specialised
131 RHS.  We can work out what they are by instantiating the call-instance
132 set from f's RHS with the types t1, t2.
133
134 Add this new id to f's IdInfo, to record that f has a specialised version.
135
136 Before doing any of this, check that f's IdInfo doesn't already
137 tell us about an existing instance of f at the required type/s.
138 (This might happen if specialisation was applied more than once, or
139 it might arise from user SPECIALIZE pragmas.)
140
141 Recursion
142 ~~~~~~~~~
143 Wait a minute!  What if f is recursive?  Then we can't just plug in
144 its right-hand side, can we?
145
146 But it's ok.  The type checker *always* creates non-recursive definitions
147 for overloaded recursive functions.  For example:
148
149         f x = f (x+x)           -- Yes I know its silly
150
151 becomes
152
153         f a (d::Num a) = let p = +.sel a d
154                          in
155                          letrec fl (y::a) = fl (p y y)
156                          in
157                          fl
158
159 We still have recusion for non-overloaded functions which we
160 speciailise, but the recursive call should get specialised to the
161 same recursive version.
162
163
164 Polymorphism 1
165 ~~~~~~~~~~~~~~
166
167 All this is crystal clear when the function is applied to *constant
168 types*; that is, types which have no type variables inside.  But what if
169 it is applied to non-constant types?  Suppose we find a call of f at type
170 t1/t2.  There are two possibilities:
171
172 (a) The free type variables of t1, t2 are in scope at the definition point
173 of f.  In this case there's no problem, we proceed just as before.  A common
174 example is as follows.  Here's the Haskell:
175
176         g y = let f x = x+x
177               in f y + f y
178
179 After typechecking we have
180
181         g a (d::Num a) (y::a) = let f b (d'::Num b) (x::b) = +.sel b d' x x
182                                 in +.sel a d (f a d y) (f a d y)
183
184 Notice that the call to f is at type type "a"; a non-constant type.
185 Both calls to f are at the same type, so we can specialise to give:
186
187         g a (d::Num a) (y::a) = let f@a (x::a) = +.sel a d x x
188                                 in +.sel a d (f@a y) (f@a y)
189
190
191 (b) The other case is when the type variables in the instance types
192 are *not* in scope at the definition point of f.  The example we are
193 working with above is a good case.  There are two instances of (+.sel a d),
194 but "a" is not in scope at the definition of +.sel.  Can we do anything?
195 Yes, we can "common them up", a sort of limited common sub-expression deal.
196 This would give:
197
198         g a (d::Num a) (y::a) = let +.sel@a = +.sel a d
199                                     f@a (x::a) = +.sel@a x x
200                                 in +.sel@a (f@a y) (f@a y)
201
202 This can save work, and can't be spotted by the type checker, because
203 the two instances of +.sel weren't originally at the same type.
204
205 Further notes on (b)
206
207 * There are quite a few variations here.  For example, the defn of
208   +.sel could be floated ouside the \y, to attempt to gain laziness.
209   It certainly mustn't be floated outside the \d because the d has to
210   be in scope too.
211
212 * We don't want to inline f_rhs in this case, because
213 that will duplicate code.  Just commoning up the call is the point.
214
215 * Nothing gets added to +.sel's IdInfo.
216
217 * Don't bother unless the equivalence class has more than one item!
218
219 Not clear whether this is all worth it.  It is of course OK to
220 simply discard call-instances when passing a big lambda.
221
222 Polymorphism 2 -- Overloading
223 ~~~~~~~~~~~~~~
224 Consider a function whose most general type is
225
226         f :: forall a b. Ord a => [a] -> b -> b
227
228 There is really no point in making a version of g at Int/Int and another
229 at Int/Bool, because it's only instancing the type variable "a" which
230 buys us any efficiency. Since g is completely polymorphic in b there
231 ain't much point in making separate versions of g for the different
232 b types.
233
234 That suggests that we should identify which of g's type variables
235 are constrained (like "a") and which are unconstrained (like "b").
236 Then when taking equivalence classes in STEP 2, we ignore the type args
237 corresponding to unconstrained type variable.  In STEP 3 we make
238 polymorphic versions.  Thus:
239
240         f@t1/ = /\b -> <f_rhs> t1 b d1 d2
241
242 We do this.
243
244
245 Dictionary floating
246 ~~~~~~~~~~~~~~~~~~~
247 Consider this
248
249         f a (d::Num a) = let g = ...
250                          in
251                          ...(let d1::Ord a = Num.Ord.sel a d in g a d1)...
252
253 Here, g is only called at one type, but the dictionary isn't in scope at the
254 definition point for g.  Usually the type checker would build a
255 definition for d1 which enclosed g, but the transformation system
256 might have moved d1's defn inward.  Solution: float dictionary bindings
257 outwards along with call instances.
258
259 Consider
260
261         f x = let g p q = p==q
262                   h r s = (r+s, g r s)
263               in
264               h x x
265
266
267 Before specialisation, leaving out type abstractions we have
268
269         f df x = let g :: Eq a => a -> a -> Bool
270                      g dg p q = == dg p q
271                      h :: Num a => a -> a -> (a, Bool)
272                      h dh r s = let deq = eqFromNum dh
273                                 in (+ dh r s, g deq r s)
274               in
275               h df x x
276
277 After specialising h we get a specialised version of h, like this:
278
279                     h' r s = let deq = eqFromNum df
280                              in (+ df r s, g deq r s)
281
282 But we can't naively make an instance for g from this, because deq is not in scope
283 at the defn of g.  Instead, we have to float out the (new) defn of deq
284 to widen its scope.  Notice that this floating can't be done in advance -- it only
285 shows up when specialisation is done.
286
287 User SPECIALIZE pragmas
288 ~~~~~~~~~~~~~~~~~~~~~~~
289 Specialisation pragmas can be digested by the type checker, and implemented
290 by adding extra definitions along with that of f, in the same way as before
291
292         f@t1/t2 = <f_rhs> t1 t2 d1 d2
293
294 Indeed the pragmas *have* to be dealt with by the type checker, because
295 only it knows how to build the dictionaries d1 and d2!  For example
296
297         g :: Ord a => [a] -> [a]
298         {-# SPECIALIZE f :: [Tree Int] -> [Tree Int] #-}
299
300 Here, the specialised version of g is an application of g's rhs to the
301 Ord dictionary for (Tree Int), which only the type checker can conjure
302 up.  There might not even *be* one, if (Tree Int) is not an instance of
303 Ord!  (All the other specialision has suitable dictionaries to hand
304 from actual calls.)
305
306 Problem.  The type checker doesn't have to hand a convenient <f_rhs>, because
307 it is buried in a complex (as-yet-un-desugared) binding group.
308 Maybe we should say
309
310         f@t1/t2 = f* t1 t2 d1 d2
311
312 where f* is the Id f with an IdInfo which says "inline me regardless!".
313 Indeed all the specialisation could be done in this way.
314 That in turn means that the simplifier has to be prepared to inline absolutely
315 any in-scope let-bound thing.
316
317
318 Again, the pragma should permit polymorphism in unconstrained variables:
319
320         h :: Ord a => [a] -> b -> b
321         {-# SPECIALIZE h :: [Int] -> b -> b #-}
322
323 We *insist* that all overloaded type variables are specialised to ground types,
324 (and hence there can be no context inside a SPECIALIZE pragma).
325 We *permit* unconstrained type variables to be specialised to
326         - a ground type
327         - or left as a polymorphic type variable
328 but nothing in between.  So
329
330         {-# SPECIALIZE h :: [Int] -> [c] -> [c] #-}
331
332 is *illegal*.  (It can be handled, but it adds complication, and gains the
333 programmer nothing.)
334
335
336 SPECIALISING INSTANCE DECLARATIONS
337 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
338 Consider
339
340         instance Foo a => Foo [a] where
341                 ...
342         {-# SPECIALIZE instance Foo [Int] #-}
343
344 The original instance decl creates a dictionary-function
345 definition:
346
347         dfun.Foo.List :: forall a. Foo a -> Foo [a]
348
349 The SPECIALIZE pragma just makes a specialised copy, just as for
350 ordinary function definitions:
351
352         dfun.Foo.List@Int :: Foo [Int]
353         dfun.Foo.List@Int = dfun.Foo.List Int dFooInt
354
355 The information about what instance of the dfun exist gets added to
356 the dfun's IdInfo in the same way as a user-defined function too.
357
358
359 Automatic instance decl specialisation?
360 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
361 Can instance decls be specialised automatically?  It's tricky.
362 We could collect call-instance information for each dfun, but
363 then when we specialised their bodies we'd get new call-instances
364 for ordinary functions; and when we specialised their bodies, we might get
365 new call-instances of the dfuns, and so on.  This all arises because of
366 the unrestricted mutual recursion between instance decls and value decls.
367
368 Still, there's no actual problem; it just means that we may not do all
369 the specialisation we could theoretically do.
370
371 Furthermore, instance decls are usually exported and used non-locally,
372 so we'll want to compile enough to get those specialisations done.
373
374 Lastly, there's no such thing as a local instance decl, so we can
375 survive solely by spitting out *usage* information, and then reading that
376 back in as a pragma when next compiling the file.  So for now,
377 we only specialise instance decls in response to pragmas.
378
379
380 SPITTING OUT USAGE INFORMATION
381 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
382
383 To spit out usage information we need to traverse the code collecting
384 call-instance information for all imported (non-prelude?) functions
385 and data types. Then we equivalence-class it and spit it out.
386
387 This is done at the top-level when all the call instances which escape
388 must be for imported functions and data types.
389
390 *** Not currently done ***
391
392
393 Partial specialisation by pragmas
394 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
395 What about partial specialisation:
396
397         k :: (Ord a, Eq b) => [a] -> b -> b -> [a]
398         {-# SPECIALIZE k :: Eq b => [Int] -> b -> b -> [a] #-}
399
400 or even
401
402         {-# SPECIALIZE k :: Eq b => [Int] -> [b] -> [b] -> [a] #-}
403
404 Seems quite reasonable.  Similar things could be done with instance decls:
405
406         instance (Foo a, Foo b) => Foo (a,b) where
407                 ...
408         {-# SPECIALIZE instance Foo a => Foo (a,Int) #-}
409         {-# SPECIALIZE instance Foo b => Foo (Int,b) #-}
410
411 Ho hum.  Things are complex enough without this.  I pass.
412
413
414 Requirements for the simplifer
415 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
416 The simplifier has to be able to take advantage of the specialisation.
417
418 * When the simplifier finds an application of a polymorphic f, it looks in
419 f's IdInfo in case there is a suitable instance to call instead.  This converts
420
421         f t1 t2 d1 d2   ===>   f_t1_t2
422
423 Note that the dictionaries get eaten up too!
424
425 * Dictionary selection operations on constant dictionaries must be
426   short-circuited:
427
428         +.sel Int d     ===>  +Int
429
430 The obvious way to do this is in the same way as other specialised
431 calls: +.sel has inside it some IdInfo which tells that if it's applied
432 to the type Int then it should eat a dictionary and transform to +Int.
433
434 In short, dictionary selectors need IdInfo inside them for constant
435 methods.
436
437 * Exactly the same applies if a superclass dictionary is being
438   extracted:
439
440         Eq.sel Int d   ===>   dEqInt
441
442 * Something similar applies to dictionary construction too.  Suppose
443 dfun.Eq.List is the function taking a dictionary for (Eq a) to
444 one for (Eq [a]).  Then we want
445
446         dfun.Eq.List Int d      ===> dEq.List_Int
447
448 Where does the Eq [Int] dictionary come from?  It is built in
449 response to a SPECIALIZE pragma on the Eq [a] instance decl.
450
451 In short, dfun Ids need IdInfo with a specialisation for each
452 constant instance of their instance declaration.
453
454 All this uses a single mechanism: the SpecEnv inside an Id
455
456
457 What does the specialisation IdInfo look like?
458 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
459
460 The SpecEnv of an Id maps a list of types (the template) to an expression
461
462         [Type]  |->  Expr
463
464 For example, if f has this SpecInfo:
465
466         [Int, a]  ->  \d:Ord Int. f' a
467
468 it means that we can replace the call
469
470         f Int t  ===>  (\d. f' t)
471
472 This chucks one dictionary away and proceeds with the
473 specialised version of f, namely f'.
474
475
476 What can't be done this way?
477 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
478 There is no way, post-typechecker, to get a dictionary for (say)
479 Eq a from a dictionary for Eq [a].  So if we find
480
481         ==.sel [t] d
482
483 we can't transform to
484
485         eqList (==.sel t d')
486
487 where
488         eqList :: (a->a->Bool) -> [a] -> [a] -> Bool
489
490 Of course, we currently have no way to automatically derive
491 eqList, nor to connect it to the Eq [a] instance decl, but you
492 can imagine that it might somehow be possible.  Taking advantage
493 of this is permanently ruled out.
494
495 Still, this is no great hardship, because we intend to eliminate
496 overloading altogether anyway!
497
498
499
500 A note about non-tyvar dictionaries
501 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
502 Some Ids have types like
503
504         forall a,b,c. Eq a -> Ord [a] -> tau
505
506 This seems curious at first, because we usually only have dictionary
507 args whose types are of the form (C a) where a is a type variable.
508 But this doesn't hold for the functions arising from instance decls,
509 which sometimes get arguements with types of form (C (T a)) for some
510 type constructor T.
511
512 Should we specialise wrt this compound-type dictionary?  We used to say
513 "no", saying:
514         "This is a heuristic judgement, as indeed is the fact that we 
515         specialise wrt only dictionaries.  We choose *not* to specialise
516         wrt compound dictionaries because at the moment the only place
517         they show up is in instance decls, where they are simply plugged
518         into a returned dictionary.  So nothing is gained by specialising
519         wrt them."
520
521 But it is simpler and more uniform to specialise wrt these dicts too;
522 and in future GHC is likely to support full fledged type signatures 
523 like
524         f ;: Eq [(a,b)] => ...
525
526
527 %************************************************************************
528 %*                                                                      *
529 \subsubsection{The new specialiser}
530 %*                                                                      *
531 %************************************************************************
532
533 Our basic game plan is this.  For let(rec) bound function
534         f :: (C a, D c) => (a,b,c,d) -> Bool
535
536 * Find any specialised calls of f, (f ts ds), where 
537   ts are the type arguments t1 .. t4, and
538   ds are the dictionary arguments d1 .. d2.
539
540 * Add a new definition for f1 (say):
541
542         f1 = /\ b d -> (..body of f..) t1 b t3 d d1 d2
543
544   Note that we abstract over the unconstrained type arguments.
545
546 * Add the mapping
547
548         [t1,b,t3,d]  |->  \d1 d2 -> f1 b d
549
550   to the specialisations of f.  This will be used by the
551   simplifier to replace calls 
552                 (f t1 t2 t3 t4) da db
553   by
554                 (\d1 d1 -> f1 t2 t4) da db
555
556   All the stuff about how many dictionaries to discard, and what types
557   to apply the specialised function to, are handled by the fact that the
558   SpecEnv contains a template for the result of the specialisation.
559
560 We don't build *partial* specialisations for f.  For example:
561
562   f :: Eq a => a -> a -> Bool
563   {-# SPECIALISE f :: (Eq b, Eq c) => (b,c) -> (b,c) -> Bool #-}
564
565 Here, little is gained by making a specialised copy of f.
566 There's a distinct danger that the specialised version would
567 first build a dictionary for (Eq b, Eq c), and then select the (==) 
568 method from it!  Even if it didn't, not a great deal is saved.
569
570 We do, however, generate polymorphic, but not overloaded, specialisations:
571
572   f :: Eq a => [a] -> b -> b -> b
573   {#- SPECIALISE f :: [Int] -> b -> b -> b #-}
574
575 Hence, the invariant is this: 
576
577         *** no specialised version is overloaded ***
578
579
580 %************************************************************************
581 %*                                                                      *
582 \subsubsection{The exported function}
583 %*                                                                      *
584 %************************************************************************
585
586 \begin{code}
587 specProgram :: UniqSupply -> [CoreBinding] -> [CoreBinding]
588 specProgram us binds
589   = initSM us (go binds         `thenSM` \ (binds', uds') ->
590                returnSM (dumpAllDictBinds uds' binds')
591               )
592   where
593     go []           = returnSM ([], emptyUDs)
594     go (bind:binds) = go binds          `thenSM` \ (binds', uds) ->
595                       specBind bind uds `thenSM` \ (bind', uds') ->
596                       returnSM (bind' ++ binds', uds')
597 \end{code}
598
599 %************************************************************************
600 %*                                                                      *
601 \subsubsection{@specExpr@: the main function}
602 %*                                                                      *
603 %************************************************************************
604
605 \begin{code}
606 specExpr :: CoreExpr -> SpecM (CoreExpr, UsageDetails)
607
608 ---------------- First the easy cases --------------------
609 specExpr e@(Var _)    = returnSM (e, emptyUDs)
610 specExpr e@(Lit _)    = returnSM (e, emptyUDs)
611 specExpr e@(Con _ _)  = returnSM (e, emptyUDs)
612 specExpr e@(Prim _ _) = returnSM (e, emptyUDs)
613
614 specExpr (Note note body)
615   = specExpr body       `thenSM` \ (body', uds) ->
616     returnSM (Note note body', uds)
617
618
619 ---------------- Applications might generate a call instance --------------------
620 specExpr e@(App fun arg)
621   = go fun [arg]
622   where
623     go (App fun arg) args = go fun (arg:args)
624     go (Var f)       args = returnSM (e, mkCallUDs f args)
625     go other         args = specExpr other      `thenSM` \ (e', uds) ->
626                             returnSM (foldl App e' args, uds)
627
628 ---------------- Lambda/case require dumping of usage details --------------------
629 specExpr e@(Lam _ _)
630   = specExpr body       `thenSM` \ (body', uds) ->
631     let
632         (filtered_uds, body'') = dumpUDs bndrs uds body'
633     in
634     returnSM (foldr Lam body'' bndrs, filtered_uds)
635   where
636     (bndrs, body) = go [] e
637
638         -- More efficient to collect a group of binders together all at once
639     go bndrs (Lam bndr e) = go (bndr:bndrs) e
640     go bndrs e            = (reverse bndrs, e)
641
642
643 specExpr (Case scrut alts)
644   = specExpr scrut      `thenSM` \ (scrut', uds_scrut) ->
645     spec_alts alts      `thenSM` \ (alts', uds_alts) ->
646     returnSM (Case scrut' alts', uds_scrut `plusUDs` uds_alts)
647   where
648     spec_alts (AlgAlts alts deflt)
649         = mapAndCombineSM spec_alg_alt alts     `thenSM` \ (alts', uds1) ->
650           spec_deflt deflt                      `thenSM` \ (deflt', uds2) ->
651           returnSM (AlgAlts alts' deflt', uds1 `plusUDs` uds2)
652
653     spec_alts (PrimAlts alts deflt)
654         = mapAndCombineSM spec_prim_alt alts    `thenSM` \ (alts', uds1) ->
655           spec_deflt deflt                      `thenSM` \ (deflt', uds2) ->
656           returnSM (PrimAlts alts' deflt', uds1 `plusUDs` uds2)
657
658     spec_alg_alt (con, args, rhs)
659         = specExpr rhs          `thenSM` \ (rhs', uds) ->
660           let
661              (uds', rhs'') = dumpUDs (map ValBinder args) uds rhs'
662           in
663           returnSM ((con, args, rhs''), uds')
664
665     spec_prim_alt (lit, rhs)
666         = specExpr rhs          `thenSM` \ (rhs', uds) ->
667           returnSM ((lit, rhs'), uds)
668
669     spec_deflt NoDefault = returnSM (NoDefault, emptyUDs)
670     spec_deflt (BindDefault arg rhs)
671         = specExpr rhs          `thenSM` \ (rhs', uds) ->
672           let
673              (uds', rhs'') = dumpUDs [ValBinder arg] uds rhs'
674           in
675           returnSM (BindDefault arg rhs'', uds')
676
677 ---------------- Finally, let is the interesting case --------------------
678 specExpr (Let bind body)
679   =     -- Deal with the body
680     specExpr body                               `thenSM` \ (body', body_uds) ->
681
682         -- Deal with the bindings
683     specBind bind body_uds                      `thenSM` \ (binds', uds) ->
684
685         -- All done
686     returnSM (foldr Let body' binds', uds)
687 \end{code}
688
689 %************************************************************************
690 %*                                                                      *
691 \subsubsection{Dealing with a binding}
692 %*                                                                      *
693 %************************************************************************
694
695 \begin{code}
696 specBind :: CoreBinding
697          -> UsageDetails                -- Info on how the scope of the binding
698          -> SpecM ([CoreBinding],       -- New bindings
699                    UsageDetails)        -- And info to pass upstream
700
701 specBind (NonRec bndr rhs) body_uds
702   | isDictTy (idType bndr)
703   =     -- It's a dictionary binding
704         -- Pick it up and float it outwards.
705     specExpr rhs                                `thenSM` \ (rhs', rhs_uds) ->
706     let
707         all_uds = rhs_uds `plusUDs` addDictBind body_uds bndr rhs'
708     in
709     returnSM ([], all_uds)
710
711   | isSpecPragmaId bndr
712   = specExpr rhs                                `thenSM` \ (rhs', rhs_uds) ->
713     returnSM ([], rhs_uds `plusUDs` body_uds)
714
715   | otherwise
716   =   -- Deal with the RHS, specialising it according
717       -- to the calls found in the body
718     specDefn (calls body_uds) (bndr,rhs)        `thenSM` \ ((bndr',rhs'), spec_defns, spec_uds) ->
719     let
720         (all_uds, (dict_binds, dump_calls)) 
721                 = splitUDs [ValBinder bndr] (spec_uds `plusUDs` body_uds)
722
723         -- If we make specialisations then we Rec the whole lot together
724         -- If not, leave it as a NonRec
725         new_bind | null spec_defns = NonRec bndr' rhs'
726                  | otherwise       = Rec ((bndr',rhs'):spec_defns)
727     in
728     returnSM ( new_bind : dict_binds, all_uds )
729
730 specBind (Rec pairs) body_uds
731   = mapSM (specDefn (calls body_uds)) pairs     `thenSM` \ stuff ->
732     let
733         (pairs', spec_defns_s, spec_uds_s) = unzip3 stuff
734         spec_defns = concat spec_defns_s
735         spec_uds   = plusUDList spec_uds_s
736         (all_uds, (dict_binds, dump_calls)) 
737                 = splitUDs (map (ValBinder . fst) pairs) (spec_uds `plusUDs` body_uds)
738         new_bind = Rec (spec_defns ++ pairs')
739     in
740     returnSM (  new_bind : dict_binds, all_uds )
741     
742 specDefn :: CallDetails                 -- Info on how it is used in its scope
743          -> (Id, CoreExpr)              -- The thing being bound and its un-processed RHS
744          -> SpecM ((Id, CoreExpr),      -- The thing and its processed RHS
745                                         --      the Id may now have specialisations attached
746                    [(Id,CoreExpr)],     -- Extra, specialised bindings
747                    UsageDetails         -- Stuff to fling upwards from the RHS and its
748             )                           --      specialised versions
749
750 specDefn calls (fn, rhs)
751         -- The first case is the interesting one
752   |  n_tyvars == length rhs_tyvars      -- Rhs of fn's defn has right number of big lambdas
753   && n_dicts  <= length rhs_bndrs       -- and enough dict args
754   && not (null calls_for_me)            -- And there are some calls to specialise
755   =   -- Specialise the body of the function
756     specExpr body                                       `thenSM` \ (body', body_uds) ->
757     let
758         (float_uds, bound_uds@(dict_binds,_)) = splitUDs rhs_bndrs body_uds
759     in
760
761       -- Make a specialised version for each call in calls_for_me
762     mapSM (spec_call bound_uds) calls_for_me            `thenSM` \ stuff ->
763     let
764         (spec_defns, spec_uds, spec_env_stuff) = unzip3 stuff
765
766         fn'  = addIdSpecialisations fn spec_env_stuff
767         rhs' = foldr Lam (foldr Let body' dict_binds) rhs_bndrs 
768     in
769     returnSM ((fn',rhs'), 
770               spec_defns, 
771               float_uds `plusUDs` plusUDList spec_uds)
772
773   | otherwise   -- No calls or RHS doesn't fit our preconceptions
774   = specExpr rhs                        `thenSM` \ (rhs', rhs_uds) ->
775     returnSM ((fn, rhs'), [], rhs_uds)
776   
777   where
778     fn_type              = idType fn
779     (tyvars, theta, tau) = splitSigmaTy fn_type
780     n_tyvars             = length tyvars
781     n_dicts              = length theta
782     mk_spec_tys call_ts  = zipWith mk_spec_ty call_ts alphaTyVars
783                          where
784                            mk_spec_ty (Just ty) _     = ty
785                            mk_spec_ty Nothing   tyvar = mkTyVarTy tyvar
786
787     (rhs_tyvars, rhs_ids, rhs_body) = collectBinders rhs
788     rhs_dicts = take n_dicts rhs_ids
789     rhs_bndrs = map TyBinder rhs_tyvars ++ map ValBinder rhs_dicts
790     body      = mkValLam (drop n_dicts rhs_ids) rhs_body
791                 -- Glue back on the non-dict lambdas
792
793     calls_for_me = case lookupFM calls fn of
794                         Nothing -> []
795                         Just cs -> fmToList cs
796
797     ----------------------------------------------------------
798         -- Specialise to one particular call pattern
799     spec_call :: ProtoUsageDetails          -- From the original body, captured by
800                                             -- the dictionary lambdas
801               -> ([Maybe Type], [DictVar])  -- Call instance
802               -> SpecM ((Id,CoreExpr),            -- Specialised definition
803                         UsageDetails,             -- Usage details from specialised body
804                         ([TyVar], [Type], CoreExpr))       -- Info for the Id's SpecEnv
805     spec_call bound_uds (call_ts, call_ds)
806       = ASSERT( length call_ts == n_tyvars && length call_ds == n_dicts )
807                 -- Calls are only recorded for properly-saturated applications
808         
809         -- Supppose the call is for f [Just t1, Nothing, Just t3, Nothing] [d1, d2]
810
811                 -- Construct the new binding
812                 --      f1 = /\ b d -> (..rhs of f..) t1 b t3 d d1 d2
813                 -- and the type of this binder
814         let
815            spec_tyvars = [tyvar | (tyvar, Nothing) <- alphaTyVars `zip` call_ts]
816            spec_tys    = mk_spec_tys call_ts
817            spec_rhs    = mkTyLam spec_tyvars $
818                          mkGenApp rhs (map TyArg spec_tys ++ map VarArg call_ds)
819            spec_id_ty  = mkForAllTys spec_tyvars (instantiateTy ty_env tau)
820            ty_env      = mkTyVarEnv (zipEqual "spec_call" tyvars spec_tys)
821         in
822
823         newIdSM fn spec_id_ty           `thenSM` \ spec_f ->
824
825
826                 -- Construct the stuff for f's spec env
827                 --      [b,d] [t1,b,t3,d]  |->  \d1 d2 -> f1 b d
828                 -- The only awkward bit is that d1,d2 might well be global
829                 -- dictionaries, so it's tidier to make new local variables
830                 -- for the lambdas in the RHS, rather than lambda-bind the
831                 -- dictionaries themselves.
832                 --
833                 -- In fact we use the standard template locals, so that the
834                 -- they don't need to be "tidied" before putting in interface files
835         let
836            arg_ds        = mkTemplateLocals (map idType call_ds)
837            spec_env_rhs  = mkValLam arg_ds $
838                            mkTyApp (Var spec_f) $
839                            map mkTyVarTy spec_tyvars
840            spec_env_info = (spec_tyvars, spec_tys, spec_env_rhs)
841         in
842
843                 -- Specialise the UDs from f's RHS
844         let
845                 -- Only the overloaded tyvars should be free in the uds
846            ty_env   = [ (rhs_tyvar,ty) 
847                       | (rhs_tyvar, Just ty) <- zipEqual "specUDs1" rhs_tyvars call_ts
848                       ]
849            dict_env = zipEqual "specUDs2" rhs_dicts call_ds
850         in
851         specUDs ty_env dict_env bound_uds                       `thenSM` \ spec_uds ->
852
853         returnSM ((spec_f, spec_rhs),
854                   spec_uds,
855                   spec_env_info
856         )
857 \end{code}
858
859 %************************************************************************
860 %*                                                                      *
861 \subsubsection{UsageDetails and suchlike}
862 %*                                                                      *
863 %************************************************************************
864
865 \begin{code}
866 type FreeDicts = IdSet
867
868 data UsageDetails 
869   = MkUD {
870         dict_binds :: !(Bag (DictVar, CoreExpr, TyVarSet, FreeDicts)),
871                         -- Floated dictionary bindings
872                         -- The order is important; 
873                         -- in ds1 `union` ds2, bindings in ds2 can depend on those in ds1
874                         -- (Remember, Bags preserve order in GHC.)
875                         -- The FreeDicts is the free vars of the RHS
876
877         calls     :: !CallDetails
878     }
879
880 emptyUDs = MkUD { dict_binds = emptyBag, calls = emptyFM }
881
882 type ProtoUsageDetails = ([CoreBinding],                -- Dict bindings
883                           [(Id, [Maybe Type], [DictVar])]
884                          )
885
886 ------------------------------------------------------------                    
887 type CallDetails  = FiniteMap Id CallInfo
888 type CallInfo     = FiniteMap [Maybe Type]      -- Nothing => unconstrained type argument
889                               [DictVar]         -- Dict args
890         -- The finite maps eliminate duplicates
891         -- The list of types and dictionaries is guaranteed to
892         -- match the type of f
893
894 callDetailsToList calls = [ (id,tys,dicts)
895                           | (id,fm) <- fmToList calls,
896                             (tys,dicts) <- fmToList fm
897                           ]
898
899 listToCallDetails calls  = foldr (unionCalls . singleCall) emptyFM calls
900
901 unionCalls :: CallDetails -> CallDetails -> CallDetails
902 unionCalls c1 c2 = plusFM_C plusFM c1 c2
903
904 singleCall (id, tys, dicts) = unitFM id (unitFM tys dicts)
905
906 mkCallUDs f args 
907   | null theta
908   || length spec_tys /= n_tyvars
909   || length dicts    /= n_dicts
910   = emptyUDs    -- Not overloaded
911
912   | otherwise
913   = MkUD {dict_binds = emptyBag, 
914           calls = singleCall (f, spec_tys, dicts)
915     }
916   where
917     (tyvars, theta, tau) = splitSigmaTy (idType f)
918     constrained_tyvars   = foldr (unionTyVarSets . tyVarsOfTypes . snd) emptyTyVarSet theta 
919     n_tyvars             = length tyvars
920     n_dicts              = length theta
921
922     spec_tys = [mk_spec_ty tv ty | (tv, TyArg ty) <- tyvars `zip` args]
923     dicts    = [d | (_, VarArg d) <- theta `zip` (drop n_tyvars args)]
924     
925     mk_spec_ty tyvar ty | tyvar `elementOfTyVarSet` constrained_tyvars
926                         = Just ty
927                         | otherwise
928                         = Nothing
929
930 ------------------------------------------------------------                    
931 plusUDs :: UsageDetails -> UsageDetails -> UsageDetails
932 plusUDs (MkUD {dict_binds = db1, calls = calls1})
933         (MkUD {dict_binds = db2, calls = calls2})
934   = MkUD {dict_binds, calls}
935   where
936     dict_binds = db1    `unionBags`   db2 
937     calls      = calls1 `unionCalls`  calls2
938
939 plusUDList = foldr plusUDs emptyUDs
940
941 mkDB dict rhs = (dict, rhs, db_ftvs, db_fvs)
942               where
943                 db_ftvs = tyVarsOfType (idType dict)    -- Superset of RHS fvs
944                 db_fvs  = dictRhsFVs rhs
945
946 addDictBind uds dict rhs = uds { dict_binds = mkDB dict rhs `consBag` dict_binds uds }
947
948 dumpAllDictBinds (MkUD {dict_binds = dbs}) binds
949   = foldrBag add binds dbs
950   where
951     add (dict,rhs,_,_) binds = NonRec dict rhs : binds
952
953 dumpUDs :: [CoreBinder]
954         -> UsageDetails -> CoreExpr
955         -> (UsageDetails, CoreExpr)
956 dumpUDs bndrs uds body
957   = (free_uds, foldr Let body dict_binds)
958   where
959     (free_uds, (dict_binds, _)) = splitUDs bndrs uds
960
961 splitUDs :: [CoreBinder]
962          -> UsageDetails
963          -> (UsageDetails,              -- These don't mention the binders
964              ProtoUsageDetails)         -- These do
965              
966 splitUDs bndrs uds@(MkUD {dict_binds = orig_dbs, 
967                           calls      = orig_calls})
968
969   = if isEmptyBag dump_dbs && null dump_calls then
970         -- Common case: binder doesn't affect floats
971         (uds, ([],[]))  
972
973     else
974         -- Binders bind some of the fvs of the floats
975         (MkUD {dict_binds = free_dbs, 
976                calls      = listToCallDetails free_calls},
977          (bagToList dump_dbs, dump_calls)
978         )
979
980   where
981     tyvar_set    = mkTyVarSet [tv | TyBinder tv <- bndrs]
982     id_set       = mkIdSet    [id | ValBinder id <- bndrs]
983
984     (free_dbs, dump_dbs, dump_idset) 
985           = foldlBag dump_db (emptyBag, emptyBag, id_set) orig_dbs
986                 -- Important that it's foldl not foldr;
987                 -- we're accumulating the set of dumped ids in dump_set
988
989         -- Filter out any calls that mention things that are being dumped
990         -- Don't need to worry about the tyvars because the dicts will
991         -- spot the captured ones; any fully polymorphic arguments will
992         -- be Nothings in the call details
993     orig_call_list = callDetailsToList orig_calls
994     (dump_calls, free_calls) = partition captured orig_call_list
995     captured (id,tys,dicts)  = any (`elementOfIdSet` dump_idset) (id:dicts)
996
997     dump_db (free_dbs, dump_dbs, dump_idset) db@(dict, rhs, ftvs, fvs)
998         |  isEmptyIdSet    (dump_idset `intersectIdSets`    fvs)
999         && isEmptyTyVarSet (tyvar_set  `intersectTyVarSets` ftvs)
1000         = (free_dbs `snocBag` db, dump_dbs, dump_idset)
1001
1002         | otherwise     -- Dump it
1003         = (free_dbs, dump_dbs `snocBag` NonRec dict rhs, 
1004            dump_idset `addOneToIdSet` dict)
1005 \end{code}
1006
1007 Given a type and value substitution, specUDs creates a specialised copy of
1008 the given UDs
1009
1010 \begin{code}
1011 specUDs :: [(TyVar,Type)] -> [(DictVar,DictVar)] -> ProtoUsageDetails -> SpecM UsageDetails
1012 specUDs tv_env_list dict_env_list (dbs, calls)
1013   = specDBs dict_env dbs                `thenSM` \ (dict_env', dbs') ->
1014     returnSM (MkUD { dict_binds = dbs',
1015                      calls      = listToCallDetails (map (inst_call dict_env') calls)
1016     })
1017   where
1018     tv_env   = mkTyVarEnv tv_env_list
1019     dict_env = mkIdEnv dict_env_list
1020
1021     inst_call dict_env (id, tys, dicts) = (id, map inst_maybe_ty tys, 
1022                                                map (lookupId dict_env) dicts)
1023
1024     inst_maybe_ty Nothing   = Nothing
1025     inst_maybe_ty (Just ty) = Just (instantiateTy tv_env ty)
1026
1027     specDBs dict_env []
1028         = returnSM (dict_env, emptyBag)
1029     specDBs dict_env (NonRec dict rhs : dbs)
1030         = newIdSM dict (instantiateTy tv_env (idType dict))     `thenSM` \ dict' ->
1031           let
1032             dict_env' = addOneToIdEnv dict_env dict dict'
1033             rhs'      = instantiateDictRhs tv_env dict_env rhs
1034           in
1035           specDBs dict_env' dbs         `thenSM` \ (dict_env'', dbs') ->
1036           returnSM ( dict_env'', mkDB dict' rhs' `consBag` dbs' )
1037 \end{code}
1038
1039 %************************************************************************
1040 %*                                                                      *
1041 \subsubsection{Boring helper functions}
1042 %*                                                                      *
1043 %************************************************************************
1044
1045 \begin{code}
1046 lookupId:: IdEnv Id -> Id -> Id
1047 lookupId env id = case lookupIdEnv env id of
1048                         Nothing  -> id
1049                         Just id' -> id'
1050
1051 instantiateDictRhs :: TyVarEnv Type -> IdEnv Id -> CoreExpr -> CoreExpr
1052         -- Cheapo function for simple RHSs
1053 instantiateDictRhs ty_env id_env rhs
1054   = go rhs
1055   where
1056     go_arg (VarArg a) = VarArg (lookupId id_env a)
1057     go_arg (TyArg t)  = TyArg (instantiateTy ty_env t)
1058
1059     go (App e1 arg)   = App (go e1) (go_arg arg)
1060     go (Var v)        = Var (lookupId id_env v)
1061     go (Lit l)        = Lit l
1062     go (Con con args) = Con con (map go_arg args)
1063     go (Note n e)     = Note (go_note n) (go e)
1064     go (Case e alts)  = Case (go e) alts                -- See comment below re alts
1065     go other          = pprPanic "instantiateDictRhs" (ppr rhs)
1066
1067     go_note (Coerce t1 t2) = Coerce (instantiateTy ty_env t1) (instantiateTy ty_env t2)
1068     go_note note           = note
1069
1070 dictRhsFVs :: CoreExpr -> IdSet
1071         -- Cheapo function for simple RHSs
1072 dictRhsFVs e
1073   = go e
1074   where
1075     go (App e1 (VarArg a)) = go e1 `addOneToIdSet` a
1076     go (App e1 (LitArg l)) = go e1
1077     go (App e1 (TyArg t))  = go e1
1078     go (Var v)             = unitIdSet v
1079     go (Lit l)             = emptyIdSet
1080     go (Con _ args)        = mkIdSet [id | VarArg id <- args]
1081     go (Note _ e)          = go e
1082
1083     go (Case e _)          = go e       -- Claim: no free dictionaries in the alternatives
1084                                         -- These case expressions are of the form
1085                                         --   case d of { D a b c -> b }
1086
1087     go other               = pprPanic "dictRhsFVs" (ppr e)
1088
1089
1090 addIdSpecialisations id spec_stuff
1091   = (if not (null errs) then
1092         pprTrace "Duplicate specialisations" (vcat (map ppr errs))
1093      else \x -> x
1094     )
1095     setIdSpecialisation id new_spec_env
1096   where
1097     (new_spec_env, errs) = foldr add (getIdSpecialisation id, []) spec_stuff
1098
1099     add (tyvars, tys, template) (spec_env, errs)
1100         = case addToSpecEnv True spec_env tyvars tys template of
1101                 Succeeded spec_env' -> (spec_env', errs)
1102                 Failed err          -> (spec_env, err:errs)
1103
1104 -- Given an Id, isSpecVars returns all its specialisations.
1105 -- We extract these from its SpecEnv.
1106 -- This is used by the occurrence analyser and free-var finder;
1107 -- we regard an Id's specialisations as free in the Id's definition.
1108
1109 idSpecVars :: Id -> [Id]
1110 idSpecVars id 
1111   = map get_spec (specEnvValues (getIdSpecialisation id))
1112   where
1113     -- get_spec is another cheapo function like dictRhsFVs
1114     -- It knows what these specialisation temlates look like,
1115     -- and just goes for the jugular
1116     get_spec (App f _) = get_spec f
1117     get_spec (Lam _ b) = get_spec b
1118     get_spec (Var v)   = v
1119
1120 ----------------------------------------
1121 type SpecM a = UniqSM a
1122
1123 thenSM    = thenUs
1124 returnSM  = returnUs
1125 getUniqSM = getUnique
1126 mapSM     = mapUs
1127 initSM    = initUs
1128
1129 mapAndCombineSM f []     = returnSM ([], emptyUDs)
1130 mapAndCombineSM f (x:xs) = f x  `thenSM` \ (y, uds1) ->
1131                            mapAndCombineSM f xs `thenSM` \ (ys, uds2) ->
1132                            returnSM (y:ys, uds1 `plusUDs` uds2)
1133
1134 newIdSM old_id new_ty
1135   = getUnique           `thenSM` \ uniq ->
1136     returnSM (mkUserLocal (getOccName old_id) 
1137                           uniq
1138                           new_ty
1139                           (getSrcLoc old_id)
1140     )
1141 \end{code}
1142
1143
1144                 Old (but interesting) stuff about unboxed bindings
1145                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1146
1147 What should we do when a value is specialised to a *strict* unboxed value?
1148
1149         map_*_* f (x:xs) = let h = f x
1150                                t = map f xs
1151                            in h:t
1152
1153 Could convert let to case:
1154
1155         map_*_Int# f (x:xs) = case f x of h# ->
1156                               let t = map f xs
1157                               in h#:t
1158
1159 This may be undesirable since it forces evaluation here, but the value
1160 may not be used in all branches of the body. In the general case this
1161 transformation is impossible since the mutual recursion in a letrec
1162 cannot be expressed as a case.
1163
1164 There is also a problem with top-level unboxed values, since our
1165 implementation cannot handle unboxed values at the top level.
1166
1167 Solution: Lift the binding of the unboxed value and extract it when it
1168 is used:
1169
1170         map_*_Int# f (x:xs) = let h = case (f x) of h# -> _Lift h#
1171                                   t = map f xs
1172                               in case h of
1173                                  _Lift h# -> h#:t
1174
1175 Now give it to the simplifier and the _Lifting will be optimised away.
1176
1177 The benfit is that we have given the specialised "unboxed" values a
1178 very simplep lifted semantics and then leave it up to the simplifier to
1179 optimise it --- knowing that the overheads will be removed in nearly
1180 all cases.
1181
1182 In particular, the value will only be evaluted in the branches of the
1183 program which use it, rather than being forced at the point where the
1184 value is bound. For example:
1185
1186         filtermap_*_* p f (x:xs)
1187           = let h = f x
1188                 t = ...
1189             in case p x of
1190                 True  -> h:t
1191                 False -> t
1192    ==>
1193         filtermap_*_Int# p f (x:xs)
1194           = let h = case (f x) of h# -> _Lift h#
1195                 t = ...
1196             in case p x of
1197                 True  -> case h of _Lift h#
1198                            -> h#:t
1199                 False -> t
1200
1201 The binding for h can still be inlined in the one branch and the
1202 _Lifting eliminated.
1203
1204
1205 Question: When won't the _Lifting be eliminated?
1206
1207 Answer: When they at the top-level (where it is necessary) or when
1208 inlining would duplicate work (or possibly code depending on
1209 options). However, the _Lifting will still be eliminated if the
1210 strictness analyser deems the lifted binding strict.
1211