Id.lhs 24 KB
Newer Older
1
%
Simon Marlow's avatar
Simon Marlow committed
2
% (c) The University of Glasgow 2006
3
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 5 6 7
%
\section[Id]{@Ids@: Value and constructor identifiers}

\begin{code}
batterseapower's avatar
batterseapower committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
-- |
-- #name_types#
-- GHC uses several kinds of name internally:
--
-- * 'OccName.OccName': see "OccName#name_types"
--
-- * 'RdrName.RdrName': see "RdrName#name_types"
--
-- * 'Name.Name': see "Name#name_types"
--
-- * 'Id.Id' represents names that not only have a 'Name.Name' but also a 'TypeRep.Type' and some additional
--   details (a 'IdInfo.IdInfo' and one of 'Var.LocalIdDetails' or 'IdInfo.GlobalIdDetails') that
--   are added, modified and inspected by various compiler passes. These 'Var.Var' names may either 
--   be global or local, see "Var#globalvslocal"
--
-- * 'Var.Var': see "Var#name_types"
Ian Lynagh's avatar
Ian Lynagh committed
24 25 26 27 28 29 30 31

{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details

32
module Id (
33
        -- * The main types
34
	Var, Id, isId,
35

36 37
	-- ** Simple construction
	mkGlobalId, mkVanillaGlobal, mkVanillaGlobalWithInfo,
38
	mkLocalId, mkLocalIdWithInfo, mkExportedLocalId,
39
	mkSysLocal, mkSysLocalM, mkUserLocal, mkUserLocalM,
40
	mkTemplateLocals, mkTemplateLocalsNum, mkTemplateLocal,
41
	mkWorkerId, mkWiredInIdName,
42

43
	-- ** Taking an Id apart
44
	idName, idType, idUnique, idInfo, idDetails,
45
	idPrimRep, recordSelectorFieldLabel,
46

47
	-- ** Modifying an Id
48 49 50 51
	setIdName, setIdUnique, Id.setIdType, 
	setIdExported, setIdNotExported, 
	globaliseId, localiseId, 
	setIdInfo, lazySetIdInfo, modifyIdInfo, maybeModifyIdInfo,
52
	zapLamIdInfo, zapDemandIdInfo, zapFragileIdInfo, transferPolyIdInfo,
53
	
54

55
	-- ** Predicates on Ids
56 57
	isImplicitId, isDeadBinder, 
        isStrictId,
58
	isExportedId, isLocalId, isGlobalId,
59
	isRecordSelector, isNaughtyRecordSelector,
60
        isClassOpId_maybe, isDFunId, 
61
	isPrimOpId, isPrimOpId_maybe, 
62
	isFCallId, isFCallId_maybe,
63
	isDataConWorkId, isDataConWorkId_maybe, isDataConId_maybe, idDataCon,
64
        isConLikeId, isBottomingId, idIsFrom,
65
        hasNoBinding,
66

67
	-- ** Evidence variables
68
	DictId, isDictId, isEvVar,
69

70
	-- ** Inline pragma stuff
71 72
	idInlinePragma, setInlinePragma, modifyInlinePragma,
        idInlineActivation, setInlineActivation, idRuleMatchInfo,
73

batterseapower's avatar
batterseapower committed
74
	-- ** One-shot lambdas
75 76
	isOneShotBndr, isOneShotLambda, isStateHackType,
	setOneShotLambda, clearOneShotLambda,
77

batterseapower's avatar
batterseapower committed
78 79
	-- ** Reading 'IdInfo' fields
	idArity, 
80 81
	idDemandInfo, idDemandInfo_maybe,
	idStrictness, idStrictness_maybe, 
82
	idUnfolding, realIdUnfolding,
batterseapower's avatar
batterseapower committed
83 84 85 86 87 88
	idSpecialisation, idCoreRules, idHasRules,
	idCafInfo,
	idLBVarInfo,
	idOccInfo,

	-- ** Writing 'IdInfo' fields
89
	setIdUnfoldingLazily,
90
	setIdUnfolding,
91
	setIdArity,
92 93
	setIdDemandInfo, 
	setIdStrictness, zapIdStrictness,
94
	setIdSpecialisation,
95
	setIdCafInfo,
96
	setIdOccInfo, zapIdOccInfo,
97

98
    ) where
99

100
#include "HsVersions.h"
sof's avatar
sof committed
101

102
import CoreSyn ( CoreRule, Unfolding( NoUnfolding ) )
103 104

import IdInfo
Simon Marlow's avatar
Simon Marlow committed
105
import BasicTypes
106 107

-- Imported and re-exported 
108
import Var( Var, Id, DictId,
109
            idInfo, idDetails, globaliseId, varType,
110
            isId, isLocalId, isGlobalId, isExportedId )
Simon Marlow's avatar
Simon Marlow committed
111
import qualified Var
112

Simon Marlow's avatar
Simon Marlow committed
113 114
import TyCon
import Type
batterseapower's avatar
batterseapower committed
115
import TysPrim
Simon Marlow's avatar
Simon Marlow committed
116
import DataCon
117
import Demand
Simon Marlow's avatar
Simon Marlow committed
118 119
import Name
import Module
twanvl's avatar
twanvl committed
120 121 122
import Class
import PrimOp
import ForeignCall
Simon Marlow's avatar
Simon Marlow committed
123 124
import Maybes
import SrcLoc
125
import Outputable
Simon Marlow's avatar
Simon Marlow committed
126
import Unique
127
import UniqSupply
Simon Marlow's avatar
Simon Marlow committed
128
import FastString
129
import Util( count )
Simon Marlow's avatar
Simon Marlow committed
130
import StaticFlags
131

132
-- infixl so you can say (id `set` a `set` b)
133 134
infixl 	1 `setIdUnfoldingLazily`,
	  `setIdUnfolding`,
135
	  `setIdArity`,
136
	  `setIdOccInfo`,
137 138
	  `setIdDemandInfo`,
	  `setIdStrictness`,
139
	  `setIdSpecialisation`,
140
	  `setInlinePragma`,
141
	  `setInlineActivation`,
142
	  `idCafInfo`
143
\end{code}
batterseapower's avatar
batterseapower committed
144

145 146 147 148 149 150 151 152 153 154 155
%************************************************************************
%*									*
\subsection{Basic Id manipulation}
%*									*
%************************************************************************

\begin{code}
idName   :: Id -> Name
idName    = Var.varName

idUnique :: Id -> Unique
156
idUnique  = Var.varUnique
157 158

idType   :: Id -> Kind
159
idType    = Var.varType
batterseapower's avatar
batterseapower committed
160 161 162 163

idPrimRep :: Id -> PrimRep
idPrimRep id = typePrimRep (idType id)

164
setIdName :: Id -> Name -> Id
165
setIdName = Var.setVarName
166

batterseapower's avatar
batterseapower committed
167
setIdUnique :: Id -> Unique -> Id
168
setIdUnique = Var.setVarUnique
batterseapower's avatar
batterseapower committed
169 170 171

-- | Not only does this set the 'Id' 'Type', it also evaluates the type to try and
-- reduce space usage
172 173
setIdType :: Id -> Type -> Id
setIdType id ty = seqType ty `seq` Var.setVarType id ty
174

175
setIdExported :: Id -> Id
176
setIdExported = Var.setIdExported
177

178
setIdNotExported :: Id -> Id
179
setIdNotExported = Var.setIdNotExported
180

181 182 183 184
localiseId :: Id -> Id
-- Make an with the same unique and type as the 
-- incoming Id, but with an *Internal* Name and *LocalId* flavour
localiseId id 
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
185
  | ASSERT( isId id ) isLocalId id && isInternalName name
186 187 188 189 190 191
  = id
  | otherwise
  = mkLocalIdWithInfo (localiseName name) (idType id) (idInfo id)
  where
    name = idName id

192
lazySetIdInfo :: Id -> IdInfo -> Id
193
lazySetIdInfo = Var.lazySetIdInfo
194 195 196 197 198 199 200 201 202 203 204 205 206

setIdInfo :: Id -> IdInfo -> Id
setIdInfo id info = seqIdInfo info `seq` (lazySetIdInfo id info)
        -- Try to avoid spack leaks by seq'ing

modifyIdInfo :: (IdInfo -> IdInfo) -> Id -> Id
modifyIdInfo fn id = setIdInfo id (fn (idInfo id))

-- maybeModifyIdInfo tries to avoid unnecesary thrashing
maybeModifyIdInfo :: Maybe IdInfo -> Id -> Id
maybeModifyIdInfo (Just new_info) id = lazySetIdInfo id new_info
maybeModifyIdInfo Nothing	  id = id
\end{code}
207

208 209
%************************************************************************
%*									*
210
\subsection{Simple Id construction}
211 212 213
%*									*
%************************************************************************

214 215 216
Absolutely all Ids are made by mkId.  It is just like Var.mkId,
but in addition it pins free-tyvar-info onto the Id's type, 
where it can easily be found.
217

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
218 219 220 221 222 223 224 225 226 227
Note [Free type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~
At one time we cached the free type variables of the type of an Id
at the root of the type in a TyNote.  The idea was to avoid repeating
the free-type-variable calculation.  But it turned out to slow down
the compiler overall. I don't quite know why; perhaps finding free
type variables of an Id isn't all that common whereas applying a 
substitution (which changes the free type variables) is more common.
Anyway, we removed it in March 2008.

228
\begin{code}
batterseapower's avatar
batterseapower committed
229
-- | For an explanation of global vs. local 'Id's, see "Var#globalvslocal"
230 231
mkGlobalId :: IdDetails -> Name -> Type -> IdInfo -> Id
mkGlobalId = Var.mkGlobalVar
232

batterseapower's avatar
batterseapower committed
233
-- | Make a global 'Id' without any extra information at all
234 235
mkVanillaGlobal :: Name -> Type -> Id
mkVanillaGlobal name ty = mkVanillaGlobalWithInfo name ty vanillaIdInfo
236

batterseapower's avatar
batterseapower committed
237
-- | Make a global 'Id' with no global information but some generic 'IdInfo'
238
mkVanillaGlobalWithInfo :: Name -> Type -> IdInfo -> Id
239
mkVanillaGlobalWithInfo = mkGlobalId VanillaId
240

241

batterseapower's avatar
batterseapower committed
242
-- | For an explanation of global vs. local 'Id's, see "Var#globalvslocal"
243
mkLocalId :: Name -> Type -> Id
244
mkLocalId name ty = mkLocalIdWithInfo name ty vanillaIdInfo
245

246
mkLocalIdWithInfo :: Name -> Type -> IdInfo -> Id
247
mkLocalIdWithInfo name ty info = Var.mkLocalVar VanillaId name ty info
batterseapower's avatar
batterseapower committed
248
	-- Note [Free type variables]
249

250 251
-- | Create a local 'Id' that is marked as exported. 
-- This prevents things attached to it from being removed as dead code.
252
mkExportedLocalId :: Name -> Type -> Id
253
mkExportedLocalId name ty = Var.mkExportedLocalVar VanillaId name ty vanillaIdInfo
254 255 256
	-- Note [Free type variables]


257 258
-- | Create a system local 'Id'. These are local 'Id's (see "Var#globalvslocal") 
-- that are created by the compiler out of thin air
259 260 261
mkSysLocal :: FastString -> Unique -> Type -> Id
mkSysLocal fs uniq ty = mkLocalId (mkSystemVarName uniq fs) ty

262 263 264
mkSysLocalM :: MonadUnique m => FastString -> Type -> m Id
mkSysLocalM fs ty = getUniqueM >>= (\uniq -> return (mkSysLocal fs uniq ty))

265

batterseapower's avatar
batterseapower committed
266
-- | Create a user local 'Id'. These are local 'Id's (see "Var#globalvslocal") with a name and location that the user might recognize
267
mkUserLocal :: OccName -> Unique -> Type -> SrcSpan -> Id
268
mkUserLocal occ uniq ty loc = mkLocalId (mkInternalName uniq occ loc) ty
269

270 271
mkUserLocalM :: MonadUnique m => OccName -> Type -> SrcSpan -> m Id
mkUserLocalM occ ty loc = getUniqueM >>= (\uniq -> return (mkUserLocal occ uniq ty loc))
batterseapower's avatar
batterseapower committed
272

273 274 275
mkWiredInIdName :: Module -> FastString -> Unique -> Id -> Name
mkWiredInIdName mod fs uniq id
 = mkWiredInName mod (mkOccNameFS varName fs) uniq (AnId id) UserSyntax
276
\end{code}
277 278 279 280

Make some local @Ids@ for a template @CoreExpr@.  These have bogus
@Uniques@, but that's OK because the templates are supposed to be
instantiated before use.
281
 
282
\begin{code}
batterseapower's avatar
batterseapower committed
283
-- | Workers get local names. "CoreTidy" will externalise these if necessary
284 285
mkWorkerId :: Unique -> Id -> Type -> Id
mkWorkerId uniq unwrkr ty
286
  = mkLocalId (mkDerivedInternalName mkWorkerOcc uniq (getName unwrkr)) ty
287

batterseapower's avatar
batterseapower committed
288
-- | Create a /template local/: a family of system local 'Id's in bijection with @Int@s, typically used in unfoldings
289 290 291 292
mkTemplateLocal :: Int -> Type -> Id
mkTemplateLocal i ty = mkSysLocal (fsLit "tpl") (mkBuiltinUnique i) ty

-- | Create a template local for a series of types
293
mkTemplateLocals :: [Type] -> [Id]
294
mkTemplateLocals = mkTemplateLocalsNum 1
295

296
-- | Create a template local for a series of type, but start from a specified template local
297
mkTemplateLocalsNum :: Int -> [Type] -> [Id]
298
mkTemplateLocalsNum n tys = zipWith mkTemplateLocal [n..] tys
299 300 301
\end{code}


302 303
%************************************************************************
%*									*
304
\subsection{Special Ids}
305 306 307
%*									*
%************************************************************************

308
\begin{code}
batterseapower's avatar
batterseapower committed
309
-- | If the 'Id' is that for a record selector, extract the 'sel_tycon' and label. Panic otherwise
310
recordSelectorFieldLabel :: Id -> (TyCon, FieldLabel)
311
recordSelectorFieldLabel id
312 313
  = case Var.idDetails id of
        RecSelId { sel_tycon = tycon } -> (tycon, idName id)
twanvl's avatar
twanvl committed
314 315
        _ -> panic "recordSelectorFieldLabel"

316 317 318 319 320
isRecordSelector        :: Id -> Bool
isNaughtyRecordSelector :: Id -> Bool
isPrimOpId              :: Id -> Bool
isFCallId               :: Id -> Bool
isDataConWorkId         :: Id -> Bool
321
isDFunId                :: Id -> Bool
twanvl's avatar
twanvl committed
322

323 324 325 326
isClassOpId_maybe       :: Id -> Maybe Class
isPrimOpId_maybe        :: Id -> Maybe PrimOp
isFCallId_maybe         :: Id -> Maybe ForeignCall
isDataConWorkId_maybe   :: Id -> Maybe DataCon
sof's avatar
sof committed
327

328 329
isRecordSelector id = case Var.idDetails id of
                        RecSelId {}  -> True
twanvl's avatar
twanvl committed
330
                        _               -> False
sof's avatar
sof committed
331

332 333
isNaughtyRecordSelector id = case Var.idDetails id of
                        RecSelId { sel_naughty = n } -> n
twanvl's avatar
twanvl committed
334
                        _                               -> False
335

336
isClassOpId_maybe id = case Var.idDetails id of
337 338 339
			ClassOpId cls -> Just cls
			_other        -> Nothing

340
isPrimOpId id = case Var.idDetails id of
twanvl's avatar
twanvl committed
341 342
                        PrimOpId _ -> True
                        _          -> False
343

344
isDFunId id = case Var.idDetails id of
345 346 347
                        DFunId {} -> True
                        _         -> False

348
isPrimOpId_maybe id = case Var.idDetails id of
twanvl's avatar
twanvl committed
349 350
                        PrimOpId op -> Just op
                        _           -> Nothing
351

352
isFCallId id = case Var.idDetails id of
twanvl's avatar
twanvl committed
353 354
                        FCallId _ -> True
                        _         -> False
355

356
isFCallId_maybe id = case Var.idDetails id of
twanvl's avatar
twanvl committed
357 358
                        FCallId call -> Just call
                        _            -> Nothing
359

360
isDataConWorkId id = case Var.idDetails id of
twanvl's avatar
twanvl committed
361 362
                        DataConWorkId _ -> True
                        _               -> False
sof's avatar
sof committed
363

364
isDataConWorkId_maybe id = case Var.idDetails id of
twanvl's avatar
twanvl committed
365 366
                        DataConWorkId con -> Just con
                        _                 -> Nothing
sof's avatar
sof committed
367

368
isDataConId_maybe :: Id -> Maybe DataCon
369
isDataConId_maybe id = case Var.idDetails id of
twanvl's avatar
twanvl committed
370 371 372
                         DataConWorkId con -> Just con
                         DataConWrapId con -> Just con
                         _                 -> Nothing
373

374
idDataCon :: Id -> DataCon
batterseapower's avatar
batterseapower committed
375
-- ^ Get from either the worker or the wrapper 'Id' to the 'DataCon'. Currently used only in the desugarer.
376
--
batterseapower's avatar
batterseapower committed
377 378
-- INVARIANT: @idDataCon (dataConWrapId d) = d@: remember, 'dataConWrapId' can return either the wrapper or the worker
idDataCon id = isDataConId_maybe id `orElse` pprPanic "idDataCon" (ppr id)
379

380
hasNoBinding :: Id -> Bool
batterseapower's avatar
batterseapower committed
381 382 383
-- ^ Returns @True@ of an 'Id' which may not have a
-- binding, even though it is defined in this module.

384 385
-- Data constructor workers used to be things of this kind, but
-- they aren't any more.  Instead, we inject a binding for 
386 387
-- them at the CorePrep stage. 
-- EXCEPT: unboxed tuples, which definitely have no binding
388
hasNoBinding id = case Var.idDetails id of
389
			PrimOpId _  	 -> True	-- See Note [Primop wrappers]
390 391
			FCallId _   	 -> True
			DataConWorkId dc -> isUnboxedTupleCon dc
twanvl's avatar
twanvl committed
392
			_                -> False
393

394
isImplicitId :: Id -> Bool
batterseapower's avatar
batterseapower committed
395
-- ^ 'isImplicitId' tells whether an 'Id's info is implied by other
396 397
-- declarations, so we don't need to put its signature in an interface
-- file, even if it's mentioned in some other interface unfolding.
398
isImplicitId id
399
  = case Var.idDetails id of
400 401 402 403 404
        FCallId {}       -> True
	ClassOpId {}     -> True
        PrimOpId {}      -> True
        DataConWorkId {} -> True
	DataConWrapId {} -> True
405
		-- These are are implied by their type or class decl;
406
		-- remember that all type and class decls appear in the interface file.
407 408
		-- The dfun id is not an implicit Id; it must *not* be omitted, because 
		-- it carries version info for the instance decl
twanvl's avatar
twanvl committed
409
        _               -> False
410 411 412

idIsFrom :: Module -> Id -> Bool
idIsFrom mod id = nameIsLocalOrFrom mod (idName id)
413 414
\end{code}

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
Note [Primop wrappers]
~~~~~~~~~~~~~~~~~~~~~~
Currently hasNoBinding claims that PrimOpIds don't have a curried
function definition.  But actually they do, in GHC.PrimopWrappers,
which is auto-generated from prelude/primops.txt.pp.  So actually, hasNoBinding
could return 'False' for PrimOpIds.

But we'd need to add something in CoreToStg to swizzle any unsaturated
applications of GHC.Prim.plusInt# to GHC.PrimopWrappers.plusInt#.

Nota Bene: GHC.PrimopWrappers is needed *regardless*, because it's
used by GHCi, which does not implement primops direct at all.



430 431
\begin{code}
isDeadBinder :: Id -> Bool
432
isDeadBinder bndr | isId bndr = isDeadOcc (idOccInfo bndr)
433
		  | otherwise = False	-- TyVars count as not dead
434 435
\end{code}

436 437 438 439 440 441 442
%************************************************************************
%*									*
              Evidence variables									
%*									*
%************************************************************************

\begin{code}
443 444
isEvVar :: Var -> Bool
isEvVar var = isPredTy (varType var)
445 446 447 448 449

isDictId :: Id -> Bool
isDictId id = isDictTy (idType id)
\end{code}

450 451
%************************************************************************
%*									*
452
\subsection{IdInfo stuff}
453 454 455
%*									*
%************************************************************************

456
\begin{code}
457 458
	---------------------------------
	-- ARITY
459
idArity :: Id -> Arity
460
idArity id = arityInfo (idInfo id)
461

462 463
setIdArity :: Id -> Arity -> Id
setIdArity id arity = modifyIdInfo (`setArityInfo` arity) id
464

465
-- | Returns true if an application to n args would diverge
466
isBottomingId :: Id -> Bool
467
isBottomingId id = isBottomingSig (idStrictness id)
468

469 470
idStrictness_maybe :: Id -> Maybe StrictSig
idStrictness :: Id -> StrictSig
471

472 473
idStrictness_maybe id = strictnessInfo (idInfo id)
idStrictness       id = idStrictness_maybe id `orElse` topSig
474

475 476
setIdStrictness :: Id -> StrictSig -> Id
setIdStrictness id sig = modifyIdInfo (`setStrictnessInfo` Just sig) id
477

478 479
zapIdStrictness :: Id -> Id
zapIdStrictness id = modifyIdInfo (`setStrictnessInfo` Nothing) id
480

batterseapower's avatar
batterseapower committed
481
-- | This predicate says whether the 'Id' has a strict demand placed on it or
482 483
-- has a type such that it can always be evaluated strictly (e.g., an
-- unlifted type, but see the comment for 'isStrictType').  We need to
batterseapower's avatar
batterseapower committed
484 485 486
-- check separately whether the 'Id' has a so-called \"strict type\" because if
-- the demand for the given @id@ hasn't been computed yet but @id@ has a strict
-- type, we still want @isStrictId id@ to be @True@.
487 488 489
isStrictId :: Id -> Bool
isStrictId id
  = ASSERT2( isId id, text "isStrictId: not an id: " <+> ppr id )
490
           (isStrictDmd (idDemandInfo id)) || 
491
           (isStrictType (idType id))
492

493 494
	---------------------------------
	-- UNFOLDING
495
idUnfolding :: Id -> Unfolding
496 497
-- Do not expose the unfolding of a loop breaker!
idUnfolding id 
498 499
  | isStrongLoopBreaker (occInfo info) = NoUnfolding
  | otherwise                          = unfoldingInfo info
500 501 502 503 504 505
  where
    info = idInfo id

realIdUnfolding :: Id -> Unfolding
-- Expose the unfolding if there is one, including for loop breakers
realIdUnfolding id = unfoldingInfo (idInfo id)
506

507 508 509
setIdUnfoldingLazily :: Id -> Unfolding -> Id
setIdUnfoldingLazily id unfolding = modifyIdInfo (`setUnfoldingInfoLazily` unfolding) id

510
setIdUnfolding :: Id -> Unfolding -> Id
511
setIdUnfolding id unfolding = modifyIdInfo (`setUnfoldingInfo` unfolding) id
sof's avatar
sof committed
512

513 514
idDemandInfo_maybe :: Id -> Maybe Demand
idDemandInfo       :: Id -> Demand
515

516 517
idDemandInfo_maybe id = demandInfo (idInfo id)
idDemandInfo       id = demandInfo (idInfo id) `orElse` topDmd
518

519 520
setIdDemandInfo :: Id -> Demand -> Id
setIdDemandInfo id dmd = modifyIdInfo (`setDemandInfo` Just dmd) id
521

522 523
	---------------------------------
	-- SPECIALISATION
524 525 526

-- See Note [Specialisations and RULES in IdInfo] in IdInfo.lhs

527
idSpecialisation :: Id -> SpecInfo
528
idSpecialisation id = specInfo (idInfo id)
529

530 531
idCoreRules :: Id -> [CoreRule]
idCoreRules id = specInfoRules (idSpecialisation id)
532

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
533 534 535
idHasRules :: Id -> Bool
idHasRules id = not (isEmptySpecInfo (idSpecialisation id))

536
setIdSpecialisation :: Id -> SpecInfo -> Id
537
setIdSpecialisation id spec_info = modifyIdInfo (`setSpecInfo` spec_info) id
538

539 540
	---------------------------------
	-- CAF INFO
541
idCafInfo :: Id -> CafInfo
542 543 544 545 546
idCafInfo id = cafInfo (idInfo id)

setIdCafInfo :: Id -> CafInfo -> Id
setIdCafInfo id caf_info = modifyIdInfo (`setCafInfo` caf_info) id

547 548
	---------------------------------
	-- Occcurrence INFO
549 550
idOccInfo :: Id -> OccInfo
idOccInfo id = occInfo (idInfo id)
551 552 553

setIdOccInfo :: Id -> OccInfo -> Id
setIdOccInfo id occ_info = modifyIdInfo (`setOccInfo` occ_info) id
554 555 556

zapIdOccInfo :: Id -> Id
zapIdOccInfo b = b `setIdOccInfo` NoOccInfo
557 558
\end{code}

sof's avatar
sof committed
559

560 561 562 563
	---------------------------------
	-- INLINING
The inline pragma tells us to be very keen to inline this Id, but it's still
OK not to if optimisation is switched off.
564 565

\begin{code}
566
idInlinePragma :: Id -> InlinePragma
567
idInlinePragma id = inlinePragInfo (idInfo id)
568

569
setInlinePragma :: Id -> InlinePragma -> Id
570
setInlinePragma id prag = modifyIdInfo (`setInlinePragInfo` prag) id
571

572
modifyInlinePragma :: Id -> (InlinePragma -> InlinePragma) -> Id
573
modifyInlinePragma id fn = modifyIdInfo (\info -> info `setInlinePragInfo` (fn (inlinePragInfo info))) id
574 575 576 577 578

idInlineActivation :: Id -> Activation
idInlineActivation id = inlinePragmaActivation (idInlinePragma id)

setInlineActivation :: Id -> Activation -> Id
579
setInlineActivation id act = modifyInlinePragma id (\prag -> setInlinePragmaActivation prag act)
580 581 582 583 584 585

idRuleMatchInfo :: Id -> RuleMatchInfo
idRuleMatchInfo id = inlinePragmaRuleMatchInfo (idInlinePragma id)

isConLikeId :: Id -> Bool
isConLikeId id = isDataConWorkId id || isConLike (idRuleMatchInfo id)
586
\end{code}
587 588 589 590 591


	---------------------------------
	-- ONE-SHOT LAMBDAS
\begin{code}
592 593 594
idLBVarInfo :: Id -> LBVarInfo
idLBVarInfo id = lbvarInfo (idInfo id)

batterseapower's avatar
batterseapower committed
595 596 597
-- | Returns whether the lambda associated with the 'Id' is certainly applied at most once
-- OR we are applying the \"state hack\" which makes it appear as if theis is the case for
-- lambdas used in @IO@. You should prefer using this over 'isOneShotLambda'
598 599 600
isOneShotBndr :: Id -> Bool
-- This one is the "business end", called externally.
-- Its main purpose is to encapsulate the Horrible State Hack
601
isOneShotBndr id = isOneShotLambda id || isStateHackType (idType id)
602

batterseapower's avatar
batterseapower committed
603
-- | Should we apply the state hack to values of this 'Type'?
604 605
isStateHackType :: Type -> Bool
isStateHackType ty
606 607 608
  | opt_NoStateHack 
  = False
  | otherwise
609 610 611
  = case tyConAppTyCon_maybe ty of
	Just tycon -> tycon == statePrimTyCon
        _          -> False
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
	-- This is a gross hack.  It claims that 
	-- every function over realWorldStatePrimTy is a one-shot
	-- function.  This is pretty true in practice, and makes a big
	-- difference.  For example, consider
	--	a `thenST` \ r -> ...E...
	-- The early full laziness pass, if it doesn't know that r is one-shot
	-- will pull out E (let's say it doesn't mention r) to give
	--	let lvl = E in a `thenST` \ r -> ...lvl...
	-- When `thenST` gets inlined, we end up with
	--	let lvl = E in \s -> case a s of (r, s') -> ...lvl...
	-- and we don't re-inline E.
	--
	-- It would be better to spot that r was one-shot to start with, but
	-- I don't want to rely on that.
	--
	-- Another good example is in fill_in in PrelPack.lhs.  We should be able to
	-- spot that fill_in has arity 2 (and when Keith is done, we will) but we can't yet.


batterseapower's avatar
batterseapower committed
631 632
-- | Returns whether the lambda associated with the 'Id' is certainly applied at most once.
-- You probably want to use 'isOneShotBndr' instead
633
isOneShotLambda :: Id -> Bool
634 635 636
isOneShotLambda id = case idLBVarInfo id of
                       IsOneShotLambda  -> True
                       NoLBVarInfo      -> False
637 638

setOneShotLambda :: Id -> Id
639
setOneShotLambda id = modifyIdInfo (`setLBVarInfo` IsOneShotLambda) id
640 641 642 643 644 645

clearOneShotLambda :: Id -> Id
clearOneShotLambda id 
  | isOneShotLambda id = modifyIdInfo (`setLBVarInfo` NoLBVarInfo) id
  | otherwise	       = id			

batterseapower's avatar
batterseapower committed
646
-- The OneShotLambda functions simply fiddle with the IdInfo flag
647 648 649
-- But watch out: this may change the type of something else
--	f = \x -> e
-- If we change the one-shot-ness of x, f's type changes
650
\end{code}
651 652

\begin{code}
653 654 655
zapInfo :: (IdInfo -> Maybe IdInfo) -> Id -> Id
zapInfo zapper id = maybeModifyIdInfo (zapper (idInfo id)) id

656
zapLamIdInfo :: Id -> Id
657 658
zapLamIdInfo = zapInfo zapLamInfo

twanvl's avatar
twanvl committed
659
zapDemandIdInfo :: Id -> Id
660
zapDemandIdInfo = zapInfo zapDemandInfo
661

662 663
zapFragileIdInfo :: Id -> Id
zapFragileIdInfo = zapInfo zapFragileInfo 
664
\end{code}
665

666 667
Note [transferPolyIdInfo]
~~~~~~~~~~~~~~~~~~~~~~~~~
668 669 670 671 672
This transfer is used in two places: 
	FloatOut (long-distance let-floating)
	SimplUtils.abstractFloats (short-distance let-floating)

Consider the short-distance let-floating:
673 674 675

   f = /\a. let g = rhs in ...

676
Then if we float thus
677 678

   g' = /\a. rhs
679
   f = /\a. ...[g' a/g]....
680

681 682 683 684
we *do not* want to lose g's
  * strictness information
  * arity 
  * inline pragma (though that is bit more debatable)
685 686 687 688 689 690 691 692
  * occurrence info

Mostly this is just an optimisation, but it's *vital* to
transfer the occurrence info.  Consider
   
   NonRec { f = /\a. let Rec { g* = ..g.. } in ... }

where the '*' means 'LoopBreaker'.  Then if we float we must get
693

694 695 696 697 698 699 700 701
   Rec { g'* = /\a. ...(g' a)... }
   NonRec { f = /\a. ...[g' a/g]....}

where g' is also marked as LoopBreaker.  If not, terrible things
can happen if we re-simplify the binding (and the Simplifier does
sometimes simplify a term twice); see Trac #4345.

It's not so simple to retain
702 703
  * worker info
  * rules
704 705
so we simply discard those.  Sooner or later this may bite us.

706 707 708 709 710 711 712 713
If we abstract wrt one or more *value* binders, we must modify the 
arity and strictness info before transferring it.  E.g. 
      f = \x. e
-->
      g' = \y. \x. e
      + substitute (g' y) for g
Notice that g' has an arity one more than the original g

714
\begin{code}
715 716 717 718 719
transferPolyIdInfo :: Id	-- Original Id
		   -> [Var]	-- Abstract wrt these variables
		   -> Id	-- New Id
		   -> Id
transferPolyIdInfo old_id abstract_wrt new_id
720 721
  = modifyIdInfo transfer new_id
  where
722 723 724 725 726 727
    arity_increase = count isId abstract_wrt	-- Arity increases by the
    		     	   			-- number of value binders

    old_info 	    = idInfo old_id
    old_arity       = arityInfo old_info
    old_inline_prag = inlinePragInfo old_info
728
    old_occ_info    = occInfo old_info
729
    new_arity       = old_arity + arity_increase
730
    old_strictness  = strictnessInfo old_info
731 732
    new_strictness  = fmap (increaseStrictSigArity arity_increase) old_strictness

733
    transfer new_info = new_info `setStrictnessInfo` new_strictness
734 735
			         `setArityInfo` new_arity
 			         `setInlinePragInfo` old_inline_prag
736
				 `setOccInfo` old_occ_info
737
\end{code}