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