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