70980f978539bb59e32bb0326e6a5d645f90b05a
[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, DictId, idType, idName, isExportedId, mkLocalId, setInlinePragma )
32 import Rules            ( addIdSpecialisations, mkLocalRule )
33 import Var              ( TyVar, Var, isGlobalId, setIdNotExported )
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(..), InlineSpec(..), isAlwaysActive, defaultInlineSpec )
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     in
121     mappM (dsSpec all_tyvars dicts tyvars global local core_bind) 
122           prags                         `thenDs` \ mb_specs ->
123     let
124         (spec_binds, rules) = unzip (catMaybes mb_specs)
125         global' = addIdSpecialisations global rules
126         rhs'    = mkLams tyvars $ mkLams dicts $ Let core_bind (Var local)
127         inl     = case [inl | InlinePrag inl <- prags] of
128                         []      -> defaultInlineSpec 
129                         (inl:_) -> inl
130     in
131     returnDs (addInlineInfo inl global' rhs' : spec_binds ++ rest)
132
133 dsHsBind auto_scc rest (AbsBinds all_tyvars dicts exports binds)
134   = ds_lhs_binds (addSccs auto_scc exports) binds       `thenDs` \ core_prs ->
135      let 
136         -- Rec because of mixed-up dictionary bindings
137         core_bind = Rec (addLocalInlines exports core_prs)
138
139         tup_expr      = mkTupleExpr locals
140         tup_ty        = exprType tup_expr
141         poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
142                         Let core_bind tup_expr
143         locals        = [local | (_, _, local, _) <- exports]
144         local_tys     = map idType locals
145     in
146     newSysLocalDs (exprType poly_tup_expr)              `thenDs` \ poly_tup_id ->
147     let
148         dict_args = map Var dicts
149
150         mk_bind ((tyvars, global, local, prags), n)     -- locals !! n == local
151           =     -- Need to make fresh locals to bind in the selector, because
152                 -- some of the tyvars will be bound to voidTy
153             newSysLocalsDs (map substitute local_tys)   `thenDs` \ locals' ->
154             newSysLocalDs  (substitute tup_ty)          `thenDs` \ tup_id ->
155             mapM (dsSpec all_tyvars dicts tyvars global local core_bind) 
156                  prags                          `thenDs` \ mb_specs ->
157             let
158                 (spec_binds, rules) = unzip (catMaybes mb_specs)
159                 global' = addIdSpecialisations global rules
160                 rhs = mkLams tyvars $ mkLams dicts $
161                       mkTupleSelector locals' (locals' !! n) tup_id $
162                       mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args
163             in
164             returnDs ((global', rhs) : spec_binds)
165           where
166             mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
167                                 | otherwise               = voidTy
168             ty_args    = map mk_ty_arg all_tyvars
169             substitute = substTyWith all_tyvars ty_args
170     in
171     mappM mk_bind (exports `zip` [0..])         `thenDs` \ export_binds_s ->
172      -- don't scc (auto-)annotate the tuple itself.
173
174     returnDs ((poly_tup_id, poly_tup_expr) : (concat export_binds_s ++ rest))
175
176 dsSpec :: [TyVar] -> [DictId] -> [TyVar]
177        -> Id -> Id              -- Global, local
178        -> CoreBind -> Prag
179        -> DsM (Maybe ((Id,CoreExpr),    -- Binding for specialised Id
180                       CoreRule))        -- Rule for the Global Id
181
182 -- Example:
183 --      f :: (Eq a, Ix b) => a -> b -> b
184 --      {-# SPECIALISE f :: Ix b => Int -> b -> b #-}
185 --
186 --      AbsBinds [ab] [d1,d2] [([ab], f, f_mono, prags)] binds
187 -- 
188 --      SpecPrag (/\b.\(d:Ix b). f Int b dInt d) 
189 --               (forall b. Ix b => Int -> b -> b)
190 --
191 -- Rule:        forall b,(d:Ix b). f Int b dInt d = f_spec b d
192 --
193 -- Spec bind:   f_spec = Let f = /\ab \(d1:Eq a)(d2:Ix b). let binds in f_mono 
194 --                       /\b.\(d:Ix b). in f Int b dInt d
195 --              The idea is that f occurs just once, so it'll be 
196 --              inlined and specialised
197
198 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind (InlinePrag {})
199   = return Nothing
200
201 dsSpec all_tvs dicts tvs poly_id mono_id mono_bind
202        (SpecPrag spec_expr spec_ty const_dicts inl)
203   = do  { let poly_name = idName poly_id
204         ; spec_name <- newLocalName poly_name
205         ; ds_spec_expr  <- dsExpr spec_expr
206         ; let (bndrs, body) = collectBinders ds_spec_expr
207               mb_lhs        = decomposeRuleLhs (bndrs ++ const_dicts) body
208
209         ; case mb_lhs of
210             Nothing -> do { dsWarn msg; return Nothing }
211
212             Just (bndrs', var, args) -> return (Just (addInlineInfo inl spec_id spec_rhs, rule))
213                 where
214                   local_poly  = setIdNotExported poly_id
215                         -- Very important to make the 'f' non-exported,
216                         -- else it won't be inlined!
217                   spec_id     = mkLocalId spec_name spec_ty
218                   spec_rhs    = Let (NonRec local_poly poly_f_body) ds_spec_expr
219                   poly_f_body = mkLams (tvs ++ dicts) $
220                                 fix_up (Let mono_bind (Var mono_id))
221
222                         -- Quantify over constant dicts on the LHS, since
223                         -- their value depends only on their type
224                         -- The ones we are interested in may even be imported
225                         -- e.g. GHC.Base.dEqInt
226
227                   rule =  mkLocalRule (mkFastString ("SPEC " ++ showSDoc (ppr poly_name)))
228                                 AlwaysActive poly_name
229                                 bndrs'  -- Includes constant dicts
230                                 args
231                                 (mkVarApps (Var spec_id) bndrs)
232         }
233   where
234         -- Bind to voidTy any of all_ptvs that aren't 
235         -- relevant for this particular function 
236     fix_up body | null void_tvs = body
237                 | otherwise     = mkTyApps (mkLams void_tvs body) 
238                                            (map (const voidTy) void_tvs)
239     void_tvs = all_tvs \\ tvs
240
241     msg = hang (ptext SLIT("Specialisation too complicated to desugar; ignored"))
242              2 (ppr spec_expr)
243 \end{code}
244
245
246 %************************************************************************
247 %*                                                                      *
248 \subsection{Adding inline pragmas}
249 %*                                                                      *
250 %************************************************************************
251
252 \begin{code}
253 decomposeRuleLhs :: [Var] -> CoreExpr -> Maybe ([Var], Id, [CoreExpr])
254 -- Returns Nothing if the LHS isn't of the expected shape
255 -- The argument 'all_bndrs' includes the "constant dicts" of the LHS,
256 -- and they may be GlobalIds, which we can't forall-ify. 
257 -- So we substitute them out instead
258 decomposeRuleLhs all_bndrs lhs 
259   = go init_env (occurAnalyseExpr lhs)  -- Occurrence analysis sorts out the dict
260                                         -- bindings so we know if they are recursive
261   where
262
263         -- all_bndrs may include top-level imported dicts, 
264         -- imported things with a for-all.  
265         -- So we localise them and subtitute them out
266     bndr_prs =  [ (id, Var (localise id)) | id <- all_bndrs, isGlobalId id ]
267     localise d = mkLocalId (idName d) (idType d)
268
269     init_env = mkVarEnv bndr_prs
270     all_bndrs' = map subst_bndr all_bndrs
271     subst_bndr bndr = case lookupVarEnv init_env bndr of
272                         Just (Var bndr') -> bndr'
273                         Just other       -> panic "decomposeRuleLhs"
274                         Nothing          -> bndr
275
276         -- Substitute dicts in the LHS args, so that there 
277         -- aren't any lets getting in the way
278         -- Note that we substitute the function too; we might have this as
279         -- a LHS:       let f71 = M.f Int in f71
280     go env (Let (NonRec dict rhs) body) 
281         = go (extendVarEnv env dict (simpleSubst env rhs)) body
282     go env body 
283         = case collectArgs (simpleSubst env body) of
284             (Var fn, args) -> Just (all_bndrs', fn, args)
285             other          -> Nothing
286
287 simpleSubst :: IdEnv CoreExpr -> CoreExpr -> CoreExpr
288 -- Similar to CoreSubst.substExpr, except that 
289 -- (a) takes no account of capture; dictionary bindings use new names
290 -- (b) can have a GlobalId (imported) in its domain
291 -- (c) Ids only; no types are substituted
292
293 simpleSubst subst expr
294   = go expr
295   where
296     go (Var v)         = lookupVarEnv subst v `orElse` Var v
297     go (Type ty)       = Type ty
298     go (Lit lit)       = Lit lit
299     go (App fun arg)   = App (go fun) (go arg)
300     go (Note note e)   = Note note (go e)
301     go (Lam bndr body) = Lam bndr (go body)
302     go (Let (NonRec bndr rhs) body) = Let (NonRec bndr (go rhs)) (go body)
303     go (Let (Rec pairs) body)       = Let (Rec (mapSnd go pairs)) (go body)
304     go (Case scrut bndr ty alts)    = Case (go scrut) bndr ty 
305                                            [(c,bs,go r) | (c,bs,r) <- alts]
306
307 addLocalInlines exports core_prs
308   = map add_inline core_prs
309   where
310     add_inline (bndr,rhs) | Just inl <- lookupVarEnv inline_env bndr
311                           = addInlineInfo inl bndr rhs
312                           | otherwise 
313                           = (bndr,rhs)
314     inline_env = mkVarEnv [(mono_id, prag) 
315                           | (_, _, mono_id, prags) <- exports,
316                             InlinePrag prag <- prags]
317                                            
318 addInlineInfo :: InlineSpec -> Id -> CoreExpr -> (Id,CoreExpr)
319 addInlineInfo (Inline phase is_inline) bndr rhs
320   = (attach_phase bndr phase, wrap_inline is_inline rhs)
321   where
322     attach_phase bndr phase 
323         | isAlwaysActive phase = bndr   -- Default phase
324         | otherwise            = bndr `setInlinePragma` phase
325
326     wrap_inline True  body = mkInlineMe body
327     wrap_inline False body = body
328 \end{code}
329
330
331 %************************************************************************
332 %*                                                                      *
333 \subsection[addAutoScc]{Adding automatic sccs}
334 %*                                                                      *
335 %************************************************************************
336
337 \begin{code}
338 data AutoScc
339         = TopLevel
340         | TopLevelAddSccs (Id -> Maybe Id)
341         | NoSccs
342
343 addSccs :: AutoScc -> [(a,Id,Id,[Prag])] -> AutoScc
344 addSccs auto_scc@(TopLevelAddSccs _) exports = auto_scc
345 addSccs NoSccs   exports = NoSccs
346 addSccs TopLevel exports 
347   = TopLevelAddSccs (\id -> case [ exp | (_,exp,loc,_) <- exports, loc == id ] of
348                                 (exp:_)  | opt_AutoSccsOnAllToplevs || 
349                                             (isExportedId exp && 
350                                              opt_AutoSccsOnExportedToplevs)
351                                         -> Just exp
352                                 _ -> Nothing)
353
354 addAutoScc :: AutoScc           -- if needs be, decorate toplevs?
355            -> (Id, CoreExpr)
356            -> DsM (Id, CoreExpr)
357
358 addAutoScc (TopLevelAddSccs auto_scc_fn) pair@(bndr, core_expr) 
359  | do_auto_scc
360      = getModuleDs `thenDs` \ mod ->
361        returnDs (bndr, mkSCC (mkAutoCC top_bndr mod NotCafCC) core_expr)
362  where do_auto_scc = isJust maybe_auto_scc
363        maybe_auto_scc = auto_scc_fn bndr
364        (Just top_bndr) = maybe_auto_scc
365
366 addAutoScc _ pair
367      = returnDs pair
368 \end{code}
369
370 If profiling and dealing with a dict binding,
371 wrap the dict in @_scc_ DICT <dict>@:
372
373 \begin{code}
374 addDictScc var rhs = returnDs rhs
375
376 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
377   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
378     || not (isDictId var)
379   = returnDs rhs                                -- That's easy: do nothing
380
381   | otherwise
382   = getModuleAndGroupDs         `thenDs` \ (mod, grp) ->
383         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
384     returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
385 -}
386 \end{code}