Record evaluated-ness on workers and wrappers
[ghc.git] / compiler / coreSyn / CoreSubst.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 Utility functions on @Core@ syntax
7 -}
8
9 {-# LANGUAGE CPP #-}
10 module CoreSubst (
11 -- * Main data types
12 Subst(..), -- Implementation exported for supercompiler's Renaming.hs only
13 TvSubstEnv, IdSubstEnv, InScopeSet,
14
15 -- ** Substituting into expressions and related types
16 deShadowBinds, substSpec, substRulesForImportedIds,
17 substTy, substCo, substExpr, substExprSC, substBind, substBindSC,
18 substUnfolding, substUnfoldingSC,
19 lookupIdSubst, lookupTCvSubst, substIdOcc,
20 substTickish, substDVarSet,
21
22 -- ** Operations on substitutions
23 emptySubst, mkEmptySubst, mkSubst, mkOpenSubst, substInScope, isEmptySubst,
24 extendIdSubst, extendIdSubstList, extendTCvSubst, extendTvSubstList,
25 extendSubst, extendSubstList, extendSubstWithVar, zapSubstEnv,
26 addInScopeSet, extendInScope, extendInScopeList, extendInScopeIds,
27 isInScope, setInScope,
28 delBndr, delBndrs,
29
30 -- ** Substituting and cloning binders
31 substBndr, substBndrs, substRecBndrs,
32 cloneBndr, cloneBndrs, cloneIdBndr, cloneIdBndrs, cloneRecIdBndrs,
33
34 -- ** Simple expression optimiser
35 simpleOptPgm, simpleOptExpr, simpleOptExprWith,
36 exprIsConApp_maybe, exprIsLiteral_maybe, exprIsLambda_maybe,
37 pushCoArg, pushCoValArg, pushCoTyArg
38 ) where
39
40 #include "HsVersions.h"
41
42 import CoreSyn
43 import CoreFVs
44 import CoreSeq
45 import CoreUtils
46 import Literal ( Literal(MachStr) )
47 import qualified Data.ByteString as BS
48 import OccurAnal( occurAnalyseExpr, occurAnalysePgm )
49
50 import qualified Type
51 import qualified Coercion
52
53 -- We are defining local versions
54 import Type hiding ( substTy, extendTvSubst, extendCvSubst, extendTvSubstList
55 , isInScope, substTyVarBndr, cloneTyVarBndr )
56 import Coercion hiding ( substCo, substCoVarBndr )
57
58 import TyCon ( tyConArity )
59 import DataCon
60 import PrelNames
61 import OptCoercion ( optCoercion )
62 import PprCore ( pprCoreBindings, pprRules )
63 import Module ( Module )
64 import VarSet
65 import VarEnv
66 import Id
67 import Name ( Name )
68 import Var
69 import IdInfo
70 import UniqSupply
71 import Maybes
72 import ErrUtils
73 import DynFlags
74 import BasicTypes ( isAlwaysActive )
75 import Util
76 import Pair
77 import Outputable
78 import PprCore () -- Instances
79 import FastString
80
81 import Data.List
82
83 import TysWiredIn
84
85
86 {-
87 ************************************************************************
88 * *
89 \subsection{Substitutions}
90 * *
91 ************************************************************************
92 -}
93
94 -- | A substitution environment, containing 'Id', 'TyVar', and 'CoVar'
95 -- substitutions.
96 --
97 -- Some invariants apply to how you use the substitution:
98 --
99 -- 1. #in_scope_invariant# The in-scope set contains at least those 'Id's and 'TyVar's that will be in scope /after/
100 -- applying the substitution to a term. Precisely, the in-scope set must be a superset of the free vars of the
101 -- substitution range that might possibly clash with locally-bound variables in the thing being substituted in.
102 --
103 -- 2. #apply_once# You may apply the substitution only /once/
104 --
105 -- There are various ways of setting up the in-scope set such that the first of these invariants hold:
106 --
107 -- * Arrange that the in-scope set really is all the things in scope
108 --
109 -- * Arrange that it's the free vars of the range of the substitution
110 --
111 -- * Make it empty, if you know that all the free vars of the substitution are fresh, and hence can't possibly clash
112 data Subst
113 = Subst InScopeSet -- Variables in in scope (both Ids and TyVars) /after/
114 -- applying the substitution
115 IdSubstEnv -- Substitution from NcIds to CoreExprs
116 TvSubstEnv -- Substitution from TyVars to Types
117 CvSubstEnv -- Substitution from CoVars to Coercions
118
119 -- INVARIANT 1: See #in_scope_invariant#
120 -- This is what lets us deal with name capture properly
121 -- It's a hard invariant to check...
122 --
123 -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with
124 -- Types.TvSubstEnv
125 --
126 -- INVARIANT 3: See Note [Extending the Subst]
127
128 {-
129 Note [Extending the Subst]
130 ~~~~~~~~~~~~~~~~~~~~~~~~~~
131 For a core Subst, which binds Ids as well, we make a different choice for Ids
132 than we do for TyVars.
133
134 For TyVars, see Note [Extending the TCvSubst] with Type.TvSubstEnv
135
136 For Ids, we have a different invariant
137 The IdSubstEnv is extended *only* when the Unique on an Id changes
138 Otherwise, we just extend the InScopeSet
139
140 In consequence:
141
142 * If all subst envs are empty, substExpr would be a
143 no-op, so substExprSC ("short cut") does nothing.
144
145 However, substExpr still goes ahead and substitutes. Reason: we may
146 want to replace existing Ids with new ones from the in-scope set, to
147 avoid space leaks.
148
149 * In substIdBndr, we extend the IdSubstEnv only when the unique changes
150
151 * If the CvSubstEnv, TvSubstEnv and IdSubstEnv are all empty,
152 substExpr does nothing (Note that the above rule for substIdBndr
153 maintains this property. If the incoming envts are both empty, then
154 substituting the type and IdInfo can't change anything.)
155
156 * In lookupIdSubst, we *must* look up the Id in the in-scope set, because
157 it may contain non-trivial changes. Example:
158 (/\a. \x:a. ...x...) Int
159 We extend the TvSubstEnv with [a |-> Int]; but x's unique does not change
160 so we only extend the in-scope set. Then we must look up in the in-scope
161 set when we find the occurrence of x.
162
163 * The requirement to look up the Id in the in-scope set means that we
164 must NOT take no-op short cut when the IdSubst is empty.
165 We must still look up every Id in the in-scope set.
166
167 * (However, we don't need to do so for expressions found in the IdSubst
168 itself, whose range is assumed to be correct wrt the in-scope set.)
169
170 Why do we make a different choice for the IdSubstEnv than the
171 TvSubstEnv and CvSubstEnv?
172
173 * For Ids, we change the IdInfo all the time (e.g. deleting the
174 unfolding), and adding it back later, so using the TyVar convention
175 would entail extending the substitution almost all the time
176
177 * The simplifier wants to look up in the in-scope set anyway, in case it
178 can see a better unfolding from an enclosing case expression
179
180 * For TyVars, only coercion variables can possibly change, and they are
181 easy to spot
182 -}
183
184 -- | An environment for substituting for 'Id's
185 type IdSubstEnv = IdEnv CoreExpr -- Domain is NcIds, i.e. not coercions
186
187 ----------------------------
188 isEmptySubst :: Subst -> Bool
189 isEmptySubst (Subst _ id_env tv_env cv_env)
190 = isEmptyVarEnv id_env && isEmptyVarEnv tv_env && isEmptyVarEnv cv_env
191
192 emptySubst :: Subst
193 emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv emptyVarEnv
194
195 mkEmptySubst :: InScopeSet -> Subst
196 mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv emptyVarEnv
197
198 mkSubst :: InScopeSet -> TvSubstEnv -> CvSubstEnv -> IdSubstEnv -> Subst
199 mkSubst in_scope tvs cvs ids = Subst in_scope ids tvs cvs
200
201 -- | Find the in-scope set: see "CoreSubst#in_scope_invariant"
202 substInScope :: Subst -> InScopeSet
203 substInScope (Subst in_scope _ _ _) = in_scope
204
205 -- | Remove all substitutions for 'Id's and 'Var's that might have been built up
206 -- while preserving the in-scope set
207 zapSubstEnv :: Subst -> Subst
208 zapSubstEnv (Subst in_scope _ _ _) = Subst in_scope emptyVarEnv emptyVarEnv emptyVarEnv
209
210 -- | Add a substitution for an 'Id' to the 'Subst': you must ensure that the in-scope set is
211 -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this
212 extendIdSubst :: Subst -> Id -> CoreExpr -> Subst
213 -- ToDo: add an ASSERT that fvs(subst-result) is already in the in-scope set
214 extendIdSubst (Subst in_scope ids tvs cvs) v r
215 = ASSERT2( isNonCoVarId v, ppr v $$ ppr r )
216 Subst in_scope (extendVarEnv ids v r) tvs cvs
217
218 -- | Adds multiple 'Id' substitutions to the 'Subst': see also 'extendIdSubst'
219 extendIdSubstList :: Subst -> [(Id, CoreExpr)] -> Subst
220 extendIdSubstList (Subst in_scope ids tvs cvs) prs
221 = ASSERT( all (isNonCoVarId . fst) prs )
222 Subst in_scope (extendVarEnvList ids prs) tvs cvs
223
224 -- | Add a substitution for a 'TyVar' to the 'Subst'
225 -- The 'TyVar' *must* be a real TyVar, and not a CoVar
226 -- You must ensure that the in-scope set is such that
227 -- the "CoreSubst#in_scope_invariant" is true after extending
228 -- the substitution like this.
229 extendTvSubst :: Subst -> TyVar -> Type -> Subst
230 extendTvSubst (Subst in_scope ids tvs cvs) tv ty
231 = ASSERT( isTyVar tv )
232 Subst in_scope ids (extendVarEnv tvs tv ty) cvs
233
234 -- | Adds multiple 'TyVar' substitutions to the 'Subst': see also 'extendTvSubst'
235 extendTvSubstList :: Subst -> [(TyVar,Type)] -> Subst
236 extendTvSubstList subst vrs
237 = foldl' extend subst vrs
238 where
239 extend subst (v, r) = extendTvSubst subst v r
240
241 -- | Add a substitution from a 'CoVar' to a 'Coercion' to the 'Subst': you must ensure that the in-scope set is
242 -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this
243 extendCvSubst :: Subst -> CoVar -> Coercion -> Subst
244 extendCvSubst (Subst in_scope ids tvs cvs) v r
245 = ASSERT( isCoVar v )
246 Subst in_scope ids tvs (extendVarEnv cvs v r)
247
248 -- | Add a substitution appropriate to the thing being substituted
249 -- (whether an expression, type, or coercion). See also
250 -- 'extendIdSubst', 'extendTvSubst', 'extendCvSubst'
251 extendSubst :: Subst -> Var -> CoreArg -> Subst
252 extendSubst subst var arg
253 = case arg of
254 Type ty -> ASSERT( isTyVar var ) extendTvSubst subst var ty
255 Coercion co -> ASSERT( isCoVar var ) extendCvSubst subst var co
256 _ -> ASSERT( isId var ) extendIdSubst subst var arg
257
258 extendSubstWithVar :: Subst -> Var -> Var -> Subst
259 extendSubstWithVar subst v1 v2
260 | isTyVar v1 = ASSERT( isTyVar v2 ) extendTvSubst subst v1 (mkTyVarTy v2)
261 | isCoVar v1 = ASSERT( isCoVar v2 ) extendCvSubst subst v1 (mkCoVarCo v2)
262 | otherwise = ASSERT( isId v2 ) extendIdSubst subst v1 (Var v2)
263
264 -- | Add a substitution as appropriate to each of the terms being
265 -- substituted (whether expressions, types, or coercions). See also
266 -- 'extendSubst'.
267 extendSubstList :: Subst -> [(Var,CoreArg)] -> Subst
268 extendSubstList subst [] = subst
269 extendSubstList subst ((var,rhs):prs) = extendSubstList (extendSubst subst var rhs) prs
270
271 -- | Find the substitution for an 'Id' in the 'Subst'
272 lookupIdSubst :: SDoc -> Subst -> Id -> CoreExpr
273 lookupIdSubst doc (Subst in_scope ids _ _) v
274 | not (isLocalId v) = Var v
275 | Just e <- lookupVarEnv ids v = e
276 | Just v' <- lookupInScope in_scope v = Var v'
277 -- Vital! See Note [Extending the Subst]
278 | otherwise = WARN( True, text "CoreSubst.lookupIdSubst" <+> doc <+> ppr v
279 $$ ppr in_scope)
280 Var v
281
282 -- | Find the substitution for a 'TyVar' in the 'Subst'
283 lookupTCvSubst :: Subst -> TyVar -> Type
284 lookupTCvSubst (Subst _ _ tvs cvs) v
285 | isTyVar v
286 = lookupVarEnv tvs v `orElse` Type.mkTyVarTy v
287 | otherwise
288 = mkCoercionTy $ lookupVarEnv cvs v `orElse` mkCoVarCo v
289
290 delBndr :: Subst -> Var -> Subst
291 delBndr (Subst in_scope ids tvs cvs) v
292 | isCoVar v = Subst in_scope ids tvs (delVarEnv cvs v)
293 | isTyVar v = Subst in_scope ids (delVarEnv tvs v) cvs
294 | otherwise = Subst in_scope (delVarEnv ids v) tvs cvs
295
296 delBndrs :: Subst -> [Var] -> Subst
297 delBndrs (Subst in_scope ids tvs cvs) vs
298 = Subst in_scope (delVarEnvList ids vs) (delVarEnvList tvs vs) (delVarEnvList cvs vs)
299 -- Easiest thing is just delete all from all!
300
301 -- | Simultaneously substitute for a bunch of variables
302 -- No left-right shadowing
303 -- ie the substitution for (\x \y. e) a1 a2
304 -- so neither x nor y scope over a1 a2
305 mkOpenSubst :: InScopeSet -> [(Var,CoreArg)] -> Subst
306 mkOpenSubst in_scope pairs = Subst in_scope
307 (mkVarEnv [(id,e) | (id, e) <- pairs, isId id])
308 (mkVarEnv [(tv,ty) | (tv, Type ty) <- pairs])
309 (mkVarEnv [(v,co) | (v, Coercion co) <- pairs])
310
311 ------------------------------
312 isInScope :: Var -> Subst -> Bool
313 isInScope v (Subst in_scope _ _ _) = v `elemInScopeSet` in_scope
314
315 -- | Add the 'Var' to the in-scope set, but do not remove
316 -- any existing substitutions for it
317 addInScopeSet :: Subst -> VarSet -> Subst
318 addInScopeSet (Subst in_scope ids tvs cvs) vs
319 = Subst (in_scope `extendInScopeSetSet` vs) ids tvs cvs
320
321 -- | Add the 'Var' to the in-scope set: as a side effect,
322 -- and remove any existing substitutions for it
323 extendInScope :: Subst -> Var -> Subst
324 extendInScope (Subst in_scope ids tvs cvs) v
325 = Subst (in_scope `extendInScopeSet` v)
326 (ids `delVarEnv` v) (tvs `delVarEnv` v) (cvs `delVarEnv` v)
327
328 -- | Add the 'Var's to the in-scope set: see also 'extendInScope'
329 extendInScopeList :: Subst -> [Var] -> Subst
330 extendInScopeList (Subst in_scope ids tvs cvs) vs
331 = Subst (in_scope `extendInScopeSetList` vs)
332 (ids `delVarEnvList` vs) (tvs `delVarEnvList` vs) (cvs `delVarEnvList` vs)
333
334 -- | Optimized version of 'extendInScopeList' that can be used if you are certain
335 -- all the things being added are 'Id's and hence none are 'TyVar's or 'CoVar's
336 extendInScopeIds :: Subst -> [Id] -> Subst
337 extendInScopeIds (Subst in_scope ids tvs cvs) vs
338 = Subst (in_scope `extendInScopeSetList` vs)
339 (ids `delVarEnvList` vs) tvs cvs
340
341 setInScope :: Subst -> InScopeSet -> Subst
342 setInScope (Subst _ ids tvs cvs) in_scope = Subst in_scope ids tvs cvs
343
344 -- Pretty printing, for debugging only
345
346 instance Outputable Subst where
347 ppr (Subst in_scope ids tvs cvs)
348 = text "<InScope =" <+> in_scope_doc
349 $$ text " IdSubst =" <+> ppr ids
350 $$ text " TvSubst =" <+> ppr tvs
351 $$ text " CvSubst =" <+> ppr cvs
352 <> char '>'
353 where
354 in_scope_doc = pprVarSet (getInScopeVars in_scope) (braces . fsep . map ppr)
355
356 {-
357 ************************************************************************
358 * *
359 Substituting expressions
360 * *
361 ************************************************************************
362 -}
363
364 -- | Apply a substitution to an entire 'CoreExpr'. Remember, you may only
365 -- apply the substitution /once/: see "CoreSubst#apply_once"
366 --
367 -- Do *not* attempt to short-cut in the case of an empty substitution!
368 -- See Note [Extending the Subst]
369 substExprSC :: SDoc -> Subst -> CoreExpr -> CoreExpr
370 substExprSC doc subst orig_expr
371 | isEmptySubst subst = orig_expr
372 | otherwise = -- pprTrace "enter subst-expr" (doc $$ ppr orig_expr) $
373 subst_expr doc subst orig_expr
374
375 substExpr :: SDoc -> Subst -> CoreExpr -> CoreExpr
376 substExpr doc subst orig_expr = subst_expr doc subst orig_expr
377
378 subst_expr :: SDoc -> Subst -> CoreExpr -> CoreExpr
379 subst_expr doc subst expr
380 = go expr
381 where
382 go (Var v) = lookupIdSubst (doc $$ text "subst_expr") subst v
383 go (Type ty) = Type (substTy subst ty)
384 go (Coercion co) = Coercion (substCo subst co)
385 go (Lit lit) = Lit lit
386 go (App fun arg) = App (go fun) (go arg)
387 go (Tick tickish e) = mkTick (substTickish subst tickish) (go e)
388 go (Cast e co) = Cast (go e) (substCo subst co)
389 -- Do not optimise even identity coercions
390 -- Reason: substitution applies to the LHS of RULES, and
391 -- if you "optimise" an identity coercion, you may
392 -- lose a binder. We optimise the LHS of rules at
393 -- construction time
394
395 go (Lam bndr body) = Lam bndr' (subst_expr doc subst' body)
396 where
397 (subst', bndr') = substBndr subst bndr
398
399 go (Let bind body) = Let bind' (subst_expr doc subst' body)
400 where
401 (subst', bind') = substBind subst bind
402
403 go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts)
404 where
405 (subst', bndr') = substBndr subst bndr
406
407 go_alt subst (con, bndrs, rhs) = (con, bndrs', subst_expr doc subst' rhs)
408 where
409 (subst', bndrs') = substBndrs subst bndrs
410
411 -- | Apply a substitution to an entire 'CoreBind', additionally returning an updated 'Subst'
412 -- that should be used by subsequent substitutions.
413 substBind, substBindSC :: Subst -> CoreBind -> (Subst, CoreBind)
414
415 substBindSC subst bind -- Short-cut if the substitution is empty
416 | not (isEmptySubst subst)
417 = substBind subst bind
418 | otherwise
419 = case bind of
420 NonRec bndr rhs -> (subst', NonRec bndr' rhs)
421 where
422 (subst', bndr') = substBndr subst bndr
423 Rec pairs -> (subst', Rec (bndrs' `zip` rhss'))
424 where
425 (bndrs, rhss) = unzip pairs
426 (subst', bndrs') = substRecBndrs subst bndrs
427 rhss' | isEmptySubst subst'
428 = rhss
429 | otherwise
430 = map (subst_expr (text "substBindSC") subst') rhss
431
432 substBind subst (NonRec bndr rhs)
433 = (subst', NonRec bndr' (subst_expr (text "substBind") subst rhs))
434 where
435 (subst', bndr') = substBndr subst bndr
436
437 substBind subst (Rec pairs)
438 = (subst', Rec (bndrs' `zip` rhss'))
439 where
440 (bndrs, rhss) = unzip pairs
441 (subst', bndrs') = substRecBndrs subst bndrs
442 rhss' = map (subst_expr (text "substBind") subst') rhss
443
444 -- | De-shadowing the program is sometimes a useful pre-pass. It can be done simply
445 -- by running over the bindings with an empty substitution, because substitution
446 -- returns a result that has no-shadowing guaranteed.
447 --
448 -- (Actually, within a single /type/ there might still be shadowing, because
449 -- 'substTy' is a no-op for the empty substitution, but that's probably OK.)
450 --
451 -- [Aug 09] This function is not used in GHC at the moment, but seems so
452 -- short and simple that I'm going to leave it here
453 deShadowBinds :: CoreProgram -> CoreProgram
454 deShadowBinds binds = snd (mapAccumL substBind emptySubst binds)
455
456 {-
457 ************************************************************************
458 * *
459 Substituting binders
460 * *
461 ************************************************************************
462
463 Remember that substBndr and friends are used when doing expression
464 substitution only. Their only business is substitution, so they
465 preserve all IdInfo (suitably substituted). For example, we *want* to
466 preserve occ info in rules.
467 -}
468
469 -- | Substitutes a 'Var' for another one according to the 'Subst' given, returning
470 -- the result and an updated 'Subst' that should be used by subsequent substitutions.
471 -- 'IdInfo' is preserved by this process, although it is substituted into appropriately.
472 substBndr :: Subst -> Var -> (Subst, Var)
473 substBndr subst bndr
474 | isTyVar bndr = substTyVarBndr subst bndr
475 | isCoVar bndr = substCoVarBndr subst bndr
476 | otherwise = substIdBndr (text "var-bndr") subst subst bndr
477
478 -- | Applies 'substBndr' to a number of 'Var's, accumulating a new 'Subst' left-to-right
479 substBndrs :: Subst -> [Var] -> (Subst, [Var])
480 substBndrs subst bndrs = mapAccumL substBndr subst bndrs
481
482 -- | Substitute in a mutually recursive group of 'Id's
483 substRecBndrs :: Subst -> [Id] -> (Subst, [Id])
484 substRecBndrs subst bndrs
485 = (new_subst, new_bndrs)
486 where -- Here's the reason we need to pass rec_subst to subst_id
487 (new_subst, new_bndrs) = mapAccumL (substIdBndr (text "rec-bndr") new_subst) subst bndrs
488
489 substIdBndr :: SDoc
490 -> Subst -- ^ Substitution to use for the IdInfo
491 -> Subst -> Id -- ^ Substitution and Id to transform
492 -> (Subst, Id) -- ^ Transformed pair
493 -- NB: unfolding may be zapped
494
495 substIdBndr _doc rec_subst subst@(Subst in_scope env tvs cvs) old_id
496 = -- pprTrace "substIdBndr" (doc $$ ppr old_id $$ ppr in_scope) $
497 (Subst (in_scope `extendInScopeSet` new_id) new_env tvs cvs, new_id)
498 where
499 id1 = uniqAway in_scope old_id -- id1 is cloned if necessary
500 id2 | no_type_change = id1
501 | otherwise = setIdType id1 (substTy subst old_ty)
502
503 old_ty = idType old_id
504 no_type_change = (isEmptyVarEnv tvs && isEmptyVarEnv cvs) ||
505 noFreeVarsOfType old_ty
506
507 -- new_id has the right IdInfo
508 -- The lazy-set is because we're in a loop here, with
509 -- rec_subst, when dealing with a mutually-recursive group
510 new_id = maybeModifyIdInfo mb_new_info id2
511 mb_new_info = substIdInfo rec_subst id2 (idInfo id2)
512 -- NB: unfolding info may be zapped
513
514 -- Extend the substitution if the unique has changed
515 -- See the notes with substTyVarBndr for the delVarEnv
516 new_env | no_change = delVarEnv env old_id
517 | otherwise = extendVarEnv env old_id (Var new_id)
518
519 no_change = id1 == old_id
520 -- See Note [Extending the Subst]
521 -- it's /not/ necessary to check mb_new_info and no_type_change
522
523 {-
524 Now a variant that unconditionally allocates a new unique.
525 It also unconditionally zaps the OccInfo.
526 -}
527
528 -- | Very similar to 'substBndr', but it always allocates a new 'Unique' for
529 -- each variable in its output. It substitutes the IdInfo though.
530 cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id)
531 cloneIdBndr subst us old_id
532 = clone_id subst subst (old_id, uniqFromSupply us)
533
534 -- | Applies 'cloneIdBndr' to a number of 'Id's, accumulating a final
535 -- substitution from left to right
536 cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
537 cloneIdBndrs subst us ids
538 = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us)
539
540 cloneBndrs :: Subst -> UniqSupply -> [Var] -> (Subst, [Var])
541 -- Works for all kinds of variables (typically case binders)
542 -- not just Ids
543 cloneBndrs subst us vs
544 = mapAccumL (\subst (v, u) -> cloneBndr subst u v) subst (vs `zip` uniqsFromSupply us)
545
546 cloneBndr :: Subst -> Unique -> Var -> (Subst, Var)
547 cloneBndr subst uniq v
548 | isTyVar v = cloneTyVarBndr subst v uniq
549 | otherwise = clone_id subst subst (v,uniq) -- Works for coercion variables too
550
551 -- | Clone a mutually recursive group of 'Id's
552 cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id])
553 cloneRecIdBndrs subst us ids
554 = (subst', ids')
555 where
556 (subst', ids') = mapAccumL (clone_id subst') subst
557 (ids `zip` uniqsFromSupply us)
558
559 -- Just like substIdBndr, except that it always makes a new unique
560 -- It is given the unique to use
561 clone_id :: Subst -- Substitution for the IdInfo
562 -> Subst -> (Id, Unique) -- Substitution and Id to transform
563 -> (Subst, Id) -- Transformed pair
564
565 clone_id rec_subst subst@(Subst in_scope idvs tvs cvs) (old_id, uniq)
566 = (Subst (in_scope `extendInScopeSet` new_id) new_idvs tvs new_cvs, new_id)
567 where
568 id1 = setVarUnique old_id uniq
569 id2 = substIdType subst id1
570 new_id = maybeModifyIdInfo (substIdInfo rec_subst id2 (idInfo old_id)) id2
571 (new_idvs, new_cvs) | isCoVar old_id = (idvs, extendVarEnv cvs old_id (mkCoVarCo new_id))
572 | otherwise = (extendVarEnv idvs old_id (Var new_id), cvs)
573
574 {-
575 ************************************************************************
576 * *
577 Types and Coercions
578 * *
579 ************************************************************************
580
581 For types and coercions we just call the corresponding functions in
582 Type and Coercion, but we have to repackage the substitution, from a
583 Subst to a TCvSubst.
584 -}
585
586 substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar)
587 substTyVarBndr (Subst in_scope id_env tv_env cv_env) tv
588 = case Type.substTyVarBndr (TCvSubst in_scope tv_env cv_env) tv of
589 (TCvSubst in_scope' tv_env' cv_env', tv')
590 -> (Subst in_scope' id_env tv_env' cv_env', tv')
591
592 cloneTyVarBndr :: Subst -> TyVar -> Unique -> (Subst, TyVar)
593 cloneTyVarBndr (Subst in_scope id_env tv_env cv_env) tv uniq
594 = case Type.cloneTyVarBndr (TCvSubst in_scope tv_env cv_env) tv uniq of
595 (TCvSubst in_scope' tv_env' cv_env', tv')
596 -> (Subst in_scope' id_env tv_env' cv_env', tv')
597
598 substCoVarBndr :: Subst -> TyVar -> (Subst, TyVar)
599 substCoVarBndr (Subst in_scope id_env tv_env cv_env) cv
600 = case Coercion.substCoVarBndr (TCvSubst in_scope tv_env cv_env) cv of
601 (TCvSubst in_scope' tv_env' cv_env', cv')
602 -> (Subst in_scope' id_env tv_env' cv_env', cv')
603
604 -- | See 'Type.substTy'
605 substTy :: Subst -> Type -> Type
606 substTy subst ty = Type.substTyUnchecked (getTCvSubst subst) ty
607
608 getTCvSubst :: Subst -> TCvSubst
609 getTCvSubst (Subst in_scope _ tenv cenv) = TCvSubst in_scope tenv cenv
610
611 -- | See 'Coercion.substCo'
612 substCo :: Subst -> Coercion -> Coercion
613 substCo subst co = Coercion.substCo (getTCvSubst subst) co
614
615 {-
616 ************************************************************************
617 * *
618 \section{IdInfo substitution}
619 * *
620 ************************************************************************
621 -}
622
623 substIdType :: Subst -> Id -> Id
624 substIdType subst@(Subst _ _ tv_env cv_env) id
625 | (isEmptyVarEnv tv_env && isEmptyVarEnv cv_env) || noFreeVarsOfType old_ty = id
626 | otherwise = setIdType id (substTy subst old_ty)
627 -- The tyCoVarsOfType is cheaper than it looks
628 -- because we cache the free tyvars of the type
629 -- in a Note in the id's type itself
630 where
631 old_ty = idType id
632
633 ------------------
634 -- | Substitute into some 'IdInfo' with regard to the supplied new 'Id'.
635 substIdInfo :: Subst -> Id -> IdInfo -> Maybe IdInfo
636 substIdInfo subst new_id info
637 | nothing_to_do = Nothing
638 | otherwise = Just (info `setRuleInfo` substSpec subst new_id old_rules
639 `setUnfoldingInfo` substUnfolding subst old_unf)
640 where
641 old_rules = ruleInfo info
642 old_unf = unfoldingInfo info
643 nothing_to_do = isEmptyRuleInfo old_rules && not (isFragileUnfolding old_unf)
644
645 ------------------
646 -- | Substitutes for the 'Id's within an unfolding
647 substUnfolding, substUnfoldingSC :: Subst -> Unfolding -> Unfolding
648 -- Seq'ing on the returned Unfolding is enough to cause
649 -- all the substitutions to happen completely
650
651 substUnfoldingSC subst unf -- Short-cut version
652 | isEmptySubst subst = unf
653 | otherwise = substUnfolding subst unf
654
655 substUnfolding subst df@(DFunUnfolding { df_bndrs = bndrs, df_args = args })
656 = df { df_bndrs = bndrs', df_args = args' }
657 where
658 (subst',bndrs') = substBndrs subst bndrs
659 args' = map (substExpr (text "subst-unf:dfun") subst') args
660
661 substUnfolding subst unf@(CoreUnfolding { uf_tmpl = tmpl, uf_src = src })
662 -- Retain an InlineRule!
663 | not (isStableSource src) -- Zap an unstable unfolding, to save substitution work
664 = NoUnfolding
665 | otherwise -- But keep a stable one!
666 = seqExpr new_tmpl `seq`
667 unf { uf_tmpl = new_tmpl }
668 where
669 new_tmpl = substExpr (text "subst-unf") subst tmpl
670
671 substUnfolding _ unf = unf -- NoUnfolding, OtherCon
672
673 ------------------
674 substIdOcc :: Subst -> Id -> Id
675 -- These Ids should not be substituted to non-Ids
676 substIdOcc subst v = case lookupIdSubst (text "substIdOcc") subst v of
677 Var v' -> v'
678 other -> pprPanic "substIdOcc" (vcat [ppr v <+> ppr other, ppr subst])
679
680 ------------------
681 -- | Substitutes for the 'Id's within the 'WorkerInfo' given the new function 'Id'
682 substSpec :: Subst -> Id -> RuleInfo -> RuleInfo
683 substSpec subst new_id (RuleInfo rules rhs_fvs)
684 = seqRuleInfo new_spec `seq` new_spec
685 where
686 subst_ru_fn = const (idName new_id)
687 new_spec = RuleInfo (map (substRule subst subst_ru_fn) rules)
688 (substDVarSet subst rhs_fvs)
689
690 ------------------
691 substRulesForImportedIds :: Subst -> [CoreRule] -> [CoreRule]
692 substRulesForImportedIds subst rules
693 = map (substRule subst not_needed) rules
694 where
695 not_needed name = pprPanic "substRulesForImportedIds" (ppr name)
696
697 ------------------
698 substRule :: Subst -> (Name -> Name) -> CoreRule -> CoreRule
699
700 -- The subst_ru_fn argument is applied to substitute the ru_fn field
701 -- of the rule:
702 -- - Rules for *imported* Ids never change ru_fn
703 -- - Rules for *local* Ids are in the IdInfo for that Id,
704 -- and the ru_fn field is simply replaced by the new name
705 -- of the Id
706 substRule _ _ rule@(BuiltinRule {}) = rule
707 substRule subst subst_ru_fn rule@(Rule { ru_bndrs = bndrs, ru_args = args
708 , ru_fn = fn_name, ru_rhs = rhs
709 , ru_local = is_local })
710 = rule { ru_bndrs = bndrs'
711 , ru_fn = if is_local
712 then subst_ru_fn fn_name
713 else fn_name
714 , ru_args = map (substExpr doc subst') args
715 , ru_rhs = substExpr (text "foo") subst' rhs }
716 -- Do NOT optimise the RHS (previously we did simplOptExpr here)
717 -- See Note [Substitute lazily]
718 where
719 doc = text "subst-rule" <+> ppr fn_name
720 (subst', bndrs') = substBndrs subst bndrs
721
722 ------------------
723 substVects :: Subst -> [CoreVect] -> [CoreVect]
724 substVects subst = map (substVect subst)
725
726 ------------------
727 substVect :: Subst -> CoreVect -> CoreVect
728 substVect subst (Vect v rhs) = Vect v (simpleOptExprWith subst rhs)
729 substVect _subst vd@(NoVect _) = vd
730 substVect _subst vd@(VectType _ _ _) = vd
731 substVect _subst vd@(VectClass _) = vd
732 substVect _subst vd@(VectInst _) = vd
733
734 ------------------
735 substDVarSet :: Subst -> DVarSet -> DVarSet
736 substDVarSet subst fvs
737 = mkDVarSet $ fst $ foldr (subst_fv subst) ([], emptyVarSet) $ dVarSetElems fvs
738 where
739 subst_fv subst fv acc
740 | isId fv = expr_fvs (lookupIdSubst (text "substDVarSet") subst fv) isLocalVar emptyVarSet $! acc
741 | otherwise = tyCoFVsOfType (lookupTCvSubst subst fv) (const True) emptyVarSet $! acc
742
743 ------------------
744 substTickish :: Subst -> Tickish Id -> Tickish Id
745 substTickish subst (Breakpoint n ids)
746 = Breakpoint n (map do_one ids)
747 where
748 do_one = getIdFromTrivialExpr . lookupIdSubst (text "subst_tickish") subst
749 substTickish _subst other = other
750
751 {- Note [Substitute lazily]
752 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
753 The functions that substitute over IdInfo must be pretty lazy, because
754 they are knot-tied by substRecBndrs.
755
756 One case in point was Trac #10627 in which a rule for a function 'f'
757 referred to 'f' (at a differnet type) on the RHS. But instead of just
758 substituting in the rhs of the rule, we were calling simpleOptExpr, which
759 looked at the idInfo for 'f'; result <<loop>>.
760
761 In any case we don't need to optimise the RHS of rules, or unfoldings,
762 because the simplifier will do that.
763
764
765 Note [substTickish]
766 ~~~~~~~~~~~~~~~~~~~~~~
767 A Breakpoint contains a list of Ids. What happens if we ever want to
768 substitute an expression for one of these Ids?
769
770 First, we ensure that we only ever substitute trivial expressions for
771 these Ids, by marking them as NoOccInfo in the occurrence analyser.
772 Then, when substituting for the Id, we unwrap any type applications
773 and abstractions to get back to an Id, with getIdFromTrivialExpr.
774
775 Second, we have to ensure that we never try to substitute a literal
776 for an Id in a breakpoint. We ensure this by never storing an Id with
777 an unlifted type in a Breakpoint - see Coverage.mkTickish.
778 Breakpoints can't handle free variables with unlifted types anyway.
779 -}
780
781 {-
782 Note [Worker inlining]
783 ~~~~~~~~~~~~~~~~~~~~~~
784 A worker can get sustituted away entirely.
785 - it might be trivial
786 - it might simply be very small
787 We do not treat an InlWrapper as an 'occurrence' in the occurrence
788 analyser, so it's possible that the worker is not even in scope any more.
789
790 In all all these cases we simply drop the special case, returning to
791 InlVanilla. The WARN is just so I can see if it happens a lot.
792
793
794 ************************************************************************
795 * *
796 The Very Simple Optimiser
797 * *
798 ************************************************************************
799
800 Note [Getting the map/coerce RULE to work]
801 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
802 We wish to allow the "map/coerce" RULE to fire:
803
804 {-# RULES "map/coerce" map coerce = coerce #-}
805
806 The naive core produced for this is
807
808 forall a b (dict :: Coercible * a b).
809 map @a @b (coerce @a @b @dict) = coerce @[a] @[b] @dict'
810
811 where dict' :: Coercible [a] [b]
812 dict' = ...
813
814 This matches literal uses of `map coerce` in code, but that's not what we
815 want. We want it to match, say, `map MkAge` (where newtype Age = MkAge Int)
816 too. Some of this is addressed by compulsorily unfolding coerce on the LHS,
817 yielding
818
819 forall a b (dict :: Coercible * a b).
820 map @a @b (\(x :: a) -> case dict of
821 MkCoercible (co :: a ~R# b) -> x |> co) = ...
822
823 Getting better. But this isn't exactly what gets produced. This is because
824 Coercible essentially has ~R# as a superclass, and superclasses get eagerly
825 extracted during solving. So we get this:
826
827 forall a b (dict :: Coercible * a b).
828 case Coercible_SCSel @* @a @b dict of
829 _ [Dead] -> map @a @b (\(x :: a) -> case dict of
830 MkCoercible (co :: a ~R# b) -> x |> co) = ...
831
832 Unfortunately, this still abstracts over a Coercible dictionary. We really
833 want it to abstract over the ~R# evidence. So, we have Desugar.unfold_coerce,
834 which transforms the above to (see also Note [Desugaring coerce as cast] in
835 Desugar)
836
837 forall a b (co :: a ~R# b).
838 let dict = MkCoercible @* @a @b co in
839 case Coercible_SCSel @* @a @b dict of
840 _ [Dead] -> map @a @b (\(x :: a) -> case dict of
841 MkCoercible (co :: a ~R# b) -> x |> co) = let dict = ... in ...
842
843 Now, we need simpleOptExpr to fix this up. It does so by taking three
844 separate actions:
845 1. Inline certain non-recursive bindings. The choice whether to inline
846 is made in maybe_substitute. Note the rather specific check for
847 MkCoercible in there.
848
849 2. Stripping case expressions like the Coercible_SCSel one.
850 See the `Case` case of simple_opt_expr's `go` function.
851
852 3. Look for case expressions that unpack something that was
853 just packed and inline them. This is also done in simple_opt_expr's
854 `go` function.
855
856 This is all a fair amount of special-purpose hackery, but it's for
857 a good cause. And it won't hurt other RULES and such that it comes across.
858
859 -}
860
861 simpleOptExpr :: CoreExpr -> CoreExpr
862 -- Do simple optimisation on an expression
863 -- The optimisation is very straightforward: just
864 -- inline non-recursive bindings that are used only once,
865 -- or where the RHS is trivial
866 --
867 -- We also inline bindings that bind a Eq# box: see
868 -- See Note [Getting the map/coerce RULE to work].
869 --
870 -- The result is NOT guaranteed occurrence-analysed, because
871 -- in (let x = y in ....) we substitute for x; so y's occ-info
872 -- may change radically
873
874 simpleOptExpr expr
875 = -- pprTrace "simpleOptExpr" (ppr init_subst $$ ppr expr)
876 simpleOptExprWith init_subst expr
877 where
878 init_subst = mkEmptySubst (mkInScopeSet (exprFreeVars expr))
879 -- It's potentially important to make a proper in-scope set
880 -- Consider let x = ..y.. in \y. ...x...
881 -- Then we should remember to clone y before substituting
882 -- for x. It's very unlikely to occur, because we probably
883 -- won't *be* substituting for x if it occurs inside a
884 -- lambda.
885 --
886 -- It's a bit painful to call exprFreeVars, because it makes
887 -- three passes instead of two (occ-anal, and go)
888
889 simpleOptExprWith :: Subst -> InExpr -> OutExpr
890 simpleOptExprWith subst expr = simple_opt_expr subst (occurAnalyseExpr expr)
891
892 ----------------------
893 simpleOptPgm :: DynFlags -> Module
894 -> CoreProgram -> [CoreRule] -> [CoreVect]
895 -> IO (CoreProgram, [CoreRule], [CoreVect])
896 simpleOptPgm dflags this_mod binds rules vects
897 = do { dumpIfSet_dyn dflags Opt_D_dump_occur_anal "Occurrence analysis"
898 (pprCoreBindings occ_anald_binds $$ pprRules rules );
899
900 ; return (reverse binds', substRulesForImportedIds subst' rules, substVects subst' vects) }
901 where
902 occ_anald_binds = occurAnalysePgm this_mod (\_ -> False) {- No rules active -}
903 rules vects emptyVarEnv binds
904 (subst', binds') = foldl do_one (emptySubst, []) occ_anald_binds
905
906 do_one (subst, binds') bind
907 = case simple_opt_bind subst bind of
908 (subst', Nothing) -> (subst', binds')
909 (subst', Just bind') -> (subst', bind':binds')
910
911 -- In these functions the substitution maps InVar -> OutExpr
912
913 ----------------------
914 simple_opt_expr :: Subst -> InExpr -> OutExpr
915 simple_opt_expr subst expr
916 = go expr
917 where
918 in_scope_env = (substInScope subst, simpleUnfoldingFun)
919
920 go (Var v) = lookupIdSubst (text "simpleOptExpr") subst v
921 go (App e1 e2) = simple_app subst e1 [go e2]
922 go (Type ty) = Type (substTy subst ty)
923 go (Coercion co) = Coercion (optCoercion (getTCvSubst subst) co)
924 go (Lit lit) = Lit lit
925 go (Tick tickish e) = mkTick (substTickish subst tickish) (go e)
926 go (Cast e co) | isReflCo co' = go e
927 | otherwise = Cast (go e) co'
928 where
929 co' = optCoercion (getTCvSubst subst) co
930
931 go (Let bind body) = case simple_opt_bind subst bind of
932 (subst', Nothing) -> simple_opt_expr subst' body
933 (subst', Just bind) -> Let bind (simple_opt_expr subst' body)
934
935 go lam@(Lam {}) = go_lam [] subst lam
936 go (Case e b ty as)
937 -- See Note [Getting the map/coerce RULE to work]
938 | isDeadBinder b
939 , Just (con, _tys, es) <- exprIsConApp_maybe in_scope_env e'
940 , Just (altcon, bs, rhs) <- findAlt (DataAlt con) as
941 = case altcon of
942 DEFAULT -> go rhs
943 _ -> mkLets (catMaybes mb_binds) $ simple_opt_expr subst' rhs
944 where (subst', mb_binds) = mapAccumL simple_opt_out_bind subst
945 (zipEqual "simpleOptExpr" bs es)
946
947 -- Note [Getting the map/coerce RULE to work]
948 | isDeadBinder b
949 , [(DEFAULT, _, rhs)] <- as
950 , isCoercionType (varType b)
951 , (Var fun, _args) <- collectArgs e
952 , fun `hasKey` coercibleSCSelIdKey
953 -- without this last check, we get #11230
954 = go rhs
955
956 | otherwise
957 = Case e' b' (substTy subst ty)
958 (map (go_alt subst') as)
959 where
960 e' = go e
961 (subst', b') = subst_opt_bndr subst b
962
963 ----------------------
964 go_alt subst (con, bndrs, rhs)
965 = (con, bndrs', simple_opt_expr subst' rhs)
966 where
967 (subst', bndrs') = subst_opt_bndrs subst bndrs
968
969 ----------------------
970 -- go_lam tries eta reduction
971 go_lam bs' subst (Lam b e)
972 = go_lam (b':bs') subst' e
973 where
974 (subst', b') = subst_opt_bndr subst b
975 go_lam bs' subst e
976 | Just etad_e <- tryEtaReduce bs e' = etad_e
977 | otherwise = mkLams bs e'
978 where
979 bs = reverse bs'
980 e' = simple_opt_expr subst e
981
982 ----------------------
983 -- simple_app collects arguments for beta reduction
984 simple_app :: Subst -> InExpr -> [OutExpr] -> CoreExpr
985 simple_app subst (App e1 e2) as
986 = simple_app subst e1 (simple_opt_expr subst e2 : as)
987 simple_app subst (Lam b e) (a:as)
988 = case maybe_substitute subst b a of
989 Just ext_subst -> simple_app ext_subst e as
990 Nothing -> Let (NonRec b2 a) (simple_app subst' e as)
991 where
992 (subst', b') = subst_opt_bndr subst b
993 b2 = add_info subst' b b'
994 simple_app subst (Var v) as
995 | isCompulsoryUnfolding (idUnfolding v)
996 , isAlwaysActive (idInlineActivation v)
997 -- See Note [Unfold compulsory unfoldings in LHSs]
998 = simple_app subst (unfoldingTemplate (idUnfolding v)) as
999 simple_app subst (Tick t e) as
1000 -- Okay to do "(Tick t e) x ==> Tick t (e x)"?
1001 | t `tickishScopesLike` SoftScope
1002 = mkTick t $ simple_app subst e as
1003 simple_app subst e as
1004 = foldl App (simple_opt_expr subst e) as
1005
1006 ----------------------
1007 simple_opt_bind,simple_opt_bind' :: Subst -> CoreBind -> (Subst, Maybe CoreBind)
1008 simple_opt_bind s b -- Can add trace stuff here
1009 = simple_opt_bind' s b
1010
1011 simple_opt_bind' subst (Rec prs)
1012 = (subst'', res_bind)
1013 where
1014 res_bind = Just (Rec (reverse rev_prs'))
1015 (subst', bndrs') = subst_opt_bndrs subst (map fst prs)
1016 (subst'', rev_prs') = foldl do_pr (subst', []) (prs `zip` bndrs')
1017 do_pr (subst, prs) ((b,r), b')
1018 = case maybe_substitute subst b r2 of
1019 Just subst' -> (subst', prs)
1020 Nothing -> (subst, (b2,r2):prs)
1021 where
1022 b2 = add_info subst b b'
1023 r2 = simple_opt_expr subst r
1024
1025 simple_opt_bind' subst (NonRec b r)
1026 = simple_opt_out_bind subst (b, simple_opt_expr subst r)
1027
1028 ----------------------
1029 simple_opt_out_bind :: Subst -> (InVar, OutExpr) -> (Subst, Maybe CoreBind)
1030 simple_opt_out_bind subst (b, r')
1031 | Just ext_subst <- maybe_substitute subst b r'
1032 = (ext_subst, Nothing)
1033 | otherwise
1034 = (subst', Just (NonRec b2 r'))
1035 where
1036 (subst', b') = subst_opt_bndr subst b
1037 b2 = add_info subst' b b'
1038
1039 ----------------------
1040 maybe_substitute :: Subst -> InVar -> OutExpr -> Maybe Subst
1041 -- (maybe_substitute subst in_var out_rhs)
1042 -- either extends subst with (in_var -> out_rhs)
1043 -- or returns Nothing
1044 maybe_substitute subst b r
1045 | Type ty <- r -- let a::* = TYPE ty in <body>
1046 = ASSERT( isTyVar b )
1047 Just (extendTvSubst subst b ty)
1048
1049 | Coercion co <- r
1050 = ASSERT( isCoVar b )
1051 Just (extendCvSubst subst b co)
1052
1053 | isId b -- let x = e in <body>
1054 , not (isCoVar b) -- See Note [Do not inline CoVars unconditionally]
1055 -- in SimplUtils
1056 , safe_to_inline (idOccInfo b)
1057 , isAlwaysActive (idInlineActivation b) -- Note [Inline prag in simplOpt]
1058 , not (isStableUnfolding (idUnfolding b))
1059 , not (isExportedId b)
1060 , let id_ty = idType b
1061 -- A levity-polymorphic id? Impossible you say?
1062 -- See Note [Levity polymorphism invariants] in CoreSyn
1063 -- Ah, but it *is* possible in the compulsory unfolding of unsafeCoerce#
1064 -- This check prevents the isUnliftedType check from panicking.
1065 , isTypeLevPoly id_ty || not (isUnliftedType (idType b)) || exprOkForSpeculation r
1066 = Just (extendIdSubst subst b r)
1067
1068 | otherwise
1069 = Nothing
1070 where
1071 -- Unconditionally safe to inline
1072 safe_to_inline :: OccInfo -> Bool
1073 safe_to_inline (IAmALoopBreaker {}) = False
1074 safe_to_inline IAmDead = True
1075 safe_to_inline (OneOcc in_lam one_br _) = (not in_lam && one_br) || trivial
1076 safe_to_inline NoOccInfo = trivial
1077
1078 trivial | exprIsTrivial r = True
1079 | (Var fun, args) <- collectArgs r
1080 , Just dc <- isDataConWorkId_maybe fun
1081 , dc `hasKey` heqDataConKey || dc `hasKey` coercibleDataConKey
1082 , all exprIsTrivial args = True
1083 -- See Note [Getting the map/coerce RULE to work]
1084 | otherwise = False
1085
1086 ----------------------
1087 subst_opt_bndr :: Subst -> InVar -> (Subst, OutVar)
1088 subst_opt_bndr subst bndr
1089 | isTyVar bndr = substTyVarBndr subst bndr
1090 | isCoVar bndr = substCoVarBndr subst bndr
1091 | otherwise = subst_opt_id_bndr subst bndr
1092
1093 subst_opt_id_bndr :: Subst -> InId -> (Subst, OutId)
1094 -- Nuke all fragile IdInfo, unfolding, and RULES;
1095 -- it gets added back later by add_info
1096 -- Rather like SimplEnv.substIdBndr
1097 --
1098 -- It's important to zap fragile OccInfo (which CoreSubst.substIdBndr
1099 -- carefully does not do) because simplOptExpr invalidates it
1100
1101 subst_opt_id_bndr subst@(Subst in_scope id_subst tv_subst cv_subst) old_id
1102 = (Subst new_in_scope new_id_subst tv_subst cv_subst, new_id)
1103 where
1104 id1 = uniqAway in_scope old_id
1105 id2 = setIdType id1 (substTy subst (idType old_id))
1106 new_id = zapFragileIdInfo id2
1107 -- Zaps rules, worker-info, unfolding, and fragile OccInfo
1108 -- The unfolding and rules will get added back later, by add_info
1109
1110 new_in_scope = in_scope `extendInScopeSet` new_id
1111
1112 -- Extend the substitution if the unique has changed,
1113 -- or there's some useful occurrence information
1114 -- See the notes with substTyVarBndr for the delSubstEnv
1115 new_id_subst | new_id /= old_id
1116 = extendVarEnv id_subst old_id (Var new_id)
1117 | otherwise
1118 = delVarEnv id_subst old_id
1119
1120 ----------------------
1121 subst_opt_bndrs :: Subst -> [InVar] -> (Subst, [OutVar])
1122 subst_opt_bndrs subst bndrs
1123 = mapAccumL subst_opt_bndr subst bndrs
1124
1125 ----------------------
1126 add_info :: Subst -> InVar -> OutVar -> OutVar
1127 add_info subst old_bndr new_bndr
1128 | isTyVar old_bndr = new_bndr
1129 | otherwise = maybeModifyIdInfo mb_new_info new_bndr
1130 where
1131 mb_new_info = substIdInfo subst new_bndr (idInfo old_bndr)
1132
1133 simpleUnfoldingFun :: IdUnfoldingFun
1134 simpleUnfoldingFun id
1135 | isAlwaysActive (idInlineActivation id) = idUnfolding id
1136 | otherwise = noUnfolding
1137
1138 {-
1139 Note [Inline prag in simplOpt]
1140 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1141 If there's an INLINE/NOINLINE pragma that restricts the phase in
1142 which the binder can be inlined, we don't inline here; after all,
1143 we don't know what phase we're in. Here's an example
1144
1145 foo :: Int -> Int -> Int
1146 {-# INLINE foo #-}
1147 foo m n = inner m
1148 where
1149 {-# INLINE [1] inner #-}
1150 inner m = m+n
1151
1152 bar :: Int -> Int
1153 bar n = foo n 1
1154
1155 When inlining 'foo' in 'bar' we want the let-binding for 'inner'
1156 to remain visible until Phase 1
1157
1158 Note [Unfold compulsory unfoldings in LHSs]
1159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1160 When the user writes `RULES map coerce = coerce` as a rule, the rule
1161 will only ever match if simpleOptExpr replaces coerce by its unfolding
1162 on the LHS, because that is the core that the rule matching engine
1163 will find. So do that for everything that has a compulsory
1164 unfolding. Also see Note [Desugaring coerce as cast] in Desugar.
1165
1166 However, we don't want to inline 'seq', which happens to also have a
1167 compulsory unfolding, so we only do this unfolding only for things
1168 that are always-active. See Note [User-defined RULES for seq] in MkId.
1169
1170
1171 ************************************************************************
1172 * *
1173 exprIsConApp_maybe
1174 * *
1175 ************************************************************************
1176
1177 Note [exprIsConApp_maybe]
1178 ~~~~~~~~~~~~~~~~~~~~~~~~~
1179 exprIsConApp_maybe is a very important function. There are two principal
1180 uses:
1181 * case e of { .... }
1182 * cls_op e, where cls_op is a class operation
1183
1184 In both cases you want to know if e is of form (C e1..en) where C is
1185 a data constructor.
1186
1187 However e might not *look* as if
1188
1189
1190 Note [exprIsConApp_maybe on literal strings]
1191 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1192 See #9400.
1193
1194 Conceptually, a string literal "abc" is just ('a':'b':'c':[]), but in Core
1195 they are represented as unpackCString# "abc"# by MkCore.mkStringExprFS, or
1196 unpackCStringUtf8# when the literal contains multi-byte UTF8 characters.
1197
1198 For optimizations we want to be able to treat it as a list, so they can be
1199 decomposed when used in a case-statement. exprIsConApp_maybe detects those
1200 calls to unpackCString# and returns:
1201
1202 Just (':', [Char], ['a', unpackCString# "bc"]).
1203
1204 We need to be careful about UTF8 strings here. ""# contains a ByteString, so
1205 we must parse it back into a FastString to split off the first character.
1206 That way we can treat unpackCString# and unpackCStringUtf8# in the same way.
1207
1208 Note [Push coercions in exprIsConApp_maybe]
1209 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1210 In Trac #13025 I found a case where we had
1211 op (df @t1 @t2) -- op is a ClassOp
1212 where
1213 df = (/\a b. K e1 e2) |> g
1214
1215 To get this to come out we need to simplify on the fly
1216 ((/\a b. K e1 e2) |> g) @t1 @t2
1217
1218 Hence the use of pushCoArgs.
1219 -}
1220
1221 data ConCont = CC [CoreExpr] Coercion
1222 -- Substitution already applied
1223
1224 -- | Returns @Just (dc, [t1..tk], [x1..xn])@ if the argument expression is
1225 -- a *saturated* constructor application of the form @dc t1..tk x1 .. xn@,
1226 -- where t1..tk are the *universally-qantified* type args of 'dc'
1227 exprIsConApp_maybe :: InScopeEnv -> CoreExpr -> Maybe (DataCon, [Type], [CoreExpr])
1228 exprIsConApp_maybe (in_scope, id_unf) expr
1229 = go (Left in_scope) expr (CC [] (mkRepReflCo (exprType expr)))
1230 where
1231 go :: Either InScopeSet Subst
1232 -- Left in-scope means "empty substitution"
1233 -- Right subst means "apply this substitution to the CoreExpr"
1234 -> CoreExpr -> ConCont
1235 -> Maybe (DataCon, [Type], [CoreExpr])
1236 go subst (Tick t expr) cont
1237 | not (tickishIsCode t) = go subst expr cont
1238 go subst (Cast expr co1) (CC args co2)
1239 | Just (args', co1') <- pushCoArgs (subst_co subst co1) args
1240 -- See Note [Push coercions in exprIsConApp_maybe]
1241 = go subst expr (CC args' (co1' `mkTransCo` co2))
1242 go subst (App fun arg) (CC args co)
1243 = go subst fun (CC (subst_arg subst arg : args) co)
1244 go subst (Lam var body) (CC (arg:args) co)
1245 | exprIsTrivial arg -- Don't duplicate stuff!
1246 = go (extend subst var arg) body (CC args co)
1247 go (Right sub) (Var v) cont
1248 = go (Left (substInScope sub))
1249 (lookupIdSubst (text "exprIsConApp" <+> ppr expr) sub v)
1250 cont
1251
1252 go (Left in_scope) (Var fun) cont@(CC args co)
1253
1254 | Just con <- isDataConWorkId_maybe fun
1255 , count isValArg args == idArity fun
1256 = pushCoDataCon con args co
1257
1258 -- Look through dictionary functions; see Note [Unfolding DFuns]
1259 | DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = dfun_args } <- unfolding
1260 , bndrs `equalLength` args -- See Note [DFun arity check]
1261 , let subst = mkOpenSubst in_scope (bndrs `zip` args)
1262 = pushCoDataCon con (map (substExpr (text "exprIsConApp1") subst) dfun_args) co
1263
1264 -- Look through unfoldings, but only arity-zero one;
1265 -- if arity > 0 we are effectively inlining a function call,
1266 -- and that is the business of callSiteInline.
1267 -- In practice, without this test, most of the "hits" were
1268 -- CPR'd workers getting inlined back into their wrappers,
1269 | idArity fun == 0
1270 , Just rhs <- expandUnfolding_maybe unfolding
1271 , let in_scope' = extendInScopeSetSet in_scope (exprFreeVars rhs)
1272 = go (Left in_scope') rhs cont
1273
1274 | (fun `hasKey` unpackCStringIdKey)
1275 || (fun `hasKey` unpackCStringUtf8IdKey)
1276 , [Lit (MachStr str)] <- args
1277 = dealWithStringLiteral fun str co
1278 where
1279 unfolding = id_unf fun
1280
1281 go _ _ _ = Nothing
1282
1283 ----------------------------
1284 -- Operations on the (Either InScopeSet CoreSubst)
1285 -- The Left case is wildly dominant
1286 subst_co (Left {}) co = co
1287 subst_co (Right s) co = CoreSubst.substCo s co
1288
1289 subst_arg (Left {}) e = e
1290 subst_arg (Right s) e = substExpr (text "exprIsConApp2") s e
1291
1292 extend (Left in_scope) v e = Right (extendSubst (mkEmptySubst in_scope) v e)
1293 extend (Right s) v e = Right (extendSubst s v e)
1294
1295
1296 -- See Note [exprIsConApp_maybe on literal strings]
1297 dealWithStringLiteral :: Var -> BS.ByteString -> Coercion
1298 -> Maybe (DataCon, [Type], [CoreExpr])
1299
1300 -- This is not possible with user-supplied empty literals, MkCore.mkStringExprFS
1301 -- turns those into [] automatically, but just in case something else in GHC
1302 -- generates a string literal directly.
1303 dealWithStringLiteral _ str co
1304 | BS.null str
1305 = pushCoDataCon nilDataCon [Type charTy] co
1306
1307 dealWithStringLiteral fun str co
1308 = let strFS = mkFastStringByteString str
1309
1310 char = mkConApp charDataCon [mkCharLit (headFS strFS)]
1311 charTail = fastStringToByteString (tailFS strFS)
1312
1313 -- In singleton strings, just add [] instead of unpackCstring# ""#.
1314 rest = if BS.null charTail
1315 then mkConApp nilDataCon [Type charTy]
1316 else App (Var fun)
1317 (Lit (MachStr charTail))
1318
1319 in pushCoDataCon consDataCon [Type charTy, char, rest] co
1320
1321 {-
1322 Note [Unfolding DFuns]
1323 ~~~~~~~~~~~~~~~~~~~~~~
1324 DFuns look like
1325
1326 df :: forall a b. (Eq a, Eq b) -> Eq (a,b)
1327 df a b d_a d_b = MkEqD (a,b) ($c1 a b d_a d_b)
1328 ($c2 a b d_a d_b)
1329
1330 So to split it up we just need to apply the ops $c1, $c2 etc
1331 to the very same args as the dfun. It takes a little more work
1332 to compute the type arguments to the dictionary constructor.
1333
1334 Note [DFun arity check]
1335 ~~~~~~~~~~~~~~~~~~~~~~~
1336 Here we check that the total number of supplied arguments (inclding
1337 type args) matches what the dfun is expecting. This may be *less*
1338 than the ordinary arity of the dfun: see Note [DFun unfoldings] in CoreSyn
1339 -}
1340
1341 exprIsLiteral_maybe :: InScopeEnv -> CoreExpr -> Maybe Literal
1342 -- Same deal as exprIsConApp_maybe, but much simpler
1343 -- Nevertheless we do need to look through unfoldings for
1344 -- Integer and string literals, which are vigorously hoisted to top level
1345 -- and not subsequently inlined
1346 exprIsLiteral_maybe env@(_, id_unf) e
1347 = case e of
1348 Lit l -> Just l
1349 Tick _ e' -> exprIsLiteral_maybe env e' -- dubious?
1350 Var v | Just rhs <- expandUnfolding_maybe (id_unf v)
1351 -> exprIsLiteral_maybe env rhs
1352 _ -> Nothing
1353
1354 {-
1355 Note [exprIsLambda_maybe]
1356 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1357 exprIsLambda_maybe will, given an expression `e`, try to turn it into the form
1358 `Lam v e'` (returned as `Just (v,e')`). Besides using lambdas, it looks through
1359 casts (using the Push rule), and it unfolds function calls if the unfolding
1360 has a greater arity than arguments are present.
1361
1362 Currently, it is used in Rules.match, and is required to make
1363 "map coerce = coerce" match.
1364 -}
1365
1366 exprIsLambda_maybe :: InScopeEnv -> CoreExpr
1367 -> Maybe (Var, CoreExpr,[Tickish Id])
1368 -- See Note [exprIsLambda_maybe]
1369
1370 -- The simple case: It is a lambda already
1371 exprIsLambda_maybe _ (Lam x e)
1372 = Just (x, e, [])
1373
1374 -- Still straightforward: Ticks that we can float out of the way
1375 exprIsLambda_maybe (in_scope_set, id_unf) (Tick t e)
1376 | tickishFloatable t
1377 , Just (x, e, ts) <- exprIsLambda_maybe (in_scope_set, id_unf) e
1378 = Just (x, e, t:ts)
1379
1380 -- Also possible: A casted lambda. Push the coercion inside
1381 exprIsLambda_maybe (in_scope_set, id_unf) (Cast casted_e co)
1382 | Just (x, e,ts) <- exprIsLambda_maybe (in_scope_set, id_unf) casted_e
1383 -- Only do value lambdas.
1384 -- this implies that x is not in scope in gamma (makes this code simpler)
1385 , not (isTyVar x) && not (isCoVar x)
1386 , ASSERT( not $ x `elemVarSet` tyCoVarsOfCo co) True
1387 , Just (x',e') <- pushCoercionIntoLambda in_scope_set x e co
1388 , let res = Just (x',e',ts)
1389 = --pprTrace "exprIsLambda_maybe:Cast" (vcat [ppr casted_e,ppr co,ppr res)])
1390 res
1391
1392 -- Another attempt: See if we find a partial unfolding
1393 exprIsLambda_maybe (in_scope_set, id_unf) e
1394 | (Var f, as, ts) <- collectArgsTicks tickishFloatable e
1395 , idArity f > count isValArg as
1396 -- Make sure there is hope to get a lambda
1397 , Just rhs <- expandUnfolding_maybe (id_unf f)
1398 -- Optimize, for beta-reduction
1399 , let e' = simpleOptExprWith (mkEmptySubst in_scope_set) (rhs `mkApps` as)
1400 -- Recurse, because of possible casts
1401 , Just (x', e'', ts') <- exprIsLambda_maybe (in_scope_set, id_unf) e'
1402 , let res = Just (x', e'', ts++ts')
1403 = -- pprTrace "exprIsLambda_maybe:Unfold" (vcat [ppr e, ppr (x',e'')])
1404 res
1405
1406 exprIsLambda_maybe _ _e
1407 = -- pprTrace "exprIsLambda_maybe:Fail" (vcat [ppr _e])
1408 Nothing
1409
1410
1411 {- *********************************************************************
1412 * *
1413 The "push rules"
1414 * *
1415 ************************************************************************
1416
1417 Here we implement the "push rules" from FC papers:
1418
1419 * The push-argument ules, where we can move a coercion past an argument.
1420 We have
1421 (fun |> co) arg
1422 and we want to transform it to
1423 (fun arg') |> co'
1424 for some suitable co' and tranformed arg'.
1425
1426 * The PushK rule for data constructors. We have
1427 (K e1 .. en) |> co
1428 and we want to tranform to
1429 (K e1' .. en')
1430 by pushing the coercion into the oarguments
1431 -}
1432
1433 pushCoArgs :: Coercion -> [CoreArg] -> Maybe ([CoreArg], Coercion)
1434 pushCoArgs co [] = return ([], co)
1435 pushCoArgs co (arg:args) = do { (arg', co1) <- pushCoArg co arg
1436 ; (args', co2) <- pushCoArgs co1 args
1437 ; return (arg':args', co2) }
1438
1439 pushCoArg :: Coercion -> CoreArg -> Maybe (CoreArg, Coercion)
1440 -- We have (fun |> co) arg, and we want to transform it to
1441 -- (fun arg) |> co
1442 -- This may fail, e.g. if (fun :: N) where N is a newtype
1443 -- C.f. simplCast in Simplify.hs
1444 -- 'co' is always Representational
1445
1446 pushCoArg co (Type ty) = do { (ty', co') <- pushCoTyArg co ty
1447 ; return (Type ty', co') }
1448 pushCoArg co val_arg = do { (arg_co, co') <- pushCoValArg co
1449 ; return (mkCast val_arg arg_co, co') }
1450
1451 pushCoTyArg :: Coercion -> Type -> Maybe (Type, Coercion)
1452 -- We have (fun |> co) @ty
1453 -- Push the coercion through to return
1454 -- (fun @ty') |> co'
1455 -- 'co' is always Representational
1456 pushCoTyArg co ty
1457 | tyL `eqType` tyR
1458 = Just (ty, mkRepReflCo (piResultTy tyR ty))
1459
1460 | isForAllTy tyL
1461 = ASSERT2( isForAllTy tyR, ppr co $$ ppr ty )
1462 Just (ty `mkCastTy` mkSymCo co1, co2)
1463
1464 | otherwise
1465 = Nothing
1466 where
1467 Pair tyL tyR = coercionKind co
1468 -- co :: tyL ~ tyR
1469 -- tyL = forall (a1 :: k1). ty1
1470 -- tyR = forall (a2 :: k2). ty2
1471
1472 co1 = mkNthCo 0 co
1473 -- co1 :: k1 ~ k2
1474 -- Note that NthCo can extract an equality between the kinds
1475 -- of the types related by a coercion between forall-types.
1476 -- See the NthCo case in CoreLint.
1477
1478 co2 = mkInstCo co (mkCoherenceLeftCo (mkNomReflCo ty) co1)
1479 -- co2 :: ty1[ (ty|>co1)/a1 ] ~ ty2[ ty/a2 ]
1480 -- Arg of mkInstCo is always nominal, hence mkNomReflCo
1481
1482 pushCoValArg :: Coercion -> Maybe (Coercion, Coercion)
1483 -- We have (fun |> co) arg
1484 -- Push the coercion through to return
1485 -- (fun (arg |> co_arg)) |> co_res
1486 -- 'co' is always Representational
1487 pushCoValArg co
1488 | tyL `eqType` tyR
1489 = Just (mkRepReflCo arg, mkRepReflCo res)
1490
1491 | isFunTy tyL
1492 , [co1, co2] <- decomposeCo 2 co
1493 -- If co :: (tyL1 -> tyL2) ~ (tyR1 -> tyR2)
1494 -- then co1 :: tyL1 ~ tyR1
1495 -- co2 :: tyL2 ~ tyR2
1496 = ASSERT2( isFunTy tyR, ppr co $$ ppr arg )
1497 Just (mkSymCo co1, co2)
1498
1499 | otherwise
1500 = Nothing
1501 where
1502 (arg, res) = splitFunTy tyR
1503 Pair tyL tyR = coercionKind co
1504
1505 pushCoercionIntoLambda
1506 :: InScopeSet -> Var -> CoreExpr -> Coercion -> Maybe (Var, CoreExpr)
1507 -- This implements the Push rule from the paper on coercions
1508 -- (\x. e) |> co
1509 -- ===>
1510 -- (\x'. e |> co')
1511 pushCoercionIntoLambda in_scope x e co
1512 | ASSERT(not (isTyVar x) && not (isCoVar x)) True
1513 , Pair s1s2 t1t2 <- coercionKind co
1514 , Just (_s1,_s2) <- splitFunTy_maybe s1s2
1515 , Just (t1,_t2) <- splitFunTy_maybe t1t2
1516 = let [co1, co2] = decomposeCo 2 co
1517 -- Should we optimize the coercions here?
1518 -- Otherwise they might not match too well
1519 x' = x `setIdType` t1
1520 in_scope' = in_scope `extendInScopeSet` x'
1521 subst = extendIdSubst (mkEmptySubst in_scope')
1522 x
1523 (mkCast (Var x') co1)
1524 in Just (x', subst_expr (text "pushCoercionIntoLambda") subst e `mkCast` co2)
1525 | otherwise
1526 = pprTrace "exprIsLambda_maybe: Unexpected lambda in case" (ppr (Lam x e))
1527 Nothing
1528
1529 pushCoDataCon :: DataCon -> [CoreExpr] -> Coercion
1530 -> Maybe (DataCon
1531 , [Type] -- Universal type args
1532 , [CoreExpr]) -- All other args incl existentials
1533 -- Implement the KPush reduction rule as described in "Down with kinds"
1534 -- The transformation applies iff we have
1535 -- (C e1 ... en) `cast` co
1536 -- where co :: (T t1 .. tn) ~ to_ty
1537 -- The left-hand one must be a T, because exprIsConApp returned True
1538 -- but the right-hand one might not be. (Though it usually will.)
1539 pushCoDataCon dc dc_args co
1540 | isReflCo co || from_ty `eqType` to_ty -- try cheap test first
1541 , let (univ_ty_args, rest_args) = splitAtList (dataConUnivTyVars dc) dc_args
1542 = Just (dc, map exprToType univ_ty_args, rest_args)
1543
1544 | Just (to_tc, to_tc_arg_tys) <- splitTyConApp_maybe to_ty
1545 , to_tc == dataConTyCon dc
1546 -- These two tests can fail; we might see
1547 -- (C x y) `cast` (g :: T a ~ S [a]),
1548 -- where S is a type function. In fact, exprIsConApp
1549 -- will probably not be called in such circumstances,
1550 -- but there't nothing wrong with it
1551
1552 = let
1553 tc_arity = tyConArity to_tc
1554 dc_univ_tyvars = dataConUnivTyVars dc
1555 dc_ex_tyvars = dataConExTyVars dc
1556 arg_tys = dataConRepArgTys dc
1557
1558 non_univ_args = dropList dc_univ_tyvars dc_args
1559 (ex_args, val_args) = splitAtList dc_ex_tyvars non_univ_args
1560
1561 -- Make the "Psi" from the paper
1562 omegas = decomposeCo tc_arity co
1563 (psi_subst, to_ex_arg_tys)
1564 = liftCoSubstWithEx Representational
1565 dc_univ_tyvars
1566 omegas
1567 dc_ex_tyvars
1568 (map exprToType ex_args)
1569
1570 -- Cast the value arguments (which include dictionaries)
1571 new_val_args = zipWith cast_arg arg_tys val_args
1572 cast_arg arg_ty arg = mkCast arg (psi_subst arg_ty)
1573
1574 to_ex_args = map Type to_ex_arg_tys
1575
1576 dump_doc = vcat [ppr dc, ppr dc_univ_tyvars, ppr dc_ex_tyvars,
1577 ppr arg_tys, ppr dc_args,
1578 ppr ex_args, ppr val_args, ppr co, ppr from_ty, ppr to_ty, ppr to_tc ]
1579 in
1580 ASSERT2( eqType from_ty (mkTyConApp to_tc (map exprToType $ takeList dc_univ_tyvars dc_args)), dump_doc )
1581 ASSERT2( equalLength val_args arg_tys, dump_doc )
1582 Just (dc, to_tc_arg_tys, to_ex_args ++ new_val_args)
1583
1584 | otherwise
1585 = Nothing
1586
1587 where
1588 Pair from_ty to_ty = coercionKind co