Tidy up the treatment of SPECIALISE pragmas
[ghc-hetmet.git] / compiler / deSugar / DsBinds.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Pattern-matching bindings (HsBinds and MonoBinds)
7
8 Handles @HsBinds@; those at the top level require different handling,
9 in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at
10 lower levels it is preserved with @let@/@letrec@s).
11
12 \begin{code}
13 {-# OPTIONS -w #-}
14 -- The above warning supression flag is a temporary kludge.
15 -- While working on this module you are encouraged to remove it and fix
16 -- any warnings in the module. See
17 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
18 -- for details
19
20 module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, 
21                  dsCoercion,
22                  AutoScc(..)
23   ) where
24
25 #include "HsVersions.h"
26
27 import {-# SOURCE #-}   DsExpr( dsLExpr, dsExpr )
28 import {-# SOURCE #-}   Match( matchWrapper )
29
30 import DsMonad
31 import DsGRHSs
32 import DsUtils
33
34 import HsSyn            -- lots of things
35 import CoreSyn          -- lots of things
36 import CoreUtils
37 import CoreFVs
38
39 import TcHsSyn          ( mkArbitraryType )     -- Mis-placed?
40 import TcType
41 import OccurAnal
42 import CostCentre
43 import Module
44 import Id
45 import Var      ( TyVar )
46 import VarSet
47 import Rules
48 import VarEnv
49 import Type
50 import Outputable
51 import SrcLoc
52 import Maybes
53 import Bag
54 import BasicTypes hiding ( TopLevel )
55 import FastString
56 import Util             ( mapSnd )
57
58 import Control.Monad
59 import Data.List
60 \end{code}
61
62 %************************************************************************
63 %*                                                                      *
64 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
65 %*                                                                      *
66 %************************************************************************
67
68 \begin{code}
69 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
70 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
71
72 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
73 dsLHsBinds binds = ds_lhs_binds NoSccs binds
74
75
76 ------------------------
77 ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
78          -- scc annotation policy (see below)
79 ds_lhs_binds auto_scc binds =  foldM (dsLHsBind auto_scc) [] (bagToList binds)
80
81 dsLHsBind :: AutoScc
82          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
83          -> LHsBind Id
84          -> DsM [(Id,CoreExpr)] -- Result
85 dsLHsBind auto_scc rest (L loc bind)
86   = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
87
88 dsHsBind :: AutoScc
89          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
90          -> HsBind Id
91          -> DsM [(Id,CoreExpr)] -- Result
92
93 dsHsBind auto_scc rest (VarBind var expr)
94   = dsLExpr expr                `thenDs` \ core_expr ->
95
96         -- Dictionary bindings are always VarMonoBinds, so
97         -- we only need do this here
98     addDictScc var core_expr    `thenDs` \ core_expr' ->
99     returnDs ((var, core_expr') : rest)
100
101 dsHsBind auto_scc rest (FunBind { fun_id = L _ fun, fun_matches = matches, 
102                                   fun_co_fn = co_fn, fun_tick = tick, fun_infix = inf })
103   = matchWrapper (FunRhs (idName fun) inf) matches      `thenDs` \ (args, body) ->
104     mkOptTickBox tick body                              `thenDs` \ body' ->
105     dsCoercion co_fn (return (mkLams args body'))       `thenDs` \ rhs ->
106     returnDs ((fun,rhs) : rest)
107
108 dsHsBind auto_scc rest (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty })
109   = dsGuarded grhss ty                          `thenDs` \ body_expr ->
110     mkSelectorBinds pat body_expr               `thenDs` \ sel_binds ->
111     returnDs (sel_binds ++ rest)
112
113 -- Note [Rules and inlining]
114 -- Common special case: no type or dictionary abstraction
115 -- This is a bit less trivial than you might suppose
116 -- The naive way woudl be to desguar to something like
117 --      f_lcl = ...f_lcl...     -- The "binds" from AbsBinds
118 --      M.f = f_lcl             -- Generated from "exports"
119 -- But we don't want that, because if M.f isn't exported,
120 -- it'll be inlined unconditionally at every call site (its rhs is 
121 -- trivial).  That would be ok unless it has RULES, which would 
122 -- thereby be completely lost.  Bad, bad, bad.
123 --
124 -- Instead we want to generate
125 --      M.f = ...f_lcl...
126 --      f_lcl = M.f
127 -- Now all is cool. The RULES are attached to M.f (by SimplCore), 
128 -- and f_lcl is rapidly inlined away.
129 --
130 -- This does not happen in the same way to polymorphic binds,
131 -- because they desugar to
132 --      M.f = /\a. let f_lcl = ...f_lcl... in f_lcl
133 -- Although I'm a bit worried about whether full laziness might
134 -- float the f_lcl binding out and then inline M.f at its call site
135
136 dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
137   = do  { core_prs <- ds_lhs_binds NoSccs binds
138         ; let env = mkABEnv exports
139               do_one (lcl_id, rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
140                                    = addInlinePrags prags gbl_id $
141                                      addAutoScc auto_scc gbl_id rhs
142                                    | otherwise = (lcl_id, rhs)
143               locals'  = [(lcl_id, Var gbl_id) | (_, gbl_id, lcl_id, _) <- exports]
144         ; return (map do_one core_prs ++ locals' ++ rest) }
145                 -- No Rec needed here (contrast the other AbsBinds cases)
146                 -- because we can rely on the enclosing dsBind to wrap in Rec
147
148         -- Another common case: one exported variable
149         -- Non-recursive bindings come through this way
150 dsHsBind auto_scc rest
151      (AbsBinds all_tyvars dicts exports@[(tyvars, global, local, prags)] binds)
152   = ASSERT( all (`elem` tyvars) all_tyvars )
153     ds_lhs_binds NoSccs binds   `thenDs` \ core_prs ->
154     let 
155         -- Always treat the binds as recursive, because the typechecker
156         -- makes rather mixed-up dictionary bindings
157         core_bind = Rec core_prs
158     in
159     mappM (dsSpec all_tyvars dicts tyvars global local core_bind) 
160           prags                         `thenDs` \ mb_specs ->
161     let
162         (spec_binds, rules) = unzip (catMaybes mb_specs)
163         global' = addIdSpecialisations global rules
164         rhs'    = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
165         bind    = addInlinePrags prags global' $ addAutoScc auto_scc global' rhs'
166     in
167     returnDs (bind  : spec_binds ++ rest)
168
169 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
170   = do  { core_prs <- ds_lhs_binds NoSccs binds
171         ; let env = mkABEnv exports
172               do_one (lcl_id,rhs) | Just (gbl_id, prags) <- lookupVarEnv env lcl_id
173                                   = addInlinePrags prags lcl_id $
174                                     addAutoScc auto_scc gbl_id rhs
175                                   | otherwise = (lcl_id,rhs)
176                
177                 -- Rec because of mixed-up dictionary bindings
178               core_bind = Rec (map do_one core_prs)
179
180               tup_expr      = mkBigCoreVarTup locals
181               tup_ty        = exprType tup_expr
182               poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
183                               Let core_bind tup_expr
184               locals        = [local | (_, _, local, _) <- exports]
185               local_tys     = map idType locals
186
187         ; poly_tup_id <- newSysLocalDs (exprType poly_tup_expr)
188
189         ; let dict_args = map Var dicts
190
191               mk_bind ((tyvars, global, local, prags), n)       -- locals !! n == local
192                 =       -- Need to make fresh locals to bind in the selector, because
193                         -- some of the tyvars will be bound to 'Any'
194                   do { ty_args <- mapM mk_ty_arg all_tyvars
195                      ; let substitute = substTyWith all_tyvars ty_args
196                      ; locals' <- newSysLocalsDs (map substitute local_tys)
197                      ; tup_id  <- newSysLocalDs  (substitute tup_ty)
198                      ; mb_specs <- mapM (dsSpec all_tyvars dicts tyvars global local core_bind) 
199                                          prags
200                      ; let (spec_binds, rules) = unzip (catMaybes mb_specs)
201                            global' = addIdSpecialisations global rules
202                            rhs = mkLams tyvars $ mkLams dicts $
203                                  mkTupleSelector locals' (locals' !! n) tup_id $
204                                  mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
205                      ; returnDs ((global', rhs) : spec_binds) }
206                 where
207                   mk_ty_arg all_tyvar
208                         | all_tyvar `elem` tyvars = return (mkTyVarTy all_tyvar)
209                         | otherwise               = dsMkArbitraryType all_tyvar
210
211         ; export_binds_s <- mappM mk_bind (exports `zip` [0..])
212              -- don't scc (auto-)annotate the tuple itself.
213
214         ; returnDs ((poly_tup_id, poly_tup_expr) : 
215                     (concat export_binds_s ++ rest)) }
216
217 mkABEnv :: [([TyVar], Id, Id, [LPrag])] -> VarEnv (Id, [LPrag])
218 -- Takes the exports of a AbsBinds, and returns a mapping
219 --      lcl_id -> (gbl_id, prags)
220 mkABEnv exports = mkVarEnv [ (lcl_id, (gbl_id, prags)) 
221                            | (_, gbl_id, lcl_id, prags) <- exports]
222
223
224 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
225        -> Id -> Id              -- Global, local
226        -> CoreBind -> LPrag
227        -> DsM (Maybe ((Id,CoreExpr),    -- Binding for specialised Id
228                       CoreRule))        -- Rule for the Global Id
229
230 -- Example:
231 --      f :: (Eq a, Ix b) => a -> b -> b
232 --      {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
233 --
234 --      AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
235 -- 
236 --      SpecPrag (/\b.\(d:Ix b). f Int b dInt d) 
237 --               (forall b. Ix b => Int -> b -> b)
238 --
239 -- Rule:        forall b,(d:Ix b). f Int b dInt d = f_spec b d
240 --
241 -- Spec bind:   f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono 
242 --                       /\b.\(d:Ix b). in f Int b dInt d
243 --              The idea is that f occurs just once, so it'll be 
244 --              inlined and specialised
245 --
246 -- Given SpecPrag (/\as.\ds. f es) t, we have
247 -- the defn             f_spec as ds = let-nonrec f = /\fas\fds. let f_mono = <f-rhs> in f_mono
248 --                                     in f es 
249 -- and the RULE         forall as, ds. f es = f_spec as ds
250 --
251 -- It is *possible* that 'es' does not mention all of the dictionaries 'ds'
252 -- (a bit silly, because then the 
253 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (L _ (InlinePrag {}))
254   = return Nothing
255
256 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
257        (L loc (SpecPrag spec_expr spec_ty inl))
258   = putSrcSpanDs loc $ 
259     do  { let poly_name = idName poly_id
260         ; spec_name <- newLocalName poly_name
261         ; ds_spec_expr  <- dsExpr spec_expr
262         ; let (bndrs, body) = collectBinders (occurAnalyseExpr ds_spec_expr)
263                 -- The occurrence-analysis does two things
264                 -- (a) identifies unused binders: Note [Unused spec binders]
265                 -- (b) sorts dict bindings into NonRecs 
266                 --      so they can be inlined by decomposeRuleLhs
267               mb_lhs = decomposeRuleLhs body
268
269         -- Check for dead binders: Note [Unused spec binders]
270         ; case filter isDeadBinder bndrs of {
271                 bs | not (null bs) -> do { warnDs (dead_msg bs); return Nothing }
272                    | otherwise -> 
273
274           case mb_lhs of
275             Nothing -> do { warnDs decomp_msg; return Nothing }
276
277             Just (var, args) -> do
278         
279         { f_body <- fix_up (Let mono_bind (Var mono_id))
280
281         ; let     local_poly  = setIdNotExported poly_id
282                         -- Very important to make the 'f' non-exported,
283                         -- else it won't be inlined!
284                   spec_id     = mkLocalId spec_name spec_ty
285                   spec_rhs    = Let (NonRec local_poly poly_f_body) ds_spec_expr
286                   poly_f_body = mkLams (tvs ++ dicts) f_body
287                                 
288                   extra_dict_bndrs = filter isDictId (varSetElems (exprFreeVars ds_spec_expr))
289                         -- Note [Const rule dicts]
290
291                   rule =  mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
292                                 AlwaysActive poly_name
293                                 (extra_dict_bndrs ++ bndrs) args
294                                 (mkVarApps (Var spec_id) bndrs)
295         ; return (Just (addInlineInfo inl spec_id spec_rhs, rule))
296         } } }
297   where
298         -- Bind to Any any of all_ptvs that aren't 
299         -- relevant for this particular function 
300     fix_up body | null void_tvs = return body
301                 | otherwise     = do { void_tys <- mapM dsMkArbitraryType void_tvs
302                                      ; return (mkTyApps (mkLams void_tvs body) void_tys) }
303
304     void_tvs = all_tvs \\ tvs
305
306     dead_msg bs = vcat [ sep [ptext SLIT("Useless constraint") <> plural bs
307                                  <+> ptext SLIT("in specialied type:"),
308                              nest 2 (pprTheta (map get_pred bs))]
309                        , ptext SLIT("SPECIALISE pragma ignored")]
310     get_pred b = ASSERT( isId b ) expectJust "dsSpec" (tcSplitPredTy_maybe (idType b))
311
312     decomp_msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
313                     2 (ppr spec_expr)
314
315 dsMkArbitraryType tv = mkArbitraryType warn tv
316   where
317     warn span msg = putSrcSpanDs span (warnDs msg)
318 \end{code}
319
320 Note [Unused spec binders]
321 ~~~~~~~~~~~~~~~~~~~~~~~~~~
322 Consider
323         f :: a -> a
324         {-# SPECIALISE f :: Eq a => a -> a #-}
325 It's true that this *is* a more specialised type, but the rule
326 we get is something like this:
327         f_spec d = f
328         RULE: f = f_spec d
329 Note that the rule is bogus, becuase it mentions a 'd' that is
330 not bound on the LHS!  But it's a silly specialisation anyway, becuase
331 the constraint is unused.  We could bind 'd' to (error "unused")
332 but it seems better to reject the program because it's almost certainly
333 a mistake.  That's what the isDeadBinder call detects.
334
335 Note [Const rule dicts]
336 ~~~~~~~~~~~~~~~~~~~~~~~
337 When the LHS of a specialisation rule, (/\as\ds. f es) has a free dict, 
338 which is presumably in scope at the function definition site, we can quantify 
339 over it too.  *Any* dict with that type will do.
340
341 So for example when you have
342         f :: Eq a => a -> a
343         f = <rhs>
344         {-# SPECIALISE f :: Int -> Int #-}
345
346 Then we get the SpecPrag
347         SpecPrag (f Int dInt) Int
348
349 And from that we want the rule
350         
351         RULE forall dInt. f Int dInt = f_spec
352         f_spec = let f = <rhs> in f Int dInt
353
354
355
356 %************************************************************************
357 %*                                                                      *
358 \subsection{Adding inline pragmas}
359 %*                                                                      *
360 %************************************************************************
361
362 \begin{code}
363 decomposeRuleLhs :: CoreExpr -> Maybe (Id, [CoreExpr])
364 -- Returns Nothing if the LHS isn't of the expected shape
365 decomposeRuleLhs lhs 
366   = go emptyVarEnv (occurAnalyseExpr lhs)       -- Occurrence analysis sorts out the dict
367                                                 -- bindings so we know if they are recursive
368   where
369         -- Substitute dicts in the LHS args, so that there 
370         -- aren't any lets getting in the way
371         -- Note that we substitute the function too; we might have this as
372         -- a LHS:       let f71 = M.f Int in f71
373     go env (Let (NonRec dict rhs) body) 
374         = go (extendVarEnv env dict (simpleSubst env rhs)) body
375     go env body 
376         = case collectArgs (simpleSubst env body) of
377             (Var fn, args) -> Just (fn, args)
378             other          -> Nothing
379
380 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
381 -- Similar to CoreSubst.substExpr, except that 
382 -- (a) takes no account of capture; dictionary bindings use new names
383 -- (b) can have a GlobalId (imported) in its domain
384 -- (c) Ids only; no types are substituted
385 --
386 -- (b) is the reason we can't use CoreSubst... and it's no longer relevant
387 --      so really we should replace simpleSubst 
388 simpleSubst subst expr
389   = go expr
390   where
391     go (Var v)         = lookupVarEnv subst v `orElse` Var v
392     go (Cast e co)     = Cast (go e) co
393     go (Type ty)       = Type ty
394     go (Lit lit)       = Lit lit
395     go (App fun arg)   = App (go fun) (go arg)
396     go (Note note e)   = Note note (go e)
397     go (Lam bndr body) = Lam bndr (go body)
398     go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
399     go (Let (Rec pairs) body)       = Let (Rec (mapSnd go pairs)) (go body)
400     go (Case scrut bndr ty alts)    = Case (go scrut) bndr ty 
401                                            [(c,bs,go r) | (c,bs,r) <- alts]
402
403 addInlinePrags :: [LPrag] -> Id -> CoreExpr -> (Id,CoreExpr)
404 addInlinePrags prags bndr rhs
405   = case [inl | L _ (InlinePrag inl) <- prags] of
406         []      -> (bndr, rhs)
407         (inl:_) -> addInlineInfo inl bndr rhs
408
409 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
410 addInlineInfo (Inline phase is_inline) bndr rhs
411   = (attach_phase bndr phase, wrap_inline is_inline rhs)
412   where
413     attach_phase bndr phase 
414         | isAlwaysActive phase = bndr   -- Default phase
415         | otherwise            = bndr `setInlinePragma` phase
416
417     wrap_inline True  body = mkInlineMe body
418     wrap_inline False body = body
419 \end{code}
420
421
422 %************************************************************************
423 %*                                                                      *
424 \subsection[addAutoScc]{Adding automatic sccs}
425 %*                                                                      *
426 %************************************************************************
427
428 \begin{code}
429 data AutoScc = NoSccs 
430              | AddSccs Module (Id -> Bool)
431 -- The (Id->Bool) says which Ids to add SCCs to 
432
433 addAutoScc :: AutoScc   
434            -> Id        -- Binder
435            -> CoreExpr  -- Rhs
436            -> CoreExpr  -- Scc'd Rhs
437
438 addAutoScc NoSccs _ rhs
439   = rhs
440 addAutoScc (AddSccs mod add_scc) id rhs
441   | add_scc id = mkSCC (mkAutoCC id mod NotCafCC) rhs
442   | otherwise  = rhs
443 \end{code}
444
445 If profiling and dealing with a dict binding,
446 wrap the dict in @_scc_ DICT <dict>@:
447
448 \begin{code}
449 addDictScc var rhs = returnDs rhs
450
451 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
452   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
453     || not (isDictId var)
454   = returnDs rhs                                -- That's easy: do nothing
455
456   | otherwise
457   = getModuleAndGroupDs         `thenDs` \ (mod, grp) ->
458         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
459     returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
460 -}
461 \end{code}
462
463
464 %************************************************************************
465 %*                                                                      *
466                 Desugaring coercions
467 %*                                                                      *
468 %************************************************************************
469
470
471 \begin{code}
472 dsCoercion :: HsWrapper -> DsM CoreExpr -> DsM CoreExpr
473 dsCoercion WpHole            thing_inside = thing_inside
474 dsCoercion (WpCompose c1 c2) thing_inside = dsCoercion c1 (dsCoercion c2 thing_inside)
475 dsCoercion (WpCo co)     thing_inside = do { expr <- thing_inside
476                                                ; return (Cast expr co) }
477 dsCoercion (WpLam id)        thing_inside = do { expr <- thing_inside
478                                                ; return (Lam id expr) }
479 dsCoercion (WpTyLam tv)      thing_inside = do { expr <- thing_inside
480                                                ; return (Lam tv expr) }
481 dsCoercion (WpApp id)        thing_inside = do { expr <- thing_inside
482                                                ; return (App expr (Var id)) }
483 dsCoercion (WpTyApp ty)      thing_inside = do { expr <- thing_inside
484                                                ; return (App expr (Type ty)) }
485 dsCoercion WpInline          thing_inside = do { expr <- thing_inside
486                                                ; return (mkInlineMe expr) }
487 dsCoercion (WpLet bs)        thing_inside = do { prs <- dsLHsBinds bs
488                                                ; expr <- thing_inside
489                                                ; return (Let (Rec prs) expr) }
490 \end{code}