6045937173d109bbf4e5a088eeac249518344735
[ghc.git] / compiler / basicTypes / Id.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5 \section[Id]{@Ids@: Value and constructor identifiers}
6 -}
7
8 {-# LANGUAGE CPP #-}
9
10 -- |
11 -- #name_types#
12 -- GHC uses several kinds of name internally:
13 --
14 -- * 'OccName.OccName': see "OccName#name_types"
15 --
16 -- * 'RdrName.RdrName': see "RdrName#name_types"
17 --
18 -- * 'Name.Name': see "Name#name_types"
19 --
20 -- * 'Id.Id' represents names that not only have a 'Name.Name' but also a 'TyCoRep.Type' and some additional
21 -- details (a 'IdInfo.IdInfo' and one of 'Var.LocalIdDetails' or 'IdInfo.GlobalIdDetails') that
22 -- are added, modified and inspected by various compiler passes. These 'Var.Var' names may either
23 -- be global or local, see "Var#globalvslocal"
24 --
25 -- * 'Var.Var': see "Var#name_types"
26
27 module Id (
28 -- * The main types
29 Var, Id, isId,
30
31 -- ** Simple construction
32 mkGlobalId, mkVanillaGlobal, mkVanillaGlobalWithInfo,
33 mkLocalId, mkLocalCoVar, mkLocalIdOrCoVar,
34 mkLocalIdOrCoVarWithInfo,
35 mkLocalIdWithInfo, mkExportedLocalId, mkExportedVanillaId,
36 mkNonExportedLocalId,
37 mkSysLocal, mkSysLocalM, mkSysLocalOrCoVar, mkSysLocalOrCoVarM,
38 mkUserLocal, mkUserLocalOrCoVar,
39 mkTemplateLocals, mkTemplateLocalsNum, mkTemplateLocal,
40 mkWorkerId,
41
42 -- ** Taking an Id apart
43 idName, idType, idUnique, idInfo, idDetails, idRepArity,
44 recordSelectorTyCon,
45
46 -- ** Modifying an Id
47 setIdName, setIdUnique, Id.setIdType,
48 setIdExported, setIdNotExported,
49 globaliseId, localiseId,
50 setIdInfo, lazySetIdInfo, modifyIdInfo, maybeModifyIdInfo,
51 zapLamIdInfo, zapIdDemandInfo, zapIdUsageInfo, zapIdUsageEnvInfo,
52 zapIdUsedOnceInfo,
53 zapFragileIdInfo, zapIdStrictness,
54 transferPolyIdInfo,
55
56 -- ** Predicates on Ids
57 isImplicitId, isDeadBinder,
58 isStrictId,
59 isExportedId, isLocalId, isGlobalId,
60 isRecordSelector, isNaughtyRecordSelector,
61 isPatSynRecordSelector,
62 isDataConRecordSelector,
63 isClassOpId_maybe, isDFunId,
64 isPrimOpId, isPrimOpId_maybe,
65 isFCallId, isFCallId_maybe,
66 isDataConWorkId, isDataConWorkId_maybe, isDataConId_maybe, idDataCon,
67 isConLikeId, isBottomingId, idIsFrom,
68 hasNoBinding,
69
70 -- ** Evidence variables
71 DictId, isDictId, isEvVar,
72
73 -- ** Inline pragma stuff
74 idInlinePragma, setInlinePragma, modifyInlinePragma,
75 idInlineActivation, setInlineActivation, idRuleMatchInfo,
76
77 -- ** One-shot lambdas
78 isOneShotBndr, isProbablyOneShotLambda,
79 setOneShotLambda, clearOneShotLambda,
80 updOneShotInfo, setIdOneShotInfo,
81 isStateHackType, stateHackOneShot, typeOneShot,
82
83 -- ** Reading 'IdInfo' fields
84 idArity,
85 idCallArity,
86 idUnfolding, realIdUnfolding,
87 idSpecialisation, idCoreRules, idHasRules,
88 idCafInfo,
89 idOneShotInfo, idStateHackOneShotInfo,
90 idOccInfo,
91
92 -- ** Writing 'IdInfo' fields
93 setIdUnfoldingLazily,
94 setIdUnfolding,
95 setIdArity,
96 setIdCallArity,
97
98 setIdSpecialisation,
99 setIdCafInfo,
100 setIdOccInfo, zapIdOccInfo,
101
102 setIdDemandInfo,
103 setIdStrictness,
104
105 idDemandInfo,
106 idStrictness,
107
108 ) where
109
110 #include "HsVersions.h"
111
112 import CoreSyn ( CoreRule, Unfolding( NoUnfolding ) )
113
114 import IdInfo
115 import BasicTypes
116
117 -- Imported and re-exported
118 import Var( Id, CoVar, DictId,
119 idInfo, idDetails, globaliseId, varType,
120 isId, isLocalId, isGlobalId, isExportedId )
121 import qualified Var
122
123 import Type
124 import TysPrim
125 import DataCon
126 import Demand
127 import Name
128 import Module
129 import Class
130 import {-# SOURCE #-} PrimOp (PrimOp)
131 import ForeignCall
132 import Maybes
133 import SrcLoc
134 import Outputable
135 import Unique
136 import UniqSupply
137 import FastString
138 import Util
139 import StaticFlags
140
141 -- infixl so you can say (id `set` a `set` b)
142 infixl 1 `setIdUnfoldingLazily`,
143 `setIdUnfolding`,
144 `setIdArity`,
145 `setIdCallArity`,
146 `setIdOccInfo`,
147 `setIdOneShotInfo`,
148
149 `setIdSpecialisation`,
150 `setInlinePragma`,
151 `setInlineActivation`,
152 `idCafInfo`,
153
154 `setIdDemandInfo`,
155 `setIdStrictness`
156
157 {-
158 ************************************************************************
159 * *
160 \subsection{Basic Id manipulation}
161 * *
162 ************************************************************************
163 -}
164
165 idName :: Id -> Name
166 idName = Var.varName
167
168 idUnique :: Id -> Unique
169 idUnique = Var.varUnique
170
171 idType :: Id -> Kind
172 idType = Var.varType
173
174 setIdName :: Id -> Name -> Id
175 setIdName = Var.setVarName
176
177 setIdUnique :: Id -> Unique -> Id
178 setIdUnique = Var.setVarUnique
179
180 -- | Not only does this set the 'Id' 'Type', it also evaluates the type to try and
181 -- reduce space usage
182 setIdType :: Id -> Type -> Id
183 setIdType id ty = seqType ty `seq` Var.setVarType id ty
184
185 setIdExported :: Id -> Id
186 setIdExported = Var.setIdExported
187
188 setIdNotExported :: Id -> Id
189 setIdNotExported = Var.setIdNotExported
190
191 localiseId :: Id -> Id
192 -- Make an with the same unique and type as the
193 -- incoming Id, but with an *Internal* Name and *LocalId* flavour
194 localiseId id
195 | ASSERT( isId id ) isLocalId id && isInternalName name
196 = id
197 | otherwise
198 = Var.mkLocalVar (idDetails id) (localiseName name) (idType id) (idInfo id)
199 where
200 name = idName id
201
202 lazySetIdInfo :: Id -> IdInfo -> Id
203 lazySetIdInfo = Var.lazySetIdInfo
204
205 setIdInfo :: Id -> IdInfo -> Id
206 setIdInfo id info = info `seq` (lazySetIdInfo id info)
207 -- Try to avoid spack leaks by seq'ing
208
209 modifyIdInfo :: (IdInfo -> IdInfo) -> Id -> Id
210 modifyIdInfo fn id = setIdInfo id (fn (idInfo id))
211
212 -- maybeModifyIdInfo tries to avoid unnecessary thrashing
213 maybeModifyIdInfo :: Maybe IdInfo -> Id -> Id
214 maybeModifyIdInfo (Just new_info) id = lazySetIdInfo id new_info
215 maybeModifyIdInfo Nothing id = id
216
217 {-
218 ************************************************************************
219 * *
220 \subsection{Simple Id construction}
221 * *
222 ************************************************************************
223
224 Absolutely all Ids are made by mkId. It is just like Var.mkId,
225 but in addition it pins free-tyvar-info onto the Id's type,
226 where it can easily be found.
227
228 Note [Free type variables]
229 ~~~~~~~~~~~~~~~~~~~~~~~~~~
230 At one time we cached the free type variables of the type of an Id
231 at the root of the type in a TyNote. The idea was to avoid repeating
232 the free-type-variable calculation. But it turned out to slow down
233 the compiler overall. I don't quite know why; perhaps finding free
234 type variables of an Id isn't all that common whereas applying a
235 substitution (which changes the free type variables) is more common.
236 Anyway, we removed it in March 2008.
237 -}
238
239 -- | For an explanation of global vs. local 'Id's, see "Var#globalvslocal"
240 mkGlobalId :: IdDetails -> Name -> Type -> IdInfo -> Id
241 mkGlobalId = Var.mkGlobalVar
242
243 -- | Make a global 'Id' without any extra information at all
244 mkVanillaGlobal :: Name -> Type -> Id
245 mkVanillaGlobal name ty = mkVanillaGlobalWithInfo name ty vanillaIdInfo
246
247 -- | Make a global 'Id' with no global information but some generic 'IdInfo'
248 mkVanillaGlobalWithInfo :: Name -> Type -> IdInfo -> Id
249 mkVanillaGlobalWithInfo = mkGlobalId VanillaId
250
251
252 -- | For an explanation of global vs. local 'Id's, see "Var#globalvslocal"
253 mkLocalId :: Name -> Type -> Id
254 mkLocalId name ty = mkLocalIdWithInfo name ty vanillaIdInfo
255 -- It's tempting to ASSERT( not (isCoercionType ty) ), but don't. Sometimes,
256 -- the type is a panic. (Search invented_id)
257
258 -- | Make a local CoVar
259 mkLocalCoVar :: Name -> Type -> CoVar
260 mkLocalCoVar name ty
261 = ASSERT( isCoercionType ty )
262 Var.mkLocalVar CoVarId name ty vanillaIdInfo
263
264 -- | Like 'mkLocalId', but checks the type to see if it should make a covar
265 mkLocalIdOrCoVar :: Name -> Type -> Id
266 mkLocalIdOrCoVar name ty
267 | isCoercionType ty = mkLocalCoVar name ty
268 | otherwise = mkLocalId name ty
269
270 -- | Make a local id, with the IdDetails set to CoVarId if the type indicates
271 -- so.
272 mkLocalIdOrCoVarWithInfo :: Name -> Type -> IdInfo -> Id
273 mkLocalIdOrCoVarWithInfo name ty info
274 = Var.mkLocalVar details name ty info
275 where
276 details | isCoercionType ty = CoVarId
277 | otherwise = VanillaId
278
279 -- proper ids only; no covars!
280 mkLocalIdWithInfo :: Name -> Type -> IdInfo -> Id
281 mkLocalIdWithInfo name ty info = Var.mkLocalVar VanillaId name ty info
282 -- Note [Free type variables]
283
284 -- | Create a local 'Id' that is marked as exported.
285 -- This prevents things attached to it from being removed as dead code.
286 -- See Note [Exported LocalIds]
287 mkExportedLocalId :: IdDetails -> Name -> Type -> Id
288 mkExportedLocalId details name ty = Var.mkExportedLocalVar details name ty vanillaIdInfo
289 -- Note [Free type variables]
290
291 -- | Create a local 'Id' that is marked as not-exported.
292 -- These may be removed as dead code.
293 mkNonExportedLocalId :: IdDetails -> Name -> Type -> Id
294 mkNonExportedLocalId details name ty =
295 Var.mkLocalVar details name ty vanillaIdInfo
296
297 mkExportedVanillaId :: Name -> Type -> Id
298 mkExportedVanillaId name ty = Var.mkExportedLocalVar VanillaId name ty vanillaIdInfo
299 -- Note [Free type variables]
300
301
302 -- | Create a system local 'Id'. These are local 'Id's (see "Var#globalvslocal")
303 -- that are created by the compiler out of thin air
304 mkSysLocal :: FastString -> Unique -> Type -> Id
305 mkSysLocal fs uniq ty = ASSERT( not (isCoercionType ty) )
306 mkLocalId (mkSystemVarName uniq fs) ty
307
308 -- | Like 'mkSysLocal', but checks to see if we have a covar type
309 mkSysLocalOrCoVar :: FastString -> Unique -> Type -> Id
310 mkSysLocalOrCoVar fs uniq ty
311 = mkLocalIdOrCoVar (mkSystemVarName uniq fs) ty
312
313 mkSysLocalM :: MonadUnique m => FastString -> Type -> m Id
314 mkSysLocalM fs ty = getUniqueM >>= (\uniq -> return (mkSysLocal fs uniq ty))
315
316 mkSysLocalOrCoVarM :: MonadUnique m => FastString -> Type -> m Id
317 mkSysLocalOrCoVarM fs ty
318 = getUniqueM >>= (\uniq -> return (mkSysLocalOrCoVar fs uniq ty))
319
320 -- | Create a user local 'Id'. These are local 'Id's (see "Var#globalvslocal") with a name and location that the user might recognize
321 mkUserLocal :: OccName -> Unique -> Type -> SrcSpan -> Id
322 mkUserLocal occ uniq ty loc = ASSERT( not (isCoercionType ty) )
323 mkLocalId (mkInternalName uniq occ loc) ty
324
325 -- | Like 'mkUserLocal', but checks if we have a coercion type
326 mkUserLocalOrCoVar :: OccName -> Unique -> Type -> SrcSpan -> Id
327 mkUserLocalOrCoVar occ uniq ty loc
328 = mkLocalIdOrCoVar (mkInternalName uniq occ loc) ty
329
330 {-
331 Make some local @Ids@ for a template @CoreExpr@. These have bogus
332 @Uniques@, but that's OK because the templates are supposed to be
333 instantiated before use.
334 -}
335
336 -- | Workers get local names. "CoreTidy" will externalise these if necessary
337 mkWorkerId :: Unique -> Id -> Type -> Id
338 mkWorkerId uniq unwrkr ty
339 = mkLocalIdOrCoVar (mkDerivedInternalName mkWorkerOcc uniq (getName unwrkr)) ty
340
341 -- | Create a /template local/: a family of system local 'Id's in bijection with @Int@s, typically used in unfoldings
342 mkTemplateLocal :: Int -> Type -> Id
343 mkTemplateLocal i ty = mkSysLocalOrCoVar (fsLit "tpl") (mkBuiltinUnique i) ty
344
345 -- | Create a template local for a series of types
346 mkTemplateLocals :: [Type] -> [Id]
347 mkTemplateLocals = mkTemplateLocalsNum 1
348
349 -- | Create a template local for a series of type, but start from a specified template local
350 mkTemplateLocalsNum :: Int -> [Type] -> [Id]
351 mkTemplateLocalsNum n tys = zipWith mkTemplateLocal [n..] tys
352
353 {- Note [Exported LocalIds]
354 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
355 We use mkExportedLocalId for things like
356 - Dictionary functions (DFunId)
357 - Wrapper and matcher Ids for pattern synonyms
358 - Default methods for classes
359 - Pattern-synonym matcher and builder Ids
360 - etc
361
362 They marked as "exported" in the sense that they should be kept alive
363 even if apparently unused in other bindings, and not dropped as dead
364 code by the occurrence analyser. (But "exported" here does not mean
365 "brought into lexical scope by an import declaration". Indeed these
366 things are always internal Ids that the user never sees.)
367
368 It's very important that they are *LocalIds*, not GlobalIds, for lots
369 of reasons:
370
371 * We want to treat them as free variables for the purpose of
372 dependency analysis (e.g. CoreFVs.exprFreeVars).
373
374 * Look them up in the current substitution when we come across
375 occurrences of them (in Subst.lookupIdSubst). Lacking this we
376 can get an out-of-date unfolding, which can in turn make the
377 simplifier go into an infinite loop (Trac #9857)
378
379 * Ensure that for dfuns that the specialiser does not float dict uses
380 above their defns, which would prevent good simplifications happening.
381
382 * The strictness analyser treats a occurrence of a GlobalId as
383 imported and assumes it contains strictness in its IdInfo, which
384 isn't true if the thing is bound in the same module as the
385 occurrence.
386
387 In CoreTidy we must make all these LocalIds into GlobalIds, so that in
388 importing modules (in --make mode) we treat them as properly global.
389 That is what is happening in, say tidy_insts in TidyPgm.
390
391 ************************************************************************
392 * *
393 \subsection{Special Ids}
394 * *
395 ************************************************************************
396 -}
397
398 -- | If the 'Id' is that for a record selector, extract the 'sel_tycon'. Panic otherwise.
399 recordSelectorTyCon :: Id -> RecSelParent
400 recordSelectorTyCon id
401 = case Var.idDetails id of
402 RecSelId { sel_tycon = parent } -> parent
403 _ -> panic "recordSelectorTyCon"
404
405
406 isRecordSelector :: Id -> Bool
407 isNaughtyRecordSelector :: Id -> Bool
408 isPatSynRecordSelector :: Id -> Bool
409 isDataConRecordSelector :: Id -> Bool
410 isPrimOpId :: Id -> Bool
411 isFCallId :: Id -> Bool
412 isDataConWorkId :: Id -> Bool
413 isDFunId :: Id -> Bool
414
415 isClassOpId_maybe :: Id -> Maybe Class
416 isPrimOpId_maybe :: Id -> Maybe PrimOp
417 isFCallId_maybe :: Id -> Maybe ForeignCall
418 isDataConWorkId_maybe :: Id -> Maybe DataCon
419
420 isRecordSelector id = case Var.idDetails id of
421 RecSelId {} -> True
422 _ -> False
423
424 isDataConRecordSelector id = case Var.idDetails id of
425 RecSelId {sel_tycon = RecSelData _} -> True
426 _ -> False
427
428 isPatSynRecordSelector id = case Var.idDetails id of
429 RecSelId {sel_tycon = RecSelPatSyn _} -> True
430 _ -> False
431
432 isNaughtyRecordSelector id = case Var.idDetails id of
433 RecSelId { sel_naughty = n } -> n
434 _ -> False
435
436 isClassOpId_maybe id = case Var.idDetails id of
437 ClassOpId cls -> Just cls
438 _other -> Nothing
439
440 isPrimOpId id = case Var.idDetails id of
441 PrimOpId _ -> True
442 _ -> False
443
444 isDFunId id = case Var.idDetails id of
445 DFunId {} -> True
446 _ -> False
447
448 isPrimOpId_maybe id = case Var.idDetails id of
449 PrimOpId op -> Just op
450 _ -> Nothing
451
452 isFCallId id = case Var.idDetails id of
453 FCallId _ -> True
454 _ -> False
455
456 isFCallId_maybe id = case Var.idDetails id of
457 FCallId call -> Just call
458 _ -> Nothing
459
460 isDataConWorkId id = case Var.idDetails id of
461 DataConWorkId _ -> True
462 _ -> False
463
464 isDataConWorkId_maybe id = case Var.idDetails id of
465 DataConWorkId con -> Just con
466 _ -> Nothing
467
468 isDataConId_maybe :: Id -> Maybe DataCon
469 isDataConId_maybe id = case Var.idDetails id of
470 DataConWorkId con -> Just con
471 DataConWrapId con -> Just con
472 _ -> Nothing
473
474 idDataCon :: Id -> DataCon
475 -- ^ Get from either the worker or the wrapper 'Id' to the 'DataCon'. Currently used only in the desugarer.
476 --
477 -- INVARIANT: @idDataCon (dataConWrapId d) = d@: remember, 'dataConWrapId' can return either the wrapper or the worker
478 idDataCon id = isDataConId_maybe id `orElse` pprPanic "idDataCon" (ppr id)
479
480 hasNoBinding :: Id -> Bool
481 -- ^ Returns @True@ of an 'Id' which may not have a
482 -- binding, even though it is defined in this module.
483
484 -- Data constructor workers used to be things of this kind, but
485 -- they aren't any more. Instead, we inject a binding for
486 -- them at the CorePrep stage.
487 -- EXCEPT: unboxed tuples, which definitely have no binding
488 hasNoBinding id = case Var.idDetails id of
489 PrimOpId _ -> True -- See Note [Primop wrappers]
490 FCallId _ -> True
491 DataConWorkId dc -> isUnboxedTupleCon dc
492 _ -> False
493
494 isImplicitId :: Id -> Bool
495 -- ^ 'isImplicitId' tells whether an 'Id's info is implied by other
496 -- declarations, so we don't need to put its signature in an interface
497 -- file, even if it's mentioned in some other interface unfolding.
498 isImplicitId id
499 = case Var.idDetails id of
500 FCallId {} -> True
501 ClassOpId {} -> True
502 PrimOpId {} -> True
503 DataConWorkId {} -> True
504 DataConWrapId {} -> True
505 -- These are implied by their type or class decl;
506 -- remember that all type and class decls appear in the interface file.
507 -- The dfun id is not an implicit Id; it must *not* be omitted, because
508 -- it carries version info for the instance decl
509 _ -> False
510
511 idIsFrom :: Module -> Id -> Bool
512 idIsFrom mod id = nameIsLocalOrFrom mod (idName id)
513
514 {-
515 Note [Primop wrappers]
516 ~~~~~~~~~~~~~~~~~~~~~~
517 Currently hasNoBinding claims that PrimOpIds don't have a curried
518 function definition. But actually they do, in GHC.PrimopWrappers,
519 which is auto-generated from prelude/primops.txt.pp. So actually, hasNoBinding
520 could return 'False' for PrimOpIds.
521
522 But we'd need to add something in CoreToStg to swizzle any unsaturated
523 applications of GHC.Prim.plusInt# to GHC.PrimopWrappers.plusInt#.
524
525 Nota Bene: GHC.PrimopWrappers is needed *regardless*, because it's
526 used by GHCi, which does not implement primops direct at all.
527 -}
528
529 isDeadBinder :: Id -> Bool
530 isDeadBinder bndr | isId bndr = isDeadOcc (idOccInfo bndr)
531 | otherwise = False -- TyVars count as not dead
532
533 {-
534 ************************************************************************
535 * *
536 Evidence variables
537 * *
538 ************************************************************************
539 -}
540
541 isEvVar :: Var -> Bool
542 isEvVar var = isPredTy (varType var)
543
544 isDictId :: Id -> Bool
545 isDictId id = isDictTy (idType id)
546
547 {-
548 ************************************************************************
549 * *
550 \subsection{IdInfo stuff}
551 * *
552 ************************************************************************
553 -}
554
555 ---------------------------------
556 -- ARITY
557 idArity :: Id -> Arity
558 idArity id = arityInfo (idInfo id)
559
560 setIdArity :: Id -> Arity -> Id
561 setIdArity id arity = modifyIdInfo (`setArityInfo` arity) id
562
563 idCallArity :: Id -> Arity
564 idCallArity id = callArityInfo (idInfo id)
565
566 setIdCallArity :: Id -> Arity -> Id
567 setIdCallArity id arity = modifyIdInfo (`setCallArityInfo` arity) id
568
569 idRepArity :: Id -> RepArity
570 idRepArity x = typeRepArity (idArity x) (idType x)
571
572 -- | Returns true if an application to n args would diverge
573 isBottomingId :: Id -> Bool
574 isBottomingId id = isBottomingSig (idStrictness id)
575
576 idStrictness :: Id -> StrictSig
577 idStrictness id = strictnessInfo (idInfo id)
578
579 setIdStrictness :: Id -> StrictSig -> Id
580 setIdStrictness id sig = modifyIdInfo (`setStrictnessInfo` sig) id
581
582 zapIdStrictness :: Id -> Id
583 zapIdStrictness id = modifyIdInfo (`setStrictnessInfo` nopSig) id
584
585 -- | This predicate says whether the 'Id' has a strict demand placed on it or
586 -- has a type such that it can always be evaluated strictly (i.e an
587 -- unlifted type, as of GHC 7.6). We need to
588 -- check separately whether the 'Id' has a so-called \"strict type\" because if
589 -- the demand for the given @id@ hasn't been computed yet but @id@ has a strict
590 -- type, we still want @isStrictId id@ to be @True@.
591 isStrictId :: Id -> Bool
592 isStrictId id
593 = ASSERT2( isId id, text "isStrictId: not an id: " <+> ppr id )
594 (isStrictType (idType id)) ||
595 -- Take the best of both strictnesses - old and new
596 (isStrictDmd (idDemandInfo id))
597
598 ---------------------------------
599 -- UNFOLDING
600 idUnfolding :: Id -> Unfolding
601 -- Do not expose the unfolding of a loop breaker!
602 idUnfolding id
603 | isStrongLoopBreaker (occInfo info) = NoUnfolding
604 | otherwise = unfoldingInfo info
605 where
606 info = idInfo id
607
608 realIdUnfolding :: Id -> Unfolding
609 -- Expose the unfolding if there is one, including for loop breakers
610 realIdUnfolding id = unfoldingInfo (idInfo id)
611
612 setIdUnfoldingLazily :: Id -> Unfolding -> Id
613 setIdUnfoldingLazily id unfolding = modifyIdInfo (`setUnfoldingInfoLazily` unfolding) id
614
615 setIdUnfolding :: Id -> Unfolding -> Id
616 setIdUnfolding id unfolding = modifyIdInfo (`setUnfoldingInfo` unfolding) id
617
618 idDemandInfo :: Id -> Demand
619 idDemandInfo id = demandInfo (idInfo id)
620
621 setIdDemandInfo :: Id -> Demand -> Id
622 setIdDemandInfo id dmd = modifyIdInfo (`setDemandInfo` dmd) id
623
624 ---------------------------------
625 -- SPECIALISATION
626
627 -- See Note [Specialisations and RULES in IdInfo] in IdInfo.hs
628
629 idSpecialisation :: Id -> RuleInfo
630 idSpecialisation id = ruleInfo (idInfo id)
631
632 idCoreRules :: Id -> [CoreRule]
633 idCoreRules id = ruleInfoRules (idSpecialisation id)
634
635 idHasRules :: Id -> Bool
636 idHasRules id = not (isEmptyRuleInfo (idSpecialisation id))
637
638 setIdSpecialisation :: Id -> RuleInfo -> Id
639 setIdSpecialisation id spec_info = modifyIdInfo (`setRuleInfo` spec_info) id
640
641 ---------------------------------
642 -- CAF INFO
643 idCafInfo :: Id -> CafInfo
644 idCafInfo id = cafInfo (idInfo id)
645
646 setIdCafInfo :: Id -> CafInfo -> Id
647 setIdCafInfo id caf_info = modifyIdInfo (`setCafInfo` caf_info) id
648
649 ---------------------------------
650 -- Occcurrence INFO
651 idOccInfo :: Id -> OccInfo
652 idOccInfo id = occInfo (idInfo id)
653
654 setIdOccInfo :: Id -> OccInfo -> Id
655 setIdOccInfo id occ_info = modifyIdInfo (`setOccInfo` occ_info) id
656
657 zapIdOccInfo :: Id -> Id
658 zapIdOccInfo b = b `setIdOccInfo` NoOccInfo
659
660 {-
661 ---------------------------------
662 -- INLINING
663 The inline pragma tells us to be very keen to inline this Id, but it's still
664 OK not to if optimisation is switched off.
665 -}
666
667 idInlinePragma :: Id -> InlinePragma
668 idInlinePragma id = inlinePragInfo (idInfo id)
669
670 setInlinePragma :: Id -> InlinePragma -> Id
671 setInlinePragma id prag = modifyIdInfo (`setInlinePragInfo` prag) id
672
673 modifyInlinePragma :: Id -> (InlinePragma -> InlinePragma) -> Id
674 modifyInlinePragma id fn = modifyIdInfo (\info -> info `setInlinePragInfo` (fn (inlinePragInfo info))) id
675
676 idInlineActivation :: Id -> Activation
677 idInlineActivation id = inlinePragmaActivation (idInlinePragma id)
678
679 setInlineActivation :: Id -> Activation -> Id
680 setInlineActivation id act = modifyInlinePragma id (\prag -> setInlinePragmaActivation prag act)
681
682 idRuleMatchInfo :: Id -> RuleMatchInfo
683 idRuleMatchInfo id = inlinePragmaRuleMatchInfo (idInlinePragma id)
684
685 isConLikeId :: Id -> Bool
686 isConLikeId id = isDataConWorkId id || isConLike (idRuleMatchInfo id)
687
688 {-
689 ---------------------------------
690 -- ONE-SHOT LAMBDAS
691 -}
692
693 idOneShotInfo :: Id -> OneShotInfo
694 idOneShotInfo id = oneShotInfo (idInfo id)
695
696 -- | Like 'idOneShotInfo', but taking the Horrible State Hack in to account
697 -- See Note [The state-transformer hack] in CoreArity
698 idStateHackOneShotInfo :: Id -> OneShotInfo
699 idStateHackOneShotInfo id
700 | isStateHackType (idType id) = stateHackOneShot
701 | otherwise = idOneShotInfo id
702
703 -- | Returns whether the lambda associated with the 'Id' is certainly applied at most once
704 -- This one is the "business end", called externally.
705 -- It works on type variables as well as Ids, returning True
706 -- Its main purpose is to encapsulate the Horrible State Hack
707 -- See Note [The state-transformer hack] in CoreArity
708 isOneShotBndr :: Var -> Bool
709 isOneShotBndr var
710 | isTyVar var = True
711 | OneShotLam <- idStateHackOneShotInfo var = True
712 | otherwise = False
713
714 -- | Should we apply the state hack to values of this 'Type'?
715 stateHackOneShot :: OneShotInfo
716 stateHackOneShot = OneShotLam -- Or maybe ProbOneShot?
717
718 typeOneShot :: Type -> OneShotInfo
719 typeOneShot ty
720 | isStateHackType ty = stateHackOneShot
721 | otherwise = NoOneShotInfo
722
723 isStateHackType :: Type -> Bool
724 isStateHackType ty
725 | opt_NoStateHack
726 = False
727 | otherwise
728 = case tyConAppTyCon_maybe ty of
729 Just tycon -> tycon == statePrimTyCon
730 _ -> False
731 -- This is a gross hack. It claims that
732 -- every function over realWorldStatePrimTy is a one-shot
733 -- function. This is pretty true in practice, and makes a big
734 -- difference. For example, consider
735 -- a `thenST` \ r -> ...E...
736 -- The early full laziness pass, if it doesn't know that r is one-shot
737 -- will pull out E (let's say it doesn't mention r) to give
738 -- let lvl = E in a `thenST` \ r -> ...lvl...
739 -- When `thenST` gets inlined, we end up with
740 -- let lvl = E in \s -> case a s of (r, s') -> ...lvl...
741 -- and we don't re-inline E.
742 --
743 -- It would be better to spot that r was one-shot to start with, but
744 -- I don't want to rely on that.
745 --
746 -- Another good example is in fill_in in PrelPack.hs. We should be able to
747 -- spot that fill_in has arity 2 (and when Keith is done, we will) but we can't yet.
748
749 isProbablyOneShotLambda :: Id -> Bool
750 isProbablyOneShotLambda id = case idStateHackOneShotInfo id of
751 OneShotLam -> True
752 ProbOneShot -> True
753 NoOneShotInfo -> False
754
755 setOneShotLambda :: Id -> Id
756 setOneShotLambda id = modifyIdInfo (`setOneShotInfo` OneShotLam) id
757
758 clearOneShotLambda :: Id -> Id
759 clearOneShotLambda id = modifyIdInfo (`setOneShotInfo` NoOneShotInfo) id
760
761 setIdOneShotInfo :: Id -> OneShotInfo -> Id
762 setIdOneShotInfo id one_shot = modifyIdInfo (`setOneShotInfo` one_shot) id
763
764 updOneShotInfo :: Id -> OneShotInfo -> Id
765 -- Combine the info in the Id with new info
766 updOneShotInfo id one_shot
767 | do_upd = setIdOneShotInfo id one_shot
768 | otherwise = id
769 where
770 do_upd = case (idOneShotInfo id, one_shot) of
771 (NoOneShotInfo, _) -> True
772 (OneShotLam, _) -> False
773 (_, NoOneShotInfo) -> False
774 _ -> True
775
776 -- The OneShotLambda functions simply fiddle with the IdInfo flag
777 -- But watch out: this may change the type of something else
778 -- f = \x -> e
779 -- If we change the one-shot-ness of x, f's type changes
780
781 zapInfo :: (IdInfo -> Maybe IdInfo) -> Id -> Id
782 zapInfo zapper id = maybeModifyIdInfo (zapper (idInfo id)) id
783
784 zapLamIdInfo :: Id -> Id
785 zapLamIdInfo = zapInfo zapLamInfo
786
787 zapFragileIdInfo :: Id -> Id
788 zapFragileIdInfo = zapInfo zapFragileInfo
789
790 zapIdDemandInfo :: Id -> Id
791 zapIdDemandInfo = zapInfo zapDemandInfo
792
793 zapIdUsageInfo :: Id -> Id
794 zapIdUsageInfo = zapInfo zapUsageInfo
795
796 zapIdUsageEnvInfo :: Id -> Id
797 zapIdUsageEnvInfo = zapInfo zapUsageEnvInfo
798
799 zapIdUsedOnceInfo :: Id -> Id
800 zapIdUsedOnceInfo = zapInfo zapUsedOnceInfo
801
802 {-
803 Note [transferPolyIdInfo]
804 ~~~~~~~~~~~~~~~~~~~~~~~~~
805 This transfer is used in two places:
806 FloatOut (long-distance let-floating)
807 SimplUtils.abstractFloats (short-distance let-floating)
808
809 Consider the short-distance let-floating:
810
811 f = /\a. let g = rhs in ...
812
813 Then if we float thus
814
815 g' = /\a. rhs
816 f = /\a. ...[g' a/g]....
817
818 we *do not* want to lose g's
819 * strictness information
820 * arity
821 * inline pragma (though that is bit more debatable)
822 * occurrence info
823
824 Mostly this is just an optimisation, but it's *vital* to
825 transfer the occurrence info. Consider
826
827 NonRec { f = /\a. let Rec { g* = ..g.. } in ... }
828
829 where the '*' means 'LoopBreaker'. Then if we float we must get
830
831 Rec { g'* = /\a. ...(g' a)... }
832 NonRec { f = /\a. ...[g' a/g]....}
833
834 where g' is also marked as LoopBreaker. If not, terrible things
835 can happen if we re-simplify the binding (and the Simplifier does
836 sometimes simplify a term twice); see Trac #4345.
837
838 It's not so simple to retain
839 * worker info
840 * rules
841 so we simply discard those. Sooner or later this may bite us.
842
843 If we abstract wrt one or more *value* binders, we must modify the
844 arity and strictness info before transferring it. E.g.
845 f = \x. e
846 -->
847 g' = \y. \x. e
848 + substitute (g' y) for g
849 Notice that g' has an arity one more than the original g
850 -}
851
852 transferPolyIdInfo :: Id -- Original Id
853 -> [Var] -- Abstract wrt these variables
854 -> Id -- New Id
855 -> Id
856 transferPolyIdInfo old_id abstract_wrt new_id
857 = modifyIdInfo transfer new_id
858 where
859 arity_increase = count isId abstract_wrt -- Arity increases by the
860 -- number of value binders
861
862 old_info = idInfo old_id
863 old_arity = arityInfo old_info
864 old_inline_prag = inlinePragInfo old_info
865 old_occ_info = occInfo old_info
866 new_arity = old_arity + arity_increase
867
868 old_strictness = strictnessInfo old_info
869 new_strictness = increaseStrictSigArity arity_increase old_strictness
870
871 transfer new_info = new_info `setArityInfo` new_arity
872 `setInlinePragInfo` old_inline_prag
873 `setOccInfo` old_occ_info
874 `setStrictnessInfo` new_strictness