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