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