Substitution should just substitute, not optimise
[ghc-hetmet.git] / compiler / coreSyn / CoreSubst.lhs
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 \begin{code}
9 module CoreSubst (
10         -- * Main data types
11         Subst, TvSubstEnv, IdSubstEnv, InScopeSet,
12
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,
18
19         -- ** Operations on substitutions
20         emptySubst, mkEmptySubst, mkSubst, mkOpenSubst, substInScope, isEmptySubst, 
21         extendIdSubst, extendIdSubstList, extendTvSubst, extendTvSubstList,
22         extendSubst, extendSubstList, zapSubstEnv,
23         extendInScope, extendInScopeList, extendInScopeIds, 
24         isInScope,
25
26         -- ** Substituting and cloning binders
27         substBndr, substBndrs, substRecBndrs,
28         cloneIdBndr, cloneIdBndrs, cloneRecIdBndrs,
29
30         -- ** Simple expression optimiser
31         simpleOptPgm, simpleOptExpr, simpleOptExprWith
32     ) where
33
34 #include "HsVersions.h"
35
36 import CoreSyn
37 import CoreFVs
38 import CoreUtils
39 import PprCore
40 import OccurAnal( occurAnalyseExpr, occurAnalysePgm )
41
42 import qualified Type
43 import Type     ( Type, TvSubst(..), TvSubstEnv )
44 import Coercion    ( isIdentityCoercion )
45 import OptCoercion ( optCoercion )
46 import VarSet
47 import VarEnv
48 import Id
49 import Name     ( Name )
50 import Var      ( Var, TyVar, setVarUnique )
51 import IdInfo
52 import Unique
53 import UniqSupply
54 import Maybes
55 import ErrUtils
56 import DynFlags   ( DynFlags, DynFlag(..) )
57 import BasicTypes ( isAlwaysActive )
58 import Outputable
59 import PprCore          ()              -- Instances
60 import FastString
61
62 import Data.List
63 \end{code}
64
65
66 %************************************************************************
67 %*                                                                      *
68 \subsection{Substitutions}
69 %*                                                                      *
70 %************************************************************************
71
72 \begin{code}
73 -- | A substitution environment, containing both 'Id' and 'TyVar' substitutions.
74 --
75 -- Some invariants apply to how you use the substitution:
76 --
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.
80 --
81 -- 2. #apply_once# You may apply the substitution only /once/
82 --
83 -- There are various ways of setting up the in-scope set such that the first of these invariants hold:
84 --
85 -- * Arrange that the in-scope set really is all the things in scope
86 --
87 -- * Arrange that it's the free vars of the range of the substitution
88 --
89 -- * Make it empty, if you know that all the free vars of the substitution are fresh, and hence can't possibly clash
90 data Subst 
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
95
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...
99         --
100         -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with
101         --              Types.TvSubstEnv
102         --
103         -- INVARIANT 3: See Note [Extending the Subst]
104 \end{code}
105
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.  
110
111 For TyVars, see Note [Extending the TvSubst] with Type.TvSubstEnv
112
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
116
117 In consequence:
118
119 * If the TvSubstEnv and IdSubstEnv are both empty, substExpr would be a
120   no-op, so substExprSC ("short cut") does nothing.
121
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
124   avoid space leaks.
125
126 * In substIdBndr, we extend the IdSubstEnv only when the unique changes
127
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.
134
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.
138
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.)
141
142 Why do we make a different choice for the IdSubstEnv than the TvSubstEnv?
143
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
147
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
150
151 * For TyVars, only coercion variables can possibly change, and they are 
152   easy to spot
153
154 \begin{code}
155 -- | An environment for substituting for 'Id's
156 type IdSubstEnv = IdEnv CoreExpr
157
158 ----------------------------
159 isEmptySubst :: Subst -> Bool
160 isEmptySubst (Subst _ id_env tv_env) = isEmptyVarEnv id_env && isEmptyVarEnv tv_env
161
162 emptySubst :: Subst
163 emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv
164
165 mkEmptySubst :: InScopeSet -> Subst
166 mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv
167
168 mkSubst :: InScopeSet -> TvSubstEnv -> IdSubstEnv -> Subst
169 mkSubst in_scope tvs ids = Subst in_scope ids tvs
170
171 -- getTvSubst :: Subst -> TvSubst
172 -- getTvSubst (Subst in_scope _ tv_env) = TvSubst in_scope tv_env
173
174 -- getTvSubstEnv :: Subst -> TvSubstEnv
175 -- getTvSubstEnv (Subst _ _ tv_env) = tv_env
176 -- 
177 -- setTvSubstEnv :: Subst -> TvSubstEnv -> Subst
178 -- setTvSubstEnv (Subst in_scope ids _) tvs = Subst in_scope ids tvs
179
180 -- | Find the in-scope set: see "CoreSubst#in_scope_invariant"
181 substInScope :: Subst -> InScopeSet
182 substInScope (Subst in_scope _ _) = in_scope
183
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
188
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
194
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
198
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) 
203
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)
207
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
215
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
220
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) 
229                 Var v
230
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
234
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])
243
244 ------------------------------
245 isInScope :: Var -> Subst -> Bool
246 isInScope v (Subst in_scope _ _) = v `elemInScopeSet` in_scope
247
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)
253
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)
259
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
266 \end{code}
267
268 Pretty printing, for debugging only
269
270 \begin{code}
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
276          <> char '>'
277 \end{code}
278
279
280 %************************************************************************
281 %*                                                                      *
282         Substituting expressions
283 %*                                                                      *
284 %************************************************************************
285
286 \begin{code}
287 -- | Apply a substititon to an entire 'CoreExpr'. Rememeber, you may only 
288 -- apply the substitution /once/: see "CoreSubst#apply_once"
289 --
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
297
298 substExpr :: SDoc -> Subst -> CoreExpr -> CoreExpr
299 substExpr _doc subst orig_expr = subst_expr subst orig_expr
300
301 subst_expr :: Subst -> CoreExpr -> CoreExpr
302 subst_expr subst expr
303   = go expr
304   where
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)
310     go (Cast e co)     = Cast (go e) (optCoercion (getTvSubst subst) co)
311        -- Do not optimise even identity coercions
312        -- Reason: substitution applies to the LHS of RULES, and
313        --         if you "optimise" an identity coercion, you may
314        --         lose a binder. We optimise the LHS of rules at
315        --         construction time
316
317     go (Lam bndr body) = Lam bndr' (subst_expr subst' body)
318                        where
319                          (subst', bndr') = substBndr subst bndr
320
321     go (Let bind body) = Let bind' (subst_expr subst' body)
322                        where
323                          (subst', bind') = substBind subst bind
324
325     go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts)
326                                  where
327                                  (subst', bndr') = substBndr subst bndr
328
329     go_alt subst (con, bndrs, rhs) = (con, bndrs', subst_expr subst' rhs)
330                                  where
331                                    (subst', bndrs') = substBndrs subst bndrs
332
333     go_note note             = note
334
335 -- | Apply a substititon to an entire 'CoreBind', additionally returning an updated 'Subst'
336 -- that should be used by subsequent substitutons.
337 substBind, substBindSC :: Subst -> CoreBind -> (Subst, CoreBind)
338
339 substBindSC subst bind    -- Short-cut if the substitution is empty
340   | not (isEmptySubst subst)
341   = substBind subst bind
342   | otherwise
343   = case bind of
344        NonRec bndr rhs -> (subst', NonRec bndr' rhs)
345           where
346             (subst', bndr') = substBndr subst bndr
347        Rec pairs -> (subst', Rec (bndrs' `zip` rhss'))
348           where
349             (bndrs, rhss)    = unzip pairs
350             (subst', bndrs') = substRecBndrs subst bndrs
351             rhss' | isEmptySubst subst' = rhss
352                   | otherwise           = map (subst_expr subst') rhss
353
354 substBind subst (NonRec bndr rhs) = (subst', NonRec bndr' (subst_expr subst rhs))
355                                   where
356                                     (subst', bndr') = substBndr subst bndr
357
358 substBind subst (Rec pairs) = (subst', Rec (bndrs' `zip` rhss'))
359                             where
360                                 (bndrs, rhss)    = unzip pairs
361                                 (subst', bndrs') = substRecBndrs subst bndrs
362                                 rhss' = map (subst_expr subst') rhss
363 \end{code}
364
365 \begin{code}
366 -- | De-shadowing the program is sometimes a useful pre-pass. It can be done simply
367 -- by running over the bindings with an empty substitution, becuase substitution
368 -- returns a result that has no-shadowing guaranteed.
369 --
370 -- (Actually, within a single /type/ there might still be shadowing, because 
371 -- 'substTy' is a no-op for the empty substitution, but that's probably OK.)
372 --
373 -- [Aug 09] This function is not used in GHC at the moment, but seems so 
374 --          short and simple that I'm going to leave it here
375 deShadowBinds :: [CoreBind] -> [CoreBind]
376 deShadowBinds binds = snd (mapAccumL substBind emptySubst binds)
377 \end{code}
378
379
380 %************************************************************************
381 %*                                                                      *
382         Substituting binders
383 %*                                                                      *
384 %************************************************************************
385
386 Remember that substBndr and friends are used when doing expression
387 substitution only.  Their only business is substitution, so they
388 preserve all IdInfo (suitably substituted).  For example, we *want* to
389 preserve occ info in rules.
390
391 \begin{code}
392 -- | Substitutes a 'Var' for another one according to the 'Subst' given, returning
393 -- the result and an updated 'Subst' that should be used by subsequent substitutons.
394 -- 'IdInfo' is preserved by this process, although it is substituted into appropriately.
395 substBndr :: Subst -> Var -> (Subst, Var)
396 substBndr subst bndr
397   | isTyCoVar bndr  = substTyVarBndr subst bndr
398   | otherwise       = substIdBndr (text "var-bndr") subst subst bndr
399
400 -- | Applies 'substBndr' to a number of 'Var's, accumulating a new 'Subst' left-to-right
401 substBndrs :: Subst -> [Var] -> (Subst, [Var])
402 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
403
404 -- | Substitute in a mutually recursive group of 'Id's
405 substRecBndrs :: Subst -> [Id] -> (Subst, [Id])
406 substRecBndrs subst bndrs 
407   = (new_subst, new_bndrs)
408   where         -- Here's the reason we need to pass rec_subst to subst_id
409     (new_subst, new_bndrs) = mapAccumL (substIdBndr (text "rec-bndr") new_subst) subst bndrs
410 \end{code}
411
412
413 \begin{code}
414 substIdBndr :: SDoc 
415             -> Subst            -- ^ Substitution to use for the IdInfo
416             -> Subst -> Id      -- ^ Substitition and Id to transform
417             -> (Subst, Id)      -- ^ Transformed pair
418                                 -- NB: unfolding may be zapped
419
420 substIdBndr _doc rec_subst subst@(Subst in_scope env tvs) old_id
421   = -- pprTrace "substIdBndr" (doc $$ ppr old_id $$ ppr in_scope) $
422     (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
423   where
424     id1 = uniqAway in_scope old_id      -- id1 is cloned if necessary
425     id2 | no_type_change = id1
426         | otherwise      = setIdType id1 (substTy subst old_ty)
427
428     old_ty = idType old_id
429     no_type_change = isEmptyVarEnv tvs || 
430                      isEmptyVarSet (Type.tyVarsOfType old_ty)
431
432         -- new_id has the right IdInfo
433         -- The lazy-set is because we're in a loop here, with 
434         -- rec_subst, when dealing with a mutually-recursive group
435     new_id = maybeModifyIdInfo mb_new_info id2
436     mb_new_info = substIdInfo rec_subst id2 (idInfo id2)
437         -- NB: unfolding info may be zapped
438
439         -- Extend the substitution if the unique has changed
440         -- See the notes with substTyVarBndr for the delVarEnv
441     new_env | no_change = delVarEnv env old_id
442             | otherwise = extendVarEnv env old_id (Var new_id)
443
444     no_change = id1 == old_id
445         -- See Note [Extending the Subst]
446         -- it's /not/ necessary to check mb_new_info and no_type_change
447 \end{code}
448
449 Now a variant that unconditionally allocates a new unique.
450 It also unconditionally zaps the OccInfo.
451
452 \begin{code}
453 -- | Very similar to 'substBndr', but it always allocates a new 'Unique' for
454 -- each variable in its output.  It substitutes the IdInfo though.
455 cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id)
456 cloneIdBndr subst us old_id
457   = clone_id subst subst (old_id, uniqFromSupply us)
458
459 -- | Applies 'cloneIdBndr' to a number of 'Id's, accumulating a final
460 -- substitution from left to right
461 cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
462 cloneIdBndrs subst us ids
463   = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us)
464
465 -- | Clone a mutually recursive group of 'Id's
466 cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
467 cloneRecIdBndrs subst us ids
468   = (subst', ids')
469   where
470     (subst', ids') = mapAccumL (clone_id subst') subst
471                                (ids `zip` uniqsFromSupply us)
472
473 -- Just like substIdBndr, except that it always makes a new unique
474 -- It is given the unique to use
475 clone_id    :: Subst                    -- Substitution for the IdInfo
476             -> Subst -> (Id, Unique)    -- Substitition and Id to transform
477             -> (Subst, Id)              -- Transformed pair
478
479 clone_id rec_subst subst@(Subst in_scope env tvs) (old_id, uniq)
480   = (Subst (in_scope `extendInScopeSet` new_id) new_env tvs, new_id)
481   where
482     id1     = setVarUnique old_id uniq
483     id2     = substIdType subst id1
484     new_id  = maybeModifyIdInfo (substIdInfo rec_subst id2 (idInfo old_id)) id2
485     new_env = extendVarEnv env old_id (Var new_id)
486 \end{code}
487
488
489 %************************************************************************
490 %*                                                                      *
491                 Types
492 %*                                                                      *
493 %************************************************************************
494
495 For types we just call the corresponding function in Type, but we have
496 to repackage the substitution, from a Subst to a TvSubst
497
498 \begin{code}
499 substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar)
500 substTyVarBndr (Subst in_scope id_env tv_env) tv
501   = case Type.substTyVarBndr (TvSubst in_scope tv_env) tv of
502         (TvSubst in_scope' tv_env', tv') 
503            -> (Subst in_scope' id_env tv_env', tv')
504
505 -- | See 'Type.substTy'
506 substTy :: Subst -> Type -> Type 
507 substTy subst ty = Type.substTy (getTvSubst subst) ty
508
509 getTvSubst :: Subst -> TvSubst
510 getTvSubst (Subst in_scope _id_env tv_env) = TvSubst in_scope tv_env
511 \end{code}
512
513
514 %************************************************************************
515 %*                                                                      *
516 \section{IdInfo substitution}
517 %*                                                                      *
518 %************************************************************************
519
520 \begin{code}
521 substIdType :: Subst -> Id -> Id
522 substIdType subst@(Subst _ _ tv_env) id
523   | isEmptyVarEnv tv_env || isEmptyVarSet (Type.tyVarsOfType old_ty) = id
524   | otherwise   = setIdType id (substTy subst old_ty)
525                 -- The tyVarsOfType is cheaper than it looks
526                 -- because we cache the free tyvars of the type
527                 -- in a Note in the id's type itself
528   where
529     old_ty = idType id
530
531 ------------------
532 -- | Substitute into some 'IdInfo' with regard to the supplied new 'Id'.
533 substIdInfo :: Subst -> Id -> IdInfo -> Maybe IdInfo
534 substIdInfo subst new_id info
535   | nothing_to_do = Nothing
536   | otherwise     = Just (info `setSpecInfo`      substSpec subst new_id old_rules
537                                `setUnfoldingInfo` substUnfolding subst old_unf)
538   where
539     old_rules     = specInfo info
540     old_unf       = unfoldingInfo info
541     nothing_to_do = isEmptySpecInfo old_rules && isClosedUnfolding old_unf
542     
543
544 ------------------
545 -- | Substitutes for the 'Id's within an unfolding
546 substUnfolding, substUnfoldingSC :: Subst -> Unfolding -> Unfolding
547         -- Seq'ing on the returned Unfolding is enough to cause
548         -- all the substitutions to happen completely
549
550 substUnfoldingSC subst unf       -- Short-cut version
551   | isEmptySubst subst = unf
552   | otherwise          = substUnfolding subst unf
553
554 substUnfolding subst (DFunUnfolding ar con args)
555   = DFunUnfolding ar con (map (substExpr (text "dfun-unf") subst) args)
556
557 substUnfolding subst unf@(CoreUnfolding { uf_tmpl = tmpl, uf_src = src })
558         -- Retain an InlineRule!
559   | not (isStableSource src)  -- Zap an unstable unfolding, to save substitution work
560   = NoUnfolding
561   | otherwise                 -- But keep a stable one!
562   = seqExpr new_tmpl `seq` 
563     new_src `seq`
564     unf { uf_tmpl = new_tmpl, uf_src = new_src }
565   where
566     new_tmpl = substExpr (text "subst-unf") subst tmpl
567     new_src  = substUnfoldingSource subst src
568
569 substUnfolding _ unf = unf      -- NoUnfolding, OtherCon
570
571 -------------------
572 substUnfoldingSource :: Subst -> UnfoldingSource -> UnfoldingSource
573 substUnfoldingSource (Subst in_scope ids _) (InlineWrapper wkr)
574   | Just wkr_expr <- lookupVarEnv ids wkr 
575   = case wkr_expr of
576       Var w1 -> InlineWrapper w1
577       _other -> -- WARN( True, text "Interesting! CoreSubst.substWorker1:" <+> ppr wkr 
578                 --             <+> ifPprDebug (equals <+> ppr wkr_expr) )   
579                               -- Note [Worker inlining]
580                 InlineStable  -- It's not a wrapper any more, but still inline it!
581
582   | Just w1  <- lookupInScope in_scope wkr = InlineWrapper w1
583   | otherwise = -- WARN( True, text "Interesting! CoreSubst.substWorker2:" <+> ppr wkr )
584                 -- This can legitimately happen.  The worker has been inlined and
585                 -- dropped as dead code, because we don't treat the UnfoldingSource
586                 -- as an "occurrence".
587                 -- Note [Worker inlining]
588                 InlineStable
589
590 substUnfoldingSource _ src = src
591
592 ------------------
593 substIdOcc :: Subst -> Id -> Id
594 -- These Ids should not be substituted to non-Ids
595 substIdOcc subst v = case lookupIdSubst (text "substIdOcc") subst v of
596                         Var v' -> v'
597                         other  -> pprPanic "substIdOcc" (vcat [ppr v <+> ppr other, ppr subst])
598
599 ------------------
600 -- | Substitutes for the 'Id's within the 'WorkerInfo' given the new function 'Id'
601 substSpec :: Subst -> Id -> SpecInfo -> SpecInfo
602 substSpec subst new_id (SpecInfo rules rhs_fvs)
603   = seqSpecInfo new_spec `seq` new_spec
604   where
605     subst_ru_fn = const (idName new_id)
606     new_spec = SpecInfo (map (substRule subst subst_ru_fn) rules)
607                          (substVarSet subst rhs_fvs)
608
609 ------------------
610 substRulesForImportedIds :: Subst -> [CoreRule] -> [CoreRule]
611 substRulesForImportedIds subst rules 
612   = map (substRule subst not_needed) rules
613   where
614     not_needed name = pprPanic "substRulesForImportedIds" (ppr name)
615
616 ------------------
617 substRule :: Subst -> (Name -> Name) -> CoreRule -> CoreRule
618
619 -- The subst_ru_fn argument is applied to substitute the ru_fn field
620 -- of the rule:
621 --    - Rules for *imported* Ids never change ru_fn
622 --    - Rules for *local* Ids are in the IdInfo for that Id,
623 --      and the ru_fn field is simply replaced by the new name 
624 --      of the Id
625
626 substRule _ _ rule@(BuiltinRule {}) = rule
627 substRule subst subst_ru_fn rule@(Rule { ru_bndrs = bndrs, ru_args = args
628                                        , ru_fn = fn_name, ru_rhs = rhs
629                                        , ru_local = is_local })
630   = rule { ru_bndrs = bndrs', 
631            ru_fn    = if is_local 
632                         then subst_ru_fn fn_name 
633                         else fn_name,
634            ru_args  = map (substExpr (text "subst-rule" <+> ppr fn_name) subst') args,
635            ru_rhs   = simpleOptExprWith subst' rhs }
636            -- Do simple optimisation on RHS, in case substitution lets
637            -- you improve it.  The real simplifier never gets to look at it.
638   where
639     (subst', bndrs') = substBndrs subst bndrs
640
641 ------------------
642 substVarSet :: Subst -> VarSet -> VarSet
643 substVarSet subst fvs 
644   = foldVarSet (unionVarSet . subst_fv subst) emptyVarSet fvs
645   where
646     subst_fv subst fv 
647         | isId fv   = exprFreeVars (lookupIdSubst (text "substVarSet") subst fv)
648         | otherwise = Type.tyVarsOfType (lookupTvSubst subst fv)
649 \end{code}
650
651 Note [Worker inlining]
652 ~~~~~~~~~~~~~~~~~~~~~~
653 A worker can get sustituted away entirely.
654         - it might be trivial
655         - it might simply be very small
656 We do not treat an InlWrapper as an 'occurrence' in the occurence 
657 analyser, so it's possible that the worker is not even in scope any more.
658
659 In all all these cases we simply drop the special case, returning to
660 InlVanilla.  The WARN is just so I can see if it happens a lot.
661
662
663 %************************************************************************
664 %*                                                                      *
665         The Very Simple Optimiser
666 %*                                                                      *
667 %************************************************************************
668
669 \begin{code}
670 simpleOptExpr :: CoreExpr -> CoreExpr
671 -- Do simple optimisation on an expression
672 -- The optimisation is very straightforward: just
673 -- inline non-recursive bindings that are used only once, 
674 -- or where the RHS is trivial
675 --
676 -- The result is NOT guaranteed occurence-analysed, becuase
677 -- in  (let x = y in ....) we substitute for x; so y's occ-info
678 -- may change radically
679
680 simpleOptExpr expr
681   = -- pprTrace "simpleOptExpr" (ppr init_subst $$ ppr expr)
682     simpleOptExprWith init_subst expr
683   where
684     init_subst = mkEmptySubst (mkInScopeSet (exprFreeVars expr))
685         -- It's potentially important to make a proper in-scope set
686         -- Consider  let x = ..y.. in \y. ...x...
687         -- Then we should remember to clone y before substituting
688         -- for x.  It's very unlikely to occur, because we probably
689         -- won't *be* substituting for x if it occurs inside a
690         -- lambda.  
691         --
692         -- It's a bit painful to call exprFreeVars, because it makes
693         -- three passes instead of two (occ-anal, and go)
694
695 simpleOptExprWith :: Subst -> InExpr -> OutExpr
696 simpleOptExprWith subst expr = simple_opt_expr subst (occurAnalyseExpr expr)
697
698 ----------------------
699 simpleOptPgm :: DynFlags -> [CoreBind] -> [CoreRule] -> IO ([CoreBind], [CoreRule])
700 simpleOptPgm dflags binds rules
701   = do { dumpIfSet_dyn dflags Opt_D_dump_occur_anal "Occurrence analysis"
702                        (pprCoreBindings occ_anald_binds);
703
704        ; return (reverse binds', substRulesForImportedIds subst' rules) }
705   where
706     occ_anald_binds  = occurAnalysePgm Nothing {- No rules active -}
707                                        rules binds
708     (subst', binds') = foldl do_one (emptySubst, []) occ_anald_binds
709                        
710     do_one (subst, binds') bind 
711       = case simple_opt_bind subst bind of
712           (subst', Nothing)    -> (subst', binds')
713           (subst', Just bind') -> (subst', bind':binds')
714
715 ----------------------
716 type InVar   = Var
717 type OutVar  = Var
718 type InId    = Id
719 type OutId   = Id
720 type InExpr  = CoreExpr
721 type OutExpr = CoreExpr
722
723 -- In these functions the substitution maps InVar -> OutExpr
724
725 ----------------------
726 simple_opt_expr :: Subst -> InExpr -> OutExpr
727 simple_opt_expr subst expr
728   = go expr
729   where
730     go (Var v)          = lookupIdSubst (text "simpleOptExpr") subst v
731     go (App e1 e2)      = simple_app subst e1 [go e2]
732     go (Type ty)        = Type (substTy subst ty)
733     go (Lit lit)        = Lit lit
734     go (Note note e)    = Note note (go e)
735     go (Cast e co)      | isIdentityCoercion co' = go e
736                         | otherwise              = Cast (go e) co' 
737                         where
738                           co' = substTy subst co
739
740     go (Let bind body) = case simple_opt_bind subst bind of
741                            (subst', Nothing)   -> simple_opt_expr subst' body
742                            (subst', Just bind) -> Let bind (simple_opt_expr subst' body)
743
744     go lam@(Lam {})     = go_lam [] subst lam
745     go (Case e b ty as) = Case (go e) b' (substTy subst ty)
746                                (map (go_alt subst') as)
747                         where
748                           (subst', b') = subst_opt_bndr subst b
749
750     ----------------------
751     go_alt subst (con, bndrs, rhs) 
752       = (con, bndrs', simple_opt_expr subst' rhs)
753       where
754         (subst', bndrs') = subst_opt_bndrs subst bndrs
755
756     ----------------------
757     -- go_lam tries eta reduction
758     go_lam bs' subst (Lam b e) 
759        = go_lam (b':bs') subst' e
760        where
761          (subst', b') = subst_opt_bndr subst b
762     go_lam bs' subst e 
763        | Just etad_e <- tryEtaReduce bs e' = etad_e
764        | otherwise                         = mkLams bs e'
765        where
766          bs = reverse bs'
767          e' = simple_opt_expr subst e
768
769 ----------------------
770 -- simple_app collects arguments for beta reduction
771 simple_app :: Subst -> InExpr -> [OutExpr] -> CoreExpr
772 simple_app subst (App e1 e2) as   
773   = simple_app subst e1 (simple_opt_expr subst e2 : as)
774 simple_app subst (Lam b e) (a:as) 
775   = case maybe_substitute subst b a of
776       Just ext_subst -> simple_app ext_subst e as
777       Nothing        -> Let (NonRec b2 a) (simple_app subst' e as)
778   where
779     (subst', b') = subst_opt_bndr subst b
780     b2 = add_info subst' b b'
781 simple_app subst e as
782   = foldl App (simple_opt_expr subst e) as
783
784 ----------------------
785 simple_opt_bind :: Subst -> CoreBind -> (Subst, Maybe CoreBind)
786 simple_opt_bind subst (Rec prs)
787   = (subst'', Just (Rec (reverse rev_prs')))
788   where
789     (subst', bndrs')    = subst_opt_bndrs subst (map fst prs)
790     (subst'', rev_prs') = foldl do_pr (subst', []) (prs `zip` bndrs')
791     do_pr (subst, prs) ((b,r), b') 
792        = case maybe_substitute subst b r2 of
793            Just subst' -> (subst', prs)
794            Nothing     -> (subst,  (b2,r2):prs)
795        where
796          b2 = add_info subst b b'
797          r2 = simple_opt_expr subst r
798
799 simple_opt_bind subst (NonRec b r)
800   = case maybe_substitute subst b r' of
801       Just ext_subst -> (ext_subst, Nothing)
802       Nothing        -> (subst', Just (NonRec b2 r'))
803   where
804     r' = simple_opt_expr subst r
805     (subst', b') = subst_opt_bndr subst b
806     b2 = add_info subst' b b'
807
808 ----------------------
809 maybe_substitute :: Subst -> InVar -> OutExpr -> Maybe Subst
810     -- (maybe_substitute subst in_var out_rhs)  
811     --   either extends subst with (in_var -> out_rhs)
812     --   or     returns Nothing
813 maybe_substitute subst b r
814   | Type ty <- r        -- let a::* = TYPE ty in <body>
815   = ASSERT( isTyCoVar b )
816     Just (extendTvSubst subst b ty)
817
818   | isId b              -- let x = e in <body>
819   , safe_to_inline (idOccInfo b) 
820   , isAlwaysActive (idInlineActivation b)       -- Note [Inline prag in simplOpt]
821   , not (isStableUnfolding (idUnfolding b))
822   , not (isExportedId b)
823   = Just (extendIdSubst subst b r)
824   
825   | otherwise
826   = Nothing
827   where
828         -- Unconditionally safe to inline
829     safe_to_inline :: OccInfo -> Bool
830     safe_to_inline (IAmALoopBreaker {})     = False
831     safe_to_inline IAmDead                  = True
832     safe_to_inline (OneOcc in_lam one_br _) = (not in_lam && one_br) || exprIsTrivial r
833     safe_to_inline NoOccInfo                = exprIsTrivial r
834
835 ----------------------
836 subst_opt_bndr :: Subst -> InVar -> (Subst, OutVar)
837 subst_opt_bndr subst bndr
838   | isTyCoVar bndr  = substTyVarBndr subst bndr
839   | otherwise       = subst_opt_id_bndr subst bndr
840
841 subst_opt_id_bndr :: Subst -> InId -> (Subst, OutId)
842 -- Nuke all fragile IdInfo, unfolding, and RULES; 
843 --    it gets added back later by add_info
844 -- Rather like SimplEnv.substIdBndr
845 --
846 -- It's important to zap fragile OccInfo (which CoreSubst.SubstIdBndr 
847 -- carefully does not do) because simplOptExpr invalidates it
848
849 subst_opt_id_bndr subst@(Subst in_scope id_subst tv_subst) old_id
850   = (Subst new_in_scope new_id_subst tv_subst, new_id)
851   where
852     id1    = uniqAway in_scope old_id
853     id2    = setIdType id1 (substTy subst (idType old_id))
854     new_id = zapFragileIdInfo id2       -- Zaps rules, worker-info, unfolding
855                                         -- and fragile OccInfo
856     new_in_scope = in_scope `extendInScopeSet` new_id
857
858         -- Extend the substitution if the unique has changed,
859         -- or there's some useful occurrence information
860         -- See the notes with substTyVarBndr for the delSubstEnv
861     new_id_subst | new_id /= old_id
862                  = extendVarEnv id_subst old_id (Var new_id)
863                  | otherwise 
864                  = delVarEnv id_subst old_id
865
866 ----------------------
867 subst_opt_bndrs :: Subst -> [InVar] -> (Subst, [OutVar])
868 subst_opt_bndrs subst bndrs
869   = mapAccumL subst_opt_bndr subst bndrs
870
871 ----------------------
872 add_info :: Subst -> InVar -> OutVar -> OutVar
873 add_info subst old_bndr new_bndr 
874  | isTyCoVar old_bndr = new_bndr
875  | otherwise          = maybeModifyIdInfo mb_new_info new_bndr
876  where
877    mb_new_info = substIdInfo subst new_bndr (idInfo old_bndr)
878 \end{code}
879
880 Note [Inline prag in simplOpt]
881 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
882 If there's an INLINE/NOINLINE pragma that restricts the phase in 
883 which the binder can be inlined, we don't inline here; after all,
884 we don't know what phase we're in.  Here's an example
885
886   foo :: Int -> Int -> Int
887   {-# INLINE foo #-}
888   foo m n = inner m
889      where
890        {-# INLINE [1] inner #-}
891        inner m = m+n
892
893   bar :: Int -> Int
894   bar n = foo n 1
895
896 When inlining 'foo' in 'bar' we want the let-binding for 'inner' 
897 to remain visible until Phase 1
898