[project @ 1999-06-17 09:51:16 by simonmar]
[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 ( dsMonoBinds, AutoScc(..) ) where
12
13 #include "HsVersions.h"
14
15
16 import {-# SOURCE #-}   DsExpr( dsExpr )
17
18 import HsSyn            -- lots of things
19 import CoreSyn          -- lots of things
20 import CoreUtils        ( coreExprType )
21 import TcHsSyn          ( TypecheckedMonoBinds )
22 import DsMonad
23 import DsGRHSs          ( dsGuarded )
24 import DsUtils
25 import Match            ( matchWrapper )
26
27 import BasicTypes       ( RecFlag(..) )
28 import CmdLineOpts      ( opt_SccProfilingOn, opt_AutoSccsOnAllToplevs, 
29                           opt_AutoSccsOnExportedToplevs, opt_AutoSccsOnDicts
30                         )
31 import CostCentre       ( CostCentre, mkAutoCC, IsCafCC(..) )
32 import Id               ( idType, idName, isUserExportedId, Id )
33 import NameSet
34 import VarEnv
35 import VarSet
36 import Type             ( mkTyVarTy, isDictTy )
37 import Subst            ( mkTyVarSubst, substTy )
38 import TysWiredIn       ( voidTy )
39 import Outputable
40
41 import Maybe
42 import IOExts (trace)
43 \end{code}
44
45 %************************************************************************
46 %*                                                                      *
47 \subsection[dsMonoBinds]{Desugaring a @MonoBinds@}
48 %*                                                                      *
49 %************************************************************************
50
51 \begin{code}
52 dsMonoBinds :: AutoScc                  -- scc annotation policy (see below)
53             -> TypecheckedMonoBinds
54             -> [(Id,CoreExpr)]          -- Put this on the end (avoid quadratic append)
55             -> DsM [(Id,CoreExpr)]      -- Result
56
57 dsMonoBinds _ EmptyMonoBinds rest = returnDs rest
58
59 dsMonoBinds auto_scc (AndMonoBinds  binds_1 binds_2) rest
60   = dsMonoBinds auto_scc binds_2 rest   `thenDs` \ rest' ->
61     dsMonoBinds auto_scc binds_1 rest'
62
63 dsMonoBinds _ (CoreMonoBind var core_expr) rest
64   = returnDs ((var, core_expr) : rest)
65
66 dsMonoBinds _ (VarMonoBind var expr) rest
67   = dsExpr expr                 `thenDs` \ core_expr ->
68
69         -- Dictionary bindings are always VarMonoBinds, so
70         -- we only need do this here
71     addDictScc var core_expr    `thenDs` \ core_expr' ->
72
73     returnDs ((var, core_expr') : rest)
74
75 dsMonoBinds auto_scc (FunMonoBind fun _ matches locn) rest
76   = putSrcLocDs locn    $
77     matchWrapper (FunMatch fun) matches error_string    `thenDs` \ (args, body) ->
78     addAutoScc auto_scc (fun, mkLams args body)         `thenDs` \ pair ->
79     returnDs (pair : rest)
80   where
81     error_string = "function " ++ showSDoc (ppr fun)
82
83 dsMonoBinds auto_scc (PatMonoBind pat grhss locn) rest
84   = putSrcLocDs locn $
85     dsGuarded grhss                             `thenDs` \ body_expr ->
86     mkSelectorBinds pat body_expr               `thenDs` \ sel_binds ->
87     mapDs (addAutoScc auto_scc) sel_binds       `thenDs` \ sel_binds ->
88     returnDs (sel_binds ++ rest)
89
90         -- Common case: one exported variable
91         -- All non-recursive bindings come through this way
92 dsMonoBinds auto_scc
93      (AbsBinds all_tyvars dicts exps@[(tyvars, global, local)] inlines binds) rest
94   = ASSERT( all (`elem` tyvars) all_tyvars )
95     dsMonoBinds (addSccs auto_scc exps) binds []        `thenDs` \ core_prs ->
96     let 
97         -- Always treat the binds as recursive, because the typechecker
98         -- makes rather mixed-up dictionary bindings
99         core_binds = [Rec core_prs]
100         global'    = (global, mkInline (idName global `elemNameSet` inlines) $
101                               mkLams tyvars $ mkLams dicts $ 
102                               mkDsLets core_binds (Var local))
103     in
104     returnDs (global' : rest)
105
106         -- Another common special case: no type or dictionary abstraction
107 dsMonoBinds auto_scc (AbsBinds [] [] exports inlines binds) rest
108   = dsMonoBinds (addSccs auto_scc exports) binds []`thenDs` \ core_prs ->
109     let 
110         exports' = [(global, Var local) | (_, global, local) <- exports]
111     in
112     returnDs (addLocalInlines exports inlines core_prs ++ exports' ++ rest)
113
114 dsMonoBinds auto_scc (AbsBinds all_tyvars dicts exports inlines binds) rest
115   = dsMonoBinds (addSccs auto_scc exports) binds []`thenDs` \ core_prs ->
116     let 
117         core_binds = [Rec (addLocalInlines exports inlines core_prs)]
118
119         tup_expr      = mkTupleExpr locals
120         tup_ty        = coreExprType tup_expr
121         poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
122                         mkDsLets core_binds tup_expr
123         locals        = [local | (_, _, local) <- exports]
124         local_tys     = map idType locals
125     in
126     newSysLocalDs (coreExprType poly_tup_expr)          `thenDs` \ poly_tup_id ->
127     let
128         dict_args = map Var dicts
129
130         mk_bind (tyvars, global, local) n       -- locals !! n == local
131           =     -- Need to make fresh locals to bind in the selector, because
132                 -- some of the tyvars will be bound to voidTy
133             newSysLocalsDs (map (substTy env) local_tys)        `thenDs` \ locals' ->
134             newSysLocalDs  (substTy env tup_ty)                 `thenDs` \ tup_id ->
135             returnDs (global, mkLams tyvars $ mkLams dicts $
136                               mkTupleSelector locals' (locals' !! n) tup_id $
137                               mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args)
138           where
139             mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
140                                 | otherwise               = voidTy
141             ty_args = map mk_ty_arg all_tyvars
142             env     = mkTyVarSubst all_tyvars ty_args
143     in
144     zipWithDs mk_bind exports [0..]             `thenDs` \ export_binds ->
145      -- don't scc (auto-)annotate the tuple itself.
146     returnDs ((poly_tup_id, poly_tup_expr) : (export_binds ++ rest))
147 \end{code}
148
149
150 %************************************************************************
151 %*                                                                      *
152 \subsection{Adding inline pragmas}
153 %*                                                                      *
154 %************************************************************************
155
156 \begin{code}
157 mkInline :: Bool -> CoreExpr -> CoreExpr
158 mkInline True  body = Note InlineMe body
159 mkInline False body = body
160
161 addLocalInlines :: [(a, Id, Id)] -> NameSet -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
162 addLocalInlines exports inlines pairs
163   = [(bndr, mkInline (bndr `elemVarSet` local_inlines) rhs) | (bndr,rhs) <- pairs]
164   where
165     local_inlines = mkVarSet [l | (_,g,l) <- exports, idName g `elemNameSet` inlines]
166 \end{code}
167
168
169 %************************************************************************
170 %*                                                                      *
171 \subsection[addAutoScc]{Adding automatic sccs}
172 %*                                                                      *
173 %************************************************************************
174
175 \begin{code}
176 data AutoScc
177         = TopLevel
178         | TopLevelAddSccs (Id -> Maybe Id)
179         | NoSccs
180
181 addSccs :: AutoScc -> [(a,Id,Id)] -> AutoScc
182 addSccs auto_scc@(TopLevelAddSccs _) exports = auto_scc
183 addSccs NoSccs   exports = NoSccs
184 addSccs TopLevel exports 
185   = TopLevelAddSccs (\id -> case [ exp | (_,exp,loc) <- exports, loc == id ] of
186                                 (exp:_)  | opt_AutoSccsOnAllToplevs || 
187                                             (isUserExportedId exp && 
188                                              opt_AutoSccsOnExportedToplevs)
189                                         -> Just exp
190                                 _ -> Nothing)
191
192 addAutoScc :: AutoScc           -- if needs be, decorate toplevs?
193            -> (Id, CoreExpr)
194            -> DsM (Id, CoreExpr)
195
196 addAutoScc (TopLevelAddSccs auto_scc_fn) pair@(bndr, core_expr) 
197  | do_auto_scc && worthSCC core_expr
198      = getModuleAndGroupDs `thenDs` \ (mod,grp) ->
199        returnDs (bndr, Note (SCC (mkAutoCC top_bndr mod grp NotCafCC)) core_expr)
200  where do_auto_scc = isJust maybe_auto_scc
201        maybe_auto_scc = auto_scc_fn bndr
202        (Just top_bndr) = maybe_auto_scc
203 addAutoScc _ pair
204      = returnDs pair
205
206 worthSCC (Note (SCC _) _) = False
207 worthSCC (Con _ _)        = False
208 worthSCC core_expr        = True
209 \end{code}
210
211 If profiling and dealing with a dict binding,
212 wrap the dict in @_scc_ DICT <dict>@:
213
214 \begin{code}
215 addDictScc var rhs = returnDs rhs
216
217 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
218   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
219     || not (isDictTy (idType var))
220   = returnDs rhs                                -- That's easy: do nothing
221
222   | otherwise
223   = getModuleAndGroupDs         `thenDs` \ (mod, grp) ->
224         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
225     returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
226 -}
227 \end{code}