Don't import FastString in HsVersions.h
[ghc-hetmet.git] / compiler / coreSyn / CoreSubst.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Utility functions on @Core@ syntax
7
8 \begin{code}
9 module CoreSubst (
10         -- Substitution stuff
11         Subst, TvSubstEnv, IdSubstEnv, InScopeSet,
12
13         deShadowBinds,
14         substTy, substExpr, substSpec, substWorker,
15         lookupIdSubst, lookupTvSubst, 
16
17         emptySubst, mkEmptySubst, mkSubst, substInScope, isEmptySubst, 
18         extendIdSubst, extendIdSubstList, extendTvSubst, extendTvSubstList,
19         extendSubst, extendSubstList, zapSubstEnv,
20         extendInScope, extendInScopeList, extendInScopeIds, 
21         isInScope,
22
23         -- Binders
24         substBndr, substBndrs, substRecBndrs,
25         cloneIdBndr, cloneIdBndrs, cloneRecIdBndrs
26     ) where
27
28 #include "HsVersions.h"
29
30 import CoreSyn
31 import CoreFVs
32 import CoreUtils
33
34 import qualified Type
35 import Type     ( Type, TvSubst(..), TvSubstEnv )
36 import VarSet
37 import VarEnv
38 import Id
39 import Var      ( Var, TyVar, setVarUnique )
40 import IdInfo
41 import Unique
42 import UniqSupply
43 import Maybes
44 import Outputable
45 import PprCore          ()              -- Instances
46 import FastString
47
48 import Data.List
49 \end{code}
50
51
52 %************************************************************************
53 %*                                                                      *
54 \subsection{Substitutions}
55 %*                                                                      *
56 %************************************************************************
57
58 \begin{code}
59 data Subst 
60   = Subst InScopeSet    -- Variables in in scope (both Ids and TyVars)
61                         -- *after* applying the substitution
62           IdSubstEnv    -- Substitution for Ids
63           TvSubstEnv    -- Substitution for TyVars
64
65         -- INVARIANT 1: The (domain of the) in-scope set is a superset
66         --              of the free vars of the range of the substitution
67         --              that might possibly clash with locally-bound variables
68         --              in the thing being substituted in.
69         -- This is what lets us deal with name capture properly
70         -- It's a hard invariant to check...
71         -- There are various ways of causing it to happen:
72         --      - arrange that the in-scope set really is all the things in scope
73         --      - arrange that it's the free vars of the range of the substitution
74         --      - make it empty because all the free vars of the subst are fresh,
75         --              and hence can't possibly clash.a
76         --
77         -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with
78         --              Types.TvSubstEnv
79         --
80         -- INVARIANT 3: See Note [Extending the Subst]
81
82 {-
83 Note [Extending the Subst]
84 ~~~~~~~~~~~~~~~~~~~~~~~~~~
85 For a core Subst, which binds Ids as well, we make a different choice for Ids
86 than we do for TyVars.  
87
88 For TyVars, see Note [Extending the TvSubst] with Type.TvSubstEnv
89
90 For Ids, we have a different invariant
91         The IdSubstEnv is extended *only* when the Unique on an Id changes
92         Otherwise, we just extend the InScopeSet
93
94 In consequence:
95
96 * In substIdBndr, we extend the IdSubstEnv only when the unique changes
97
98 * If the TvSubstEnv and IdSubstEnv are both empty, substExpr does nothing
99   (Note that the above rule for substIdBndr maintains this property.  If
100    the incoming envts are both empty, then substituting the type and
101    IdInfo can't change anything.)
102
103 * In lookupIdSubst, we *must* look up the Id in the in-scope set, because
104   it may contain non-trivial changes.  Example:
105         (/\a. \x:a. ...x...) Int
106   We extend the TvSubstEnv with [a |-> Int]; but x's unique does not change
107   so we only extend the in-scope set.  Then we must look up in the in-scope
108   set when we find the occurrence of x.
109
110 Why do we make a different choice for the IdSubstEnv than the TvSubstEnv?
111
112 * For Ids, we change the IdInfo all the time (e.g. deleting the
113   unfolding), and adding it back later, so using the TyVar convention
114   would entail extending the substitution almost all the time
115
116 * The simplifier wants to look up in the in-scope set anyway, in case it 
117   can see a better unfolding from an enclosing case expression
118
119 * For TyVars, only coercion variables can possibly change, and they are 
120   easy to spot
121 -}
122
123 type IdSubstEnv = IdEnv CoreExpr
124
125 ----------------------------
126 isEmptySubst :: Subst -> Bool
127 isEmptySubst (Subst _ id_env tv_env) = isEmptyVarEnv id_env && isEmptyVarEnv tv_env
128
129 emptySubst :: Subst
130 emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv
131
132 mkEmptySubst :: InScopeSet -> Subst
133 mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv
134
135 mkSubst :: InScopeSet -> TvSubstEnv -> IdSubstEnv -> Subst
136 mkSubst in_scope tvs ids = Subst in_scope ids tvs
137
138 -- getTvSubst :: Subst -> TvSubst
139 -- getTvSubst (Subst in_scope _ tv_env) = TvSubst in_scope tv_env
140
141 -- getTvSubstEnv :: Subst -> TvSubstEnv
142 -- getTvSubstEnv (Subst _ _ tv_env) = tv_env
143 -- 
144 -- setTvSubstEnv :: Subst -> TvSubstEnv -> Subst
145 -- setTvSubstEnv (Subst in_scope ids _) tvs = Subst in_scope ids tvs
146
147 substInScope :: Subst -> InScopeSet
148 substInScope (Subst in_scope _ _) = in_scope
149
150 zapSubstEnv :: Subst -> Subst
151 zapSubstEnv (Subst in_scope _ _) = Subst in_scope emptyVarEnv emptyVarEnv
152
153 -- ToDo: add an ASSERT that fvs(subst-result) is already in the in-scope set
154 extendIdSubst :: Subst -> Id -> CoreExpr -> Subst
155 extendIdSubst (Subst in_scope ids tvs) v r = Subst in_scope (extendVarEnv ids v r) tvs
156
157 extendIdSubstList :: Subst -> [(Id, CoreExpr)] -> Subst
158 extendIdSubstList (Subst in_scope ids tvs) prs = Subst in_scope (extendVarEnvList ids prs) tvs
159
160 extendTvSubst :: Subst -> TyVar -> Type -> Subst
161 extendTvSubst (Subst in_scope ids tvs) v r = Subst in_scope ids (extendVarEnv tvs v r) 
162
163 extendTvSubstList :: Subst -> [(TyVar,Type)] -> Subst
164 extendTvSubstList (Subst in_scope ids tvs) prs = Subst in_scope ids (extendVarEnvList tvs prs)
165
166 extendSubstList :: Subst -> [(Var,CoreArg)] -> Subst
167 extendSubstList subst []              = subst
168 extendSubstList subst ((var,rhs):prs) = extendSubstList (extendSubst subst var rhs) prs
169
170 extendSubst :: Subst -> Var -> CoreArg -> Subst
171 extendSubst (Subst in_scope ids tvs) tv (Type ty)
172   = ASSERT( isTyVar tv ) Subst in_scope ids (extendVarEnv tvs tv ty)
173 extendSubst (Subst in_scope ids tvs) id expr
174   = ASSERT( isId id ) Subst in_scope (extendVarEnv ids id expr) tvs
175
176 lookupIdSubst :: Subst -> Id -> CoreExpr
177 lookupIdSubst (Subst in_scope ids _) v
178   | not (isLocalId v) = Var v
179   | Just e  <- lookupVarEnv ids       v = e
180   | Just v' <- lookupInScope in_scope v = Var v'
181         -- Vital! See Note [Extending the Subst]
182   | otherwise = WARN( True, ptext SLIT("CoreSubst.lookupIdSubst") <+> ppr v ) 
183                 Var v
184
185 lookupTvSubst :: Subst -> TyVar -> Type
186 lookupTvSubst (Subst _ _ tvs) v = lookupVarEnv tvs v `orElse` Type.mkTyVarTy v
187
188 ------------------------------
189 isInScope :: Var -> Subst -> Bool
190 isInScope v (Subst in_scope _ _) = v `elemInScopeSet` in_scope
191
192 extendInScope :: Subst -> Var -> Subst
193 extendInScope (Subst in_scope ids tvs) v
194   = Subst (in_scope `extendInScopeSet` v) 
195           (ids `delVarEnv` v) (tvs `delVarEnv` v)
196
197 extendInScopeList :: Subst -> [Var] -> Subst
198 extendInScopeList (Subst in_scope ids tvs) vs
199   = Subst (in_scope `extendInScopeSetList` vs) 
200           (ids `delVarEnvList` vs) (tvs `delVarEnvList` vs)
201
202 extendInScopeIds :: Subst -> [Id] -> Subst
203 extendInScopeIds (Subst in_scope ids tvs) vs 
204   = Subst (in_scope `extendInScopeSetList` vs) 
205           (ids `delVarEnvList` vs) tvs
206 \end{code}
207
208 Pretty printing, for debugging only
209
210 \begin{code}
211 instance Outputable Subst where
212   ppr (Subst in_scope ids tvs) 
213         =  ptext SLIT("<InScope =") <+> braces (fsep (map ppr (varEnvElts (getInScopeVars in_scope))))
214         $$ ptext SLIT(" IdSubst   =") <+> ppr ids
215         $$ ptext SLIT(" TvSubst   =") <+> ppr tvs
216          <> char '>'
217 \end{code}
218
219
220 %************************************************************************
221 %*                                                                      *
222         Substituting expressions
223 %*                                                                      *
224 %************************************************************************
225
226 \begin{code}
227 substExpr :: Subst -> CoreExpr -> CoreExpr
228 substExpr subst expr
229   = go expr
230   where
231     go (Var v)         = lookupIdSubst subst v 
232     go (Type ty)       = Type (substTy subst ty)
233     go (Lit lit)       = Lit lit
234     go (App fun arg)   = App (go fun) (go arg)
235     go (Note note e)   = Note (go_note note) (go e)
236     go (Cast e co)     = Cast (go e) (substTy subst co)
237     go (Lam bndr body) = Lam bndr' (substExpr subst' body)
238                        where
239                          (subst', bndr') = substBndr subst bndr
240
241     go (Let bind body) = Let bind' (substExpr subst' body)
242                        where
243                          (subst', bind') = substBind subst bind
244
245     go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts)
246                                  where
247                                  (subst', bndr') = substBndr subst bndr
248
249     go_alt subst (con, bndrs, rhs) = (con, bndrs', substExpr subst' rhs)
250                                  where
251                                    (subst', bndrs') = substBndrs subst bndrs
252
253     go_note note             = note
254
255 substBind :: Subst -> CoreBind -> (Subst, CoreBind)
256 substBind subst (NonRec bndr rhs) = (subst', NonRec bndr' (substExpr subst rhs))
257                                   where
258                                     (subst', bndr') = substBndr subst bndr
259
260 substBind subst (Rec pairs) = (subst', Rec pairs')
261                             where
262                                 (subst', bndrs') = substRecBndrs subst (map fst pairs)
263                                 pairs'  = bndrs' `zip` rhss'
264                                 rhss'   = map (substExpr subst' . snd) pairs
265 \end{code}
266
267 De-shadowing the program is sometimes a useful pre-pass.  It can be done simply
268 by running over the bindings with an empty substitution, becuase substitution
269 returns a result that has no-shadowing guaranteed.
270
271 (Actually, within a single *type* there might still be shadowing, because 
272 substType is a no-op for the empty substitution, but that's OK.)
273
274 \begin{code}
275 deShadowBinds :: [CoreBind] -> [CoreBind]
276 deShadowBinds binds = snd (mapAccumL substBind emptySubst binds)
277 \end{code}
278
279
280 %************************************************************************
281 %*                                                                      *
282         Substituting binders
283 %*                                                                      *
284 %************************************************************************
285
286 Remember that substBndr and friends are used when doing expression
287 substitution only.  Their only business is substitution, so they
288 preserve all IdInfo (suitably substituted).  For example, we *want* to
289 preserve occ info in rules.
290
291 \begin{code}
292 substBndr :: Subst -> Var -> (Subst, Var)
293 substBndr subst bndr
294   | isTyVar bndr  = substTyVarBndr subst bndr
295   | otherwise     = substIdBndr subst subst bndr
296
297 substBndrs :: Subst -> [Var] -> (Subst, [Var])
298 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
299
300 substRecBndrs :: Subst -> [Id] -> (Subst, [Id])
301 -- Substitute a mutually recursive group
302 substRecBndrs subst bndrs 
303   = (new_subst, new_bndrs)
304   where         -- Here's the reason we need to pass rec_subst to subst_id
305     (new_subst, new_bndrs) = mapAccumL (substIdBndr new_subst) subst bndrs
306 \end{code}
307
308
309 \begin{code}
310 substIdBndr :: Subst            -- Substitution to use for the IdInfo
311             -> Subst -> Id      -- Substitition and Id to transform
312             -> (Subst, Id)      -- Transformed pair
313                                 -- NB: unfolding may be zapped
314
315 substIdBndr rec_subst subst@(Subst in_scope env tvs) old_id
316   = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
317   where
318     id1 = uniqAway in_scope old_id      -- id1 is cloned if necessary
319     id2 | no_type_change = id1
320         | otherwise      = setIdType id1 (substTy subst old_ty)
321
322     old_ty = idType old_id
323     no_type_change = isEmptyVarEnv tvs || 
324                      isEmptyVarSet (Type.tyVarsOfType old_ty)
325
326         -- new_id has the right IdInfo
327         -- The lazy-set is because we're in a loop here, with 
328         -- rec_subst, when dealing with a mutually-recursive group
329     new_id = maybeModifyIdInfo mb_new_info id2
330     mb_new_info = substIdInfo rec_subst id2 (idInfo id2)
331         -- NB: unfolding info may be zapped
332
333         -- Extend the substitution if the unique has changed
334         -- See the notes with substTyVarBndr for the delVarEnv
335     new_env | no_change = delVarEnv env old_id
336             | otherwise = extendVarEnv env old_id (Var new_id)
337
338     no_change = id1 == old_id
339         -- See Note [Extending the Subst]
340         -- *not* necessary to check mb_new_info and no_type_change
341 \end{code}
342
343 Now a variant that unconditionally allocates a new unique.
344 It also unconditionally zaps the OccInfo.
345
346 \begin{code}
347 cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id)
348 cloneIdBndr subst us old_id
349   = clone_id subst subst (old_id, uniqFromSupply us)
350
351 cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
352 cloneIdBndrs subst us ids
353   = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us)
354
355 cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
356 cloneRecIdBndrs subst us ids
357   = (subst', ids')
358   where
359     (subst', ids') = mapAccumL (clone_id subst') subst
360                                (ids `zip` uniqsFromSupply us)
361
362 -- Just like substIdBndr, except that it always makes a new unique
363 -- It is given the unique to use
364 clone_id    :: Subst                    -- Substitution for the IdInfo
365             -> Subst -> (Id, Unique)    -- Substitition and Id to transform
366             -> (Subst, Id)              -- Transformed pair
367
368 clone_id rec_subst subst@(Subst in_scope env tvs) (old_id, uniq)
369   = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
370   where
371     id1     = setVarUnique old_id uniq
372     id2     = substIdType subst id1
373     new_id  = maybeModifyIdInfo (substIdInfo rec_subst id2 (idInfo old_id)) id2
374     new_env = extendVarEnv env old_id (Var new_id)
375 \end{code}
376
377
378 %************************************************************************
379 %*                                                                      *
380                 Types
381 %*                                                                      *
382 %************************************************************************
383
384 For types we just call the corresponding function in Type, but we have
385 to repackage the substitution, from a Subst to a TvSubst
386
387 \begin{code}
388 substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar)
389 substTyVarBndr (Subst in_scope id_env tv_env) tv
390   = case Type.substTyVarBndr (TvSubst in_scope tv_env) tv of
391         (TvSubst in_scope' tv_env', tv') 
392            -> (Subst in_scope' id_env tv_env', tv')
393
394 substTy :: Subst -> Type -> Type 
395 substTy (Subst in_scope _id_env tv_env) ty
396   = Type.substTy (TvSubst in_scope tv_env) ty
397 \end{code}
398
399
400 %************************************************************************
401 %*                                                                      *
402 \section{IdInfo substitution}
403 %*                                                                      *
404 %************************************************************************
405
406 \begin{code}
407 substIdType :: Subst -> Id -> Id
408 substIdType subst@(Subst _ _ tv_env) id
409   | isEmptyVarEnv tv_env || isEmptyVarSet (Type.tyVarsOfType old_ty) = id
410   | otherwise   = setIdType id (substTy subst old_ty)
411                 -- The tyVarsOfType is cheaper than it looks
412                 -- because we cache the free tyvars of the type
413                 -- in a Note in the id's type itself
414   where
415     old_ty = idType id
416
417 ------------------
418 substIdInfo :: Subst -> Id -> IdInfo -> Maybe IdInfo
419 -- Always zaps the unfolding, to save substitution work
420 substIdInfo subst new_id info
421   | nothing_to_do = Nothing
422   | otherwise     = Just (info `setSpecInfo`      substSpec subst new_id old_rules
423                                `setWorkerInfo`    substWorker subst old_wrkr
424                                `setUnfoldingInfo` noUnfolding)
425   where
426     old_rules     = specInfo info
427     old_wrkr      = workerInfo info
428     nothing_to_do = isEmptySpecInfo old_rules &&
429                     not (workerExists old_wrkr) &&
430                     not (hasUnfolding (unfoldingInfo info))
431     
432
433 ------------------
434 substWorker :: Subst -> WorkerInfo -> WorkerInfo
435         -- Seq'ing on the returned WorkerInfo is enough to cause all the 
436         -- substitutions to happen completely
437
438 substWorker _ NoWorker
439   = NoWorker
440 substWorker subst (HasWorker w a)
441   = case lookupIdSubst subst w of
442         Var w1 -> HasWorker w1 a
443         other  -> WARN( not (exprIsTrivial other), text "CoreSubst.substWorker:" <+> ppr w )
444                   NoWorker      -- Worker has got substituted away altogether
445                                 -- (This can happen if it's trivial, 
446                                 --  via postInlineUnconditionally, hence warning)
447
448 ------------------
449 substSpec :: Subst -> Id -> SpecInfo -> SpecInfo
450
451 substSpec subst new_fn spec@(SpecInfo rules rhs_fvs)
452   | isEmptySubst subst
453   = spec
454   | otherwise
455   = seqSpecInfo new_rules `seq` new_rules
456   where
457     new_name = idName new_fn
458     new_rules = SpecInfo (map do_subst rules) (substVarSet subst rhs_fvs)
459
460     do_subst rule@(BuiltinRule {}) = rule
461     do_subst rule@(Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs })
462         = rule { ru_bndrs = bndrs', 
463                  ru_fn = new_name,      -- Important: the function may have changed its name!
464                  ru_args  = map (substExpr subst') args,
465                  ru_rhs   = substExpr subst' rhs }
466         where
467           (subst', bndrs') = substBndrs subst bndrs
468
469 ------------------
470 substVarSet :: Subst -> VarSet -> VarSet
471 substVarSet subst fvs 
472   = foldVarSet (unionVarSet . subst_fv subst) emptyVarSet fvs
473   where
474     subst_fv subst fv 
475         | isId fv   = exprFreeVars (lookupIdSubst subst fv)
476         | otherwise = Type.tyVarsOfType (lookupTvSubst subst fv)
477 \end{code}