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 extendSubst, 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 [] = subst
176 extendSubstList subst ((var,rhs):prs) = extendSubstList (extendSubst subst var rhs) prs
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
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 )
192 lookupTvSubst :: Subst -> TyVar -> Type
193 lookupTvSubst (Subst _ ids tvs) v = lookupVarEnv tvs v `orElse` Type.mkTyVarTy v
195 ------------------------------
196 isInScope :: Var -> Subst -> Bool
197 isInScope v (Subst in_scope _ _) = v `elemInScopeSet` in_scope
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)
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)
209 extendInScopeIds :: Subst -> [Id] -> Subst
210 extendInScopeIds (Subst in_scope ids tvs) vs
211 = Subst (in_scope `extendInScopeSetList` vs)
212 (ids `delVarEnvList` vs) tvs
215 Pretty printing, for debugging only
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
227 %************************************************************************
229 Substituting expressions
231 %************************************************************************
234 substExpr :: Subst -> CoreExpr -> CoreExpr
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)
246 (subst', bndr') = substBndr subst bndr
248 go (Let bind body) = Let bind' (substExpr subst' body)
250 (subst', bind') = substBind subst bind
252 go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts)
254 (subst', bndr') = substBndr subst bndr
256 go_alt subst (con, bndrs, rhs) = (con, bndrs', substExpr subst' rhs)
258 (subst', bndrs') = substBndrs subst bndrs
262 substBind :: Subst -> CoreBind -> (Subst, CoreBind)
263 substBind subst (NonRec bndr rhs) = (subst', NonRec bndr' (substExpr subst rhs))
265 (subst', bndr') = substBndr subst bndr
267 substBind subst (Rec pairs) = (subst', Rec pairs')
269 (subst', bndrs') = substRecBndrs subst (map fst pairs)
270 pairs' = bndrs' `zip` rhss'
271 rhss' = map (substExpr subst' . snd) pairs
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.
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.)
282 deShadowBinds :: [CoreBind] -> [CoreBind]
283 deShadowBinds binds = snd (mapAccumL substBind emptySubst binds)
287 %************************************************************************
291 %************************************************************************
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.
299 substBndr :: Subst -> Var -> (Subst, Var)
301 | isTyVar bndr = substTyVarBndr subst bndr
302 | otherwise = substIdBndr subst subst bndr
304 substBndrs :: Subst -> [Var] -> (Subst, [Var])
305 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
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
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
322 substIdBndr rec_subst subst@(Subst in_scope env tvs) old_id
323 = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
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)
329 old_ty = idType old_id
330 no_type_change = isEmptyVarEnv tvs ||
331 isEmptyVarSet (Type.tyVarsOfType old_ty)
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
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)
345 no_change = id1 == old_id
346 -- See Note [Extending the Subst]
347 -- *not* necessary to check mb_new_info and no_type_change
350 Now a variant that unconditionally allocates a new unique.
351 It also unconditionally zaps the OccInfo.
354 cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id)
355 cloneIdBndr subst us old_id
356 = clone_id subst subst (old_id, uniqFromSupply us)
358 cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
359 cloneIdBndrs subst us ids
360 = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us)
362 cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
363 cloneRecIdBndrs subst us ids
366 (subst', ids') = mapAccumL (clone_id subst') subst
367 (ids `zip` uniqsFromSupply us)
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
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)
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)
385 %************************************************************************
389 %************************************************************************
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
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')
401 substTy :: Subst -> Type -> Type
402 substTy (Subst in_scope id_env tv_env) ty
403 = Type.substTy (TvSubst in_scope tv_env) ty
407 %************************************************************************
409 \section{IdInfo substitution}
411 %************************************************************************
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
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)
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))
441 substWorker :: Subst -> WorkerInfo -> WorkerInfo
442 -- Seq'ing on the returned WorkerInfo is enough to cause all the
443 -- substitutions to happen completely
445 substWorker subst 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)
456 substSpec :: Subst -> Id -> SpecInfo -> SpecInfo
458 substSpec subst new_fn spec@(SpecInfo rules rhs_fvs)
462 = seqSpecInfo new_rules `seq` new_rules
464 new_name = idName new_fn
465 new_rules = SpecInfo (map do_subst rules) (substVarSet subst rhs_fvs)
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 }
474 (subst', bndrs') = substBndrs subst bndrs
477 substVarSet subst fvs
478 = foldVarSet (unionVarSet . subst_fv subst) emptyVarSet fvs
481 | isId fv = exprFreeVars (lookupIdSubst subst fv)
482 | otherwise = Type.tyVarsOfType (lookupTvSubst subst fv)