[project @ 2005-07-19 16:44:50 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / DsBinds.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[DsBinds]{Pattern-matching bindings (HsBinds and MonoBinds)}
5
6 Handles @HsBinds@; those at the top level require different handling,
7 in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at
8 lower levels it is preserved with @let@/@letrec@s).
9
10 \begin{code}
11 module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, AutoScc(..) ) where
12
13 #include "HsVersions.h"
14
15
16 import {-# SOURCE #-}   DsExpr( dsLExpr, dsExpr )
17 import {-# SOURCE #-}   Match( matchWrapper )
18
19 import DsMonad
20 import DsGRHSs          ( dsGuarded )
21 import DsUtils
22
23 import HsSyn            -- lots of things
24 import CoreSyn          -- lots of things
25 import CoreUtils        ( exprType, mkInlineMe, mkSCC )
26
27 import StaticFlags      ( opt_AutoSccsOnAllToplevs,
28                           opt_AutoSccsOnExportedToplevs )
29 import OccurAnal        ( occurAnalyseExpr )
30 import CostCentre       ( mkAutoCC, IsCafCC(..) )
31 import Id               ( Id, idType, idName, isExportedId, mkLocalId, setInlinePragma )
32 import Rules            ( addIdSpecialisations, mkLocalRule )
33 import Var              ( Var, isGlobalId )
34 import VarEnv
35 import Type             ( mkTyVarTy, substTyWith )
36 import TysWiredIn       ( voidTy )
37 import Outputable
38 import SrcLoc           ( Located(..) )
39 import Maybes           ( isJust, catMaybes, orElse )
40 import Bag              ( bagToList )
41 import BasicTypes       ( Activation(..), isAlwaysActive )
42 import Monad            ( foldM )
43 import FastString       ( mkFastString )
44 import List             ( (\\) )
45 import Util             ( mapSnd )
46 \end{code}
47
48 %************************************************************************
49 %*                                                                      *
50 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
51 %*                                                                      *
52 %************************************************************************
53
54 \begin{code}
55 dsTopLHsBinds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
56 dsTopLHsBinds auto_scc binds = ds_lhs_binds auto_scc binds
57
58 dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)]
59 dsLHsBinds binds = ds_lhs_binds NoSccs binds
60
61
62 ------------------------
63 ds_lhs_binds :: AutoScc -> LHsBinds Id -> DsM [(Id,CoreExpr)]
64          -- scc annotation policy (see below)
65 ds_lhs_binds auto_scc binds =  foldM (dsLHsBind auto_scc) [] (bagToList binds)
66
67 dsLHsBind :: AutoScc
68          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
69          -> LHsBind Id
70          -> DsM [(Id,CoreExpr)] -- Result
71 dsLHsBind auto_scc rest (L loc bind)
72   = putSrcSpanDs loc $ dsHsBind auto_scc rest bind
73
74 dsHsBind :: AutoScc
75          -> [(Id,CoreExpr)]     -- Put this on the end (avoid quadratic append)
76          -> HsBind Id
77          -> DsM [(Id,CoreExpr)] -- Result
78
79 dsHsBind auto_scc rest (VarBind var expr)
80   = dsLExpr expr                `thenDs` \ core_expr ->
81
82         -- Dictionary bindings are always VarMonoBinds, so
83         -- we only need do this here
84     addDictScc var core_expr    `thenDs` \ core_expr' ->
85     returnDs ((var, core_expr') : rest)
86
87 dsHsBind auto_scc rest (FunBind (L _ fun) _ matches _)
88   = matchWrapper (FunRhs (idName fun)) matches          `thenDs` \ (args, body) ->
89     addAutoScc auto_scc (fun, mkLams args body)         `thenDs` \ pair ->
90     returnDs (pair : rest)
91
92 dsHsBind auto_scc rest (PatBind pat grhss ty _)
93   = dsGuarded grhss ty                          `thenDs` \ body_expr ->
94     mkSelectorBinds pat body_expr               `thenDs` \ sel_binds ->
95     mappM (addAutoScc auto_scc) sel_binds       `thenDs` \ sel_binds ->
96     returnDs (sel_binds ++ rest)
97
98         -- Common special case: no type or dictionary abstraction
99         -- For the (rare) case when there are some mixed-up
100         -- dictionary bindings (for which a Rec is convenient)
101         -- we reply on the enclosing dsBind to wrap a Rec around.
102 dsHsBind auto_scc rest (AbsBinds [] [] exports binds)
103   = ds_lhs_binds (addSccs auto_scc exports) binds       `thenDs` \ core_prs ->
104     let
105         core_prs' = addLocalInlines exports core_prs
106         exports'  = [(global, Var local) | (_, global, local, _) <- exports]
107     in
108     returnDs (core_prs' ++ exports' ++ rest)
109
110         -- Another common case: one exported variable
111         -- Non-recursive bindings come through this way
112 dsHsBind auto_scc rest
113      (AbsBinds all_tyvars dicts exports@[(tyvars, global, local, prags)] binds)
114   = ASSERT( all (`elem` tyvars) all_tyvars )
115     ds_lhs_binds (addSccs auto_scc exports) binds       `thenDs` \ core_prs ->
116     let 
117         -- Always treat the binds as recursive, because the typechecker
118         -- makes rather mixed-up dictionary bindings
119         core_bind = Rec core_prs
120         inline_env = mkVarEnv [(global, prag) | prag <- prags, isInlinePrag prag]
121     in
122     mappM (dsSpec all_tyvars dicts tyvars global local core_bind) 
123           prags                         `thenDs` \ mb_specs ->
124     let
125         (spec_binds, rules) = unzip (catMaybes mb_specs)
126         global' = addIdSpecialisations global rules
127         rhs'    = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
128     in
129     returnDs (addInlineInfo inline_env (global', rhs') : spec_binds ++ rest)
130
131 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
132   = ds_lhs_binds (addSccs auto_scc exports) binds       `thenDs` \ core_prs ->
133      let 
134         -- Rec because of mixed-up dictionary bindings
135         core_bind = Rec (addLocalInlines exports core_prs)
136
137         tup_expr      = mkTupleExpr locals
138         tup_ty        = exprType tup_expr
139         poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
140                         Let core_bind tup_expr
141         locals        = [local | (_, _, local, _) <- exports]
142         local_tys     = map idType locals
143     in
144     newSysLocalDs (exprType poly_tup_expr)              `thenDs` \ poly_tup_id ->
145     let
146         dict_args = map Var dicts
147
148         mk_bind ((tyvars, global, local, prags), n)     -- locals !! n == local
149           =     -- Need to make fresh locals to bind in the selector, because
150                 -- some of the tyvars will be bound to voidTy
151             newSysLocalsDs (map substitute local_tys)   `thenDs` \ locals' ->
152             newSysLocalDs  (substitute tup_ty)          `thenDs` \ tup_id ->
153             mapM (dsSpec all_tyvars dicts tyvars global local core_bind) 
154                  prags                          `thenDs` \ mb_specs ->
155             let
156                 (spec_binds, rules) = unzip (catMaybes mb_specs)
157                 global' = addIdSpecialisations global rules
158                 rhs = mkLams tyvars $ mkLams dicts $
159                       mkTupleSelector locals' (locals' !! n) tup_id $
160                       mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
161             in
162             returnDs ((global', rhs) : spec_binds)
163           where
164             mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
165                                 | otherwise               = voidTy
166             ty_args    = map mk_ty_arg all_tyvars
167             substitute = substTyWith all_tyvars ty_args
168     in
169     mappM mk_bind (exports `zip` [0..])         `thenDs` \ export_binds_s ->
170      -- don't scc (auto-)annotate the tuple itself.
171
172     returnDs ((poly_tup_id, poly_tup_expr) : (concat export_binds_s ++ rest))
173
174 -- Example:
175 --      f :: (Eq a, Ix b) => a -> b -> b
176 --
177 --      AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
178 -- 
179 --      SpecPrag (/\b.\(d:Ix b). f Int b dInt d) 
180 --               (forall b. Ix b => Int -> b -> b)
181 --
182 -- Rule:        forall b,(d:Ix b). f Int b dInt d = f_spec b d
183 --
184 -- Spec bind:   f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono 
185 --                       /\b.\(d:Ix b). in f Int b dInt d
186
187 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (InlinePrag {})
188   = return Nothing
189
190 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
191        (SpecPrag spec_expr spec_ty const_dicts)
192   = do  { let poly_name = idName poly_id
193         ; spec_name <- newLocalName (idName poly_id)
194         ; ds_spec_expr  <- dsExpr spec_expr
195         ; let (bndrs, body) = collectBinders ds_spec_expr
196               mb_lhs        = decomposeRuleLhs (bndrs ++ const_dicts) body
197
198         ; case mb_lhs of
199             Nothing -> do { dsWarn msg; return Nothing }
200
201             Just (bndrs', var, args) -> return (Just ((spec_id, spec_rhs), rule))
202                 where
203                   spec_id     = mkLocalId spec_name spec_ty
204                   spec_rhs    = Let (NonRec poly_id poly_f_body) ds_spec_expr
205                   poly_f_body = mkLams (tvs ++ dicts) $
206                                 fix_up (Let mono_bind (Var mono_id))
207
208                         -- Quantify over constant dicts on the LHS, since
209                         -- their value depends only on their type
210                         -- The ones we are interested in may even be imported
211                         -- e.g. GHC.Base.dEqInt
212
213                   rule =  mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
214                                 AlwaysActive poly_name
215                                 bndrs'  -- Includes constant dicts
216                                 args
217                                 (mkVarApps (Var spec_id) bndrs)
218         }
219   where
220         -- Bind to voidTy any of all_ptvs that aren't 
221         -- relevant for this particular function 
222     fix_up body | null void_tvs = body
223                 | otherwise     = mkTyApps (mkLams void_tvs body) 
224                                            (map (const voidTy) void_tvs)
225     void_tvs = all_tvs \\ tvs
226
227     msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
228              2 (ppr spec_expr)
229 \end{code}
230
231
232 %************************************************************************
233 %*                                                                      *
234 \subsection{Adding inline pragmas}
235 %*                                                                      *
236 %************************************************************************
237
238 \begin{code}
239 decomposeRuleLhs :: [Var] -> CoreExpr -> Maybe ([Var], Id, [CoreExpr])
240 -- Returns Nothing if the LHS isn't of the expected shape
241 -- The argument 'all_bndrs' includes the "constant dicts" of the LHS,
242 -- and they may be GlobalIds, which we can't forall-ify. 
243 -- So we substitute them out instead
244 decomposeRuleLhs all_bndrs lhs 
245   = go init_env (occurAnalyseExpr lhs)  -- Occurrence analysis sorts out the dict
246                                         -- bindings so we know if they are recursive
247   where
248
249         -- all_bndrs may include top-level imported dicts, 
250         -- imported things with a for-all.  
251         -- So we localise them and subtitute them out
252     bndr_prs =  [ (id, Var (localise id)) | id <- all_bndrs, isGlobalId id ]
253     localise d = mkLocalId (idName d) (idType d)
254
255     init_env = mkVarEnv bndr_prs
256     all_bndrs' = map subst_bndr all_bndrs
257     subst_bndr bndr = case lookupVarEnv init_env bndr of
258                         Just (Var bndr') -> bndr'
259                         Just other       -> panic "decomposeRuleLhs"
260                         Nothing          -> bndr
261
262         -- Substitute dicts in the LHS args, so that there 
263         -- aren't any lets getting in the way
264     go env (Let (NonRec dict rhs) body) 
265         = go (extendVarEnv env dict (simpleSubst env rhs)) body
266     go env body 
267         = case collectArgs body of
268             (Var fn, args) -> Just (all_bndrs', fn, map (simpleSubst env) args)
269             other          -> Nothing
270
271 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
272 -- Similar to CoreSubst.substExpr, except that 
273 -- (a) takes no account of capture; dictionary bindings use new names
274 -- (b) can have a GlobalId (imported) in its domain
275 -- (c) Ids only; no types are substituted
276
277 simpleSubst subst expr
278   = go expr
279   where
280     go (Var v)         = lookupVarEnv subst v `orElse` Var v
281     go (Type ty)       = Type ty
282     go (Lit lit)       = Lit lit
283     go (App fun arg)   = App (go fun) (go arg)
284     go (Note note e)   = Note note (go e)
285     go (Lam bndr body) = Lam bndr (go body)
286     go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
287     go (Let (Rec pairs) body)       = Let (Rec (mapSnd go pairs)) (go body)
288     go (Case scrut bndr ty alts)    = Case (go scrut) bndr ty 
289                                            [(c,bs,go r) | (c,bs,r) <- alts]
290
291 addLocalInlines exports core_prs
292   = map (addInlineInfo inline_env) core_prs
293   where
294     inline_env = mkVarEnv [(mono_id, prag) 
295                           | (_, _, mono_id, prags) <- exports,
296                             prag <- prags, isInlinePrag prag]
297                                            
298 addInlineInfo :: IdEnv Prag -> (Id,CoreExpr) -> (Id,CoreExpr)
299 addInlineInfo inline_env (bndr,rhs)
300   | Just (InlinePrag is_inline phase) <- lookupVarEnv inline_env bndr
301   = (attach_phase bndr phase, wrap_inline is_inline rhs)
302   | otherwise
303   = (bndr, rhs)
304   where
305     attach_phase bndr phase 
306         | isAlwaysActive phase = bndr   -- Default phase
307         | otherwise            = bndr `setInlinePragma` phase
308
309     wrap_inline True  body = mkInlineMe body
310     wrap_inline False body = body
311 \end{code}
312
313
314 %************************************************************************
315 %*                                                                      *
316 \subsection[addAutoScc]{Adding automatic sccs}
317 %*                                                                      *
318 %************************************************************************
319
320 \begin{code}
321 data AutoScc
322         = TopLevel
323         | TopLevelAddSccs (Id -> Maybe Id)
324         | NoSccs
325
326 addSccs :: AutoScc -> [(a,Id,Id,[Prag])] -> AutoScc
327 addSccs auto_scc@(TopLevelAddSccs _) exports = auto_scc
328 addSccs NoSccs   exports = NoSccs
329 addSccs TopLevel exports 
330   = TopLevelAddSccs (\id -> case [ exp | (_,exp,loc,_) <- exports, loc == id ] of
331                                 (exp:_)  | opt_AutoSccsOnAllToplevs || 
332                                             (isExportedId exp && 
333                                              opt_AutoSccsOnExportedToplevs)
334                                         -> Just exp
335                                 _ -> Nothing)
336
337 addAutoScc :: AutoScc           -- if needs be, decorate toplevs?
338            -> (Id, CoreExpr)
339            -> DsM (Id, CoreExpr)
340
341 addAutoScc (TopLevelAddSccs auto_scc_fn) pair@(bndr, core_expr) 
342  | do_auto_scc
343      = getModuleDs `thenDs` \ mod ->
344        returnDs (bndr, mkSCC (mkAutoCC top_bndr mod NotCafCC) core_expr)
345  where do_auto_scc = isJust maybe_auto_scc
346        maybe_auto_scc = auto_scc_fn bndr
347        (Just top_bndr) = maybe_auto_scc
348
349 addAutoScc _ pair
350      = returnDs pair
351 \end{code}
352
353 If profiling and dealing with a dict binding,
354 wrap the dict in @_scc_ DICT <dict>@:
355
356 \begin{code}
357 addDictScc var rhs = returnDs rhs
358
359 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
360   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
361     || not (isDictId var)
362   = returnDs rhs                                -- That's easy: do nothing
363
364   | otherwise
365   = getModuleAndGroupDs         `thenDs` \ (mod, grp) ->
366         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
367     returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
368 -}
369 \end{code}