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