[project @ 2005-06-15 12:03:19 by simonmar]
[ghc-hetmet.git] / ghc / compiler / basicTypes / Id.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[Id]{@Ids@: Value and constructor identifiers}
5
6 \begin{code}
7 module Id (
8         Id, DictId,
9
10         -- Simple construction
11         mkGlobalId, mkLocalId, mkSpecPragmaId, mkLocalIdWithInfo, 
12         mkSysLocal, mkSysLocalUnencoded, mkUserLocal, mkVanillaGlobal,
13         mkTemplateLocals, mkTemplateLocalsNum, mkWildId, mkTemplateLocal,
14         mkWorkerId, mkExportedLocalId,
15
16         -- Taking an Id apart
17         idName, idType, idUnique, idInfo,
18         isId, globalIdDetails, idPrimRep,
19         recordSelectorFieldLabel,
20
21         -- Modifying an Id
22         setIdName, setIdUnique, Id.setIdType, setIdExported, setIdNotExported, 
23         setIdInfo, lazySetIdInfo, modifyIdInfo, maybeModifyIdInfo,
24         zapLamIdInfo, zapDemandIdInfo, 
25
26         -- Predicates
27         isImplicitId, isDeadBinder,
28         isSpecPragmaId, isExportedId, isLocalId, isGlobalId,
29         isRecordSelector,
30         isClassOpId_maybe,
31         isPrimOpId, isPrimOpId_maybe, 
32         isFCallId, isFCallId_maybe,
33         isDataConWorkId, isDataConWorkId_maybe, idDataCon,
34         isBottomingId, idIsFrom,
35         hasNoBinding, 
36
37         -- Inline pragma stuff
38         idInlinePragma, setInlinePragma, modifyInlinePragma, 
39
40
41         -- One shot lambda stuff
42         isOneShotBndr, isOneShotLambda, isStateHackType,
43         setOneShotLambda, clearOneShotLambda,
44
45         -- IdInfo stuff
46         setIdUnfolding,
47         setIdArity,
48         setIdNewDemandInfo, 
49         setIdNewStrictness, zapIdNewStrictness,
50         setIdWorkerInfo,
51         setIdSpecialisation,
52         setIdCafInfo,
53         setIdOccInfo,
54
55 #ifdef OLD_STRICTNESS
56         idDemandInfo, 
57         idStrictness, 
58         idCprInfo,
59         setIdStrictness, 
60         setIdDemandInfo, 
61         setIdCprInfo,
62 #endif
63
64         idArity, 
65         idNewDemandInfo, idNewDemandInfo_maybe,
66         idNewStrictness, idNewStrictness_maybe, 
67         idWorkerInfo,
68         idUnfolding,
69         idSpecialisation, idCoreRules,
70         idCafInfo,
71         idLBVarInfo,
72         idOccInfo,
73
74 #ifdef OLD_STRICTNESS
75         newStrictnessFromOld    -- Temporary
76 #endif
77
78     ) where
79
80 #include "HsVersions.h"
81
82
83 import CoreSyn          ( Unfolding, CoreRule )
84 import BasicTypes       ( Arity )
85 import Var              ( Id, DictId,
86                           isId, isExportedId, isSpecPragmaId, isLocalId,
87                           idName, idType, idUnique, idInfo, isGlobalId,
88                           setIdName, setIdType, setIdUnique, 
89                           setIdExported, setIdNotExported,
90                           setIdInfo, lazySetIdInfo, modifyIdInfo, 
91                           maybeModifyIdInfo,
92                           globalIdDetails
93                         )
94 import qualified Var    ( mkLocalId, mkGlobalId, mkSpecPragmaId, mkExportedLocalId )
95 import TyCon            ( FieldLabel, TyCon )
96 import Type             ( Type, typePrimRep, addFreeTyVars, seqType, 
97                           splitTyConApp_maybe, PrimRep )
98 import TysPrim          ( statePrimTyCon )
99 import IdInfo 
100
101 #ifdef OLD_STRICTNESS
102 import qualified Demand ( Demand )
103 #endif
104 import DataCon          ( DataCon, isUnboxedTupleCon )
105 import NewDemand        ( Demand, StrictSig, topDmd, topSig, isBottomingSig )
106 import Name             ( Name, OccName, nameIsLocalOrFrom, 
107                           mkSystemVarName, mkSystemVarNameEncoded, mkInternalName,
108                           getOccName, getSrcLoc
109                         ) 
110 import Module           ( Module )
111 import OccName          ( EncodedFS, mkWorkerOcc )
112 import Maybes           ( orElse )
113 import SrcLoc           ( SrcLoc )
114 import Outputable
115 import Unique           ( Unique, mkBuiltinUnique )
116 import StaticFlags      ( opt_NoStateHack )
117
118 -- infixl so you can say (id `set` a `set` b)
119 infixl  1 `setIdUnfolding`,
120           `setIdArity`,
121           `setIdNewDemandInfo`,
122           `setIdNewStrictness`,
123           `setIdWorkerInfo`,
124           `setIdSpecialisation`,
125           `setInlinePragma`,
126           `idCafInfo`
127 #ifdef OLD_STRICTNESS
128           ,`idCprInfo`
129           ,`setIdStrictness`
130           ,`setIdDemandInfo`
131 #endif
132 \end{code}
133
134
135
136 %************************************************************************
137 %*                                                                      *
138 \subsection{Simple Id construction}
139 %*                                                                      *
140 %************************************************************************
141
142 Absolutely all Ids are made by mkId.  It is just like Var.mkId,
143 but in addition it pins free-tyvar-info onto the Id's type, 
144 where it can easily be found.
145
146 \begin{code}
147 mkLocalIdWithInfo :: Name -> Type -> IdInfo -> Id
148 mkLocalIdWithInfo name ty info = Var.mkLocalId name (addFreeTyVars ty) info
149
150 mkSpecPragmaId :: Name -> Type -> Id
151 mkSpecPragmaId name ty = Var.mkSpecPragmaId name (addFreeTyVars ty) vanillaIdInfo
152
153 mkExportedLocalId :: Name -> Type -> Id
154 mkExportedLocalId name ty = Var.mkExportedLocalId name (addFreeTyVars ty) vanillaIdInfo
155
156 mkGlobalId :: GlobalIdDetails -> Name -> Type -> IdInfo -> Id
157 mkGlobalId details name ty info = Var.mkGlobalId details name (addFreeTyVars ty) info
158 \end{code}
159
160 \begin{code}
161 mkLocalId :: Name -> Type -> Id
162 mkLocalId name ty = mkLocalIdWithInfo name ty vanillaIdInfo
163
164 -- SysLocal: for an Id being created by the compiler out of thin air...
165 -- UserLocal: an Id with a name the user might recognize...
166 mkUserLocal :: OccName -> Unique -> Type -> SrcLoc -> Id
167 mkSysLocal  :: EncodedFS  -> Unique -> Type -> Id
168 mkVanillaGlobal :: Name -> Type -> IdInfo -> Id
169
170 -- for SysLocal, we assume the base name is already encoded, to avoid
171 -- re-encoding the same string over and over again.
172 mkSysLocal fs uniq ty = mkLocalId (mkSystemVarNameEncoded uniq fs) ty
173
174 -- version to use when the faststring needs to be encoded
175 mkSysLocalUnencoded fs uniq ty = mkLocalId (mkSystemVarName uniq fs)  ty
176
177 mkUserLocal occ uniq ty loc = mkLocalId (mkInternalName    uniq occ loc) ty
178 mkVanillaGlobal             = mkGlobalId VanillaGlobal
179 \end{code}
180
181 Make some local @Ids@ for a template @CoreExpr@.  These have bogus
182 @Uniques@, but that's OK because the templates are supposed to be
183 instantiated before use.
184  
185 \begin{code}
186 -- "Wild Id" typically used when you need a binder that you don't expect to use
187 mkWildId :: Type -> Id
188 mkWildId ty = mkSysLocal FSLIT("wild") (mkBuiltinUnique 1) ty
189
190 mkWorkerId :: Unique -> Id -> Type -> Id
191 -- A worker gets a local name.  CoreTidy will externalise it if necessary.
192 mkWorkerId uniq unwrkr ty
193   = mkLocalId wkr_name ty
194   where
195     wkr_name = mkInternalName uniq (mkWorkerOcc (getOccName unwrkr)) (getSrcLoc unwrkr)
196
197 -- "Template locals" typically used in unfoldings
198 mkTemplateLocals :: [Type] -> [Id]
199 mkTemplateLocals tys = zipWith mkTemplateLocal [1..] tys
200
201 mkTemplateLocalsNum :: Int -> [Type] -> [Id]
202 -- The Int gives the starting point for unique allocation
203 mkTemplateLocalsNum n tys = zipWith mkTemplateLocal [n..] tys
204
205 mkTemplateLocal :: Int -> Type -> Id
206 mkTemplateLocal i ty = mkSysLocal FSLIT("tpl") (mkBuiltinUnique i) ty
207 \end{code}
208
209
210 %************************************************************************
211 %*                                                                      *
212 \subsection[Id-general-funs]{General @Id@-related functions}
213 %*                                                                      *
214 %************************************************************************
215
216 \begin{code}
217 setIdType :: Id -> Type -> Id
218         -- Add free tyvar info to the type
219 setIdType id ty = seqType ty `seq` Var.setIdType id (addFreeTyVars ty)
220
221 idPrimRep :: Id -> PrimRep
222 idPrimRep id = typePrimRep (idType id)
223 \end{code}
224
225
226 %************************************************************************
227 %*                                                                      *
228 \subsection{Special Ids}
229 %*                                                                      *
230 %************************************************************************
231
232 The @SpecPragmaId@ exists only to make Ids that are
233 on the *LHS* of bindings created by SPECIALISE pragmas; 
234 eg:             s = f Int d
235 The SpecPragmaId is never itself mentioned; it
236 exists solely so that the specialiser will find
237 the call to f, and make specialised version of it.
238 The SpecPragmaId binding is discarded by the specialiser
239 when it gathers up overloaded calls.
240 Meanwhile, it is not discarded as dead code.
241
242
243 \begin{code}
244 recordSelectorFieldLabel :: Id -> (TyCon, FieldLabel)
245 recordSelectorFieldLabel id = case globalIdDetails id of
246                                  RecordSelId tycon lbl -> (tycon,lbl)
247                                  other -> panic "recordSelectorFieldLabel"
248
249 isRecordSelector id = case globalIdDetails id of
250                         RecordSelId _ _ -> True
251                         other           -> False
252
253 isClassOpId_maybe id = case globalIdDetails id of
254                         ClassOpId cls -> Just cls
255                         _other        -> Nothing
256
257 isPrimOpId id = case globalIdDetails id of
258                     PrimOpId op -> True
259                     other       -> False
260
261 isPrimOpId_maybe id = case globalIdDetails id of
262                             PrimOpId op -> Just op
263                             other       -> Nothing
264
265 isFCallId id = case globalIdDetails id of
266                     FCallId call -> True
267                     other        -> False
268
269 isFCallId_maybe id = case globalIdDetails id of
270                             FCallId call -> Just call
271                             other        -> Nothing
272
273 isDataConWorkId id = case globalIdDetails id of
274                         DataConWorkId _ -> True
275                         other           -> False
276
277 isDataConWorkId_maybe id = case globalIdDetails id of
278                           DataConWorkId con -> Just con
279                           other             -> Nothing
280
281 idDataCon :: Id -> DataCon
282 -- Get from either the worker or the wrapper to the DataCon
283 -- Currently used only in the desugarer
284 --       INVARIANT: idDataCon (dataConWrapId d) = d
285 -- (Remember, dataConWrapId can return either the wrapper or the worker.)
286 idDataCon id = case globalIdDetails id of
287                   DataConWorkId con -> con
288                   DataConWrapId con -> con
289                   other             -> pprPanic "idDataCon" (ppr id)
290
291
292 -- hasNoBinding returns True of an Id which may not have a
293 -- binding, even though it is defined in this module.  
294 -- Data constructor workers used to be things of this kind, but
295 -- they aren't any more.  Instead, we inject a binding for 
296 -- them at the CorePrep stage. 
297 -- EXCEPT: unboxed tuples, which definitely have no binding
298 hasNoBinding id = case globalIdDetails id of
299                         PrimOpId _       -> True
300                         FCallId _        -> True
301                         DataConWorkId dc -> isUnboxedTupleCon dc
302                         other            -> False
303
304 isImplicitId :: Id -> Bool
305         -- isImplicitId tells whether an Id's info is implied by other
306         -- declarations, so we don't need to put its signature in an interface
307         -- file, even if it's mentioned in some other interface unfolding.
308 isImplicitId id
309   = case globalIdDetails id of
310         RecordSelId _ _ -> True
311         FCallId _       -> True
312         PrimOpId _      -> True
313         ClassOpId _     -> True
314         DataConWorkId _ -> True
315         DataConWrapId _ -> True
316                 -- These are are implied by their type or class decl;
317                 -- remember that all type and class decls appear in the interface file.
318                 -- The dfun id is not an implicit Id; it must *not* be omitted, because 
319                 -- it carries version info for the instance decl
320         other           -> False
321
322 idIsFrom :: Module -> Id -> Bool
323 idIsFrom mod id = nameIsLocalOrFrom mod (idName id)
324 \end{code}
325
326 \begin{code}
327 isDeadBinder :: Id -> Bool
328 isDeadBinder bndr | isId bndr = isDeadOcc (idOccInfo bndr)
329                   | otherwise = False   -- TyVars count as not dead
330 \end{code}
331
332
333 %************************************************************************
334 %*                                                                      *
335 \subsection{IdInfo stuff}
336 %*                                                                      *
337 %************************************************************************
338
339 \begin{code}
340         ---------------------------------
341         -- ARITY
342 idArity :: Id -> Arity
343 idArity id = arityInfo (idInfo id)
344
345 setIdArity :: Id -> Arity -> Id
346 setIdArity id arity = modifyIdInfo (`setArityInfo` arity) id
347
348 #ifdef OLD_STRICTNESS
349         ---------------------------------
350         -- (OLD) STRICTNESS 
351 idStrictness :: Id -> StrictnessInfo
352 idStrictness id = strictnessInfo (idInfo id)
353
354 setIdStrictness :: Id -> StrictnessInfo -> Id
355 setIdStrictness id strict_info = modifyIdInfo (`setStrictnessInfo` strict_info) id
356 #endif
357
358 -- isBottomingId returns true if an application to n args would diverge
359 isBottomingId :: Id -> Bool
360 isBottomingId id = isBottomingSig (idNewStrictness id)
361
362 idNewStrictness_maybe :: Id -> Maybe StrictSig
363 idNewStrictness :: Id -> StrictSig
364
365 idNewStrictness_maybe id = newStrictnessInfo (idInfo id)
366 idNewStrictness       id = idNewStrictness_maybe id `orElse` topSig
367
368 setIdNewStrictness :: Id -> StrictSig -> Id
369 setIdNewStrictness id sig = modifyIdInfo (`setNewStrictnessInfo` Just sig) id
370
371 zapIdNewStrictness :: Id -> Id
372 zapIdNewStrictness id = modifyIdInfo (`setNewStrictnessInfo` Nothing) id
373
374         ---------------------------------
375         -- WORKER ID
376 idWorkerInfo :: Id -> WorkerInfo
377 idWorkerInfo id = workerInfo (idInfo id)
378
379 setIdWorkerInfo :: Id -> WorkerInfo -> Id
380 setIdWorkerInfo id work_info = modifyIdInfo (`setWorkerInfo` work_info) id
381
382         ---------------------------------
383         -- UNFOLDING
384 idUnfolding :: Id -> Unfolding
385 idUnfolding id = unfoldingInfo (idInfo id)
386
387 setIdUnfolding :: Id -> Unfolding -> Id
388 setIdUnfolding id unfolding = modifyIdInfo (`setUnfoldingInfo` unfolding) id
389
390 #ifdef OLD_STRICTNESS
391         ---------------------------------
392         -- (OLD) DEMAND
393 idDemandInfo :: Id -> Demand.Demand
394 idDemandInfo id = demandInfo (idInfo id)
395
396 setIdDemandInfo :: Id -> Demand.Demand -> Id
397 setIdDemandInfo id demand_info = modifyIdInfo (`setDemandInfo` demand_info) id
398 #endif
399
400 idNewDemandInfo_maybe :: Id -> Maybe NewDemand.Demand
401 idNewDemandInfo       :: Id -> NewDemand.Demand
402
403 idNewDemandInfo_maybe id = newDemandInfo (idInfo id)
404 idNewDemandInfo       id = newDemandInfo (idInfo id) `orElse` NewDemand.topDmd
405
406 setIdNewDemandInfo :: Id -> NewDemand.Demand -> Id
407 setIdNewDemandInfo id dmd = modifyIdInfo (`setNewDemandInfo` Just dmd) id
408
409         ---------------------------------
410         -- SPECIALISATION
411 idSpecialisation :: Id -> SpecInfo
412 idSpecialisation id = specInfo (idInfo id)
413
414 idCoreRules :: Id -> [CoreRule]
415 idCoreRules id = specInfoRules (idSpecialisation id)
416
417 setIdSpecialisation :: Id -> SpecInfo -> Id
418 setIdSpecialisation id spec_info = modifyIdInfo (`setSpecInfo` spec_info) id
419
420         ---------------------------------
421         -- CAF INFO
422 idCafInfo :: Id -> CafInfo
423 #ifdef OLD_STRICTNESS
424 idCafInfo id = case cgInfo (idInfo id) of
425                   NoCgInfo -> pprPanic "idCafInfo" (ppr id)
426                   info     -> cgCafInfo info
427 #else
428 idCafInfo id = cafInfo (idInfo id)
429 #endif
430
431 setIdCafInfo :: Id -> CafInfo -> Id
432 setIdCafInfo id caf_info = modifyIdInfo (`setCafInfo` caf_info) id
433
434         ---------------------------------
435         -- CPR INFO
436 #ifdef OLD_STRICTNESS
437 idCprInfo :: Id -> CprInfo
438 idCprInfo id = cprInfo (idInfo id)
439
440 setIdCprInfo :: Id -> CprInfo -> Id
441 setIdCprInfo id cpr_info = modifyIdInfo (`setCprInfo` cpr_info) id
442 #endif
443
444         ---------------------------------
445         -- Occcurrence INFO
446 idOccInfo :: Id -> OccInfo
447 idOccInfo id = occInfo (idInfo id)
448
449 setIdOccInfo :: Id -> OccInfo -> Id
450 setIdOccInfo id occ_info = modifyIdInfo (`setOccInfo` occ_info) id
451 \end{code}
452
453
454         ---------------------------------
455         -- INLINING
456 The inline pragma tells us to be very keen to inline this Id, but it's still
457 OK not to if optimisation is switched off.
458
459 \begin{code}
460 idInlinePragma :: Id -> InlinePragInfo
461 idInlinePragma id = inlinePragInfo (idInfo id)
462
463 setInlinePragma :: Id -> InlinePragInfo -> Id
464 setInlinePragma id prag = modifyIdInfo (`setInlinePragInfo` prag) id
465
466 modifyInlinePragma :: Id -> (InlinePragInfo -> InlinePragInfo) -> Id
467 modifyInlinePragma id fn = modifyIdInfo (\info -> info `setInlinePragInfo` (fn (inlinePragInfo info))) id
468 \end{code}
469
470
471         ---------------------------------
472         -- ONE-SHOT LAMBDAS
473 \begin{code}
474 idLBVarInfo :: Id -> LBVarInfo
475 idLBVarInfo id = lbvarInfo (idInfo id)
476
477 isOneShotBndr :: Id -> Bool
478 -- This one is the "business end", called externally.
479 -- Its main purpose is to encapsulate the Horrible State Hack
480 isOneShotBndr id = isOneShotLambda id || (isStateHackType (idType id))
481
482 isStateHackType :: Type -> Bool
483 isStateHackType ty
484   | opt_NoStateHack 
485   = False
486   | otherwise
487   = case splitTyConApp_maybe ty of
488         Just (tycon,_) -> tycon == statePrimTyCon
489         other          -> False
490         -- This is a gross hack.  It claims that 
491         -- every function over realWorldStatePrimTy is a one-shot
492         -- function.  This is pretty true in practice, and makes a big
493         -- difference.  For example, consider
494         --      a `thenST` \ r -> ...E...
495         -- The early full laziness pass, if it doesn't know that r is one-shot
496         -- will pull out E (let's say it doesn't mention r) to give
497         --      let lvl = E in a `thenST` \ r -> ...lvl...
498         -- When `thenST` gets inlined, we end up with
499         --      let lvl = E in \s -> case a s of (r, s') -> ...lvl...
500         -- and we don't re-inline E.
501         --
502         -- It would be better to spot that r was one-shot to start with, but
503         -- I don't want to rely on that.
504         --
505         -- Another good example is in fill_in in PrelPack.lhs.  We should be able to
506         -- spot that fill_in has arity 2 (and when Keith is done, we will) but we can't yet.
507
508
509 -- The OneShotLambda functions simply fiddle with the IdInfo flag
510 isOneShotLambda :: Id -> Bool
511 isOneShotLambda id = case idLBVarInfo id of
512                        IsOneShotLambda  -> True
513                        NoLBVarInfo      -> False
514
515 setOneShotLambda :: Id -> Id
516 setOneShotLambda id = modifyIdInfo (`setLBVarInfo` IsOneShotLambda) id
517
518 clearOneShotLambda :: Id -> Id
519 clearOneShotLambda id 
520   | isOneShotLambda id = modifyIdInfo (`setLBVarInfo` NoLBVarInfo) id
521   | otherwise          = id                     
522
523 -- But watch out: this may change the type of something else
524 --      f = \x -> e
525 -- If we change the one-shot-ness of x, f's type changes
526 \end{code}
527
528 \begin{code}
529 zapLamIdInfo :: Id -> Id
530 zapLamIdInfo id = maybeModifyIdInfo zapLamInfo id
531
532 zapDemandIdInfo id = maybeModifyIdInfo zapDemandInfo id
533 \end{code}
534