2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Utility functions on @Core@ syntax
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
18 Subst, TvSubstEnv, IdSubstEnv, InScopeSet,
21 substTy, substExpr, substSpec, substWorker,
22 lookupIdSubst, lookupTvSubst,
24 emptySubst, mkEmptySubst, mkSubst, substInScope, isEmptySubst,
25 extendIdSubst, extendIdSubstList, extendTvSubst, extendTvSubstList,
26 extendSubstList, zapSubstEnv,
27 extendInScope, extendInScopeList, extendInScopeIds,
31 substBndr, substBndrs, substRecBndrs,
32 cloneIdBndr, cloneIdBndrs, cloneRecIdBndrs
35 #include "HsVersions.h"
42 import Type ( Type, TvSubst(..), TvSubstEnv )
46 import Var ( Var, TyVar, setVarUnique )
52 import PprCore () -- Instances
60 %************************************************************************
62 \subsection{Substitutions}
64 %************************************************************************
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
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
85 -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with
88 -- INVARIANT 3: See Note [Extending the Subst]
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.
96 For TyVars, see Note [Extending the TvSubst] with Type.TvSubstEnv
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
104 * In substIdBndr, we extend the IdSubstEnv only when the unique changes
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.)
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.
118 Why do we make a different choice for the IdSubstEnv than the TvSubstEnv?
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
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
127 * For TyVars, only coercion variables can possibly change, and they are
131 type IdSubstEnv = IdEnv CoreExpr
133 ----------------------------
134 isEmptySubst :: Subst -> Bool
135 isEmptySubst (Subst _ id_env tv_env) = isEmptyVarEnv id_env && isEmptyVarEnv tv_env
138 emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv
140 mkEmptySubst :: InScopeSet -> Subst
141 mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv
143 mkSubst :: InScopeSet -> TvSubstEnv -> IdSubstEnv -> Subst
144 mkSubst in_scope tvs ids = Subst in_scope ids tvs
146 -- getTvSubst :: Subst -> TvSubst
147 -- getTvSubst (Subst in_scope _ tv_env) = TvSubst in_scope tv_env
149 -- getTvSubstEnv :: Subst -> TvSubstEnv
150 -- getTvSubstEnv (Subst _ _ tv_env) = tv_env
152 -- setTvSubstEnv :: Subst -> TvSubstEnv -> Subst
153 -- setTvSubstEnv (Subst in_scope ids _) tvs = Subst in_scope ids tvs
155 substInScope :: Subst -> InScopeSet
156 substInScope (Subst in_scope _ _) = in_scope
158 zapSubstEnv :: Subst -> Subst
159 zapSubstEnv (Subst in_scope _ _) = Subst in_scope emptyVarEnv emptyVarEnv
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
165 extendIdSubstList :: Subst -> [(Id, CoreExpr)] -> Subst
166 extendIdSubstList (Subst in_scope ids tvs) prs = Subst in_scope (extendVarEnvList ids prs) tvs
168 extendTvSubst :: Subst -> TyVar -> Type -> Subst
169 extendTvSubst (Subst in_scope ids tvs) v r = Subst in_scope ids (extendVarEnv tvs v r)
171 extendTvSubstList :: Subst -> [(TyVar,Type)] -> Subst
172 extendTvSubstList (Subst in_scope ids tvs) prs = Subst in_scope ids (extendVarEnvList tvs prs)
174 extendSubstList :: Subst -> [(Var,CoreArg)] -> Subst
175 extendSubstList subst []
177 extendSubstList (Subst in_scope ids tvs) ((tv,Type ty):prs)
178 = ASSERT( isTyVar tv ) extendSubstList (Subst in_scope ids (extendVarEnv tvs tv ty)) prs
179 extendSubstList (Subst in_scope ids tvs) ((id,expr):prs)
180 = ASSERT( isId id ) extendSubstList (Subst in_scope (extendVarEnv ids id expr) tvs) prs
182 lookupIdSubst :: Subst -> Id -> CoreExpr
183 lookupIdSubst (Subst in_scope ids tvs) v
184 | not (isLocalId v) = Var v
185 | Just e <- lookupVarEnv ids v = e
186 | Just v' <- lookupInScope in_scope v = Var v'
187 -- Vital! See Note [Extending the Subst]
188 | otherwise = WARN( True, ptext SLIT("CoreSubst.lookupIdSubst") <+> ppr v )
191 lookupTvSubst :: Subst -> TyVar -> Type
192 lookupTvSubst (Subst _ ids tvs) v = lookupVarEnv tvs v `orElse` Type.mkTyVarTy v
194 ------------------------------
195 isInScope :: Var -> Subst -> Bool
196 isInScope v (Subst in_scope _ _) = v `elemInScopeSet` in_scope
198 extendInScope :: Subst -> Var -> Subst
199 extendInScope (Subst in_scope ids tvs) v
200 = Subst (in_scope `extendInScopeSet` v)
201 (ids `delVarEnv` v) (tvs `delVarEnv` v)
203 extendInScopeList :: Subst -> [Var] -> Subst
204 extendInScopeList (Subst in_scope ids tvs) vs
205 = Subst (in_scope `extendInScopeSetList` vs)
206 (ids `delVarEnvList` vs) (tvs `delVarEnvList` vs)
208 extendInScopeIds :: Subst -> [Id] -> Subst
209 extendInScopeIds (Subst in_scope ids tvs) vs
210 = Subst (in_scope `extendInScopeSetList` vs)
211 (ids `delVarEnvList` vs) tvs
214 Pretty printing, for debugging only
217 instance Outputable Subst where
218 ppr (Subst in_scope ids tvs)
219 = ptext SLIT("<InScope =") <+> braces (fsep (map ppr (varEnvElts (getInScopeVars in_scope))))
220 $$ ptext SLIT(" IdSubst =") <+> ppr ids
221 $$ ptext SLIT(" TvSubst =") <+> ppr tvs
226 %************************************************************************
228 Substituting expressions
230 %************************************************************************
233 substExpr :: Subst -> CoreExpr -> CoreExpr
237 go (Var v) = lookupIdSubst subst v
238 go (Type ty) = Type (substTy subst ty)
239 go (Lit lit) = Lit lit
240 go (App fun arg) = App (go fun) (go arg)
241 go (Note note e) = Note (go_note note) (go e)
242 go (Cast e co) = Cast (go e) (substTy subst co)
243 go (Lam bndr body) = Lam bndr' (substExpr subst' body)
245 (subst', bndr') = substBndr subst bndr
247 go (Let bind body) = Let bind' (substExpr subst' body)
249 (subst', bind') = substBind subst bind
251 go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts)
253 (subst', bndr') = substBndr subst bndr
255 go_alt subst (con, bndrs, rhs) = (con, bndrs', substExpr subst' rhs)
257 (subst', bndrs') = substBndrs subst bndrs
261 substBind :: Subst -> CoreBind -> (Subst, CoreBind)
262 substBind subst (NonRec bndr rhs) = (subst', NonRec bndr' (substExpr subst rhs))
264 (subst', bndr') = substBndr subst bndr
266 substBind subst (Rec pairs) = (subst', Rec pairs')
268 (subst', bndrs') = substRecBndrs subst (map fst pairs)
269 pairs' = bndrs' `zip` rhss'
270 rhss' = map (substExpr subst' . snd) pairs
273 De-shadowing the program is sometimes a useful pre-pass. It can be done simply
274 by running over the bindings with an empty substitution, becuase substitution
275 returns a result that has no-shadowing guaranteed.
277 (Actually, within a single *type* there might still be shadowing, because
278 substType is a no-op for the empty substitution, but that's OK.)
281 deShadowBinds :: [CoreBind] -> [CoreBind]
282 deShadowBinds binds = snd (mapAccumL substBind emptySubst binds)
286 %************************************************************************
290 %************************************************************************
292 Remember that substBndr and friends are used when doing expression
293 substitution only. Their only business is substitution, so they
294 preserve all IdInfo (suitably substituted). For example, we *want* to
295 preserve occ info in rules.
298 substBndr :: Subst -> Var -> (Subst, Var)
300 | isTyVar bndr = substTyVarBndr subst bndr
301 | otherwise = substIdBndr subst subst bndr
303 substBndrs :: Subst -> [Var] -> (Subst, [Var])
304 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
306 substRecBndrs :: Subst -> [Id] -> (Subst, [Id])
307 -- Substitute a mutually recursive group
308 substRecBndrs subst bndrs
309 = (new_subst, new_bndrs)
310 where -- Here's the reason we need to pass rec_subst to subst_id
311 (new_subst, new_bndrs) = mapAccumL (substIdBndr new_subst) subst bndrs
316 substIdBndr :: Subst -- Substitution to use for the IdInfo
317 -> Subst -> Id -- Substitition and Id to transform
318 -> (Subst, Id) -- Transformed pair
319 -- NB: unfolding may be zapped
321 substIdBndr rec_subst subst@(Subst in_scope env tvs) old_id
322 = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
324 id1 = uniqAway in_scope old_id -- id1 is cloned if necessary
325 id2 | no_type_change = id1
326 | otherwise = setIdType id1 (substTy subst old_ty)
328 old_ty = idType old_id
329 no_type_change = isEmptyVarEnv tvs ||
330 isEmptyVarSet (Type.tyVarsOfType old_ty)
332 -- new_id has the right IdInfo
333 -- The lazy-set is because we're in a loop here, with
334 -- rec_subst, when dealing with a mutually-recursive group
335 new_id = maybeModifyIdInfo mb_new_info id2
336 mb_new_info = substIdInfo rec_subst id2 (idInfo id2)
337 -- NB: unfolding info may be zapped
339 -- Extend the substitution if the unique has changed
340 -- See the notes with substTyVarBndr for the delVarEnv
341 new_env | no_change = delVarEnv env old_id
342 | otherwise = extendVarEnv env old_id (Var new_id)
344 no_change = id1 == old_id
345 -- See Note [Extending the Subst]
346 -- *not* necessary to check mb_new_info and no_type_change
349 Now a variant that unconditionally allocates a new unique.
350 It also unconditionally zaps the OccInfo.
353 cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id)
354 cloneIdBndr subst us old_id
355 = clone_id subst subst (old_id, uniqFromSupply us)
357 cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
358 cloneIdBndrs subst us ids
359 = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us)
361 cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
362 cloneRecIdBndrs subst us ids
365 (subst', ids') = mapAccumL (clone_id subst') subst
366 (ids `zip` uniqsFromSupply us)
368 -- Just like substIdBndr, except that it always makes a new unique
369 -- It is given the unique to use
370 clone_id :: Subst -- Substitution for the IdInfo
371 -> Subst -> (Id, Unique) -- Substitition and Id to transform
372 -> (Subst, Id) -- Transformed pair
374 clone_id rec_subst subst@(Subst in_scope env tvs) (old_id, uniq)
375 = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
377 id1 = setVarUnique old_id uniq
378 id2 = substIdType subst id1
379 new_id = maybeModifyIdInfo (substIdInfo rec_subst id2 (idInfo old_id)) id2
380 new_env = extendVarEnv env old_id (Var new_id)
384 %************************************************************************
388 %************************************************************************
390 For types we just call the corresponding function in Type, but we have
391 to repackage the substitution, from a Subst to a TvSubst
394 substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar)
395 substTyVarBndr (Subst in_scope id_env tv_env) tv
396 = case Type.substTyVarBndr (TvSubst in_scope tv_env) tv of
397 (TvSubst in_scope' tv_env', tv')
398 -> (Subst in_scope' id_env tv_env', tv')
400 substTy :: Subst -> Type -> Type
401 substTy (Subst in_scope id_env tv_env) ty
402 = Type.substTy (TvSubst in_scope tv_env) ty
406 %************************************************************************
408 \section{IdInfo substitution}
410 %************************************************************************
413 substIdType :: Subst -> Id -> Id
414 substIdType subst@(Subst in_scope id_env tv_env) id
415 | isEmptyVarEnv tv_env || isEmptyVarSet (Type.tyVarsOfType old_ty) = id
416 | otherwise = setIdType id (substTy subst old_ty)
417 -- The tyVarsOfType is cheaper than it looks
418 -- because we cache the free tyvars of the type
419 -- in a Note in the id's type itself
424 substIdInfo :: Subst -> Id -> IdInfo -> Maybe IdInfo
425 -- Always zaps the unfolding, to save substitution work
426 substIdInfo subst new_id info
427 | nothing_to_do = Nothing
428 | otherwise = Just (info `setSpecInfo` substSpec subst new_id old_rules
429 `setWorkerInfo` substWorker subst old_wrkr
430 `setUnfoldingInfo` noUnfolding)
432 old_rules = specInfo info
433 old_wrkr = workerInfo info
434 nothing_to_do = isEmptySpecInfo old_rules &&
435 not (workerExists old_wrkr) &&
436 not (hasUnfolding (unfoldingInfo info))
440 substWorker :: Subst -> WorkerInfo -> WorkerInfo
441 -- Seq'ing on the returned WorkerInfo is enough to cause all the
442 -- substitutions to happen completely
444 substWorker subst NoWorker
446 substWorker subst (HasWorker w a)
447 = case lookupIdSubst subst w of
448 Var w1 -> HasWorker w1 a
449 other -> WARN( not (exprIsTrivial other), text "CoreSubst.substWorker:" <+> ppr w )
450 NoWorker -- Worker has got substituted away altogether
451 -- (This can happen if it's trivial,
452 -- via postInlineUnconditionally, hence warning)
455 substSpec :: Subst -> Id -> SpecInfo -> SpecInfo
457 substSpec subst new_fn spec@(SpecInfo rules rhs_fvs)
461 = seqSpecInfo new_rules `seq` new_rules
463 new_name = idName new_fn
464 new_rules = SpecInfo (map do_subst rules) (substVarSet subst rhs_fvs)
466 do_subst rule@(BuiltinRule {}) = rule
467 do_subst rule@(Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs })
468 = rule { ru_bndrs = bndrs',
469 ru_fn = new_name, -- Important: the function may have changed its name!
470 ru_args = map (substExpr subst') args,
471 ru_rhs = substExpr subst' rhs }
473 (subst', bndrs') = substBndrs subst bndrs
476 substVarSet subst fvs
477 = foldVarSet (unionVarSet . subst_fv subst) emptyVarSet fvs
480 | isId fv = exprFreeVars (lookupIdSubst subst fv)
481 | otherwise = Type.tyVarsOfType (lookupTvSubst subst fv)