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