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