compiler: introduce custom "GhcPrelude" Prelude
[ghc.git] / compiler / coreSyn / CoreSubst.hs
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
9 {-# LANGUAGE CPP #-}
10 module CoreSubst (
11 -- * Main data types
12 Subst(..), -- Implementation exported for supercompiler's Renaming.hs only
13 TvSubstEnv, IdSubstEnv, InScopeSet,
14
15 -- ** Substituting into expressions and related types
16 deShadowBinds, substSpec, substRulesForImportedIds,
17 substTy, substCo, substExpr, substExprSC, substBind, substBindSC,
18 substUnfolding, substUnfoldingSC,
19 lookupIdSubst, lookupTCvSubst, substIdOcc,
20 substTickish, substDVarSet, substIdInfo,
21
22 -- ** Operations on substitutions
23 emptySubst, mkEmptySubst, mkSubst, mkOpenSubst, substInScope, isEmptySubst,
24 extendIdSubst, extendIdSubstList, extendTCvSubst, extendTvSubstList,
25 extendSubst, extendSubstList, extendSubstWithVar, zapSubstEnv,
26 addInScopeSet, extendInScope, extendInScopeList, extendInScopeIds,
27 isInScope, setInScope, getTCvSubst, extendTvSubst, extendCvSubst,
28 delBndr, delBndrs,
29
30 -- ** Substituting and cloning binders
31 substBndr, substBndrs, substRecBndrs, substTyVarBndr, substCoVarBndr,
32 cloneBndr, cloneBndrs, cloneIdBndr, cloneIdBndrs, cloneRecIdBndrs,
33
34 ) where
35
36 #include "HsVersions.h"
37
38
39 import GhcPrelude
40
41 import CoreSyn
42 import CoreFVs
43 import CoreSeq
44 import CoreUtils
45 import qualified Type
46 import qualified Coercion
47
48 -- We are defining local versions
49 import Type hiding ( substTy, extendTvSubst, extendCvSubst, extendTvSubstList
50 , isInScope, substTyVarBndr, cloneTyVarBndr )
51 import Coercion hiding ( substCo, substCoVarBndr )
52
53 import PrelNames
54 import VarSet
55 import VarEnv
56 import Id
57 import Name ( Name )
58 import Var
59 import IdInfo
60 import UniqSupply
61 import Maybes
62 import Util
63 import Outputable
64 import PprCore () -- Instances
65 import Data.List
66
67
68
69 {-
70 ************************************************************************
71 * *
72 \subsection{Substitutions}
73 * *
74 ************************************************************************
75 -}
76
77 -- | A substitution environment, containing 'Id', 'TyVar', and 'CoVar'
78 -- substitutions.
79 --
80 -- Some invariants apply to how you use the substitution:
81 --
82 -- 1. #in_scope_invariant# The in-scope set contains at least those 'Id's and 'TyVar's that will be in scope /after/
83 -- applying the substitution to a term. Precisely, the in-scope set must be a superset of the free vars of the
84 -- substitution range that might possibly clash with locally-bound variables in the thing being substituted in.
85 --
86 -- 2. #apply_once# You may apply the substitution only /once/
87 --
88 -- There are various ways of setting up the in-scope set such that the first of these invariants hold:
89 --
90 -- * Arrange that the in-scope set really is all the things in scope
91 --
92 -- * Arrange that it's the free vars of the range of the substitution
93 --
94 -- * Make it empty, if you know that all the free vars of the substitution are fresh, and hence can't possibly clash
95 data Subst
96 = Subst InScopeSet -- Variables in in scope (both Ids and TyVars) /after/
97 -- applying the substitution
98 IdSubstEnv -- Substitution from NcIds to CoreExprs
99 TvSubstEnv -- Substitution from TyVars to Types
100 CvSubstEnv -- Substitution from CoVars to Coercions
101
102 -- INVARIANT 1: See #in_scope_invariant#
103 -- This is what lets us deal with name capture properly
104 -- It's a hard invariant to check...
105 --
106 -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with
107 -- Types.TvSubstEnv
108 --
109 -- INVARIANT 3: See Note [Extending the Subst]
110
111 {-
112 Note [Extending the Subst]
113 ~~~~~~~~~~~~~~~~~~~~~~~~~~
114 For a core Subst, which binds Ids as well, we make a different choice for Ids
115 than we do for TyVars.
116
117 For TyVars, see Note [Extending the TCvSubst] with Type.TvSubstEnv
118
119 For Ids, we have a different invariant
120 The IdSubstEnv is extended *only* when the Unique on an Id changes
121 Otherwise, we just extend the InScopeSet
122
123 In consequence:
124
125 * If all subst envs are empty, substExpr would be a
126 no-op, so substExprSC ("short cut") does nothing.
127
128 However, substExpr still goes ahead and substitutes. Reason: we may
129 want to replace existing Ids with new ones from the in-scope set, to
130 avoid space leaks.
131
132 * In substIdBndr, we extend the IdSubstEnv only when the unique changes
133
134 * If the CvSubstEnv, TvSubstEnv and IdSubstEnv are all empty,
135 substExpr does nothing (Note that the above rule for substIdBndr
136 maintains this property. If the incoming envts are both empty, then
137 substituting the type and IdInfo can't change anything.)
138
139 * In lookupIdSubst, we *must* look up the Id in the in-scope set, because
140 it may contain non-trivial changes. Example:
141 (/\a. \x:a. ...x...) Int
142 We extend the TvSubstEnv with [a |-> Int]; but x's unique does not change
143 so we only extend the in-scope set. Then we must look up in the in-scope
144 set when we find the occurrence of x.
145
146 * The requirement to look up the Id in the in-scope set means that we
147 must NOT take no-op short cut when the IdSubst is empty.
148 We must still look up every Id in the in-scope set.
149
150 * (However, we don't need to do so for expressions found in the IdSubst
151 itself, whose range is assumed to be correct wrt the in-scope set.)
152
153 Why do we make a different choice for the IdSubstEnv than the
154 TvSubstEnv and CvSubstEnv?
155
156 * For Ids, we change the IdInfo all the time (e.g. deleting the
157 unfolding), and adding it back later, so using the TyVar convention
158 would entail extending the substitution almost all the time
159
160 * The simplifier wants to look up in the in-scope set anyway, in case it
161 can see a better unfolding from an enclosing case expression
162
163 * For TyVars, only coercion variables can possibly change, and they are
164 easy to spot
165 -}
166
167 -- | An environment for substituting for 'Id's
168 type IdSubstEnv = IdEnv CoreExpr -- Domain is NcIds, i.e. not coercions
169
170 ----------------------------
171 isEmptySubst :: Subst -> Bool
172 isEmptySubst (Subst _ id_env tv_env cv_env)
173 = isEmptyVarEnv id_env && isEmptyVarEnv tv_env && isEmptyVarEnv cv_env
174
175 emptySubst :: Subst
176 emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv emptyVarEnv
177
178 mkEmptySubst :: InScopeSet -> Subst
179 mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv emptyVarEnv
180
181 mkSubst :: InScopeSet -> TvSubstEnv -> CvSubstEnv -> IdSubstEnv -> Subst
182 mkSubst in_scope tvs cvs ids = Subst in_scope ids tvs cvs
183
184 -- | Find the in-scope set: see "CoreSubst#in_scope_invariant"
185 substInScope :: Subst -> InScopeSet
186 substInScope (Subst in_scope _ _ _) = in_scope
187
188 -- | Remove all substitutions for 'Id's and 'Var's that might have been built up
189 -- while preserving the in-scope set
190 zapSubstEnv :: Subst -> Subst
191 zapSubstEnv (Subst in_scope _ _ _) = Subst in_scope emptyVarEnv emptyVarEnv emptyVarEnv
192
193 -- | Add a substitution for an 'Id' to the 'Subst': you must ensure that the in-scope set is
194 -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this
195 extendIdSubst :: Subst -> Id -> CoreExpr -> Subst
196 -- ToDo: add an ASSERT that fvs(subst-result) is already in the in-scope set
197 extendIdSubst (Subst in_scope ids tvs cvs) v r
198 = ASSERT2( isNonCoVarId v, ppr v $$ ppr r )
199 Subst in_scope (extendVarEnv ids v r) tvs cvs
200
201 -- | Adds multiple 'Id' substitutions to the 'Subst': see also 'extendIdSubst'
202 extendIdSubstList :: Subst -> [(Id, CoreExpr)] -> Subst
203 extendIdSubstList (Subst in_scope ids tvs cvs) prs
204 = ASSERT( all (isNonCoVarId . fst) prs )
205 Subst in_scope (extendVarEnvList ids prs) tvs cvs
206
207 -- | Add a substitution for a 'TyVar' to the 'Subst'
208 -- The 'TyVar' *must* be a real TyVar, and not a CoVar
209 -- You must ensure that the in-scope set is such that
210 -- the "CoreSubst#in_scope_invariant" is true after extending
211 -- the substitution like this.
212 extendTvSubst :: Subst -> TyVar -> Type -> Subst
213 extendTvSubst (Subst in_scope ids tvs cvs) tv ty
214 = ASSERT( isTyVar tv )
215 Subst in_scope ids (extendVarEnv tvs tv ty) cvs
216
217 -- | Adds multiple 'TyVar' substitutions to the 'Subst': see also 'extendTvSubst'
218 extendTvSubstList :: Subst -> [(TyVar,Type)] -> Subst
219 extendTvSubstList subst vrs
220 = foldl' extend subst vrs
221 where
222 extend subst (v, r) = extendTvSubst subst v r
223
224 -- | Add a substitution from a 'CoVar' to a 'Coercion' to the 'Subst': you must ensure that the in-scope set is
225 -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this
226 extendCvSubst :: Subst -> CoVar -> Coercion -> Subst
227 extendCvSubst (Subst in_scope ids tvs cvs) v r
228 = ASSERT( isCoVar v )
229 Subst in_scope ids tvs (extendVarEnv cvs v r)
230
231 -- | Add a substitution appropriate to the thing being substituted
232 -- (whether an expression, type, or coercion). See also
233 -- 'extendIdSubst', 'extendTvSubst', 'extendCvSubst'
234 extendSubst :: Subst -> Var -> CoreArg -> Subst
235 extendSubst subst var arg
236 = case arg of
237 Type ty -> ASSERT( isTyVar var ) extendTvSubst subst var ty
238 Coercion co -> ASSERT( isCoVar var ) extendCvSubst subst var co
239 _ -> ASSERT( isId var ) extendIdSubst subst var arg
240
241 extendSubstWithVar :: Subst -> Var -> Var -> Subst
242 extendSubstWithVar subst v1 v2
243 | isTyVar v1 = ASSERT( isTyVar v2 ) extendTvSubst subst v1 (mkTyVarTy v2)
244 | isCoVar v1 = ASSERT( isCoVar v2 ) extendCvSubst subst v1 (mkCoVarCo v2)
245 | otherwise = ASSERT( isId v2 ) extendIdSubst subst v1 (Var v2)
246
247 -- | Add a substitution as appropriate to each of the terms being
248 -- substituted (whether expressions, types, or coercions). See also
249 -- 'extendSubst'.
250 extendSubstList :: Subst -> [(Var,CoreArg)] -> Subst
251 extendSubstList subst [] = subst
252 extendSubstList subst ((var,rhs):prs) = extendSubstList (extendSubst subst var rhs) prs
253
254 -- | Find the substitution for an 'Id' in the 'Subst'
255 lookupIdSubst :: SDoc -> Subst -> Id -> CoreExpr
256 lookupIdSubst doc (Subst in_scope ids _ _) v
257 | not (isLocalId v) = Var v
258 | Just e <- lookupVarEnv ids v = e
259 | Just v' <- lookupInScope in_scope v = Var v'
260 -- Vital! See Note [Extending the Subst]
261 | otherwise = WARN( True, text "CoreSubst.lookupIdSubst" <+> doc <+> ppr v
262 $$ ppr in_scope)
263 Var v
264
265 -- | Find the substitution for a 'TyVar' in the 'Subst'
266 lookupTCvSubst :: Subst -> TyVar -> Type
267 lookupTCvSubst (Subst _ _ tvs cvs) v
268 | isTyVar v
269 = lookupVarEnv tvs v `orElse` Type.mkTyVarTy v
270 | otherwise
271 = mkCoercionTy $ lookupVarEnv cvs v `orElse` mkCoVarCo v
272
273 delBndr :: Subst -> Var -> Subst
274 delBndr (Subst in_scope ids tvs cvs) v
275 | isCoVar v = Subst in_scope ids tvs (delVarEnv cvs v)
276 | isTyVar v = Subst in_scope ids (delVarEnv tvs v) cvs
277 | otherwise = Subst in_scope (delVarEnv ids v) tvs cvs
278
279 delBndrs :: Subst -> [Var] -> Subst
280 delBndrs (Subst in_scope ids tvs cvs) vs
281 = Subst in_scope (delVarEnvList ids vs) (delVarEnvList tvs vs) (delVarEnvList cvs vs)
282 -- Easiest thing is just delete all from all!
283
284 -- | Simultaneously substitute for a bunch of variables
285 -- No left-right shadowing
286 -- ie the substitution for (\x \y. e) a1 a2
287 -- so neither x nor y scope over a1 a2
288 mkOpenSubst :: InScopeSet -> [(Var,CoreArg)] -> Subst
289 mkOpenSubst in_scope pairs = Subst in_scope
290 (mkVarEnv [(id,e) | (id, e) <- pairs, isId id])
291 (mkVarEnv [(tv,ty) | (tv, Type ty) <- pairs])
292 (mkVarEnv [(v,co) | (v, Coercion co) <- pairs])
293
294 ------------------------------
295 isInScope :: Var -> Subst -> Bool
296 isInScope v (Subst in_scope _ _ _) = v `elemInScopeSet` in_scope
297
298 -- | Add the 'Var' to the in-scope set, but do not remove
299 -- any existing substitutions for it
300 addInScopeSet :: Subst -> VarSet -> Subst
301 addInScopeSet (Subst in_scope ids tvs cvs) vs
302 = Subst (in_scope `extendInScopeSetSet` vs) ids tvs cvs
303
304 -- | Add the 'Var' to the in-scope set: as a side effect,
305 -- and remove any existing substitutions for it
306 extendInScope :: Subst -> Var -> Subst
307 extendInScope (Subst in_scope ids tvs cvs) v
308 = Subst (in_scope `extendInScopeSet` v)
309 (ids `delVarEnv` v) (tvs `delVarEnv` v) (cvs `delVarEnv` v)
310
311 -- | Add the 'Var's to the in-scope set: see also 'extendInScope'
312 extendInScopeList :: Subst -> [Var] -> Subst
313 extendInScopeList (Subst in_scope ids tvs cvs) vs
314 = Subst (in_scope `extendInScopeSetList` vs)
315 (ids `delVarEnvList` vs) (tvs `delVarEnvList` vs) (cvs `delVarEnvList` vs)
316
317 -- | Optimized version of 'extendInScopeList' that can be used if you are certain
318 -- all the things being added are 'Id's and hence none are 'TyVar's or 'CoVar's
319 extendInScopeIds :: Subst -> [Id] -> Subst
320 extendInScopeIds (Subst in_scope ids tvs cvs) vs
321 = Subst (in_scope `extendInScopeSetList` vs)
322 (ids `delVarEnvList` vs) tvs cvs
323
324 setInScope :: Subst -> InScopeSet -> Subst
325 setInScope (Subst _ ids tvs cvs) in_scope = Subst in_scope ids tvs cvs
326
327 -- Pretty printing, for debugging only
328
329 instance Outputable Subst where
330 ppr (Subst in_scope ids tvs cvs)
331 = text "<InScope =" <+> in_scope_doc
332 $$ text " IdSubst =" <+> ppr ids
333 $$ text " TvSubst =" <+> ppr tvs
334 $$ text " CvSubst =" <+> ppr cvs
335 <> char '>'
336 where
337 in_scope_doc = pprVarSet (getInScopeVars in_scope) (braces . fsep . map ppr)
338
339 {-
340 ************************************************************************
341 * *
342 Substituting expressions
343 * *
344 ************************************************************************
345 -}
346
347 -- | Apply a substitution to an entire 'CoreExpr'. Remember, you may only
348 -- apply the substitution /once/: see "CoreSubst#apply_once"
349 --
350 -- Do *not* attempt to short-cut in the case of an empty substitution!
351 -- See Note [Extending the Subst]
352 substExprSC :: SDoc -> Subst -> CoreExpr -> CoreExpr
353 substExprSC doc subst orig_expr
354 | isEmptySubst subst = orig_expr
355 | otherwise = -- pprTrace "enter subst-expr" (doc $$ ppr orig_expr) $
356 subst_expr doc subst orig_expr
357
358 substExpr :: SDoc -> Subst -> CoreExpr -> CoreExpr
359 substExpr doc subst orig_expr = subst_expr doc subst orig_expr
360
361 subst_expr :: SDoc -> Subst -> CoreExpr -> CoreExpr
362 subst_expr doc subst expr
363 = go expr
364 where
365 go (Var v) = lookupIdSubst (doc $$ text "subst_expr") subst v
366 go (Type ty) = Type (substTy subst ty)
367 go (Coercion co) = Coercion (substCo subst co)
368 go (Lit lit) = Lit lit
369 go (App fun arg) = App (go fun) (go arg)
370 go (Tick tickish e) = mkTick (substTickish subst tickish) (go e)
371 go (Cast e co) = Cast (go e) (substCo subst co)
372 -- Do not optimise even identity coercions
373 -- Reason: substitution applies to the LHS of RULES, and
374 -- if you "optimise" an identity coercion, you may
375 -- lose a binder. We optimise the LHS of rules at
376 -- construction time
377
378 go (Lam bndr body) = Lam bndr' (subst_expr doc subst' body)
379 where
380 (subst', bndr') = substBndr subst bndr
381
382 go (Let bind body) = Let bind' (subst_expr doc subst' body)
383 where
384 (subst', bind') = substBind subst bind
385
386 go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts)
387 where
388 (subst', bndr') = substBndr subst bndr
389
390 go_alt subst (con, bndrs, rhs) = (con, bndrs', subst_expr doc subst' rhs)
391 where
392 (subst', bndrs') = substBndrs subst bndrs
393
394 -- | Apply a substitution to an entire 'CoreBind', additionally returning an updated 'Subst'
395 -- that should be used by subsequent substitutions.
396 substBind, substBindSC :: Subst -> CoreBind -> (Subst, CoreBind)
397
398 substBindSC subst bind -- Short-cut if the substitution is empty
399 | not (isEmptySubst subst)
400 = substBind subst bind
401 | otherwise
402 = case bind of
403 NonRec bndr rhs -> (subst', NonRec bndr' rhs)
404 where
405 (subst', bndr') = substBndr subst bndr
406 Rec pairs -> (subst', Rec (bndrs' `zip` rhss'))
407 where
408 (bndrs, rhss) = unzip pairs
409 (subst', bndrs') = substRecBndrs subst bndrs
410 rhss' | isEmptySubst subst'
411 = rhss
412 | otherwise
413 = map (subst_expr (text "substBindSC") subst') rhss
414
415 substBind subst (NonRec bndr rhs)
416 = (subst', NonRec bndr' (subst_expr (text "substBind") subst rhs))
417 where
418 (subst', bndr') = substBndr subst bndr
419
420 substBind subst (Rec pairs)
421 = (subst', Rec (bndrs' `zip` rhss'))
422 where
423 (bndrs, rhss) = unzip pairs
424 (subst', bndrs') = substRecBndrs subst bndrs
425 rhss' = map (subst_expr (text "substBind") subst') rhss
426
427 -- | De-shadowing the program is sometimes a useful pre-pass. It can be done simply
428 -- by running over the bindings with an empty substitution, because substitution
429 -- returns a result that has no-shadowing guaranteed.
430 --
431 -- (Actually, within a single /type/ there might still be shadowing, because
432 -- 'substTy' is a no-op for the empty substitution, but that's probably OK.)
433 --
434 -- [Aug 09] This function is not used in GHC at the moment, but seems so
435 -- short and simple that I'm going to leave it here
436 deShadowBinds :: CoreProgram -> CoreProgram
437 deShadowBinds binds = snd (mapAccumL substBind emptySubst binds)
438
439 {-
440 ************************************************************************
441 * *
442 Substituting binders
443 * *
444 ************************************************************************
445
446 Remember that substBndr and friends are used when doing expression
447 substitution only. Their only business is substitution, so they
448 preserve all IdInfo (suitably substituted). For example, we *want* to
449 preserve occ info in rules.
450 -}
451
452 -- | Substitutes a 'Var' for another one according to the 'Subst' given, returning
453 -- the result and an updated 'Subst' that should be used by subsequent substitutions.
454 -- 'IdInfo' is preserved by this process, although it is substituted into appropriately.
455 substBndr :: Subst -> Var -> (Subst, Var)
456 substBndr subst bndr
457 | isTyVar bndr = substTyVarBndr subst bndr
458 | isCoVar bndr = substCoVarBndr subst bndr
459 | otherwise = substIdBndr (text "var-bndr") subst subst bndr
460
461 -- | Applies 'substBndr' to a number of 'Var's, accumulating a new 'Subst' left-to-right
462 substBndrs :: Subst -> [Var] -> (Subst, [Var])
463 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
464
465 -- | Substitute in a mutually recursive group of 'Id's
466 substRecBndrs :: Subst -> [Id] -> (Subst, [Id])
467 substRecBndrs subst bndrs
468 = (new_subst, new_bndrs)
469 where -- Here's the reason we need to pass rec_subst to subst_id
470 (new_subst, new_bndrs) = mapAccumL (substIdBndr (text "rec-bndr") new_subst) subst bndrs
471
472 substIdBndr :: SDoc
473 -> Subst -- ^ Substitution to use for the IdInfo
474 -> Subst -> Id -- ^ Substitution and Id to transform
475 -> (Subst, Id) -- ^ Transformed pair
476 -- NB: unfolding may be zapped
477
478 substIdBndr _doc rec_subst subst@(Subst in_scope env tvs cvs) old_id
479 = -- pprTrace "substIdBndr" (doc $$ ppr old_id $$ ppr in_scope) $
480 (Subst (in_scope `extendInScopeSet` new_id) new_env tvs cvs, new_id)
481 where
482 id1 = uniqAway in_scope old_id -- id1 is cloned if necessary
483 id2 | no_type_change = id1
484 | otherwise = setIdType id1 (substTy subst old_ty)
485
486 old_ty = idType old_id
487 no_type_change = (isEmptyVarEnv tvs && isEmptyVarEnv cvs) ||
488 noFreeVarsOfType old_ty
489
490 -- new_id has the right IdInfo
491 -- The lazy-set is because we're in a loop here, with
492 -- rec_subst, when dealing with a mutually-recursive group
493 new_id = maybeModifyIdInfo mb_new_info id2
494 mb_new_info = substIdInfo rec_subst id2 (idInfo id2)
495 -- NB: unfolding info may be zapped
496
497 -- Extend the substitution if the unique has changed
498 -- See the notes with substTyVarBndr for the delVarEnv
499 new_env | no_change = delVarEnv env old_id
500 | otherwise = extendVarEnv env old_id (Var new_id)
501
502 no_change = id1 == old_id
503 -- See Note [Extending the Subst]
504 -- it's /not/ necessary to check mb_new_info and no_type_change
505
506 {-
507 Now a variant that unconditionally allocates a new unique.
508 It also unconditionally zaps the OccInfo.
509 -}
510
511 -- | Very similar to 'substBndr', but it always allocates a new 'Unique' for
512 -- each variable in its output. It substitutes the IdInfo though.
513 cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id)
514 cloneIdBndr subst us old_id
515 = clone_id subst subst (old_id, uniqFromSupply us)
516
517 -- | Applies 'cloneIdBndr' to a number of 'Id's, accumulating a final
518 -- substitution from left to right
519 cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
520 cloneIdBndrs subst us ids
521 = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us)
522
523 cloneBndrs :: Subst -> UniqSupply -> [Var] -> (Subst, [Var])
524 -- Works for all kinds of variables (typically case binders)
525 -- not just Ids
526 cloneBndrs subst us vs
527 = mapAccumL (\subst (v, u) -> cloneBndr subst u v) subst (vs `zip` uniqsFromSupply us)
528
529 cloneBndr :: Subst -> Unique -> Var -> (Subst, Var)
530 cloneBndr subst uniq v
531 | isTyVar v = cloneTyVarBndr subst v uniq
532 | otherwise = clone_id subst subst (v,uniq) -- Works for coercion variables too
533
534 -- | Clone a mutually recursive group of 'Id's
535 cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
536 cloneRecIdBndrs subst us ids
537 = (subst', ids')
538 where
539 (subst', ids') = mapAccumL (clone_id subst') subst
540 (ids `zip` uniqsFromSupply us)
541
542 -- Just like substIdBndr, except that it always makes a new unique
543 -- It is given the unique to use
544 clone_id :: Subst -- Substitution for the IdInfo
545 -> Subst -> (Id, Unique) -- Substitution and Id to transform
546 -> (Subst, Id) -- Transformed pair
547
548 clone_id rec_subst subst@(Subst in_scope idvs tvs cvs) (old_id, uniq)
549 = (Subst (in_scope `extendInScopeSet` new_id) new_idvs tvs new_cvs, new_id)
550 where
551 id1 = setVarUnique old_id uniq
552 id2 = substIdType subst id1
553 new_id = maybeModifyIdInfo (substIdInfo rec_subst id2 (idInfo old_id)) id2
554 (new_idvs, new_cvs) | isCoVar old_id = (idvs, extendVarEnv cvs old_id (mkCoVarCo new_id))
555 | otherwise = (extendVarEnv idvs old_id (Var new_id), cvs)
556
557 {-
558 ************************************************************************
559 * *
560 Types and Coercions
561 * *
562 ************************************************************************
563
564 For types and coercions we just call the corresponding functions in
565 Type and Coercion, but we have to repackage the substitution, from a
566 Subst to a TCvSubst.
567 -}
568
569 substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar)
570 substTyVarBndr (Subst in_scope id_env tv_env cv_env) tv
571 = case Type.substTyVarBndr (TCvSubst in_scope tv_env cv_env) tv of
572 (TCvSubst in_scope' tv_env' cv_env', tv')
573 -> (Subst in_scope' id_env tv_env' cv_env', tv')
574
575 cloneTyVarBndr :: Subst -> TyVar -> Unique -> (Subst, TyVar)
576 cloneTyVarBndr (Subst in_scope id_env tv_env cv_env) tv uniq
577 = case Type.cloneTyVarBndr (TCvSubst in_scope tv_env cv_env) tv uniq of
578 (TCvSubst in_scope' tv_env' cv_env', tv')
579 -> (Subst in_scope' id_env tv_env' cv_env', tv')
580
581 substCoVarBndr :: Subst -> TyVar -> (Subst, TyVar)
582 substCoVarBndr (Subst in_scope id_env tv_env cv_env) cv
583 = case Coercion.substCoVarBndr (TCvSubst in_scope tv_env cv_env) cv of
584 (TCvSubst in_scope' tv_env' cv_env', cv')
585 -> (Subst in_scope' id_env tv_env' cv_env', cv')
586
587 -- | See 'Type.substTy'
588 substTy :: Subst -> Type -> Type
589 substTy subst ty = Type.substTyUnchecked (getTCvSubst subst) ty
590
591 getTCvSubst :: Subst -> TCvSubst
592 getTCvSubst (Subst in_scope _ tenv cenv) = TCvSubst in_scope tenv cenv
593
594 -- | See 'Coercion.substCo'
595 substCo :: Subst -> Coercion -> Coercion
596 substCo subst co = Coercion.substCo (getTCvSubst subst) co
597
598 {-
599 ************************************************************************
600 * *
601 \section{IdInfo substitution}
602 * *
603 ************************************************************************
604 -}
605
606 substIdType :: Subst -> Id -> Id
607 substIdType subst@(Subst _ _ tv_env cv_env) id
608 | (isEmptyVarEnv tv_env && isEmptyVarEnv cv_env) || noFreeVarsOfType old_ty = id
609 | otherwise = setIdType id (substTy subst old_ty)
610 -- The tyCoVarsOfType is cheaper than it looks
611 -- because we cache the free tyvars of the type
612 -- in a Note in the id's type itself
613 where
614 old_ty = idType id
615
616 ------------------
617 -- | Substitute into some 'IdInfo' with regard to the supplied new 'Id'.
618 substIdInfo :: Subst -> Id -> IdInfo -> Maybe IdInfo
619 substIdInfo subst new_id info
620 | nothing_to_do = Nothing
621 | otherwise = Just (info `setRuleInfo` substSpec subst new_id old_rules
622 `setUnfoldingInfo` substUnfolding subst old_unf)
623 where
624 old_rules = ruleInfo info
625 old_unf = unfoldingInfo info
626 nothing_to_do = isEmptyRuleInfo old_rules && not (isFragileUnfolding old_unf)
627
628 ------------------
629 -- | Substitutes for the 'Id's within an unfolding
630 substUnfolding, substUnfoldingSC :: Subst -> Unfolding -> Unfolding
631 -- Seq'ing on the returned Unfolding is enough to cause
632 -- all the substitutions to happen completely
633
634 substUnfoldingSC subst unf -- Short-cut version
635 | isEmptySubst subst = unf
636 | otherwise = substUnfolding subst unf
637
638 substUnfolding subst df@(DFunUnfolding { df_bndrs = bndrs, df_args = args })
639 = df { df_bndrs = bndrs', df_args = args' }
640 where
641 (subst',bndrs') = substBndrs subst bndrs
642 args' = map (substExpr (text "subst-unf:dfun") subst') args
643
644 substUnfolding subst unf@(CoreUnfolding { uf_tmpl = tmpl, uf_src = src })
645 -- Retain an InlineRule!
646 | not (isStableSource src) -- Zap an unstable unfolding, to save substitution work
647 = NoUnfolding
648 | otherwise -- But keep a stable one!
649 = seqExpr new_tmpl `seq`
650 unf { uf_tmpl = new_tmpl }
651 where
652 new_tmpl = substExpr (text "subst-unf") subst tmpl
653
654 substUnfolding _ unf = unf -- NoUnfolding, OtherCon
655
656 ------------------
657 substIdOcc :: Subst -> Id -> Id
658 -- These Ids should not be substituted to non-Ids
659 substIdOcc subst v = case lookupIdSubst (text "substIdOcc") subst v of
660 Var v' -> v'
661 other -> pprPanic "substIdOcc" (vcat [ppr v <+> ppr other, ppr subst])
662
663 ------------------
664 -- | Substitutes for the 'Id's within the 'WorkerInfo' given the new function 'Id'
665 substSpec :: Subst -> Id -> RuleInfo -> RuleInfo
666 substSpec subst new_id (RuleInfo rules rhs_fvs)
667 = seqRuleInfo new_spec `seq` new_spec
668 where
669 subst_ru_fn = const (idName new_id)
670 new_spec = RuleInfo (map (substRule subst subst_ru_fn) rules)
671 (substDVarSet subst rhs_fvs)
672
673 ------------------
674 substRulesForImportedIds :: Subst -> [CoreRule] -> [CoreRule]
675 substRulesForImportedIds subst rules
676 = map (substRule subst not_needed) rules
677 where
678 not_needed name = pprPanic "substRulesForImportedIds" (ppr name)
679
680 ------------------
681 substRule :: Subst -> (Name -> Name) -> CoreRule -> CoreRule
682
683 -- The subst_ru_fn argument is applied to substitute the ru_fn field
684 -- of the rule:
685 -- - Rules for *imported* Ids never change ru_fn
686 -- - Rules for *local* Ids are in the IdInfo for that Id,
687 -- and the ru_fn field is simply replaced by the new name
688 -- of the Id
689 substRule _ _ rule@(BuiltinRule {}) = rule
690 substRule subst subst_ru_fn rule@(Rule { ru_bndrs = bndrs, ru_args = args
691 , ru_fn = fn_name, ru_rhs = rhs
692 , ru_local = is_local })
693 = rule { ru_bndrs = bndrs'
694 , ru_fn = if is_local
695 then subst_ru_fn fn_name
696 else fn_name
697 , ru_args = map (substExpr doc subst') args
698 , ru_rhs = substExpr (text "foo") subst' rhs }
699 -- Do NOT optimise the RHS (previously we did simplOptExpr here)
700 -- See Note [Substitute lazily]
701 where
702 doc = text "subst-rule" <+> ppr fn_name
703 (subst', bndrs') = substBndrs subst bndrs
704
705 ------------------
706 substDVarSet :: Subst -> DVarSet -> DVarSet
707 substDVarSet subst fvs
708 = mkDVarSet $ fst $ foldr (subst_fv subst) ([], emptyVarSet) $ dVarSetElems fvs
709 where
710 subst_fv subst fv acc
711 | isId fv = expr_fvs (lookupIdSubst (text "substDVarSet") subst fv) isLocalVar emptyVarSet $! acc
712 | otherwise = tyCoFVsOfType (lookupTCvSubst subst fv) (const True) emptyVarSet $! acc
713
714 ------------------
715 substTickish :: Subst -> Tickish Id -> Tickish Id
716 substTickish subst (Breakpoint n ids)
717 = Breakpoint n (map do_one ids)
718 where
719 do_one = getIdFromTrivialExpr . lookupIdSubst (text "subst_tickish") subst
720 substTickish _subst other = other
721
722 {- Note [Substitute lazily]
723 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
724 The functions that substitute over IdInfo must be pretty lazy, because
725 they are knot-tied by substRecBndrs.
726
727 One case in point was Trac #10627 in which a rule for a function 'f'
728 referred to 'f' (at a different type) on the RHS. But instead of just
729 substituting in the rhs of the rule, we were calling simpleOptExpr, which
730 looked at the idInfo for 'f'; result <<loop>>.
731
732 In any case we don't need to optimise the RHS of rules, or unfoldings,
733 because the simplifier will do that.
734
735
736 Note [substTickish]
737 ~~~~~~~~~~~~~~~~~~~~~~
738 A Breakpoint contains a list of Ids. What happens if we ever want to
739 substitute an expression for one of these Ids?
740
741 First, we ensure that we only ever substitute trivial expressions for
742 these Ids, by marking them as NoOccInfo in the occurrence analyser.
743 Then, when substituting for the Id, we unwrap any type applications
744 and abstractions to get back to an Id, with getIdFromTrivialExpr.
745
746 Second, we have to ensure that we never try to substitute a literal
747 for an Id in a breakpoint. We ensure this by never storing an Id with
748 an unlifted type in a Breakpoint - see Coverage.mkTickish.
749 Breakpoints can't handle free variables with unlifted types anyway.
750 -}
751
752 {-
753 Note [Worker inlining]
754 ~~~~~~~~~~~~~~~~~~~~~~
755 A worker can get sustituted away entirely.
756 - it might be trivial
757 - it might simply be very small
758 We do not treat an InlWrapper as an 'occurrence' in the occurrence
759 analyser, so it's possible that the worker is not even in scope any more.
760
761 In all all these cases we simply drop the special case, returning to
762 InlVanilla. The WARN is just so I can see if it happens a lot.
763 -}
764