8a2622002933a8eaad7a4accdfbfdc33d0c33b84
[ghc.git] / compiler / simplCore / SimplEnv.hs
1 {-
2 (c) The AQUA Project, Glasgow University, 1993-1998
3
4 \section[SimplMonad]{The simplifier Monad}
5 -}
6
7 {-# LANGUAGE CPP #-}
8
9 module SimplEnv (
10 -- * The simplifier mode
11 setMode, getMode, updMode,
12
13 -- * Environments
14 SimplEnv(..), StaticEnv, pprSimplEnv, -- Temp not abstract
15 mkSimplEnv, extendIdSubst,
16 SimplEnv.extendTvSubst, SimplEnv.extendCvSubst,
17 zapSubstEnv, setSubstEnv,
18 getInScope, setInScope, setInScopeSet, modifyInScope, addNewInScopeIds,
19 getSimplRules,
20
21 -- * Substitution results
22 SimplSR(..), mkContEx, substId, lookupRecBndr, refineFromInScope,
23
24 -- * Simplifying 'Id' binders
25 simplNonRecBndr, simplRecBndrs,
26 simplBinder, simplBinders,
27 substTy, substTyVar, getTCvSubst,
28 substCo, substCoVar,
29
30 -- * Floats
31 Floats, emptyFloats, isEmptyFloats, addNonRec, addFloats, extendFloats,
32 wrapFloats, setFloats, zapFloats, addRecFloats, mapFloats,
33 doFloatFromRhs, getFloatBinds
34 ) where
35
36 #include "HsVersions.h"
37
38 import SimplMonad
39 import CoreMonad ( SimplifierMode(..) )
40 import CoreSyn
41 import CoreUtils
42 import Var
43 import VarEnv
44 import VarSet
45 import OrdList
46 import Id
47 import MkCore ( mkWildValBinder )
48 import TysWiredIn
49 import qualified Type
50 import Type hiding ( substTy, substTyVar, substTyVarBndr )
51 import qualified Coercion
52 import Coercion hiding ( substCo, substCoVar, substCoVarBndr )
53 import BasicTypes
54 import MonadUtils
55 import Outputable
56 import Util
57
58 import Data.List
59
60 {-
61 ************************************************************************
62 * *
63 \subsubsection{The @SimplEnv@ type}
64 * *
65 ************************************************************************
66 -}
67
68 data SimplEnv
69 = SimplEnv {
70 ----------- Static part of the environment -----------
71 -- Static in the sense of lexically scoped,
72 -- wrt the original expression
73
74 seMode :: SimplifierMode,
75
76 -- The current substitution
77 seTvSubst :: TvSubstEnv, -- InTyVar |--> OutType
78 seCvSubst :: CvSubstEnv, -- InCoVar |--> OutCoercion
79 seIdSubst :: SimplIdSubst, -- InId |--> OutExpr
80
81 ----------- Dynamic part of the environment -----------
82 -- Dynamic in the sense of describing the setup where
83 -- the expression finally ends up
84
85 -- The current set of in-scope variables
86 -- They are all OutVars, and all bound in this module
87 seInScope :: InScopeSet, -- OutVars only
88 -- Includes all variables bound by seFloats
89 seFloats :: Floats
90 -- See Note [Simplifier floats]
91 }
92
93 type StaticEnv = SimplEnv -- Just the static part is relevant
94
95 pprSimplEnv :: SimplEnv -> SDoc
96 -- Used for debugging; selective
97 pprSimplEnv env
98 = vcat [text "TvSubst:" <+> ppr (seTvSubst env),
99 text "CvSubst:" <+> ppr (seCvSubst env),
100 text "IdSubst:" <+> ppr (seIdSubst env),
101 text "InScope:" <+> in_scope_vars_doc
102 ]
103 where
104 in_scope_vars_doc = pprVarSet (getInScopeVars (seInScope env))
105 (vcat . map ppr_one)
106 ppr_one v | isId v = ppr v <+> ppr (idUnfolding v)
107 | otherwise = ppr v
108
109 type SimplIdSubst = IdEnv SimplSR -- IdId |--> OutExpr
110 -- See Note [Extending the Subst] in CoreSubst
111
112 -- | A substitution result.
113 data SimplSR
114 = DoneEx OutExpr -- Completed term
115 | DoneId OutId -- Completed term variable
116 | ContEx TvSubstEnv -- A suspended substitution
117 CvSubstEnv
118 SimplIdSubst
119 InExpr
120
121 instance Outputable SimplSR where
122 ppr (DoneEx e) = text "DoneEx" <+> ppr e
123 ppr (DoneId v) = text "DoneId" <+> ppr v
124 ppr (ContEx _tv _cv _id e) = vcat [text "ContEx" <+> ppr e {-,
125 ppr (filter_env tv), ppr (filter_env id) -}]
126 -- where
127 -- fvs = exprFreeVars e
128 -- filter_env env = filterVarEnv_Directly keep env
129 -- keep uniq _ = uniq `elemUFM_Directly` fvs
130
131 {-
132 Note [SimplEnv invariants]
133 ~~~~~~~~~~~~~~~~~~~~~~~~~~
134 seInScope:
135 The in-scope part of Subst includes *all* in-scope TyVars and Ids
136 The elements of the set may have better IdInfo than the
137 occurrences of in-scope Ids, and (more important) they will
138 have a correctly-substituted type. So we use a lookup in this
139 set to replace occurrences
140
141 The Ids in the InScopeSet are replete with their Rules,
142 and as we gather info about the unfolding of an Id, we replace
143 it in the in-scope set.
144
145 The in-scope set is actually a mapping OutVar -> OutVar, and
146 in case expressions we sometimes bind
147
148 seIdSubst:
149 The substitution is *apply-once* only, because InIds and OutIds
150 can overlap.
151 For example, we generally omit mappings
152 a77 -> a77
153 from the substitution, when we decide not to clone a77, but it's quite
154 legitimate to put the mapping in the substitution anyway.
155
156 Furthermore, consider
157 let x = case k of I# x77 -> ... in
158 let y = case k of I# x77 -> ... in ...
159 and suppose the body is strict in both x and y. Then the simplifier
160 will pull the first (case k) to the top; so the second (case k) will
161 cancel out, mapping x77 to, well, x77! But one is an in-Id and the
162 other is an out-Id.
163
164 Of course, the substitution *must* applied! Things in its domain
165 simply aren't necessarily bound in the result.
166
167 * substId adds a binding (DoneId new_id) to the substitution if
168 the Id's unique has changed
169
170 Note, though that the substitution isn't necessarily extended
171 if the type of the Id changes. Why not? Because of the next point:
172
173 * We *always, always* finish by looking up in the in-scope set
174 any variable that doesn't get a DoneEx or DoneVar hit in the substitution.
175 Reason: so that we never finish up with a "old" Id in the result.
176 An old Id might point to an old unfolding and so on... which gives a space
177 leak.
178
179 [The DoneEx and DoneVar hits map to "new" stuff.]
180
181 * It follows that substExpr must not do a no-op if the substitution is empty.
182 substType is free to do so, however.
183
184 * When we come to a let-binding (say) we generate new IdInfo, including an
185 unfolding, attach it to the binder, and add this newly adorned binder to
186 the in-scope set. So all subsequent occurrences of the binder will get
187 mapped to the full-adorned binder, which is also the one put in the
188 binding site.
189
190 * The in-scope "set" usually maps x->x; we use it simply for its domain.
191 But sometimes we have two in-scope Ids that are synomyms, and should
192 map to the same target: x->x, y->x. Notably:
193 case y of x { ... }
194 That's why the "set" is actually a VarEnv Var
195 -}
196
197 mkSimplEnv :: SimplifierMode -> SimplEnv
198 mkSimplEnv mode
199 = SimplEnv { seMode = mode
200 , seInScope = init_in_scope
201 , seFloats = emptyFloats
202 , seTvSubst = emptyVarEnv
203 , seCvSubst = emptyVarEnv
204 , seIdSubst = emptyVarEnv }
205 -- The top level "enclosing CC" is "SUBSUMED".
206
207 init_in_scope :: InScopeSet
208 init_in_scope = mkInScopeSet (unitVarSet (mkWildValBinder unitTy))
209 -- See Note [WildCard binders]
210
211 {-
212 Note [WildCard binders]
213 ~~~~~~~~~~~~~~~~~~~~~~~
214 The program to be simplified may have wild binders
215 case e of wild { p -> ... }
216 We want to *rename* them away, so that there are no
217 occurrences of 'wild-id' (with wildCardKey). The easy
218 way to do that is to start of with a representative
219 Id in the in-scope set
220
221 There can be be *occurrences* of wild-id. For example,
222 MkCore.mkCoreApp transforms
223 e (a /# b) --> case (a /# b) of wild { DEFAULT -> e wild }
224 This is ok provided 'wild' isn't free in 'e', and that's the delicate
225 thing. Generally, you want to run the simplifier to get rid of the
226 wild-ids before doing much else.
227
228 It's a very dark corner of GHC. Maybe it should be cleaned up.
229 -}
230
231 getMode :: SimplEnv -> SimplifierMode
232 getMode env = seMode env
233
234 setMode :: SimplifierMode -> SimplEnv -> SimplEnv
235 setMode mode env = env { seMode = mode }
236
237 updMode :: (SimplifierMode -> SimplifierMode) -> SimplEnv -> SimplEnv
238 updMode upd env = env { seMode = upd (seMode env) }
239
240 ---------------------
241 extendIdSubst :: SimplEnv -> Id -> SimplSR -> SimplEnv
242 extendIdSubst env@(SimplEnv {seIdSubst = subst}) var res
243 = ASSERT2( isId var && not (isCoVar var), ppr var )
244 env {seIdSubst = extendVarEnv subst var res}
245
246 extendTvSubst :: SimplEnv -> TyVar -> Type -> SimplEnv
247 extendTvSubst env@(SimplEnv {seTvSubst = tsubst}) var res
248 = ASSERT( isTyVar var )
249 env {seTvSubst = extendVarEnv tsubst var res}
250
251 extendCvSubst :: SimplEnv -> CoVar -> Coercion -> SimplEnv
252 extendCvSubst env@(SimplEnv {seCvSubst = csubst}) var co
253 = ASSERT( isCoVar var )
254 env {seCvSubst = extendVarEnv csubst var co}
255
256 ---------------------
257 getInScope :: SimplEnv -> InScopeSet
258 getInScope env = seInScope env
259
260 setInScopeSet :: SimplEnv -> InScopeSet -> SimplEnv
261 setInScopeSet env in_scope = env {seInScope = in_scope}
262
263 setInScope :: SimplEnv -> SimplEnv -> SimplEnv
264 -- Set the in-scope set, and *zap* the floats
265 setInScope env env_with_scope
266 = env { seInScope = seInScope env_with_scope,
267 seFloats = emptyFloats }
268
269 setFloats :: SimplEnv -> SimplEnv -> SimplEnv
270 -- Set the in-scope set *and* the floats
271 setFloats env env_with_floats
272 = env { seInScope = seInScope env_with_floats,
273 seFloats = seFloats env_with_floats }
274
275 addNewInScopeIds :: SimplEnv -> [CoreBndr] -> SimplEnv
276 -- The new Ids are guaranteed to be freshly allocated
277 addNewInScopeIds env@(SimplEnv { seInScope = in_scope, seIdSubst = id_subst }) vs
278 = env { seInScope = in_scope `extendInScopeSetList` vs,
279 seIdSubst = id_subst `delVarEnvList` vs }
280 -- Why delete? Consider
281 -- let x = a*b in (x, \x -> x+3)
282 -- We add [x |-> a*b] to the substitution, but we must
283 -- _delete_ it from the substitution when going inside
284 -- the (\x -> ...)!
285
286 modifyInScope :: SimplEnv -> CoreBndr -> SimplEnv
287 -- The variable should already be in scope, but
288 -- replace the existing version with this new one
289 -- which has more information
290 modifyInScope env@(SimplEnv {seInScope = in_scope}) v
291 = env {seInScope = extendInScopeSet in_scope v}
292
293 ---------------------
294 zapSubstEnv :: SimplEnv -> SimplEnv
295 zapSubstEnv env = env {seTvSubst = emptyVarEnv, seCvSubst = emptyVarEnv, seIdSubst = emptyVarEnv}
296
297 setSubstEnv :: SimplEnv -> TvSubstEnv -> CvSubstEnv -> SimplIdSubst -> SimplEnv
298 setSubstEnv env tvs cvs ids = env { seTvSubst = tvs, seCvSubst = cvs, seIdSubst = ids }
299
300 mkContEx :: SimplEnv -> InExpr -> SimplSR
301 mkContEx (SimplEnv { seTvSubst = tvs, seCvSubst = cvs, seIdSubst = ids }) e = ContEx tvs cvs ids e
302
303 {-
304 ************************************************************************
305 * *
306 \subsection{Floats}
307 * *
308 ************************************************************************
309
310 Note [Simplifier floats]
311 ~~~~~~~~~~~~~~~~~~~~~~~~~
312 The Floats is a bunch of bindings, classified by a FloatFlag.
313
314 * All of them satisfy the let/app invariant
315
316 Examples
317
318 NonRec x (y:ys) FltLifted
319 Rec [(x,rhs)] FltLifted
320
321 NonRec x* (p:q) FltOKSpec -- RHS is WHNF. Question: why not FltLifted?
322 NonRec x# (y +# 3) FltOkSpec -- Unboxed, but ok-for-spec'n
323
324 NonRec x* (f y) FltCareful -- Strict binding; might fail or diverge
325
326 Can't happen:
327 NonRec x# (a /# b) -- Might fail; does not satisfy let/app
328 NonRec x# (f y) -- Might diverge; does not satisfy let/app
329 -}
330
331 data Floats = Floats (OrdList OutBind) FloatFlag
332 -- See Note [Simplifier floats]
333
334 data FloatFlag
335 = FltLifted -- All bindings are lifted and lazy
336 -- Hence ok to float to top level, or recursive
337
338 | FltOkSpec -- All bindings are FltLifted *or*
339 -- strict (perhaps because unlifted,
340 -- perhaps because of a strict binder),
341 -- *and* ok-for-speculation
342 -- Hence ok to float out of the RHS
343 -- of a lazy non-recursive let binding
344 -- (but not to top level, or into a rec group)
345
346 | FltCareful -- At least one binding is strict (or unlifted)
347 -- and not guaranteed cheap
348 -- Do not float these bindings out of a lazy let
349
350 instance Outputable Floats where
351 ppr (Floats binds ff) = ppr ff $$ ppr (fromOL binds)
352
353 instance Outputable FloatFlag where
354 ppr FltLifted = text "FltLifted"
355 ppr FltOkSpec = text "FltOkSpec"
356 ppr FltCareful = text "FltCareful"
357
358 andFF :: FloatFlag -> FloatFlag -> FloatFlag
359 andFF FltCareful _ = FltCareful
360 andFF FltOkSpec FltCareful = FltCareful
361 andFF FltOkSpec _ = FltOkSpec
362 andFF FltLifted flt = flt
363
364 doFloatFromRhs :: TopLevelFlag -> RecFlag -> Bool -> OutExpr -> SimplEnv -> Bool
365 -- If you change this function look also at FloatIn.noFloatFromRhs
366 doFloatFromRhs lvl rec str rhs (SimplEnv {seFloats = Floats fs ff})
367 = not (isNilOL fs) && want_to_float && can_float
368 where
369 want_to_float = isTopLevel lvl || exprIsCheap rhs || exprIsExpandable rhs
370 -- See Note [Float when cheap or expandable]
371 can_float = case ff of
372 FltLifted -> True
373 FltOkSpec -> isNotTopLevel lvl && isNonRec rec
374 FltCareful -> isNotTopLevel lvl && isNonRec rec && str
375
376 {-
377 Note [Float when cheap or expandable]
378 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
379 We want to float a let from a let if the residual RHS is
380 a) cheap, such as (\x. blah)
381 b) expandable, such as (f b) if f is CONLIKE
382 But there are
383 - cheap things that are not expandable (eg \x. expensive)
384 - expandable things that are not cheap (eg (f b) where b is CONLIKE)
385 so we must take the 'or' of the two.
386 -}
387
388 emptyFloats :: Floats
389 emptyFloats = Floats nilOL FltLifted
390
391 unitFloat :: OutBind -> Floats
392 -- This key function constructs a singleton float with the right form
393 unitFloat bind = Floats (unitOL bind) (flag bind)
394 where
395 flag (Rec {}) = FltLifted
396 flag (NonRec bndr rhs)
397 | not (isStrictId bndr) = FltLifted
398 | exprOkForSpeculation rhs = FltOkSpec -- Unlifted, and lifted but ok-for-spec (eg HNF)
399 | otherwise = ASSERT2( not (isUnliftedType (idType bndr)), ppr bndr )
400 FltCareful
401 -- Unlifted binders can only be let-bound if exprOkForSpeculation holds
402
403 addNonRec :: SimplEnv -> OutId -> OutExpr -> SimplEnv
404 -- Add a non-recursive binding and extend the in-scope set
405 -- The latter is important; the binder may already be in the
406 -- in-scope set (although it might also have been created with newId)
407 -- but it may now have more IdInfo
408 addNonRec env id rhs
409 = id `seq` -- This seq forces the Id, and hence its IdInfo,
410 -- and hence any inner substitutions
411 env { seFloats = seFloats env `addFlts` unitFloat (NonRec id rhs),
412 seInScope = extendInScopeSet (seInScope env) id }
413
414 extendFloats :: SimplEnv -> OutBind -> SimplEnv
415 -- Add these bindings to the floats, and extend the in-scope env too
416 extendFloats env bind
417 = env { seFloats = seFloats env `addFlts` unitFloat bind,
418 seInScope = extendInScopeSetList (seInScope env) bndrs }
419 where
420 bndrs = bindersOf bind
421
422 addFloats :: SimplEnv -> SimplEnv -> SimplEnv
423 -- Add the floats for env2 to env1;
424 -- *plus* the in-scope set for env2, which is bigger
425 -- than that for env1
426 addFloats env1 env2
427 = env1 {seFloats = seFloats env1 `addFlts` seFloats env2,
428 seInScope = seInScope env2 }
429
430 addFlts :: Floats -> Floats -> Floats
431 addFlts (Floats bs1 l1) (Floats bs2 l2)
432 = Floats (bs1 `appOL` bs2) (l1 `andFF` l2)
433
434 zapFloats :: SimplEnv -> SimplEnv
435 zapFloats env = env { seFloats = emptyFloats }
436
437 addRecFloats :: SimplEnv -> SimplEnv -> SimplEnv
438 -- Flattens the floats from env2 into a single Rec group,
439 -- prepends the floats from env1, and puts the result back in env2
440 -- This is all very specific to the way recursive bindings are
441 -- handled; see Simplify.simplRecBind
442 addRecFloats env1 env2@(SimplEnv {seFloats = Floats bs ff})
443 = ASSERT2( case ff of { FltLifted -> True; _ -> False }, ppr (fromOL bs) )
444 env2 {seFloats = seFloats env1 `addFlts` unitFloat (Rec (flattenBinds (fromOL bs)))}
445
446 wrapFloats :: SimplEnv -> OutExpr -> OutExpr
447 -- Wrap the floats around the expression; they should all
448 -- satisfy the let/app invariant, so mkLets should do the job just fine
449 wrapFloats (SimplEnv {seFloats = Floats bs _}) body
450 = foldrOL Let body bs
451
452 getFloatBinds :: SimplEnv -> [CoreBind]
453 getFloatBinds (SimplEnv {seFloats = Floats bs _})
454 = fromOL bs
455
456 isEmptyFloats :: SimplEnv -> Bool
457 isEmptyFloats (SimplEnv {seFloats = Floats bs _})
458 = isNilOL bs
459
460 mapFloats :: SimplEnv -> ((Id,CoreExpr) -> (Id,CoreExpr)) -> SimplEnv
461 mapFloats env@SimplEnv { seFloats = Floats fs ff } fun
462 = env { seFloats = Floats (mapOL app fs) ff }
463 where
464 app (NonRec b e) = case fun (b,e) of (b',e') -> NonRec b' e'
465 app (Rec bs) = Rec (map fun bs)
466
467 {-
468 ************************************************************************
469 * *
470 Substitution of Vars
471 * *
472 ************************************************************************
473
474 Note [Global Ids in the substitution]
475 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
476 We look up even a global (eg imported) Id in the substitution. Consider
477 case X.g_34 of b { (a,b) -> ... case X.g_34 of { (p,q) -> ...} ... }
478 The binder-swap in the occurrence analyser will add a binding
479 for a LocalId version of g (with the same unique though):
480 case X.g_34 of b { (a,b) -> let g_34 = b in
481 ... case X.g_34 of { (p,q) -> ...} ... }
482 So we want to look up the inner X.g_34 in the substitution, where we'll
483 find that it has been substituted by b. (Or conceivably cloned.)
484 -}
485
486 substId :: SimplEnv -> InId -> SimplSR
487 -- Returns DoneEx only on a non-Var expression
488 substId (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
489 = case lookupVarEnv ids v of -- Note [Global Ids in the substitution]
490 Nothing -> DoneId (refineFromInScope in_scope v)
491 Just (DoneId v) -> DoneId (refineFromInScope in_scope v)
492 Just (DoneEx (Var v)) -> DoneId (refineFromInScope in_scope v)
493 Just res -> res -- DoneEx non-var, or ContEx
494
495 -- Get the most up-to-date thing from the in-scope set
496 -- Even though it isn't in the substitution, it may be in
497 -- the in-scope set with better IdInfo
498 refineFromInScope :: InScopeSet -> Var -> Var
499 refineFromInScope in_scope v
500 | isLocalId v = case lookupInScope in_scope v of
501 Just v' -> v'
502 Nothing -> WARN( True, ppr v ) v -- This is an error!
503 | otherwise = v
504
505 lookupRecBndr :: SimplEnv -> InId -> OutId
506 -- Look up an Id which has been put into the envt by simplRecBndrs,
507 -- but where we have not yet done its RHS
508 lookupRecBndr (SimplEnv { seInScope = in_scope, seIdSubst = ids }) v
509 = case lookupVarEnv ids v of
510 Just (DoneId v) -> v
511 Just _ -> pprPanic "lookupRecBndr" (ppr v)
512 Nothing -> refineFromInScope in_scope v
513
514 {-
515 ************************************************************************
516 * *
517 \section{Substituting an Id binder}
518 * *
519 ************************************************************************
520
521
522 These functions are in the monad only so that they can be made strict via seq.
523 -}
524
525 simplBinders :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr])
526 simplBinders env bndrs = mapAccumLM simplBinder env bndrs
527
528 -------------
529 simplBinder :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
530 -- Used for lambda and case-bound variables
531 -- Clone Id if necessary, substitute type
532 -- Return with IdInfo already substituted, but (fragile) occurrence info zapped
533 -- The substitution is extended only if the variable is cloned, because
534 -- we *don't* need to use it to track occurrence info.
535 simplBinder env bndr
536 | isTyVar bndr = do { let (env', tv) = substTyVarBndr env bndr
537 ; seqTyVar tv `seq` return (env', tv) }
538 | otherwise = do { let (env', id) = substIdBndr env bndr
539 ; seqId id `seq` return (env', id) }
540
541 ---------------
542 simplNonRecBndr :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
543 -- A non-recursive let binder
544 simplNonRecBndr env id
545 = do { let (env1, id1) = substIdBndr env id
546 ; seqId id1 `seq` return (env1, id1) }
547
548 ---------------
549 simplRecBndrs :: SimplEnv -> [InBndr] -> SimplM SimplEnv
550 -- Recursive let binders
551 simplRecBndrs env@(SimplEnv {}) ids
552 = do { let (env1, ids1) = mapAccumL substIdBndr env ids
553 ; seqIds ids1 `seq` return env1 }
554
555 ---------------
556 substIdBndr :: SimplEnv -> InBndr -> (SimplEnv, OutBndr)
557 -- Might be a coercion variable
558 substIdBndr env bndr
559 | isCoVar bndr = substCoVarBndr env bndr
560 | otherwise = substNonCoVarIdBndr env bndr
561
562 ---------------
563 substNonCoVarIdBndr
564 :: SimplEnv
565 -> InBndr -- Env and binder to transform
566 -> (SimplEnv, OutBndr)
567 -- Clone Id if necessary, substitute its type
568 -- Return an Id with its
569 -- * Type substituted
570 -- * UnfoldingInfo, Rules, WorkerInfo zapped
571 -- * Fragile OccInfo (only) zapped: Note [Robust OccInfo]
572 -- * Robust info, retained especially arity and demand info,
573 -- so that they are available to occurrences that occur in an
574 -- earlier binding of a letrec
575 --
576 -- For the robust info, see Note [Arity robustness]
577 --
578 -- Augment the substitution if the unique changed
579 -- Extend the in-scope set with the new Id
580 --
581 -- Similar to CoreSubst.substIdBndr, except that
582 -- the type of id_subst differs
583 -- all fragile info is zapped
584 substNonCoVarIdBndr env@(SimplEnv { seInScope = in_scope, seIdSubst = id_subst })
585 old_id
586 = ASSERT2( not (isCoVar old_id), ppr old_id )
587 (env { seInScope = in_scope `extendInScopeSet` new_id,
588 seIdSubst = new_subst }, new_id)
589 where
590 id1 = uniqAway in_scope old_id
591 id2 = substIdType env id1
592 new_id = zapFragileIdInfo id2 -- Zaps rules, worker-info, unfolding
593 -- and fragile OccInfo
594
595 -- Extend the substitution if the unique has changed,
596 -- or there's some useful occurrence information
597 -- See the notes with substTyVarBndr for the delSubstEnv
598 new_subst | new_id /= old_id
599 = extendVarEnv id_subst old_id (DoneId new_id)
600 | otherwise
601 = delVarEnv id_subst old_id
602
603 ------------------------------------
604 seqTyVar :: TyVar -> ()
605 seqTyVar b = b `seq` ()
606
607 seqId :: Id -> ()
608 seqId id = seqType (idType id) `seq`
609 idInfo id `seq`
610 ()
611
612 seqIds :: [Id] -> ()
613 seqIds [] = ()
614 seqIds (id:ids) = seqId id `seq` seqIds ids
615
616 {-
617 Note [Arity robustness]
618 ~~~~~~~~~~~~~~~~~~~~~~~
619 We *do* transfer the arity from from the in_id of a let binding to the
620 out_id. This is important, so that the arity of an Id is visible in
621 its own RHS. For example:
622 f = \x. ....g (\y. f y)....
623 We can eta-reduce the arg to g, because f is a value. But that
624 needs to be visible.
625
626 This interacts with the 'state hack' too:
627 f :: Bool -> IO Int
628 f = \x. case x of
629 True -> f y
630 False -> \s -> ...
631 Can we eta-expand f? Only if we see that f has arity 1, and then we
632 take advantage of the 'state hack' on the result of
633 (f y) :: State# -> (State#, Int) to expand the arity one more.
634
635 There is a disadvantage though. Making the arity visible in the RHS
636 allows us to eta-reduce
637 f = \x -> f x
638 to
639 f = f
640 which technically is not sound. This is very much a corner case, so
641 I'm not worried about it. Another idea is to ensure that f's arity
642 never decreases; its arity started as 1, and we should never eta-reduce
643 below that.
644
645
646 Note [Robust OccInfo]
647 ~~~~~~~~~~~~~~~~~~~~~
648 It's important that we *do* retain the loop-breaker OccInfo, because
649 that's what stops the Id getting inlined infinitely, in the body of
650 the letrec.
651 -}
652
653
654 {-
655 ************************************************************************
656 * *
657 Impedence matching to type substitution
658 * *
659 ************************************************************************
660 -}
661
662 getTCvSubst :: SimplEnv -> TCvSubst
663 getTCvSubst (SimplEnv { seInScope = in_scope, seTvSubst = tv_env, seCvSubst = cv_env })
664 = mkTCvSubst in_scope (tv_env, cv_env)
665
666 substTy :: SimplEnv -> Type -> Type
667 substTy env ty = Type.substTy (getTCvSubst env) ty
668
669 substTyVar :: SimplEnv -> TyVar -> Type
670 substTyVar env tv = Type.substTyVar (getTCvSubst env) tv
671
672 substTyVarBndr :: SimplEnv -> TyVar -> (SimplEnv, TyVar)
673 substTyVarBndr env tv
674 = case Type.substTyVarBndr (getTCvSubst env) tv of
675 (TCvSubst in_scope' tv_env' cv_env', tv')
676 -> (env { seInScope = in_scope', seTvSubst = tv_env', seCvSubst = cv_env' }, tv')
677
678 substCoVar :: SimplEnv -> CoVar -> Coercion
679 substCoVar env tv = Coercion.substCoVar (getTCvSubst env) tv
680
681 substCoVarBndr :: SimplEnv -> CoVar -> (SimplEnv, CoVar)
682 substCoVarBndr env cv
683 = case Coercion.substCoVarBndr (getTCvSubst env) cv of
684 (TCvSubst in_scope' tv_env' cv_env', cv')
685 -> (env { seInScope = in_scope', seTvSubst = tv_env', seCvSubst = cv_env' }, cv')
686
687 substCo :: SimplEnv -> Coercion -> Coercion
688 substCo env co = Coercion.substCo (getTCvSubst env) co
689
690 ------------------
691 substIdType :: SimplEnv -> Id -> Id
692 substIdType (SimplEnv { seInScope = in_scope, seTvSubst = tv_env, seCvSubst = cv_env }) id
693 | (isEmptyVarEnv tv_env && isEmptyVarEnv cv_env)
694 || noFreeVarsOfType old_ty
695 = id
696 | otherwise = Id.setIdType id (Type.substTy (TCvSubst in_scope tv_env cv_env) old_ty)
697 -- The tyCoVarsOfType is cheaper than it looks
698 -- because we cache the free tyvars of the type
699 -- in a Note in the id's type itself
700 where
701 old_ty = idType id