c43f98596d58b553ad3111084c09428643e04b6f
[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, isSpecPragmaId, 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     let
74         -- Gross hack to prevent inlining into SpecPragmaId rhss
75         -- Consider     fromIntegral = fromInteger . toInteger
76         --              spec1 = fromIntegral Int Float
77         -- Even though fromIntegral is small we don't want to inline
78         -- it inside spec1, so that we collect the specialised call
79         -- Solution: make spec1 an INLINE thing.  
80         core_expr'' = mkInline (isSpecPragmaId var) core_expr'
81     in  
82
83     returnDs ((var, core_expr'') : rest)
84
85 dsMonoBinds auto_scc (FunMonoBind fun _ matches locn) rest
86   = putSrcLocDs locn    $
87     matchWrapper (FunMatch fun) matches error_string    `thenDs` \ (args, body) ->
88     addAutoScc auto_scc (fun, mkLams args body)         `thenDs` \ pair ->
89     returnDs (pair : rest)
90   where
91     error_string = "function " ++ showSDoc (ppr fun)
92
93 dsMonoBinds auto_scc (PatMonoBind pat grhss locn) rest
94   = putSrcLocDs locn $
95     dsGuarded grhss                             `thenDs` \ body_expr ->
96     mkSelectorBinds pat body_expr               `thenDs` \ sel_binds ->
97     mapDs (addAutoScc auto_scc) sel_binds       `thenDs` \ sel_binds ->
98     returnDs (sel_binds ++ rest)
99
100         -- Common case: one exported variable
101         -- All non-recursive bindings come through this way
102 dsMonoBinds auto_scc
103      (AbsBinds all_tyvars dicts exps@[(tyvars, global, local)] inlines binds) rest
104   = ASSERT( all (`elem` tyvars) all_tyvars )
105     dsMonoBinds (addSccs auto_scc exps) binds []        `thenDs` \ core_prs ->
106     let 
107         -- Always treat the binds as recursive, because the typechecker
108         -- makes rather mixed-up dictionary bindings
109         core_binds = [Rec core_prs]
110         global'    = (global, mkInline (idName global `elemNameSet` inlines) $
111                               mkLams tyvars $ mkLams dicts $ 
112                               mkDsLets core_binds (Var local))
113     in
114     returnDs (global' : rest)
115
116         -- Another common special case: no type or dictionary abstraction
117 dsMonoBinds auto_scc (AbsBinds [] [] exports inlines binds) rest
118   = dsMonoBinds (addSccs auto_scc exports) binds []`thenDs` \ core_prs ->
119     let 
120         exports' = [(global, Var local) | (_, global, local) <- exports]
121     in
122     returnDs (addLocalInlines exports inlines core_prs ++ exports' ++ rest)
123
124 dsMonoBinds auto_scc (AbsBinds all_tyvars dicts exports inlines binds) rest
125   = dsMonoBinds (addSccs auto_scc exports) binds []`thenDs` \ core_prs ->
126     let 
127         core_binds = [Rec (addLocalInlines exports inlines core_prs)]
128
129         tup_expr      = mkTupleExpr locals
130         tup_ty        = coreExprType tup_expr
131         poly_tup_expr = mkLams all_tyvars $ mkLams dicts $
132                         mkDsLets core_binds tup_expr
133         locals        = [local | (_, _, local) <- exports]
134         local_tys     = map idType locals
135     in
136     newSysLocalDs (coreExprType poly_tup_expr)          `thenDs` \ poly_tup_id ->
137     let
138         dict_args = map Var dicts
139
140         mk_bind (tyvars, global, local) n       -- locals !! n == local
141           =     -- Need to make fresh locals to bind in the selector, because
142                 -- some of the tyvars will be bound to voidTy
143             newSysLocalsDs (map (substTy env) local_tys)        `thenDs` \ locals' ->
144             newSysLocalDs  (substTy env tup_ty)                 `thenDs` \ tup_id ->
145             returnDs (global, mkLams tyvars $ mkLams dicts $
146                               mkTupleSelector locals' (locals' !! n) tup_id $
147                               mkApps (mkTyApps (Var poly_tup_id) ty_args) dict_args)
148           where
149             mk_ty_arg all_tyvar | all_tyvar `elem` tyvars = mkTyVarTy all_tyvar
150                                 | otherwise               = voidTy
151             ty_args = map mk_ty_arg all_tyvars
152             env     = mkTyVarSubst all_tyvars ty_args
153     in
154     zipWithDs mk_bind exports [0..]             `thenDs` \ export_binds ->
155      -- don't scc (auto-)annotate the tuple itself.
156     returnDs ((poly_tup_id, poly_tup_expr) : (export_binds ++ rest))
157 \end{code}
158
159
160 %************************************************************************
161 %*                                                                      *
162 \subsection{Adding inline pragmas}
163 %*                                                                      *
164 %************************************************************************
165
166 \begin{code}
167 mkInline :: Bool -> CoreExpr -> CoreExpr
168 mkInline True  body = Note InlineMe body
169 mkInline False body = body
170
171 addLocalInlines :: [(a, Id, Id)] -> NameSet -> [(Id,CoreExpr)] -> [(Id,CoreExpr)]
172 addLocalInlines exports inlines pairs
173   = [(bndr, mkInline (bndr `elemVarSet` local_inlines) rhs) | (bndr,rhs) <- pairs]
174   where
175     local_inlines = mkVarSet [l | (_,g,l) <- exports, idName g `elemNameSet` inlines]
176 \end{code}
177
178
179 %************************************************************************
180 %*                                                                      *
181 \subsection[addAutoScc]{Adding automatic sccs}
182 %*                                                                      *
183 %************************************************************************
184
185 \begin{code}
186 data AutoScc
187         = TopLevel
188         | TopLevelAddSccs (Id -> Maybe Id)
189         | NoSccs
190
191 addSccs :: AutoScc -> [(a,Id,Id)] -> AutoScc
192 addSccs auto_scc@(TopLevelAddSccs _) exports = auto_scc
193 addSccs NoSccs   exports = NoSccs
194 addSccs TopLevel exports 
195   = TopLevelAddSccs (\id -> case [ exp | (_,exp,loc) <- exports, loc == id ] of
196                                 (exp:_)  | opt_AutoSccsOnAllToplevs || 
197                                             (isUserExportedId exp && 
198                                              opt_AutoSccsOnExportedToplevs)
199                                         -> Just exp
200                                 _ -> Nothing)
201
202 addAutoScc :: AutoScc           -- if needs be, decorate toplevs?
203            -> (Id, CoreExpr)
204            -> DsM (Id, CoreExpr)
205
206 addAutoScc (TopLevelAddSccs auto_scc_fn) pair@(bndr, core_expr) 
207  | do_auto_scc && worthSCC core_expr
208      = getModuleDs `thenDs` \ mod ->
209        returnDs (bndr, Note (SCC (mkAutoCC top_bndr mod NotCafCC)) core_expr)
210  where do_auto_scc = isJust maybe_auto_scc
211        maybe_auto_scc = auto_scc_fn bndr
212        (Just top_bndr) = maybe_auto_scc
213 addAutoScc _ pair
214      = returnDs pair
215
216 worthSCC (Note (SCC _) _) = False
217 worthSCC (Con _ _)        = False
218 worthSCC core_expr        = True
219 \end{code}
220
221 If profiling and dealing with a dict binding,
222 wrap the dict in @_scc_ DICT <dict>@:
223
224 \begin{code}
225 addDictScc var rhs = returnDs rhs
226
227 {- DISABLED for now (need to somehow make up a name for the scc) -- SDM
228   | not ( opt_SccProfilingOn && opt_AutoSccsOnDicts)
229     || not (isDictTy (idType var))
230   = returnDs rhs                                -- That's easy: do nothing
231
232   | otherwise
233   = getModuleAndGroupDs         `thenDs` \ (mod, grp) ->
234         -- ToDo: do -dicts-all flag (mark dict things with individual CCs)
235     returnDs (Note (SCC (mkAllDictsCC mod grp False)) rhs)
236 -}
237 \end{code}