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