[project @ 2001-05-18 08:46:18 by simonpj]
[ghc-hetmet.git] / ghc / compiler / coreSyn / Subst.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[CoreUtils]{Utility functions on @Core@ syntax}
5
6 \begin{code}
7 module Subst (
8         -- In-scope set
9         InScopeSet, emptyInScopeSet, mkInScopeSet,
10         extendInScopeSet, extendInScopeSetList,
11         lookupInScope, elemInScopeSet, uniqAway,
12
13
14         -- Substitution stuff
15         Subst, TyVarSubst, IdSubst,
16         emptySubst, mkSubst, substEnv, substInScope,
17         lookupSubst, lookupIdSubst, isEmptySubst, extendSubst, extendSubstList,
18         zapSubstEnv, setSubstEnv, 
19         setInScope, 
20         extendInScope, extendInScopeList, extendNewInScope, extendNewInScopeList, 
21         isInScope, modifyInScope,
22
23         bindSubst, unBindSubst, bindSubstList, unBindSubstList,
24
25         -- Binders
26         simplBndr, simplBndrs, simplLetId, simplIdInfo,
27         substAndCloneId, substAndCloneIds, substAndCloneRecIds,
28
29         -- Type stuff
30         mkTyVarSubst, mkTopTyVarSubst, 
31         substTy, substTheta,
32
33         -- Expression stuff
34         substExpr, substIdInfo
35     ) where
36
37 #include "HsVersions.h"
38
39 import CmdLineOpts      ( opt_PprStyle_Debug )
40 import CoreSyn          ( Expr(..), Bind(..), Note(..), CoreExpr,
41                           CoreRules(..), CoreRule(..), 
42                           isEmptyCoreRules, seqRules, hasUnfolding, noUnfolding
43                         )
44 import CoreFVs          ( exprFreeVars )
45 import TypeRep          ( Type(..), TyNote(..) )  -- friend
46 import Type             ( ThetaType, PredType(..), 
47                           tyVarsOfType, tyVarsOfTypes, mkAppTy, mkUTy, isUTy
48                         )
49 import VarSet
50 import VarEnv
51 import Var              ( setVarUnique, isId, mustHaveLocalBinding )
52 import Id               ( idType, idInfo, setIdInfo, setIdType, 
53                           idOccInfo, maybeModifyIdInfo )
54 import IdInfo           ( IdInfo, vanillaIdInfo,
55                           occInfo, isFragileOcc, setOccInfo, 
56                           specInfo, setSpecInfo, 
57                           unfoldingInfo, setUnfoldingInfo,
58                           WorkerInfo(..), workerExists, workerInfo, setWorkerInfo, WorkerInfo,
59                           lbvarInfo, LBVarInfo(..), setLBVarInfo, hasNoLBVarInfo
60                         )
61 import BasicTypes       ( OccInfo(..) )
62 import Unique           ( Unique, Uniquable(..), deriveUnique )
63 import UniqSet          ( elemUniqSet_Directly )
64 import UniqSupply       ( UniqSupply, uniqFromSupply, uniqsFromSupply )
65 import Var              ( Var, Id, TyVar, isTyVar )
66 import Outputable
67 import PprCore          ()              -- Instances
68 import UniqFM           ( ufmToList )   -- Yuk (add a new op to VarEnv)
69 import Util             ( mapAccumL, foldl2, seqList )
70 import FastTypes
71 \end{code}
72
73
74 %************************************************************************
75 %*                                                                      *
76 \subsection{The in-scope set}
77 %*                                                                      *
78 %************************************************************************
79
80 \begin{code}
81 data InScopeSet = InScope (VarEnv Var) FastInt
82         -- The Int# is a kind of hash-value used by uniqAway
83         -- For example, it might be the size of the set
84         -- INVARIANT: it's not zero; we use it as a multiplier in uniqAway
85
86 emptyInScopeSet :: InScopeSet
87 emptyInScopeSet = InScope emptyVarSet 1#
88
89 mkInScopeSet :: VarEnv Var -> InScopeSet
90 mkInScopeSet in_scope = InScope in_scope 1#
91
92 extendInScopeSet :: InScopeSet -> Var -> InScopeSet
93 extendInScopeSet (InScope in_scope n) v = InScope (extendVarEnv in_scope v v) (n +# 1#)
94
95 extendInScopeSetList :: InScopeSet -> [Var] -> InScopeSet
96 extendInScopeSetList (InScope in_scope n) vs
97    = InScope (foldl (\s v -> extendVarEnv s v v) in_scope vs)
98                     (n +# iUnbox (length vs))
99
100 modifyInScopeSet :: InScopeSet -> Var -> Var -> InScopeSet
101 -- Exploit the fact that the in-scope "set" is really a map
102 --      Make old_v map to new_v
103 modifyInScopeSet (InScope in_scope n) old_v new_v = InScope (extendVarEnv in_scope old_v new_v) (n +# 1#)
104
105 delInScopeSet :: InScopeSet -> Var -> InScopeSet
106 delInScopeSet (InScope in_scope n) v = InScope (in_scope `delVarEnv` v) n
107
108 elemInScopeSet :: Var -> InScopeSet -> Bool
109 elemInScopeSet v (InScope in_scope n) = v `elemVarEnv` in_scope
110
111 lookupInScope :: InScopeSet -> Var -> Var
112 -- It's important to look for a fixed point
113 -- When we see (case x of y { I# v -> ... })
114 -- we add  [x -> y] to the in-scope set (Simplify.simplCaseBinder).
115 -- When we lookup up an occurrence of x, we map to y, but then
116 -- we want to look up y in case it has acquired more evaluation information by now.
117 lookupInScope (InScope in_scope n) v 
118   = go v
119   where
120     go v = case lookupVarEnv in_scope v of
121                 Just v' | v == v'   -> v'       -- Reached a fixed point
122                         | otherwise -> go v'
123                 Nothing             -> WARN( mustHaveLocalBinding v, ppr v )
124                                        v
125 \end{code}
126
127 \begin{code}
128 uniqAway :: InScopeSet -> Var -> Var
129 -- (uniqAway in_scope v) finds a unique that is not used in the
130 -- in-scope set, and gives that to v.  It starts with v's current unique, of course,
131 -- in the hope that it won't have to change it, nad thereafter uses a combination
132 -- of that and the hash-code found in the in-scope set
133 uniqAway (InScope set n) var
134   | not (var `elemVarSet` set) = var                            -- Nothing to do
135   | otherwise                  = try 1#
136   where
137     orig_unique = getUnique var
138     try k 
139 #ifdef DEBUG
140           | k ># 1000#
141           = pprPanic "uniqAway loop:" (ppr (iBox k) <+> text "tries" <+> ppr var <+> int (iBox n)) 
142 #endif                      
143           | uniq `elemUniqSet_Directly` set = try (k +# 1#)
144 #ifdef DEBUG
145           | opt_PprStyle_Debug && k ># 3#
146           = pprTrace "uniqAway:" (ppr (iBox k) <+> text "tries" <+> ppr var <+> int (iBox n)) 
147             setVarUnique var uniq
148 #endif                      
149           | otherwise = setVarUnique var uniq
150           where
151             uniq = deriveUnique orig_unique (iBox (n *# k))
152 \end{code}
153
154
155 %************************************************************************
156 %*                                                                      *
157 \subsection{Substitutions}
158 %*                                                                      *
159 %************************************************************************
160
161 \begin{code}
162 data Subst = Subst InScopeSet           -- In scope
163                    SubstEnv             -- Substitution itself
164         -- INVARIANT 1: The (domain of the) in-scope set is a superset
165         --              of the free vars of the range of the substitution
166         --              that might possibly clash with locally-bound variables
167         --              in the thing being substituted in.
168         -- This is what lets us deal with name capture properly
169         -- It's a hard invariant to check...
170         -- There are various ways of causing it to happen:
171         --      - arrange that the in-scope set really is all the things in scope
172         --      - arrange that it's the free vars of the range of the substitution
173         --      - make it empty because all the free vars of the subst are fresh,
174         --              and hence can't possibly clash.a
175         --
176         -- INVARIANT 2: No variable is both in scope and in the domain of the substitution
177         --              Equivalently, the substitution is idempotent
178         --      [Sep 2000: Lies, all lies.  The substitution now does contain
179         --                 mappings x77 -> DoneId x77 occ
180         --                 to record x's occurrence information.]
181         --      [Also watch out: the substitution can contain x77 -> DoneEx (Var x77)
182         --       Consider let x = case k of I# x77 -> ... in
183         --                let y = case k of I# x77 -> ... in ...
184         --       and suppose the body is strict in both x and y.  Then the simplifier
185         --       will pull the first (case k) to the top; so the second (case k) will
186         --       cancel out, mapping x77 to, well, x77!  But one is an in-Id and the 
187         --       other is an out-Id. So the substitution is idempotent in the sense
188         --       that we *must not* repeatedly apply it.]
189
190 type IdSubst    = Subst
191 \end{code}
192
193 The general plan about the substitution and in-scope set for Ids is as follows
194
195 * substId always adds new_id to the in-scope set.
196   new_id has a correctly-substituted type, occ info
197
198 * substId adds a binding (DoneId new_id occ) to the substitution if 
199         EITHER the Id's unique has changed
200         OR     the Id has interesting occurrence information
201   So in effect you can only get to interesting occurrence information
202   by looking up the *old* Id; it's not really attached to the new id
203   at all.
204
205   Note, though that the substitution isn't necessarily extended
206   if the type changes.  Why not?  Because of the next point:
207
208 * We *always, always* finish by looking up in the in-scope set 
209   any variable that doesn't get a DoneEx or DoneVar hit in the substitution.
210   Reason: so that we never finish up with a "old" Id in the result.  
211   An old Id might point to an old unfolding and so on... which gives a space leak.
212
213   [The DoneEx and DoneVar hits map to "new" stuff.]
214
215 * It follows that substExpr must not do a no-op if the substitution is empty.
216   substType is free to do so, however.
217
218 * When we come to a let-binding (say) we generate new IdInfo, including an
219   unfolding, attach it to the binder, and add this newly adorned binder to
220   the in-scope set.  So all subsequent occurrences of the binder will get mapped
221   to the full-adorned binder, which is also the one put in the binding site.
222
223 * The in-scope "set" usually maps x->x; we use it simply for its domain.
224   But sometimes we have two in-scope Ids that are synomyms, and should
225   map to the same target:  x->x, y->x.  Notably:
226         case y of x { ... }
227   That's why the "set" is actually a VarEnv Var
228
229
230 \begin{code}
231 isEmptySubst :: Subst -> Bool
232 isEmptySubst (Subst _ env) = isEmptySubstEnv env
233
234 emptySubst :: Subst
235 emptySubst = Subst emptyInScopeSet emptySubstEnv
236
237 mkSubst :: InScopeSet -> SubstEnv -> Subst
238 mkSubst in_scope env = Subst in_scope env
239
240 substEnv :: Subst -> SubstEnv
241 substEnv (Subst _ env) = env
242
243 substInScope :: Subst -> InScopeSet
244 substInScope (Subst in_scope _) = in_scope
245
246 zapSubstEnv :: Subst -> Subst
247 zapSubstEnv (Subst in_scope env) = Subst in_scope emptySubstEnv
248
249 extendSubst :: Subst -> Var -> SubstResult -> Subst
250 extendSubst (Subst in_scope env) v r = UASSERT( case r of { DoneTy ty -> not (isUTy ty) ; _ -> True } )
251                                        Subst in_scope (extendSubstEnv env v r)
252
253 extendSubstList :: Subst -> [Var] -> [SubstResult] -> Subst
254 extendSubstList (Subst in_scope env) v r = UASSERT( all (\ r1 -> case r1 of { DoneTy ty -> not (isUTy ty) ; _ -> True }) r )
255                                            Subst in_scope (extendSubstEnvList env v r)
256
257 lookupSubst :: Subst -> Var -> Maybe SubstResult
258 lookupSubst (Subst _ env) v = lookupSubstEnv env v
259
260 lookupIdSubst :: Subst -> Id -> SubstResult
261 -- Does the lookup in the in-scope set too
262 lookupIdSubst (Subst in_scope env) v
263   = case lookupSubstEnv env v of
264         Just (DoneId v' occ) -> DoneId (lookupInScope in_scope v') occ
265         Just res             -> res
266         Nothing              -> DoneId v' (idOccInfo v')
267                                 -- We don't use DoneId for LoopBreakers, so the idOccInfo is
268                                 -- very important!  If isFragileOcc returned True for
269                                 -- loop breakers we could avoid this call, but at the expense
270                                 -- of adding more to the substitution, and building new Ids
271                                 -- in substId a bit more often than really necessary
272                              where
273                                     v' = lookupInScope in_scope v
274
275 isInScope :: Var -> Subst -> Bool
276 isInScope v (Subst in_scope _) = v `elemInScopeSet` in_scope
277
278 modifyInScope :: Subst -> Var -> Var -> Subst
279 modifyInScope (Subst in_scope env) old_v new_v = Subst (modifyInScopeSet in_scope old_v new_v) env
280         -- make old_v map to new_v
281
282 extendInScope :: Subst -> Var -> Subst
283         -- Add a new variable as in-scope
284         -- Remember to delete any existing binding in the substitution!
285 extendInScope (Subst in_scope env) v = Subst (in_scope `extendInScopeSet` v)
286                                              (env `delSubstEnv` v)
287
288 extendInScopeList :: Subst -> [Var] -> Subst
289 extendInScopeList (Subst in_scope env) vs = Subst (extendInScopeSetList in_scope vs)
290                                                   (delSubstEnvList env vs)
291
292 -- The "New" variants are guaranteed to be adding freshly-allocated variables
293 -- It's not clear that the gain (not needing to delete it from the substitution)
294 -- is worth the extra proof obligation
295 extendNewInScope :: Subst -> Var -> Subst
296 extendNewInScope (Subst in_scope env) v = Subst (in_scope `extendInScopeSet` v) env
297
298 extendNewInScopeList :: Subst -> [Var] -> Subst
299 extendNewInScopeList (Subst in_scope env) vs = Subst (in_scope `extendInScopeSetList` vs) env
300
301 -------------------------------
302 bindSubst :: Subst -> Var -> Var -> Subst
303 -- Extend with a substitution, v1 -> Var v2
304 -- and extend the in-scopes with v2
305 bindSubst (Subst in_scope env) old_bndr new_bndr
306   = Subst (in_scope `extendInScopeSet` new_bndr)
307           (extendSubstEnv env old_bndr subst_result)
308   where
309     subst_result | isId old_bndr = DoneEx (Var new_bndr)
310                  | otherwise     = DoneTy (TyVarTy new_bndr)
311
312 unBindSubst :: Subst -> Var -> Var -> Subst
313 -- Reverse the effect of bindSubst
314 -- If old_bndr was already in the substitution, this doesn't quite work
315 unBindSubst (Subst in_scope env) old_bndr new_bndr
316   = Subst (in_scope `delInScopeSet` new_bndr) (delSubstEnv env old_bndr)
317
318 -- And the "List" forms
319 bindSubstList :: Subst -> [Var] -> [Var] -> Subst
320 bindSubstList subst old_bndrs new_bndrs
321   = foldl2 bindSubst subst old_bndrs new_bndrs
322
323 unBindSubstList :: Subst -> [Var] -> [Var] -> Subst
324 unBindSubstList subst old_bndrs new_bndrs
325   = foldl2 unBindSubst subst old_bndrs new_bndrs
326
327
328 -------------------------------
329 setInScope :: Subst     -- Take env part from here
330            -> InScopeSet
331            -> Subst
332 setInScope (Subst in_scope1 env1) in_scope2
333   = Subst in_scope2 env1
334
335 setSubstEnv :: Subst            -- Take in-scope part from here
336             -> SubstEnv         -- ... and env part from here
337             -> Subst
338 setSubstEnv (Subst in_scope1 _) env2 = Subst in_scope1 env2
339 \end{code}
340
341 Pretty printing, for debugging only
342
343 \begin{code}
344 instance Outputable SubstResult where
345   ppr (DoneEx e)   = ptext SLIT("DoneEx") <+> ppr e
346   ppr (DoneId v _) = ptext SLIT("DoneId") <+> ppr v
347   ppr (ContEx _ e) = ptext SLIT("ContEx") <+> ppr e
348   ppr (DoneTy t)   = ptext SLIT("DoneTy") <+> ppr t
349
350 instance Outputable SubstEnv where
351   ppr se = brackets (fsep (punctuate comma (map ppr_elt (ufmToList (substEnvEnv se)))))
352         where
353            ppr_elt (uniq,sr) = ppr uniq <+> ptext SLIT("->") <+> ppr sr
354
355 instance Outputable Subst where
356   ppr (Subst (InScope in_scope _) se) 
357         =  ptext SLIT("<InScope =") <+> braces   (fsep (map ppr (rngVarEnv in_scope)))
358         $$ ptext SLIT(" Subst   =") <+> ppr se <> char '>'
359 \end{code}
360
361 %************************************************************************
362 %*                                                                      *
363 \subsection{Type substitution}
364 %*                                                                      *
365 %************************************************************************
366
367 \begin{code}
368 type TyVarSubst = Subst -- TyVarSubst are expected to have range elements
369         -- (We could have a variant of Subst, but it doesn't seem worth it.)
370
371 -- mkTyVarSubst generates the in-scope set from
372 -- the types given; but it's just a thunk so with a bit of luck
373 -- it'll never be evaluated
374 mkTyVarSubst :: [TyVar] -> [Type] -> Subst
375 mkTyVarSubst tyvars tys = Subst (mkInScopeSet (tyVarsOfTypes tys)) (zip_ty_env tyvars tys emptySubstEnv)
376
377 -- mkTopTyVarSubst is called when doing top-level substitutions.
378 -- Here we expect that the free vars of the range of the
379 -- substitution will be empty.
380 mkTopTyVarSubst :: [TyVar] -> [Type] -> Subst
381 mkTopTyVarSubst tyvars tys = Subst emptyInScopeSet (zip_ty_env tyvars tys emptySubstEnv)
382
383 zip_ty_env []       []       env = env
384 zip_ty_env (tv:tvs) (ty:tys) env = UASSERT( not (isUTy ty) )
385                                    zip_ty_env tvs tys (extendSubstEnv env tv (DoneTy ty))
386 \end{code}
387
388 substTy works with general Substs, so that it can be called from substExpr too.
389
390 \begin{code}
391 substTy :: Subst -> Type  -> Type
392 substTy subst ty | isEmptySubst subst = ty
393                  | otherwise          = subst_ty subst ty
394
395 substTheta :: TyVarSubst -> ThetaType -> ThetaType
396 substTheta subst theta
397   | isEmptySubst subst = theta
398   | otherwise          = map (substPred subst) theta
399
400 substPred :: TyVarSubst -> PredType -> PredType
401 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
402 substPred subst (IParam n ty)     = IParam n (subst_ty subst ty)
403
404 subst_ty subst ty
405    = go ty
406   where
407     go (TyConApp tc tys)           = let args = map go tys
408                                      in  args `seqList` TyConApp tc args
409
410     go (PredTy p)                  = PredTy $! (substPred subst p)
411
412     go (NoteTy (SynNote ty1) ty2)  = NoteTy (SynNote $! (go ty1)) $! (go ty2)
413     go (NoteTy (FTVNote _) ty2)    = go ty2             -- Discard the free tyvar note
414
415     go (FunTy arg res)             = (FunTy $! (go arg)) $! (go res)
416     go (AppTy fun arg)             = mkAppTy (go fun) $! (go arg)
417     go ty@(TyVarTy tv)             = case (lookupSubst subst tv) of
418                                         Nothing            -> ty
419                                         Just (DoneTy ty')  -> ty'
420                                         
421     go (ForAllTy tv ty)            = case substTyVar subst tv of
422                                         (subst', tv') -> ForAllTy tv' $! (subst_ty subst' ty)
423
424     go (UsageTy u ty)              = mkUTy (go u) $! (go ty)
425 \end{code}
426
427 Here is where we invent a new binder if necessary.
428
429 \begin{code}
430 substTyVar :: Subst -> TyVar -> (Subst, TyVar)  
431 substTyVar subst@(Subst in_scope env) old_var
432   | old_var == new_var  -- No need to clone
433                         -- But we *must* zap any current substitution for the variable.
434                         --  For example:
435                         --      (\x.e) with id_subst = [x |-> e']
436                         -- Here we must simply zap the substitution for x
437                         --
438                         -- The new_id isn't cloned, but it may have a different type
439                         -- etc, so we must return it, not the old id
440   = (Subst (in_scope `extendInScopeSet` new_var)
441            (delSubstEnv env old_var),
442      new_var)
443
444   | otherwise   -- The new binder is in scope so
445                 -- we'd better rename it away from the in-scope variables
446                 -- Extending the substitution to do this renaming also
447                 -- has the (correct) effect of discarding any existing
448                 -- substitution for that variable
449   = (Subst (in_scope `extendInScopeSet` new_var) 
450            (extendSubstEnv env old_var (DoneTy (TyVarTy new_var))),
451      new_var)
452   where
453     new_var = uniqAway in_scope old_var
454         -- The uniqAway part makes sure the new variable is not already in scope
455 \end{code}
456
457
458 %************************************************************************
459 %*                                                                      *
460 \section{Expression substitution}
461 %*                                                                      *
462 %************************************************************************
463
464 This expression substituter deals correctly with name capture.
465
466 BUT NOTE that substExpr silently discards the
467         unfolding, and
468         spec env
469 IdInfo attached to any binders in the expression.  It's quite
470 tricky to do them 'right' in the case of mutually recursive bindings,
471 and so far has proved unnecessary.
472
473 \begin{code}
474 substExpr :: Subst -> CoreExpr -> CoreExpr
475 substExpr subst expr
476         -- NB: we do not do a no-op when the substitution is empty,
477         -- because we always want to substitute the variables in the
478         -- in-scope set for their occurrences.  Why?
479         --      (a) because they may contain more information
480         --      (b) because leaving an un-substituted Id might cause
481         --          a space leak (its unfolding might point to an old version
482         --          of its right hand side).
483
484   = go expr
485   where
486     go (Var v) = -- See the notes at the top, with the Subst data type declaration
487                  case lookupIdSubst subst v of
488         
489                     ContEx env' e' -> substExpr (setSubstEnv subst env') e'
490                     DoneId v _     -> Var v
491                     DoneEx e'      -> e'
492
493     go (Type ty)      = Type (go_ty ty)
494     go (Lit lit)      = Lit lit
495     go (App fun arg)  = App (go fun) (go arg)
496     go (Note note e)  = Note (go_note note) (go e)
497
498     go (Lam bndr body) = Lam bndr' (substExpr subst' body)
499                        where
500                          (subst', bndr') = substBndr subst bndr
501
502     go (Let (NonRec bndr rhs) body) = Let (NonRec bndr' (go rhs)) (substExpr subst' body)
503                                     where
504                                       (subst', bndr') = substBndr subst bndr
505
506     go (Let (Rec pairs) body) = Let (Rec pairs') (substExpr subst' body)
507                               where
508                                 (subst', bndrs') = substRecIds subst (map fst pairs)
509                                 pairs'  = bndrs' `zip` rhss'
510                                 rhss'   = map (substExpr subst' . snd) pairs
511
512     go (Case scrut bndr alts) = Case (go scrut) bndr' (map (go_alt subst') alts)
513                               where
514                                 (subst', bndr') = substBndr subst bndr
515
516     go_alt subst (con, bndrs, rhs) = (con, bndrs', substExpr subst' rhs)
517                                  where
518                                    (subst', bndrs') = substBndrs subst bndrs
519
520     go_note (Coerce ty1 ty2) = Coerce (go_ty ty1) (go_ty ty2)
521     go_note note             = note
522
523     go_ty ty = substTy subst ty
524
525 \end{code}
526
527
528 %************************************************************************
529 %*                                                                      *
530 \section{Substituting an Id binder}
531 %*                                                                      *
532 %************************************************************************
533
534 \begin{code}
535 -- simplBndr and simplLetId are used by the simplifier
536
537 simplBndr :: Subst -> Var -> (Subst, Var)
538 -- Used for lambda and case-bound variables
539 -- Clone Id if necessary, substitute type
540 -- Return with IdInfo already substituted, 
541 -- but occurrence info zapped
542 -- The substitution is extended only if the variable is cloned, because
543 -- we don't need to use it to track occurrence info.
544 simplBndr subst bndr
545   | isTyVar bndr  = substTyVar subst bndr
546   | otherwise     = subst_id isFragileOcc subst subst bndr
547
548 simplBndrs :: Subst -> [Var] -> (Subst, [Var])
549 simplBndrs subst bndrs = mapAccumL simplBndr subst bndrs
550
551 simplLetId :: Subst -> Id -> (Subst, Id)
552 -- Clone Id if necessary
553 -- Substitute its type
554 -- Return an Id with completely zapped IdInfo
555 -- Augment the subtitution if the unique changed or if there's
556 --      interesting occurrence info
557 -- [A subsequent substIdInfo will restore its IdInfo]
558 simplLetId subst@(Subst in_scope env) old_id
559   = (Subst (in_scope `extendInScopeSet` new_id) new_env, new_id)
560   where
561     old_info = idInfo old_id
562     id1     = uniqAway in_scope old_id
563     id2     = substIdType subst id1
564     new_id  = setIdInfo id2 vanillaIdInfo
565
566         -- Extend the substitution if the unique has changed,
567         -- or there's some useful occurrence information
568         -- See the notes with substTyVar for the delSubstEnv
569     occ_info = occInfo old_info
570     new_env | new_id /= old_id || isFragileOcc occ_info
571             = extendSubstEnv env old_id (DoneId new_id occ_info)
572             | otherwise 
573             = delSubstEnv env old_id
574
575 simplIdInfo :: Subst -> IdInfo -> Id -> Id
576   -- Used by the simplifier to compute new IdInfo for a let(rec) binder,
577   -- subsequent to simplLetId having zapped its IdInfo
578 simplIdInfo subst old_info bndr
579   = case substIdInfo subst isFragileOcc old_info of 
580         Just new_info -> bndr `setIdInfo` new_info
581         Nothing       -> bndr `setIdInfo` old_info
582 \end{code}
583
584 \begin{code}
585 -- substBndr and friends are used when doing expression substitution only
586 -- In this case we can preserve occurrence information, and indeed we want
587 -- to do so else lose useful occ info in rules.  Hence the calls to 
588 -- simpl_id with keepOccInfo
589
590 substBndr :: Subst -> Var -> (Subst, Var)
591 substBndr subst bndr
592   | isTyVar bndr  = substTyVar subst bndr
593   | otherwise     = subst_id keepOccInfo subst subst bndr
594
595 substBndrs :: Subst -> [Var] -> (Subst, [Var])
596 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
597
598 substRecIds :: Subst -> [Id] -> (Subst, [Id])
599 -- Substitute a mutually recursive group
600 substRecIds subst bndrs 
601   = (new_subst, new_bndrs)
602   where
603         -- Here's the reason we need to pass rec_subst to subst_id
604     (new_subst, new_bndrs) = mapAccumL (subst_id keepOccInfo new_subst) subst bndrs
605
606 keepOccInfo occ = False -- Never fragile
607 \end{code}
608
609
610 \begin{code}
611 subst_id :: (OccInfo -> Bool)   -- True <=> the OccInfo is fragile
612          -> Subst               -- Substitution to use for the IdInfo
613          -> Subst -> Id         -- Substitition and Id to transform
614          -> (Subst, Id)         -- Transformed pair
615
616 -- Returns with:
617 --      * Unique changed if necessary
618 --      * Type substituted
619 --      * Unfolding zapped
620 --      * Rules, worker, lbvar info all substituted 
621 --      * Occurrence info zapped if is_fragile_occ returns True
622 --      * The in-scope set extended with the returned Id
623 --      * The substitution extended with a DoneId if unique changed
624 --        In this case, the var in the DoneId is the same as the
625 --        var returned
626
627 subst_id is_fragile_occ rec_subst subst@(Subst in_scope env) old_id
628   = (Subst (in_scope `extendInScopeSet` new_id) new_env, new_id)
629   where
630         -- id1 is cloned if necessary
631     id1 = uniqAway in_scope old_id
632
633         -- id2 has its type zapped
634     id2 = substIdType subst id1
635
636         -- new_id has the right IdInfo
637         -- The lazy-set is because we're in a loop here, with 
638         -- rec_subst, when dealing with a mutually-recursive group
639     new_id = maybeModifyIdInfo (substIdInfo rec_subst is_fragile_occ) id2
640
641         -- Extend the substitution if the unique has changed
642         -- See the notes with substTyVar for the delSubstEnv
643     new_env | new_id /= old_id
644             = extendSubstEnv env old_id (DoneId new_id (idOccInfo old_id))
645             | otherwise 
646             = delSubstEnv env old_id
647 \end{code}
648
649 Now a variant that unconditionally allocates a new unique.
650 It also unconditionally zaps the OccInfo.
651
652 \begin{code}
653 subst_clone_id :: Subst                 -- Substitution to use (lazily) for the rules and worker
654                -> Subst -> (Id, Unique) -- Substitition and Id to transform
655                -> (Subst, Id)           -- Transformed pair
656
657 subst_clone_id rec_subst subst@(Subst in_scope env) (old_id, uniq)
658   = (Subst (in_scope `extendInScopeSet` new_id) new_env, new_id)
659   where
660     id1  = setVarUnique old_id uniq
661     id2  = substIdType subst id1
662
663     new_id  = maybeModifyIdInfo (substIdInfo rec_subst isFragileOcc) id2
664     new_env = extendSubstEnv env old_id (DoneId new_id NoOccInfo)
665
666 substAndCloneIds :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
667 substAndCloneIds subst us ids
668   = mapAccumL (subst_clone_id subst) subst (ids `zip` uniqsFromSupply us)
669
670 substAndCloneRecIds :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
671 substAndCloneRecIds subst us ids
672   = (subst', ids')
673   where
674     (subst', ids') = mapAccumL (subst_clone_id subst') subst
675                                (ids `zip` uniqsFromSupply us)
676
677 substAndCloneId :: Subst -> UniqSupply -> Id -> (Subst, Id)
678 substAndCloneId subst@(Subst in_scope env) us old_id
679   = subst_clone_id subst subst (old_id, uniqFromSupply us)
680 \end{code}
681
682
683 %************************************************************************
684 %*                                                                      *
685 \section{IdInfo substitution}
686 %*                                                                      *
687 %************************************************************************
688
689 \begin{code}
690 substIdInfo :: Subst 
691             -> (OccInfo -> Bool)        -- True <=> zap the occurrence info
692             -> IdInfo
693             -> Maybe IdInfo
694 -- Substitute the 
695 --      rules
696 --      worker info
697 --      LBVar info
698 -- Zap the unfolding 
699 -- Zap the occ info if instructed to do so
700 -- 
701 -- Seq'ing on the returned IdInfo is enough to cause all the 
702 -- substitutions to happen completely
703
704 substIdInfo subst is_fragile_occ info
705   | nothing_to_do = Nothing
706   | otherwise     = Just (info `setOccInfo`       (if zap_occ then NoOccInfo else old_occ)
707                                `setSpecInfo`      substRules  subst old_rules
708                                `setWorkerInfo`    substWorker subst old_wrkr
709                                `setLBVarInfo`     substLBVar  subst old_lbv
710                                `setUnfoldingInfo` noUnfolding)
711                         -- setSpecInfo does a seq
712                         -- setWorkerInfo does a seq
713   where
714     nothing_to_do = not zap_occ && 
715                     isEmptyCoreRules old_rules &&
716                     not (workerExists old_wrkr) &&
717                     hasNoLBVarInfo old_lbv &&
718                     not (hasUnfolding (unfoldingInfo info))
719     
720     zap_occ   = is_fragile_occ old_occ
721     old_occ   = occInfo info
722     old_rules = specInfo info
723     old_wrkr  = workerInfo info
724     old_lbv   = lbvarInfo info
725
726 substIdType :: Subst -> Id -> Id
727 substIdType subst@(Subst in_scope env) id
728   |  noTypeSubst env || isEmptyVarSet (tyVarsOfType old_ty) = id
729   | otherwise                                               = setIdType id (substTy subst old_ty)
730                 -- The tyVarsOfType is cheaper than it looks
731                 -- because we cache the free tyvars of the type
732                 -- in a Note in the id's type itself
733   where
734     old_ty = idType id
735
736 substWorker :: Subst -> WorkerInfo -> WorkerInfo
737         -- Seq'ing on the returned WorkerInfo is enough to cause all the 
738         -- substitutions to happen completely
739
740 substWorker subst NoWorker
741   = NoWorker
742 substWorker subst (HasWorker w a)
743   = case lookupIdSubst subst w of
744         (DoneId w1 _)     -> HasWorker w1 a
745         (DoneEx (Var w1)) -> HasWorker w1 a
746         (DoneEx other)    -> WARN( True, text "substWorker: DoneEx" <+> ppr w )
747                                   NoWorker      -- Worker has got substituted away altogether
748         (ContEx se1 e)    -> WARN( True, text "substWorker: ContEx" <+> ppr w <+> ppr e)
749                                   NoWorker      -- Ditto
750                         
751 substRules :: Subst -> CoreRules -> CoreRules
752         -- Seq'ing on the returned CoreRules is enough to cause all the 
753         -- substitutions to happen completely
754
755 substRules subst rules
756  | isEmptySubst subst = rules
757
758 substRules subst (Rules rules rhs_fvs)
759   = seqRules new_rules `seq` new_rules
760   where
761     new_rules = Rules (map do_subst rules) (substVarSet subst rhs_fvs)
762
763     do_subst rule@(BuiltinRule _) = rule
764     do_subst (Rule name tpl_vars lhs_args rhs)
765         = Rule name tpl_vars' 
766                (map (substExpr subst') lhs_args)
767                (substExpr subst' rhs)
768         where
769           (subst', tpl_vars') = substBndrs subst tpl_vars
770
771 substVarSet subst fvs 
772   = foldVarSet (unionVarSet . subst_fv subst) emptyVarSet fvs
773   where
774     subst_fv subst fv = case lookupIdSubst subst fv of
775                             DoneId fv' _    -> unitVarSet fv'
776                             DoneEx expr     -> exprFreeVars expr
777                             DoneTy ty       -> tyVarsOfType ty 
778                             ContEx se' expr -> substVarSet (setSubstEnv subst se') (exprFreeVars expr)
779
780 substLBVar subst NoLBVarInfo    = NoLBVarInfo
781 substLBVar subst (LBVarInfo ty) = ty1 `seq` LBVarInfo ty1
782                                 where
783                                   ty1 = substTy subst ty
784 \end{code}