Implement DuplicateRecordFields
[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 recordSelectorTyCon,
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 unnecessary 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 {- 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 GlobalIds, 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'. Panic otherwise.
357 recordSelectorTyCon :: Id -> TyCon
358 recordSelectorTyCon id
359 = case Var.idDetails id of
360 RecSelId { sel_tycon = tycon } -> tycon
361 _ -> panic "recordSelectorTyCon"
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 -> RuleInfo
577 idSpecialisation id = ruleInfo (idInfo id)
578
579 idCoreRules :: Id -> [CoreRule]
580 idCoreRules id = ruleInfoRules (idSpecialisation id)
581
582 idHasRules :: Id -> Bool
583 idHasRules id = not (isEmptyRuleInfo (idSpecialisation id))
584
585 setIdSpecialisation :: Id -> RuleInfo -> Id
586 setIdSpecialisation id spec_info = modifyIdInfo (`setRuleInfo` 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 zapIdDemandInfo :: Id -> Id
737 zapIdDemandInfo = zapInfo zapDemandInfo
738
739 zapIdUsageInfo :: Id -> Id
740 zapIdUsageInfo = zapInfo zapUsageInfo
741
742 {-
743 Note [transferPolyIdInfo]
744 ~~~~~~~~~~~~~~~~~~~~~~~~~
745 This transfer is used in two places:
746 FloatOut (long-distance let-floating)
747 SimplUtils.abstractFloats (short-distance let-floating)
748
749 Consider the short-distance let-floating:
750
751 f = /\a. let g = rhs in ...
752
753 Then if we float thus
754
755 g' = /\a. rhs
756 f = /\a. ...[g' a/g]....
757
758 we *do not* want to lose g's
759 * strictness information
760 * arity
761 * inline pragma (though that is bit more debatable)
762 * occurrence info
763
764 Mostly this is just an optimisation, but it's *vital* to
765 transfer the occurrence info. Consider
766
767 NonRec { f = /\a. let Rec { g* = ..g.. } in ... }
768
769 where the '*' means 'LoopBreaker'. Then if we float we must get
770
771 Rec { g'* = /\a. ...(g' a)... }
772 NonRec { f = /\a. ...[g' a/g]....}
773
774 where g' is also marked as LoopBreaker. If not, terrible things
775 can happen if we re-simplify the binding (and the Simplifier does
776 sometimes simplify a term twice); see Trac #4345.
777
778 It's not so simple to retain
779 * worker info
780 * rules
781 so we simply discard those. Sooner or later this may bite us.
782
783 If we abstract wrt one or more *value* binders, we must modify the
784 arity and strictness info before transferring it. E.g.
785 f = \x. e
786 -->
787 g' = \y. \x. e
788 + substitute (g' y) for g
789 Notice that g' has an arity one more than the original g
790 -}
791
792 transferPolyIdInfo :: Id -- Original Id
793 -> [Var] -- Abstract wrt these variables
794 -> Id -- New Id
795 -> Id
796 transferPolyIdInfo old_id abstract_wrt new_id
797 = modifyIdInfo transfer new_id
798 where
799 arity_increase = count isId abstract_wrt -- Arity increases by the
800 -- number of value binders
801
802 old_info = idInfo old_id
803 old_arity = arityInfo old_info
804 old_inline_prag = inlinePragInfo old_info
805 old_occ_info = occInfo old_info
806 new_arity = old_arity + arity_increase
807
808 old_strictness = strictnessInfo old_info
809 new_strictness = increaseStrictSigArity arity_increase old_strictness
810
811 transfer new_info = new_info `setArityInfo` new_arity
812 `setInlinePragInfo` old_inline_prag
813 `setOccInfo` old_occ_info
814 `setStrictnessInfo` new_strictness