2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Utility functions on @Core@ syntax
11 Subst, TvSubstEnv, IdSubstEnv, InScopeSet,
13 -- ** Substituting into expressions and related types
14 deShadowBinds, substSpec, substRulesForImportedIds,
15 substTy, substExpr, substExprSC, substBind, substBindSC,
16 substUnfolding, substUnfoldingSC,
17 substUnfoldingSource, lookupIdSubst, lookupTvSubst, substIdOcc,
19 -- ** Operations on substitutions
20 emptySubst, mkEmptySubst, mkSubst, mkOpenSubst, substInScope, isEmptySubst,
21 extendIdSubst, extendIdSubstList, extendTvSubst, extendTvSubstList,
22 extendSubst, extendSubstList, zapSubstEnv,
23 extendInScope, extendInScopeList, extendInScopeIds,
26 -- ** Substituting and cloning binders
27 substBndr, substBndrs, substRecBndrs,
28 cloneIdBndr, cloneIdBndrs, cloneRecIdBndrs,
30 -- ** Simple expression optimiser
31 simpleOptPgm, simpleOptExpr
34 #include "HsVersions.h"
40 import OccurAnal( occurAnalyseExpr, occurAnalysePgm )
43 import Type ( Type, TvSubst(..), TvSubstEnv )
44 import Coercion ( isIdentityCoercion )
45 import OptCoercion ( optCoercion )
50 import Var ( Var, TyVar, setVarUnique )
56 import DynFlags ( DynFlags, DynFlag(..) )
57 import BasicTypes ( isAlwaysActive )
59 import PprCore () -- Instances
66 %************************************************************************
68 \subsection{Substitutions}
70 %************************************************************************
73 -- | A substitution environment, containing both 'Id' and 'TyVar' substitutions.
75 -- Some invariants apply to how you use the substitution:
77 -- 1. #in_scope_invariant# The in-scope set contains at least those 'Id's and 'TyVar's that will be in scope /after/
78 -- applying the substitution to a term. Precisely, the in-scope set must be a superset of the free vars of the
79 -- substitution range that might possibly clash with locally-bound variables in the thing being substituted in.
81 -- 2. #apply_once# You may apply the substitution only /once/
83 -- There are various ways of setting up the in-scope set such that the first of these invariants hold:
85 -- * Arrange that the in-scope set really is all the things in scope
87 -- * Arrange that it's the free vars of the range of the substitution
89 -- * Make it empty, if you know that all the free vars of the substitution are fresh, and hence can't possibly clash
91 = Subst InScopeSet -- Variables in in scope (both Ids and TyVars) /after/
92 -- applying the substitution
93 IdSubstEnv -- Substitution for Ids
94 TvSubstEnv -- Substitution for TyVars
96 -- INVARIANT 1: See #in_scope_invariant#
97 -- This is what lets us deal with name capture properly
98 -- It's a hard invariant to check...
100 -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with
103 -- INVARIANT 3: See Note [Extending the Subst]
106 Note [Extending the Subst]
107 ~~~~~~~~~~~~~~~~~~~~~~~~~~
108 For a core Subst, which binds Ids as well, we make a different choice for Ids
109 than we do for TyVars.
111 For TyVars, see Note [Extending the TvSubst] with Type.TvSubstEnv
113 For Ids, we have a different invariant
114 The IdSubstEnv is extended *only* when the Unique on an Id changes
115 Otherwise, we just extend the InScopeSet
119 * If the TvSubstEnv and IdSubstEnv are both empty, substExpr would be a
120 no-op, so substExprSC ("short cut") does nothing.
122 However, substExpr still goes ahead and substitutes. Reason: we may
123 want to replace existing Ids with new ones from the in-scope set, to
126 * In substIdBndr, we extend the IdSubstEnv only when the unique changes
128 * In lookupIdSubst, we *must* look up the Id in the in-scope set, because
129 it may contain non-trivial changes. Example:
130 (/\a. \x:a. ...x...) Int
131 We extend the TvSubstEnv with [a |-> Int]; but x's unique does not change
132 so we only extend the in-scope set. Then we must look up in the in-scope
133 set when we find the occurrence of x.
135 * The requirement to look up the Id in the in-scope set means that we
136 must NOT take no-op short cut when the IdSubst is empty.
137 We must still look up every Id in the in-scope set.
139 * (However, we don't need to do so for expressions found in the IdSubst
140 itself, whose range is assumed to be correct wrt the in-scope set.)
142 Why do we make a different choice for the IdSubstEnv than the TvSubstEnv?
144 * For Ids, we change the IdInfo all the time (e.g. deleting the
145 unfolding), and adding it back later, so using the TyVar convention
146 would entail extending the substitution almost all the time
148 * The simplifier wants to look up in the in-scope set anyway, in case it
149 can see a better unfolding from an enclosing case expression
151 * For TyVars, only coercion variables can possibly change, and they are
155 -- | An environment for substituting for 'Id's
156 type IdSubstEnv = IdEnv CoreExpr
158 ----------------------------
159 isEmptySubst :: Subst -> Bool
160 isEmptySubst (Subst _ id_env tv_env) = isEmptyVarEnv id_env && isEmptyVarEnv tv_env
163 emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv
165 mkEmptySubst :: InScopeSet -> Subst
166 mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv
168 mkSubst :: InScopeSet -> TvSubstEnv -> IdSubstEnv -> Subst
169 mkSubst in_scope tvs ids = Subst in_scope ids tvs
171 -- getTvSubst :: Subst -> TvSubst
172 -- getTvSubst (Subst in_scope _ tv_env) = TvSubst in_scope tv_env
174 -- getTvSubstEnv :: Subst -> TvSubstEnv
175 -- getTvSubstEnv (Subst _ _ tv_env) = tv_env
177 -- setTvSubstEnv :: Subst -> TvSubstEnv -> Subst
178 -- setTvSubstEnv (Subst in_scope ids _) tvs = Subst in_scope ids tvs
180 -- | Find the in-scope set: see "CoreSubst#in_scope_invariant"
181 substInScope :: Subst -> InScopeSet
182 substInScope (Subst in_scope _ _) = in_scope
184 -- | Remove all substitutions for 'Id's and 'Var's that might have been built up
185 -- while preserving the in-scope set
186 zapSubstEnv :: Subst -> Subst
187 zapSubstEnv (Subst in_scope _ _) = Subst in_scope emptyVarEnv emptyVarEnv
189 -- | Add a substitution for an 'Id' to the 'Subst': you must ensure that the in-scope set is
190 -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this
191 extendIdSubst :: Subst -> Id -> CoreExpr -> Subst
192 -- ToDo: add an ASSERT that fvs(subst-result) is already in the in-scope set
193 extendIdSubst (Subst in_scope ids tvs) v r = Subst in_scope (extendVarEnv ids v r) tvs
195 -- | Adds multiple 'Id' substitutions to the 'Subst': see also 'extendIdSubst'
196 extendIdSubstList :: Subst -> [(Id, CoreExpr)] -> Subst
197 extendIdSubstList (Subst in_scope ids tvs) prs = Subst in_scope (extendVarEnvList ids prs) tvs
199 -- | Add a substitution for a 'TyVar' to the 'Subst': you must ensure that the in-scope set is
200 -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this
201 extendTvSubst :: Subst -> TyVar -> Type -> Subst
202 extendTvSubst (Subst in_scope ids tvs) v r = Subst in_scope ids (extendVarEnv tvs v r)
204 -- | Adds multiple 'TyVar' substitutions to the 'Subst': see also 'extendTvSubst'
205 extendTvSubstList :: Subst -> [(TyVar,Type)] -> Subst
206 extendTvSubstList (Subst in_scope ids tvs) prs = Subst in_scope ids (extendVarEnvList tvs prs)
208 -- | Add a substitution for a 'TyVar' or 'Id' as appropriate to the 'Var' being added. See also
209 -- 'extendIdSubst' and 'extendTvSubst'
210 extendSubst :: Subst -> Var -> CoreArg -> Subst
211 extendSubst (Subst in_scope ids tvs) tv (Type ty)
212 = ASSERT( isTyCoVar tv ) Subst in_scope ids (extendVarEnv tvs tv ty)
213 extendSubst (Subst in_scope ids tvs) id expr
214 = ASSERT( isId id ) Subst in_scope (extendVarEnv ids id expr) tvs
216 -- | Add a substitution for a 'TyVar' or 'Id' as appropriate to all the 'Var's being added. See also 'extendSubst'
217 extendSubstList :: Subst -> [(Var,CoreArg)] -> Subst
218 extendSubstList subst [] = subst
219 extendSubstList subst ((var,rhs):prs) = extendSubstList (extendSubst subst var rhs) prs
221 -- | Find the substitution for an 'Id' in the 'Subst'
222 lookupIdSubst :: SDoc -> Subst -> Id -> CoreExpr
223 lookupIdSubst doc (Subst in_scope ids _) v
224 | not (isLocalId v) = Var v
225 | Just e <- lookupVarEnv ids v = e
226 | Just v' <- lookupInScope in_scope v = Var v'
227 -- Vital! See Note [Extending the Subst]
228 | otherwise = WARN( True, ptext (sLit "CoreSubst.lookupIdSubst") <+> ppr v $$ ppr in_scope $$ doc)
231 -- | Find the substitution for a 'TyVar' in the 'Subst'
232 lookupTvSubst :: Subst -> TyVar -> Type
233 lookupTvSubst (Subst _ _ tvs) v = lookupVarEnv tvs v `orElse` Type.mkTyVarTy v
235 -- | Simultaneously substitute for a bunch of variables
236 -- No left-right shadowing
237 -- ie the substitution for (\x \y. e) a1 a2
238 -- so neither x nor y scope over a1 a2
239 mkOpenSubst :: InScopeSet -> [(Var,CoreArg)] -> Subst
240 mkOpenSubst in_scope pairs = Subst in_scope
241 (mkVarEnv [(id,e) | (id, e) <- pairs, isId id])
242 (mkVarEnv [(tv,ty) | (tv, Type ty) <- pairs])
244 ------------------------------
245 isInScope :: Var -> Subst -> Bool
246 isInScope v (Subst in_scope _ _) = v `elemInScopeSet` in_scope
248 -- | Add the 'Var' to the in-scope set: as a side effect, removes any existing substitutions for it
249 extendInScope :: Subst -> Var -> Subst
250 extendInScope (Subst in_scope ids tvs) v
251 = Subst (in_scope `extendInScopeSet` v)
252 (ids `delVarEnv` v) (tvs `delVarEnv` v)
254 -- | Add the 'Var's to the in-scope set: see also 'extendInScope'
255 extendInScopeList :: Subst -> [Var] -> Subst
256 extendInScopeList (Subst in_scope ids tvs) vs
257 = Subst (in_scope `extendInScopeSetList` vs)
258 (ids `delVarEnvList` vs) (tvs `delVarEnvList` vs)
260 -- | Optimized version of 'extendInScopeList' that can be used if you are certain
261 -- all the things being added are 'Id's and hence none are 'TyVar's
262 extendInScopeIds :: Subst -> [Id] -> Subst
263 extendInScopeIds (Subst in_scope ids tvs) vs
264 = Subst (in_scope `extendInScopeSetList` vs)
265 (ids `delVarEnvList` vs) tvs
268 Pretty printing, for debugging only
271 instance Outputable Subst where
272 ppr (Subst in_scope ids tvs)
273 = ptext (sLit "<InScope =") <+> braces (fsep (map ppr (varEnvElts (getInScopeVars in_scope))))
274 $$ ptext (sLit " IdSubst =") <+> ppr ids
275 $$ ptext (sLit " TvSubst =") <+> ppr tvs
280 %************************************************************************
282 Substituting expressions
284 %************************************************************************
287 -- | Apply a substititon to an entire 'CoreExpr'. Rememeber, you may only
288 -- apply the substitution /once/: see "CoreSubst#apply_once"
290 -- Do *not* attempt to short-cut in the case of an empty substitution!
291 -- See Note [Extending the Subst]
292 substExprSC :: SDoc -> Subst -> CoreExpr -> CoreExpr
293 substExprSC _doc subst orig_expr
294 | isEmptySubst subst = orig_expr
295 | otherwise = -- pprTrace "enter subst-expr" (doc $$ ppr orig_expr) $
296 subst_expr subst orig_expr
298 substExpr :: SDoc -> Subst -> CoreExpr -> CoreExpr
299 substExpr _doc subst orig_expr = subst_expr subst orig_expr
301 subst_expr :: Subst -> CoreExpr -> CoreExpr
302 subst_expr subst expr
305 go (Var v) = lookupIdSubst (text "subst_expr") subst v
306 go (Type ty) = Type (substTy subst ty)
307 go (Lit lit) = Lit lit
308 go (App fun arg) = App (go fun) (go arg)
309 go (Note note e) = Note (go_note note) (go e)
311 | isIdentityCoercion co' = go e
312 | otherwise = Cast (go e) co'
314 co' = optCoercion (getTvSubst subst) co
315 -- Optimise coercions as we go; this is good, for example
316 -- in the RHS of rules, which are only substituted in
318 go (Lam bndr body) = Lam bndr' (subst_expr subst' body)
320 (subst', bndr') = substBndr subst bndr
322 go (Let bind body) = Let bind' (subst_expr subst' body)
324 (subst', bind') = substBind subst bind
326 go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts)
328 (subst', bndr') = substBndr subst bndr
330 go_alt subst (con, bndrs, rhs) = (con, bndrs', subst_expr subst' rhs)
332 (subst', bndrs') = substBndrs subst bndrs
336 -- | Apply a substititon to an entire 'CoreBind', additionally returning an updated 'Subst'
337 -- that should be used by subsequent substitutons.
338 substBind, substBindSC :: Subst -> CoreBind -> (Subst, CoreBind)
340 substBindSC subst bind -- Short-cut if the substitution is empty
341 | not (isEmptySubst subst)
342 = substBind subst bind
345 NonRec bndr rhs -> (subst', NonRec bndr' rhs)
347 (subst', bndr') = substBndr subst bndr
348 Rec pairs -> (subst', Rec (bndrs' `zip` rhss'))
350 (bndrs, rhss) = unzip pairs
351 (subst', bndrs') = substRecBndrs subst bndrs
352 rhss' | isEmptySubst subst' = rhss
353 | otherwise = map (subst_expr subst') rhss
355 substBind subst (NonRec bndr rhs) = (subst', NonRec bndr' (subst_expr subst rhs))
357 (subst', bndr') = substBndr subst bndr
359 substBind subst (Rec pairs) = (subst', Rec (bndrs' `zip` rhss'))
361 (bndrs, rhss) = unzip pairs
362 (subst', bndrs') = substRecBndrs subst bndrs
363 rhss' = map (subst_expr subst') rhss
367 -- | De-shadowing the program is sometimes a useful pre-pass. It can be done simply
368 -- by running over the bindings with an empty substitution, becuase substitution
369 -- returns a result that has no-shadowing guaranteed.
371 -- (Actually, within a single /type/ there might still be shadowing, because
372 -- 'substTy' is a no-op for the empty substitution, but that's probably OK.)
374 -- [Aug 09] This function is not used in GHC at the moment, but seems so
375 -- short and simple that I'm going to leave it here
376 deShadowBinds :: [CoreBind] -> [CoreBind]
377 deShadowBinds binds = snd (mapAccumL substBind emptySubst binds)
381 %************************************************************************
385 %************************************************************************
387 Remember that substBndr and friends are used when doing expression
388 substitution only. Their only business is substitution, so they
389 preserve all IdInfo (suitably substituted). For example, we *want* to
390 preserve occ info in rules.
393 -- | Substitutes a 'Var' for another one according to the 'Subst' given, returning
394 -- the result and an updated 'Subst' that should be used by subsequent substitutons.
395 -- 'IdInfo' is preserved by this process, although it is substituted into appropriately.
396 substBndr :: Subst -> Var -> (Subst, Var)
398 | isTyCoVar bndr = substTyVarBndr subst bndr
399 | otherwise = substIdBndr (text "var-bndr") subst subst bndr
401 -- | Applies 'substBndr' to a number of 'Var's, accumulating a new 'Subst' left-to-right
402 substBndrs :: Subst -> [Var] -> (Subst, [Var])
403 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
405 -- | Substitute in a mutually recursive group of 'Id's
406 substRecBndrs :: Subst -> [Id] -> (Subst, [Id])
407 substRecBndrs subst bndrs
408 = (new_subst, new_bndrs)
409 where -- Here's the reason we need to pass rec_subst to subst_id
410 (new_subst, new_bndrs) = mapAccumL (substIdBndr (text "rec-bndr") new_subst) subst bndrs
416 -> Subst -- ^ Substitution to use for the IdInfo
417 -> Subst -> Id -- ^ Substitition and Id to transform
418 -> (Subst, Id) -- ^ Transformed pair
419 -- NB: unfolding may be zapped
421 substIdBndr _doc rec_subst subst@(Subst in_scope env tvs) old_id
422 = -- pprTrace "substIdBndr" (doc $$ ppr old_id $$ ppr in_scope) $
423 (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
425 id1 = uniqAway in_scope old_id -- id1 is cloned if necessary
426 id2 | no_type_change = id1
427 | otherwise = setIdType id1 (substTy subst old_ty)
429 old_ty = idType old_id
430 no_type_change = isEmptyVarEnv tvs ||
431 isEmptyVarSet (Type.tyVarsOfType old_ty)
433 -- new_id has the right IdInfo
434 -- The lazy-set is because we're in a loop here, with
435 -- rec_subst, when dealing with a mutually-recursive group
436 new_id = maybeModifyIdInfo mb_new_info id2
437 mb_new_info = substIdInfo rec_subst id2 (idInfo id2)
438 -- NB: unfolding info may be zapped
440 -- Extend the substitution if the unique has changed
441 -- See the notes with substTyVarBndr for the delVarEnv
442 new_env | no_change = delVarEnv env old_id
443 | otherwise = extendVarEnv env old_id (Var new_id)
445 no_change = id1 == old_id
446 -- See Note [Extending the Subst]
447 -- it's /not/ necessary to check mb_new_info and no_type_change
450 Now a variant that unconditionally allocates a new unique.
451 It also unconditionally zaps the OccInfo.
454 -- | Very similar to 'substBndr', but it always allocates a new 'Unique' for
455 -- each variable in its output. It substitutes the IdInfo though.
456 cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id)
457 cloneIdBndr subst us old_id
458 = clone_id subst subst (old_id, uniqFromSupply us)
460 -- | Applies 'cloneIdBndr' to a number of 'Id's, accumulating a final
461 -- substitution from left to right
462 cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
463 cloneIdBndrs subst us ids
464 = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us)
466 -- | Clone a mutually recursive group of 'Id's
467 cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
468 cloneRecIdBndrs subst us ids
471 (subst', ids') = mapAccumL (clone_id subst') subst
472 (ids `zip` uniqsFromSupply us)
474 -- Just like substIdBndr, except that it always makes a new unique
475 -- It is given the unique to use
476 clone_id :: Subst -- Substitution for the IdInfo
477 -> Subst -> (Id, Unique) -- Substitition and Id to transform
478 -> (Subst, Id) -- Transformed pair
480 clone_id rec_subst subst@(Subst in_scope env tvs) (old_id, uniq)
481 = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
483 id1 = setVarUnique old_id uniq
484 id2 = substIdType subst id1
485 new_id = maybeModifyIdInfo (substIdInfo rec_subst id2 (idInfo old_id)) id2
486 new_env = extendVarEnv env old_id (Var new_id)
490 %************************************************************************
494 %************************************************************************
496 For types we just call the corresponding function in Type, but we have
497 to repackage the substitution, from a Subst to a TvSubst
500 substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar)
501 substTyVarBndr (Subst in_scope id_env tv_env) tv
502 = case Type.substTyVarBndr (TvSubst in_scope tv_env) tv of
503 (TvSubst in_scope' tv_env', tv')
504 -> (Subst in_scope' id_env tv_env', tv')
506 -- | See 'Type.substTy'
507 substTy :: Subst -> Type -> Type
508 substTy subst ty = Type.substTy (getTvSubst subst) ty
510 getTvSubst :: Subst -> TvSubst
511 getTvSubst (Subst in_scope _id_env tv_env) = TvSubst in_scope tv_env
515 %************************************************************************
517 \section{IdInfo substitution}
519 %************************************************************************
522 substIdType :: Subst -> Id -> Id
523 substIdType subst@(Subst _ _ tv_env) id
524 | isEmptyVarEnv tv_env || isEmptyVarSet (Type.tyVarsOfType old_ty) = id
525 | otherwise = setIdType id (substTy subst old_ty)
526 -- The tyVarsOfType is cheaper than it looks
527 -- because we cache the free tyvars of the type
528 -- in a Note in the id's type itself
533 -- | Substitute into some 'IdInfo' with regard to the supplied new 'Id'.
534 substIdInfo :: Subst -> Id -> IdInfo -> Maybe IdInfo
535 substIdInfo subst new_id info
536 | nothing_to_do = Nothing
537 | otherwise = Just (info `setSpecInfo` substSpec subst new_id old_rules
538 `setUnfoldingInfo` substUnfolding subst old_unf)
540 old_rules = specInfo info
541 old_unf = unfoldingInfo info
542 nothing_to_do = isEmptySpecInfo old_rules && isClosedUnfolding old_unf
546 -- | Substitutes for the 'Id's within an unfolding
547 substUnfolding, substUnfoldingSC :: Subst -> Unfolding -> Unfolding
548 -- Seq'ing on the returned Unfolding is enough to cause
549 -- all the substitutions to happen completely
551 substUnfoldingSC subst unf -- Short-cut version
552 | isEmptySubst subst = unf
553 | otherwise = substUnfolding subst unf
555 substUnfolding subst (DFunUnfolding ar con args)
556 = DFunUnfolding ar con (map (substExpr (text "dfun-unf") subst) args)
558 substUnfolding subst unf@(CoreUnfolding { uf_tmpl = tmpl, uf_src = src })
559 -- Retain an InlineRule!
560 | not (isStableSource src) -- Zap an unstable unfolding, to save substitution work
562 | otherwise -- But keep a stable one!
563 = seqExpr new_tmpl `seq`
565 unf { uf_tmpl = new_tmpl, uf_src = new_src }
567 new_tmpl = substExpr (text "subst-unf") subst tmpl
568 new_src = substUnfoldingSource subst src
570 substUnfolding _ unf = unf -- NoUnfolding, OtherCon
573 substUnfoldingSource :: Subst -> UnfoldingSource -> UnfoldingSource
574 substUnfoldingSource (Subst in_scope ids _) (InlineWrapper wkr)
575 | Just wkr_expr <- lookupVarEnv ids wkr
577 Var w1 -> InlineWrapper w1
578 _other -> -- WARN( True, text "Interesting! CoreSubst.substWorker1:" <+> ppr wkr
579 -- <+> ifPprDebug (equals <+> ppr wkr_expr) )
580 -- Note [Worker inlining]
581 InlineStable -- It's not a wrapper any more, but still inline it!
583 | Just w1 <- lookupInScope in_scope wkr = InlineWrapper w1
584 | otherwise = -- WARN( True, text "Interesting! CoreSubst.substWorker2:" <+> ppr wkr )
585 -- This can legitimately happen. The worker has been inlined and
586 -- dropped as dead code, because we don't treat the UnfoldingSource
587 -- as an "occurrence".
588 -- Note [Worker inlining]
591 substUnfoldingSource _ src = src
594 substIdOcc :: Subst -> Id -> Id
595 -- These Ids should not be substituted to non-Ids
596 substIdOcc subst v = case lookupIdSubst (text "substIdOcc") subst v of
598 other -> pprPanic "substIdOcc" (vcat [ppr v <+> ppr other, ppr subst])
601 -- | Substitutes for the 'Id's within the 'WorkerInfo' given the new function 'Id'
602 substSpec :: Subst -> Id -> SpecInfo -> SpecInfo
603 substSpec subst new_id (SpecInfo rules rhs_fvs)
604 = seqSpecInfo new_spec `seq` new_spec
606 subst_ru_fn = const (idName new_id)
607 new_spec = SpecInfo (map (substRule subst subst_ru_fn) rules)
608 (substVarSet subst rhs_fvs)
611 substRulesForImportedIds :: Subst -> [CoreRule] -> [CoreRule]
612 substRulesForImportedIds subst rules
613 = map (substRule subst not_needed) rules
615 not_needed name = pprPanic "substRulesForImportedIds" (ppr name)
618 substRule :: Subst -> (Name -> Name) -> CoreRule -> CoreRule
620 -- The subst_ru_fn argument is applied to substitute the ru_fn field
622 -- - Rules for *imported* Ids never change ru_fn
623 -- - Rules for *local* Ids are in the IdInfo for that Id,
624 -- and the ru_fn field is simply replaced by the new name
627 substRule _ _ rule@(BuiltinRule {}) = rule
628 substRule subst subst_ru_fn rule@(Rule { ru_bndrs = bndrs, ru_args = args
629 , ru_fn = fn_name, ru_rhs = rhs
630 , ru_local = is_local })
631 = rule { ru_bndrs = bndrs',
633 then subst_ru_fn fn_name
635 ru_args = map (substExpr (text "subst-rule" <+> ppr fn_name) subst') args,
636 ru_rhs = substExpr (text "subst-rule" <+> ppr fn_name) subst' rhs }
638 (subst', bndrs') = substBndrs subst bndrs
641 substVarSet :: Subst -> VarSet -> VarSet
642 substVarSet subst fvs
643 = foldVarSet (unionVarSet . subst_fv subst) emptyVarSet fvs
646 | isId fv = exprFreeVars (lookupIdSubst (text "substVarSet") subst fv)
647 | otherwise = Type.tyVarsOfType (lookupTvSubst subst fv)
650 Note [Worker inlining]
651 ~~~~~~~~~~~~~~~~~~~~~~
652 A worker can get sustituted away entirely.
653 - it might be trivial
654 - it might simply be very small
655 We do not treat an InlWrapper as an 'occurrence' in the occurence
656 analyser, so it's possible that the worker is not even in scope any more.
658 In all all these cases we simply drop the special case, returning to
659 InlVanilla. The WARN is just so I can see if it happens a lot.
662 %************************************************************************
664 The Very Simple Optimiser
666 %************************************************************************
669 simpleOptExpr :: CoreExpr -> CoreExpr
670 -- Do simple optimisation on an expression
671 -- The optimisation is very straightforward: just
672 -- inline non-recursive bindings that are used only once,
673 -- or where the RHS is trivial
675 -- The result is NOT guaranteed occurence-analysed, becuase
676 -- in (let x = y in ....) we substitute for x; so y's occ-info
677 -- may change radically
680 = -- pprTrace "simpleOptExpr" (ppr init_subst $$ ppr expr)
681 simple_opt_expr init_subst (occurAnalyseExpr expr)
683 init_subst = mkEmptySubst (mkInScopeSet (exprFreeVars expr))
684 -- It's potentially important to make a proper in-scope set
685 -- Consider let x = ..y.. in \y. ...x...
686 -- Then we should remember to clone y before substituting
687 -- for x. It's very unlikely to occur, because we probably
688 -- won't *be* substituting for x if it occurs inside a
691 -- It's a bit painful to call exprFreeVars, because it makes
692 -- three passes instead of two (occ-anal, and go)
694 ----------------------
695 simpleOptPgm :: DynFlags -> [CoreBind] -> [CoreRule] -> IO ([CoreBind], [CoreRule])
696 simpleOptPgm dflags binds rules
697 = do { dumpIfSet_dyn dflags Opt_D_dump_occur_anal "Occurrence analysis"
698 (pprCoreBindings occ_anald_binds);
700 ; return (reverse binds', substRulesForImportedIds subst' rules) }
702 occ_anald_binds = occurAnalysePgm binds rules
703 (subst', binds') = foldl do_one (emptySubst, []) occ_anald_binds
705 do_one (subst, binds') bind
706 = case simple_opt_bind subst bind of
707 (subst', Nothing) -> (subst', binds')
708 (subst', Just bind') -> (subst', bind':binds')
710 ----------------------
715 type InExpr = CoreExpr
716 type OutExpr = CoreExpr
718 -- In these functions the substitution maps InVar -> OutExpr
720 ----------------------
721 simple_opt_expr :: Subst -> InExpr -> OutExpr
722 simple_opt_expr subst expr
725 go (Var v) = lookupIdSubst (text "simpleOptExpr") subst v
726 go (App e1 e2) = simple_app subst e1 [go e2]
727 go (Type ty) = Type (substTy subst ty)
728 go (Lit lit) = Lit lit
729 go (Note note e) = Note note (go e)
730 go (Cast e co) | isIdentityCoercion co' = go e
731 | otherwise = Cast (go e) co'
733 co' = substTy subst co
735 go (Let bind body) = case simple_opt_bind subst bind of
736 (subst', Nothing) -> simple_opt_expr subst' body
737 (subst', Just bind) -> Let bind (simple_opt_expr subst' body)
739 go lam@(Lam {}) = go_lam [] subst lam
740 go (Case e b ty as) = Case (go e) b' (substTy subst ty)
741 (map (go_alt subst') as)
743 (subst', b') = subst_opt_bndr subst b
745 ----------------------
746 go_alt subst (con, bndrs, rhs)
747 = (con, bndrs', simple_opt_expr subst' rhs)
749 (subst', bndrs') = subst_opt_bndrs subst bndrs
751 ----------------------
752 -- go_lam tries eta reduction
753 go_lam bs' subst (Lam b e)
754 = go_lam (b':bs') subst' e
756 (subst', b') = subst_opt_bndr subst b
758 | Just etad_e <- tryEtaReduce bs e' = etad_e
759 | otherwise = mkLams bs e'
762 e' = simple_opt_expr subst e
764 ----------------------
765 -- simple_app collects arguments for beta reduction
766 simple_app :: Subst -> InExpr -> [OutExpr] -> CoreExpr
767 simple_app subst (App e1 e2) as
768 = simple_app subst e1 (simple_opt_expr subst e2 : as)
769 simple_app subst (Lam b e) (a:as)
770 = case maybe_substitute subst b a of
771 Just ext_subst -> simple_app ext_subst e as
772 Nothing -> Let (NonRec b2 a) (simple_app subst' e as)
774 (subst', b') = subst_opt_bndr subst b
775 b2 = add_info subst' b b'
776 simple_app subst e as
777 = foldl App (simple_opt_expr subst e) as
779 ----------------------
780 simple_opt_bind :: Subst -> CoreBind -> (Subst, Maybe CoreBind)
781 simple_opt_bind subst (Rec prs)
782 = (subst'', Just (Rec (reverse rev_prs')))
784 (subst', bndrs') = subst_opt_bndrs subst (map fst prs)
785 (subst'', rev_prs') = foldl do_pr (subst', []) (prs `zip` bndrs')
786 do_pr (subst, prs) ((b,r), b')
787 = case maybe_substitute subst b r2 of
788 Just subst' -> (subst', prs)
789 Nothing -> (subst, (b2,r2):prs)
791 b2 = add_info subst b b'
792 r2 = simple_opt_expr subst r
794 simple_opt_bind subst (NonRec b r)
795 = case maybe_substitute subst b r' of
796 Just ext_subst -> (ext_subst, Nothing)
797 Nothing -> (subst', Just (NonRec b2 r'))
799 r' = simple_opt_expr subst r
800 (subst', b') = subst_opt_bndr subst b
801 b2 = add_info subst' b b'
803 ----------------------
804 maybe_substitute :: Subst -> InVar -> OutExpr -> Maybe Subst
805 -- (maybe_substitute subst in_var out_rhs)
806 -- either extends subst with (in_var -> out_rhs)
807 -- or returns Nothing
808 maybe_substitute subst b r
809 | Type ty <- r -- let a::* = TYPE ty in <body>
810 = ASSERT( isTyCoVar b )
811 Just (extendTvSubst subst b ty)
813 | isId b -- let x = e in <body>
814 , safe_to_inline (idOccInfo b)
815 , isAlwaysActive (idInlineActivation b) -- Note [Inline prag in simplOpt]
816 , not (isStableUnfolding (idUnfolding b))
817 , not (isExportedId b)
818 = Just (extendIdSubst subst b r)
823 -- Unconditionally safe to inline
824 safe_to_inline :: OccInfo -> Bool
825 safe_to_inline (IAmALoopBreaker {}) = False
826 safe_to_inline IAmDead = True
827 safe_to_inline (OneOcc in_lam one_br _) = (not in_lam && one_br) || exprIsTrivial r
828 safe_to_inline NoOccInfo = exprIsTrivial r
830 ----------------------
831 subst_opt_bndr :: Subst -> InVar -> (Subst, OutVar)
832 subst_opt_bndr subst bndr
833 | isTyCoVar bndr = substTyVarBndr subst bndr
834 | otherwise = subst_opt_id_bndr subst bndr
836 subst_opt_id_bndr :: Subst -> InId -> (Subst, OutId)
837 -- Nuke all fragile IdInfo, unfolding, and RULES;
838 -- it gets added back later by add_info
839 -- Rather like SimplEnv.substIdBndr
841 -- It's important to zap fragile OccInfo (which CoreSubst.SubstIdBndr
842 -- carefully does not do) because simplOptExpr invalidates it
844 subst_opt_id_bndr subst@(Subst in_scope id_subst tv_subst) old_id
845 = (Subst new_in_scope new_id_subst tv_subst, new_id)
847 id1 = uniqAway in_scope old_id
848 id2 = setIdType id1 (substTy subst (idType old_id))
849 new_id = zapFragileIdInfo id2 -- Zaps rules, worker-info, unfolding
850 -- and fragile OccInfo
851 new_in_scope = in_scope `extendInScopeSet` new_id
853 -- Extend the substitution if the unique has changed,
854 -- or there's some useful occurrence information
855 -- See the notes with substTyVarBndr for the delSubstEnv
856 new_id_subst | new_id /= old_id
857 = extendVarEnv id_subst old_id (Var new_id)
859 = delVarEnv id_subst old_id
861 ----------------------
862 subst_opt_bndrs :: Subst -> [InVar] -> (Subst, [OutVar])
863 subst_opt_bndrs subst bndrs
864 = mapAccumL subst_opt_bndr subst bndrs
866 ----------------------
867 add_info :: Subst -> InVar -> OutVar -> OutVar
868 add_info subst old_bndr new_bndr
869 | isTyCoVar old_bndr = new_bndr
870 | otherwise = maybeModifyIdInfo mb_new_info new_bndr
872 mb_new_info = substIdInfo subst new_bndr (idInfo old_bndr)
875 Note [Inline prag in simplOpt]
876 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
877 If there's an INLINE/NOINLINE pragma that restricts the phase in
878 which the binder can be inlined, we don't inline here; after all,
879 we don't know what phase we're in. Here's an example
881 foo :: Int -> Int -> Int
885 {-# INLINE [1] inner #-}
891 When inlining 'foo' in 'bar' we want the let-binding for 'inner'
892 to remain visible until Phase 1