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