[project @ 2000-07-11 15:57:45 by simonmar]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreTidy.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Tidying up Core}
5
6 \begin{code}
7 module CoreTidy (
8         tidyCorePgm, tidyExpr, 
9         tidyBndr, tidyBndrs
10     ) where
11
12 #include "HsVersions.h"
13
14 import CmdLineOpts      ( opt_D_dump_simpl, opt_D_verbose_core2core, opt_UsageSPOn )
15 import CoreSyn
16 import CoreUnfold       ( noUnfolding )
17 import CoreLint         ( beginPass, endPass )
18 import Rules            ( ProtoCoreRule(..), RuleBase )
19 import UsageSPInf       ( doUsageSPInf )
20 import VarEnv
21 import VarSet
22 import Var              ( Id, Var )
23 import Id               ( idType, idInfo, idName, idSpecialisation,
24                           mkVanillaId, mkId, exportWithOrigOccName,
25                           idStrictness, setIdStrictness,
26                           idDemandInfo, setIdDemandInfo,
27                         ) 
28 import IdInfo           ( specInfo, setSpecInfo, 
29                           setUnfoldingInfo, setDemandInfo,
30                           workerInfo, setWorkerInfo, WorkerInfo(..)
31                         )
32 import Demand           ( wwLazy )
33 import Name             ( getOccName, tidyTopName, mkLocalName, isLocallyDefined )
34 import OccName          ( initTidyOccEnv, tidyOccName )
35 import Type             ( tidyTopType, tidyType, tidyTypes, tidyTyVar, tidyTyVars )
36 import Module           ( Module )
37 import UniqSupply       ( UniqSupply )
38 import Unique           ( Uniquable(..) )
39 import SrcLoc           ( noSrcLoc )
40 import Util             ( mapAccumL )
41 \end{code}
42
43
44
45 %************************************************************************
46 %*                                                                      *
47 \subsection{Tidying core}
48 %*                                                                      *
49 %************************************************************************
50
51 Several tasks are done by @tidyCorePgm@
52
53 1. If @opt_UsageSPOn@ then compute usage information (which is
54    needed by Core2Stg).  ** NOTE _scc_ HERE **
55    Do this first, because it may introduce new binders.
56
57 2.  Make certain top-level bindings into Globals. The point is that 
58     Global things get externally-visible labels at code generation
59     time
60
61
62 3. Give all binders a nice print-name.  Their uniques aren't changed;
63    rather we give them lexically unique occ-names, so that we can
64    safely print the OccNae only in the interface file.  [Bad idea to
65    change the uniques, because the code generator makes global labels
66    from the uniques for local thunks etc.]
67
68 \begin{code}
69 tidyCorePgm :: UniqSupply -> Module -> [CoreBind] -> RuleBase
70             -> IO ([CoreBind], [ProtoCoreRule])
71 tidyCorePgm us module_name binds_in rulebase_in
72   = do
73         beginPass "Tidy Core"
74
75         (binds_in1,mrulebase_in1) <- if opt_UsageSPOn
76                                      then _scc_ "CoreUsageSPInf"
77                                           doUsageSPInf us binds_in rulebase_in
78                                      else return (binds_in,Nothing)
79
80         let rulebase_in1            = maybe rulebase_in id mrulebase_in1
81
82             (tidy_env1, binds_out)  = mapAccumL (tidyBind (Just module_name))
83                                                 init_tidy_env binds_in1
84             rules_out               = tidyProtoRules tidy_env1 (mk_local_protos rulebase_in1)
85
86         endPass "Tidy Core" (opt_D_dump_simpl || opt_D_verbose_core2core) binds_out
87         return (binds_out, rules_out)
88   where
89         -- We also make sure to avoid any exported binders.  Consider
90         --      f{-u1-} = 1     -- Local decl
91         --      ...
92         --      f{-u2-} = 2     -- Exported decl
93         --
94         -- The second exported decl must 'get' the name 'f', so we
95         -- have to put 'f' in the avoids list before we get to the first
96         -- decl.  tidyTopId then does a no-op on exported binders.
97     init_tidy_env = (initTidyOccEnv avoids, emptyVarEnv)
98     avoids        = [getOccName bndr | bndr <- bindersOfBinds binds_in,
99                                        exportWithOrigOccName bndr]
100
101     mk_local_protos :: RuleBase -> [ProtoCoreRule]
102     mk_local_protos (rule_ids, _)
103       = [ProtoCoreRule True id rule | id <- varSetElems rule_ids,
104                                       rule <- rulesRules (idSpecialisation id)]
105
106 tidyBind :: Maybe Module                -- (Just m) for top level, Nothing for nested
107          -> TidyEnv
108          -> CoreBind
109          -> (TidyEnv, CoreBind)
110 tidyBind maybe_mod env (NonRec bndr rhs)
111   = let
112         (env', bndr') = tidy_bndr maybe_mod env' env bndr
113         rhs'          = tidyExpr env' rhs
114         -- We use env' when tidying the RHS even though it's not
115         -- strictly necessary; it makes the code pretty hard to read
116         -- if we don't!
117     in
118     (env', NonRec bndr' rhs')
119
120 tidyBind maybe_mod env (Rec pairs)
121   = let
122         -- We use env' when tidying the rhss
123         -- When tidying the binder itself we may tidy it's
124         -- specialisations; if any of these mention other binders
125         -- in the group we should really feed env' to them too;
126         -- but that seems (a) unlikely and (b) a bit tiresome.
127         -- So I left it out for now
128
129         (bndrs, rhss)  = unzip pairs
130         (env', bndrs') = mapAccumL (tidy_bndr maybe_mod env') env bndrs
131         rhss'          = map (tidyExpr env') rhss
132   in
133   (env', Rec (zip bndrs' rhss'))
134
135 tidyExpr env (Type ty)       = Type (tidyType env ty)
136 tidyExpr env (Lit lit)       = Lit lit
137 tidyExpr env (App f a)       = App (tidyExpr env f) (tidyExpr env a)
138 tidyExpr env (Note n e)      = Note (tidyNote env n) (tidyExpr env e)
139
140 tidyExpr env (Let b e)       = Let b' (tidyExpr env' e)
141                              where
142                                (env', b') = tidyBind Nothing env b
143
144 tidyExpr env (Case e b alts) = Case (tidyExpr env e) b' (map (tidyAlt env') alts)
145                              where
146                                (env', b') = tidyBndr env b
147
148 tidyExpr env (Var v)         = Var (tidyVarOcc env v)
149
150 tidyExpr env (Lam b e)       = Lam b' (tidyExpr env' e)
151                              where
152                                (env', b') = tidyBndr env b
153
154 tidyAlt env (con, vs, rhs)   = (con, vs', tidyExpr env' rhs)
155                              where
156                                (env', vs') = tidyBndrs env vs
157
158 tidyNote env (Coerce t1 t2)  = Coerce (tidyType env t1) (tidyType env t2)
159
160 tidyNote env note            = note
161
162 tidyVarOcc (_, var_env) v = case lookupVarEnv var_env v of
163                                   Just v' -> v'
164                                   Nothing -> v
165 \end{code}
166
167 \begin{code}
168 tidy_bndr (Just mod) env_idinfo env var = tidyTopId mod env env_idinfo var
169 tidy_bndr Nothing    env_idinfo env var = tidyBndr      env            var
170 \end{code}
171
172
173
174 %************************************************************************
175 %*                                                                      *
176 \subsection{Tidying up a binder}
177 %*                                                                      *
178 %************************************************************************
179
180 \begin{code}
181 tidyBndr :: TidyEnv -> Var -> (TidyEnv, Var)
182 tidyBndr env var | isTyVar var = tidyTyVar env var
183                  | otherwise   = tidyId    env var
184
185 tidyBndrs :: TidyEnv -> [Var] -> (TidyEnv, [Var])
186 tidyBndrs env vars = mapAccumL tidyBndr env vars
187
188 tidyId :: TidyEnv -> Id -> (TidyEnv, Id)
189 tidyId env@(tidy_env, var_env) id
190   =     -- Non-top-level variables
191     let 
192         -- Give the Id a fresh print-name, *and* rename its type
193         -- The SrcLoc isn't important now, though we could extract it from the Id
194         name'             = mkLocalName (getUnique id) occ' noSrcLoc
195         (tidy_env', occ') = tidyOccName tidy_env (getOccName id)
196         ty'               = tidyType env (idType id)
197         id'               = mkVanillaId name' ty'
198                             `setIdStrictness` idStrictness id
199                             `setIdDemandInfo` idDemandInfo id
200                         -- NB: This throws away the IdInfo of the Id, which we
201                         -- no longer need.  That means we don't need to
202                         -- run over it with env, nor renumber it.
203                         --
204                         -- The exception is strictness and demand info, which 
205                         -- is used to decide whether to use let or case for
206                         -- function arguments and let bindings
207
208         var_env'          = extendVarEnv var_env id id'
209     in
210     ((tidy_env', var_env'), id')
211
212 tidyTopId :: Module -> TidyEnv -> TidyEnv -> Id -> (TidyEnv, Id)
213         -- The second env is the one to use for the IdInfo
214         -- It's necessary because when we are dealing with a recursive
215         -- group, a variable late in the group might be mentioned
216         -- in the IdInfo of one early in the group
217 tidyTopId mod env@(tidy_env, var_env) env_idinfo id
218   =     -- Top level variables
219     let
220         (tidy_env', name') | exportWithOrigOccName id = (tidy_env, idName id)
221                            | otherwise                = tidyTopName mod tidy_env (idName id)
222         ty'                = tidyTopType (idType id)
223         idinfo'            = tidyIdInfo env_idinfo (idInfo id)
224         id'                = mkId name' ty' idinfo'
225         var_env'           = extendVarEnv var_env id id'
226     in
227     ((tidy_env', var_env'), id')
228 \end{code}
229
230 \begin{code}
231 -- tidyIdInfo does these things:
232 --      a) tidy the specialisation info and worker info (if any)
233 --      b) zap the unfolding and demand info
234 -- The latter two are to avoid space leaks
235
236 tidyIdInfo env info
237   = info5
238   where
239     rules = specInfo info
240
241     info2 | isEmptyCoreRules rules = info 
242           | otherwise              = info `setSpecInfo` tidyRules env rules
243                 
244     info3 = info2 `setUnfoldingInfo` noUnfolding 
245     info4 = info3 `setDemandInfo`    wwLazy             -- I don't understand why...
246
247     info5 = case workerInfo info of
248                 NoWorker -> info4
249                 HasWorker w a  -> info4 `setWorkerInfo` HasWorker (tidyVarOcc env w) a
250
251 tidyProtoRules :: TidyEnv -> [ProtoCoreRule] -> [ProtoCoreRule]
252 tidyProtoRules env rules
253   = [ ProtoCoreRule is_local (tidyVarOcc env fn) (tidyRule env rule)
254     | ProtoCoreRule is_local fn rule <- rules
255     ]
256
257 tidyRules :: TidyEnv -> CoreRules -> CoreRules
258 tidyRules env (Rules rules fvs) 
259   = Rules (map (tidyRule env) rules)
260           (foldVarSet tidy_set_elem emptyVarSet fvs)
261   where
262     tidy_set_elem var new_set = extendVarSet new_set (tidyVarOcc env var)
263
264 tidyRule :: TidyEnv -> CoreRule -> CoreRule
265 tidyRule env rule@(BuiltinRule _) = rule
266 tidyRule env (Rule name vars tpl_args rhs)
267   = (Rule name vars' (map (tidyExpr env') tpl_args) (tidyExpr env' rhs))
268   where
269     (env', vars') = tidyBndrs env vars
270 \end{code}