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