[project @ 2000-10-24 08:40:09 by simonpj]
[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      ( DynFlags, DynFlag(..), opt_UsageSPOn, dopt )
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       ( mkSplitUniqSupply )
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 :: DynFlags -> Module -> [CoreBind] -> RuleBase
70             -> IO ([CoreBind], [ProtoCoreRule])
71 tidyCorePgm dflags module_name binds_in rulebase_in
72   = do
73         us <- mkSplitUniqSupply 'u'
74
75         beginPass dflags "Tidy Core"
76
77         binds_in1 <- if opt_UsageSPOn
78                      then _scc_ "CoreUsageSPInf"
79                                 doUsageSPInf dflags us binds_in rulebase_in
80                      else return binds_in
81
82         let (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_in)
85
86         endPass dflags "Tidy Core" (dopt Opt_D_dump_simpl dflags || 
87                                     dopt Opt_D_verbose_core2core dflags)
88                 binds_out
89
90         return (binds_out, rules_out)
91   where
92         -- We also make sure to avoid any exported binders.  Consider
93         --      f{-u1-} = 1     -- Local decl
94         --      ...
95         --      f{-u2-} = 2     -- Exported decl
96         --
97         -- The second exported decl must 'get' the name 'f', so we
98         -- have to put 'f' in the avoids list before we get to the first
99         -- decl.  tidyTopId then does a no-op on exported binders.
100     init_tidy_env = (initTidyOccEnv avoids, emptyVarEnv)
101     avoids        = [getOccName bndr | bndr <- bindersOfBinds binds_in,
102                                        exportWithOrigOccName bndr]
103
104     mk_local_protos :: RuleBase -> [ProtoCoreRule]
105     mk_local_protos (rule_ids, _)
106       = [ProtoCoreRule True id rule | id <- varSetElems rule_ids,
107                                       rule <- rulesRules (idSpecialisation id)]
108
109 tidyBind :: Maybe Module                -- (Just m) for top level, Nothing for nested
110          -> TidyEnv
111          -> CoreBind
112          -> (TidyEnv, CoreBind)
113 tidyBind maybe_mod env (NonRec bndr rhs)
114   = let
115         (env', bndr') = tidy_bndr maybe_mod env' env bndr
116         rhs'          = tidyExpr env' rhs
117         -- We use env' when tidying the RHS even though it's not
118         -- strictly necessary; it makes the code pretty hard to read
119         -- if we don't!
120     in
121     (env', NonRec bndr' rhs')
122
123 tidyBind maybe_mod env (Rec pairs)
124   = let
125         -- We use env' when tidying the rhss
126         -- When tidying the binder itself we may tidy it's
127         -- specialisations; if any of these mention other binders
128         -- in the group we should really feed env' to them too;
129         -- but that seems (a) unlikely and (b) a bit tiresome.
130         -- So I left it out for now
131
132         (bndrs, rhss)  = unzip pairs
133         (env', bndrs') = mapAccumL (tidy_bndr maybe_mod env') env bndrs
134         rhss'          = map (tidyExpr env') rhss
135   in
136   (env', Rec (zip bndrs' rhss'))
137
138 tidyExpr env (Type ty)       = Type (tidyType env ty)
139 tidyExpr env (Lit lit)       = Lit lit
140 tidyExpr env (App f a)       = App (tidyExpr env f) (tidyExpr env a)
141 tidyExpr env (Note n e)      = Note (tidyNote env n) (tidyExpr env e)
142
143 tidyExpr env (Let b e)       = Let b' (tidyExpr env' e)
144                              where
145                                (env', b') = tidyBind Nothing env b
146
147 tidyExpr env (Case e b alts) = Case (tidyExpr env e) b' (map (tidyAlt env') alts)
148                              where
149                                (env', b') = tidyBndr env b
150
151 tidyExpr env (Var v)         = Var (tidyVarOcc env v)
152
153 tidyExpr env (Lam b e)       = Lam b' (tidyExpr env' e)
154                              where
155                                (env', b') = tidyBndr env b
156
157 tidyAlt env (con, vs, rhs)   = (con, vs', tidyExpr env' rhs)
158                              where
159                                (env', vs') = tidyBndrs env vs
160
161 tidyNote env (Coerce t1 t2)  = Coerce (tidyType env t1) (tidyType env t2)
162
163 tidyNote env note            = note
164
165 tidyVarOcc (_, var_env) v = case lookupVarEnv var_env v of
166                                   Just v' -> v'
167                                   Nothing -> v
168 \end{code}
169
170 \begin{code}
171 tidy_bndr (Just mod) env_idinfo env var = tidyTopId mod env env_idinfo var
172 tidy_bndr Nothing    env_idinfo env var = tidyBndr      env            var
173 \end{code}
174
175
176
177 %************************************************************************
178 %*                                                                      *
179 \subsection{Tidying up a binder}
180 %*                                                                      *
181 %************************************************************************
182
183 \begin{code}
184 tidyBndr :: TidyEnv -> Var -> (TidyEnv, Var)
185 tidyBndr env var | isTyVar var = tidyTyVar env var
186                  | otherwise   = tidyId    env var
187
188 tidyBndrs :: TidyEnv -> [Var] -> (TidyEnv, [Var])
189 tidyBndrs env vars = mapAccumL tidyBndr env vars
190
191 tidyId :: TidyEnv -> Id -> (TidyEnv, Id)
192 tidyId env@(tidy_env, var_env) id
193   =     -- Non-top-level variables
194     let 
195         -- Give the Id a fresh print-name, *and* rename its type
196         -- The SrcLoc isn't important now, though we could extract it from the Id
197         name'             = mkLocalName (getUnique id) occ' noSrcLoc
198         (tidy_env', occ') = tidyOccName tidy_env (getOccName id)
199         ty'               = tidyType env (idType id)
200         id'               = mkVanillaId name' ty'
201                             `setIdStrictness` idStrictness id
202                             `setIdDemandInfo` idDemandInfo id
203                         -- NB: This throws away the IdInfo of the Id, which we
204                         -- no longer need.  That means we don't need to
205                         -- run over it with env, nor renumber it.
206                         --
207                         -- The exception is strictness and demand info, which 
208                         -- is used to decide whether to use let or case for
209                         -- function arguments and let bindings
210
211         var_env'          = extendVarEnv var_env id id'
212     in
213     ((tidy_env', var_env'), id')
214
215 tidyTopId :: Module -> TidyEnv -> TidyEnv -> Id -> (TidyEnv, Id)
216         -- The second env is the one to use for the IdInfo
217         -- It's necessary because when we are dealing with a recursive
218         -- group, a variable late in the group might be mentioned
219         -- in the IdInfo of one early in the group
220 tidyTopId mod env@(tidy_env, var_env) env_idinfo id
221   =     -- Top level variables
222     let
223         (tidy_env', name') | exportWithOrigOccName id = (tidy_env, idName id)
224                            | otherwise                = tidyTopName mod tidy_env (idName id)
225         ty'                = tidyTopType (idType id)
226         idinfo'            = tidyIdInfo env_idinfo (idInfo id)
227         id'                = mkId name' ty' idinfo'
228         var_env'           = extendVarEnv var_env id id'
229     in
230     ((tidy_env', var_env'), id')
231 \end{code}
232
233 \begin{code}
234 -- tidyIdInfo does these things:
235 --      a) tidy the specialisation info and worker info (if any)
236 --      b) zap the unfolding and demand info
237 -- The latter two are to avoid space leaks
238
239 tidyIdInfo env info
240   = info5
241   where
242     rules = specInfo info
243
244     info2 | isEmptyCoreRules rules = info 
245           | otherwise              = info `setSpecInfo` tidyRules env rules
246                 
247     info3 = info2 `setUnfoldingInfo` noUnfolding 
248     info4 = info3 `setDemandInfo`    wwLazy             -- I don't understand why...
249
250     info5 = case workerInfo info of
251                 NoWorker -> info4
252                 HasWorker w a  -> info4 `setWorkerInfo` HasWorker (tidyVarOcc env w) a
253
254 tidyProtoRules :: TidyEnv -> [ProtoCoreRule] -> [ProtoCoreRule]
255 tidyProtoRules env rules
256   = [ ProtoCoreRule is_local (tidyVarOcc env fn) (tidyRule env rule)
257     | ProtoCoreRule is_local fn rule <- rules
258     ]
259
260 tidyRules :: TidyEnv -> CoreRules -> CoreRules
261 tidyRules env (Rules rules fvs) 
262   = Rules (map (tidyRule env) rules)
263           (foldVarSet tidy_set_elem emptyVarSet fvs)
264   where
265     tidy_set_elem var new_set = extendVarSet new_set (tidyVarOcc env var)
266
267 tidyRule :: TidyEnv -> CoreRule -> CoreRule
268 tidyRule env rule@(BuiltinRule _) = rule
269 tidyRule env (Rule name vars tpl_args rhs)
270   = (Rule name vars' (map (tidyExpr env') tpl_args) (tidyExpr env' rhs))
271   where
272     (env', vars') = tidyBndrs env vars
273 \end{code}