Implement unboxed sum primitive type
[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,
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 || isUnboxedSumCon 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 -- | Returns true if an application to n args would diverge
570 isBottomingId :: Id -> Bool
571 isBottomingId id = isBottomingSig (idStrictness id)
572
573 idStrictness :: Id -> StrictSig
574 idStrictness id = strictnessInfo (idInfo id)
575
576 setIdStrictness :: Id -> StrictSig -> Id
577 setIdStrictness id sig = modifyIdInfo (`setStrictnessInfo` sig) id
578
579 zapIdStrictness :: Id -> Id
580 zapIdStrictness id = modifyIdInfo (`setStrictnessInfo` nopSig) id
581
582 -- | This predicate says whether the 'Id' has a strict demand placed on it or
583 -- has a type such that it can always be evaluated strictly (i.e an
584 -- unlifted type, as of GHC 7.6). We need to
585 -- check separately whether the 'Id' has a so-called \"strict type\" because if
586 -- the demand for the given @id@ hasn't been computed yet but @id@ has a strict
587 -- type, we still want @isStrictId id@ to be @True@.
588 isStrictId :: Id -> Bool
589 isStrictId id
590 = ASSERT2( isId id, text "isStrictId: not an id: " <+> ppr id )
591 (isStrictType (idType id)) ||
592 -- Take the best of both strictnesses - old and new
593 (isStrictDmd (idDemandInfo id))
594
595 ---------------------------------
596 -- UNFOLDING
597 idUnfolding :: Id -> Unfolding
598 -- Do not expose the unfolding of a loop breaker!
599 idUnfolding id
600 | isStrongLoopBreaker (occInfo info) = NoUnfolding
601 | otherwise = unfoldingInfo info
602 where
603 info = idInfo id
604
605 realIdUnfolding :: Id -> Unfolding
606 -- Expose the unfolding if there is one, including for loop breakers
607 realIdUnfolding id = unfoldingInfo (idInfo id)
608
609 setIdUnfoldingLazily :: Id -> Unfolding -> Id
610 setIdUnfoldingLazily id unfolding = modifyIdInfo (`setUnfoldingInfoLazily` unfolding) id
611
612 setIdUnfolding :: Id -> Unfolding -> Id
613 setIdUnfolding id unfolding = modifyIdInfo (`setUnfoldingInfo` unfolding) id
614
615 idDemandInfo :: Id -> Demand
616 idDemandInfo id = demandInfo (idInfo id)
617
618 setIdDemandInfo :: Id -> Demand -> Id
619 setIdDemandInfo id dmd = modifyIdInfo (`setDemandInfo` dmd) id
620
621 ---------------------------------
622 -- SPECIALISATION
623
624 -- See Note [Specialisations and RULES in IdInfo] in IdInfo.hs
625
626 idSpecialisation :: Id -> RuleInfo
627 idSpecialisation id = ruleInfo (idInfo id)
628
629 idCoreRules :: Id -> [CoreRule]
630 idCoreRules id = ruleInfoRules (idSpecialisation id)
631
632 idHasRules :: Id -> Bool
633 idHasRules id = not (isEmptyRuleInfo (idSpecialisation id))
634
635 setIdSpecialisation :: Id -> RuleInfo -> Id
636 setIdSpecialisation id spec_info = modifyIdInfo (`setRuleInfo` spec_info) id
637
638 ---------------------------------
639 -- CAF INFO
640 idCafInfo :: Id -> CafInfo
641 idCafInfo id = cafInfo (idInfo id)
642
643 setIdCafInfo :: Id -> CafInfo -> Id
644 setIdCafInfo id caf_info = modifyIdInfo (`setCafInfo` caf_info) id
645
646 ---------------------------------
647 -- Occcurrence INFO
648 idOccInfo :: Id -> OccInfo
649 idOccInfo id = occInfo (idInfo id)
650
651 setIdOccInfo :: Id -> OccInfo -> Id
652 setIdOccInfo id occ_info = modifyIdInfo (`setOccInfo` occ_info) id
653
654 zapIdOccInfo :: Id -> Id
655 zapIdOccInfo b = b `setIdOccInfo` NoOccInfo
656
657 {-
658 ---------------------------------
659 -- INLINING
660 The inline pragma tells us to be very keen to inline this Id, but it's still
661 OK not to if optimisation is switched off.
662 -}
663
664 idInlinePragma :: Id -> InlinePragma
665 idInlinePragma id = inlinePragInfo (idInfo id)
666
667 setInlinePragma :: Id -> InlinePragma -> Id
668 setInlinePragma id prag = modifyIdInfo (`setInlinePragInfo` prag) id
669
670 modifyInlinePragma :: Id -> (InlinePragma -> InlinePragma) -> Id
671 modifyInlinePragma id fn = modifyIdInfo (\info -> info `setInlinePragInfo` (fn (inlinePragInfo info))) id
672
673 idInlineActivation :: Id -> Activation
674 idInlineActivation id = inlinePragmaActivation (idInlinePragma id)
675
676 setInlineActivation :: Id -> Activation -> Id
677 setInlineActivation id act = modifyInlinePragma id (\prag -> setInlinePragmaActivation prag act)
678
679 idRuleMatchInfo :: Id -> RuleMatchInfo
680 idRuleMatchInfo id = inlinePragmaRuleMatchInfo (idInlinePragma id)
681
682 isConLikeId :: Id -> Bool
683 isConLikeId id = isDataConWorkId id || isConLike (idRuleMatchInfo id)
684
685 {-
686 ---------------------------------
687 -- ONE-SHOT LAMBDAS
688 -}
689
690 idOneShotInfo :: Id -> OneShotInfo
691 idOneShotInfo id = oneShotInfo (idInfo id)
692
693 -- | Like 'idOneShotInfo', but taking the Horrible State Hack in to account
694 -- See Note [The state-transformer hack] in CoreArity
695 idStateHackOneShotInfo :: Id -> OneShotInfo
696 idStateHackOneShotInfo id
697 | isStateHackType (idType id) = stateHackOneShot
698 | otherwise = idOneShotInfo id
699
700 -- | Returns whether the lambda associated with the 'Id' is certainly applied at most once
701 -- This one is the "business end", called externally.
702 -- It works on type variables as well as Ids, returning True
703 -- Its main purpose is to encapsulate the Horrible State Hack
704 -- See Note [The state-transformer hack] in CoreArity
705 isOneShotBndr :: Var -> Bool
706 isOneShotBndr var
707 | isTyVar var = True
708 | OneShotLam <- idStateHackOneShotInfo var = True
709 | otherwise = False
710
711 -- | Should we apply the state hack to values of this 'Type'?
712 stateHackOneShot :: OneShotInfo
713 stateHackOneShot = OneShotLam -- Or maybe ProbOneShot?
714
715 typeOneShot :: Type -> OneShotInfo
716 typeOneShot ty
717 | isStateHackType ty = stateHackOneShot
718 | otherwise = NoOneShotInfo
719
720 isStateHackType :: Type -> Bool
721 isStateHackType ty
722 | opt_NoStateHack
723 = False
724 | otherwise
725 = case tyConAppTyCon_maybe ty of
726 Just tycon -> tycon == statePrimTyCon
727 _ -> False
728 -- This is a gross hack. It claims that
729 -- every function over realWorldStatePrimTy is a one-shot
730 -- function. This is pretty true in practice, and makes a big
731 -- difference. For example, consider
732 -- a `thenST` \ r -> ...E...
733 -- The early full laziness pass, if it doesn't know that r is one-shot
734 -- will pull out E (let's say it doesn't mention r) to give
735 -- let lvl = E in a `thenST` \ r -> ...lvl...
736 -- When `thenST` gets inlined, we end up with
737 -- let lvl = E in \s -> case a s of (r, s') -> ...lvl...
738 -- and we don't re-inline E.
739 --
740 -- It would be better to spot that r was one-shot to start with, but
741 -- I don't want to rely on that.
742 --
743 -- Another good example is in fill_in in PrelPack.hs. We should be able to
744 -- spot that fill_in has arity 2 (and when Keith is done, we will) but we can't yet.
745
746 isProbablyOneShotLambda :: Id -> Bool
747 isProbablyOneShotLambda id = case idStateHackOneShotInfo id of
748 OneShotLam -> True
749 ProbOneShot -> True
750 NoOneShotInfo -> False
751
752 setOneShotLambda :: Id -> Id
753 setOneShotLambda id = modifyIdInfo (`setOneShotInfo` OneShotLam) id
754
755 clearOneShotLambda :: Id -> Id
756 clearOneShotLambda id = modifyIdInfo (`setOneShotInfo` NoOneShotInfo) id
757
758 setIdOneShotInfo :: Id -> OneShotInfo -> Id
759 setIdOneShotInfo id one_shot = modifyIdInfo (`setOneShotInfo` one_shot) id
760
761 updOneShotInfo :: Id -> OneShotInfo -> Id
762 -- Combine the info in the Id with new info
763 updOneShotInfo id one_shot
764 | do_upd = setIdOneShotInfo id one_shot
765 | otherwise = id
766 where
767 do_upd = case (idOneShotInfo id, one_shot) of
768 (NoOneShotInfo, _) -> True
769 (OneShotLam, _) -> False
770 (_, NoOneShotInfo) -> False
771 _ -> True
772
773 -- The OneShotLambda functions simply fiddle with the IdInfo flag
774 -- But watch out: this may change the type of something else
775 -- f = \x -> e
776 -- If we change the one-shot-ness of x, f's type changes
777
778 zapInfo :: (IdInfo -> Maybe IdInfo) -> Id -> Id
779 zapInfo zapper id = maybeModifyIdInfo (zapper (idInfo id)) id
780
781 zapLamIdInfo :: Id -> Id
782 zapLamIdInfo = zapInfo zapLamInfo
783
784 zapFragileIdInfo :: Id -> Id
785 zapFragileIdInfo = zapInfo zapFragileInfo
786
787 zapIdDemandInfo :: Id -> Id
788 zapIdDemandInfo = zapInfo zapDemandInfo
789
790 zapIdUsageInfo :: Id -> Id
791 zapIdUsageInfo = zapInfo zapUsageInfo
792
793 zapIdUsageEnvInfo :: Id -> Id
794 zapIdUsageEnvInfo = zapInfo zapUsageEnvInfo
795
796 zapIdUsedOnceInfo :: Id -> Id
797 zapIdUsedOnceInfo = zapInfo zapUsedOnceInfo
798
799 {-
800 Note [transferPolyIdInfo]
801 ~~~~~~~~~~~~~~~~~~~~~~~~~
802 This transfer is used in two places:
803 FloatOut (long-distance let-floating)
804 SimplUtils.abstractFloats (short-distance let-floating)
805
806 Consider the short-distance let-floating:
807
808 f = /\a. let g = rhs in ...
809
810 Then if we float thus
811
812 g' = /\a. rhs
813 f = /\a. ...[g' a/g]....
814
815 we *do not* want to lose g's
816 * strictness information
817 * arity
818 * inline pragma (though that is bit more debatable)
819 * occurrence info
820
821 Mostly this is just an optimisation, but it's *vital* to
822 transfer the occurrence info. Consider
823
824 NonRec { f = /\a. let Rec { g* = ..g.. } in ... }
825
826 where the '*' means 'LoopBreaker'. Then if we float we must get
827
828 Rec { g'* = /\a. ...(g' a)... }
829 NonRec { f = /\a. ...[g' a/g]....}
830
831 where g' is also marked as LoopBreaker. If not, terrible things
832 can happen if we re-simplify the binding (and the Simplifier does
833 sometimes simplify a term twice); see Trac #4345.
834
835 It's not so simple to retain
836 * worker info
837 * rules
838 so we simply discard those. Sooner or later this may bite us.
839
840 If we abstract wrt one or more *value* binders, we must modify the
841 arity and strictness info before transferring it. E.g.
842 f = \x. e
843 -->
844 g' = \y. \x. e
845 + substitute (g' y) for g
846 Notice that g' has an arity one more than the original g
847 -}
848
849 transferPolyIdInfo :: Id -- Original Id
850 -> [Var] -- Abstract wrt these variables
851 -> Id -- New Id
852 -> Id
853 transferPolyIdInfo old_id abstract_wrt new_id
854 = modifyIdInfo transfer new_id
855 where
856 arity_increase = count isId abstract_wrt -- Arity increases by the
857 -- number of value binders
858
859 old_info = idInfo old_id
860 old_arity = arityInfo old_info
861 old_inline_prag = inlinePragInfo old_info
862 old_occ_info = occInfo old_info
863 new_arity = old_arity + arity_increase
864
865 old_strictness = strictnessInfo old_info
866 new_strictness = increaseStrictSigArity arity_increase old_strictness
867
868 transfer new_info = new_info `setArityInfo` new_arity
869 `setInlinePragInfo` old_inline_prag
870 `setOccInfo` old_occ_info
871 `setStrictnessInfo` new_strictness