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