update submodule pointer
[ghc-hetmet.git] / compiler / basicTypes / IdInfo.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 %
5 \section[IdInfo]{@IdInfos@: Non-essential information about @Ids@}
6
7 (And a pretty good illustration of quite a few things wrong with
8 Haskell. [WDP 94/11])
9
10 \begin{code}
11 module IdInfo (
12         -- * The IdDetails type
13         IdDetails(..), pprIdDetails,
14
15         -- * The IdInfo type
16         IdInfo,         -- Abstract
17         vanillaIdInfo, noCafIdInfo,
18         seqIdInfo, megaSeqIdInfo,
19
20         -- ** Zapping various forms of Info
21         zapLamInfo, zapDemandInfo, zapFragileInfo,
22
23         -- ** The ArityInfo type
24         ArityInfo,
25         unknownArity, 
26         arityInfo, setArityInfo, ppArityInfo, 
27
28         -- ** Demand and strictness Info
29         strictnessInfo, setStrictnessInfo, 
30         demandInfo, setDemandInfo, pprStrictness,
31
32         -- ** Unfolding Info
33         unfoldingInfo, setUnfoldingInfo, setUnfoldingInfoLazily,
34
35         -- ** The InlinePragInfo type
36         InlinePragInfo,
37         inlinePragInfo, setInlinePragInfo,
38
39         -- ** The OccInfo type
40         OccInfo(..),
41         isDeadOcc, isLoopBreaker,
42         occInfo, setOccInfo,
43
44         InsideLam, OneBranch,
45         insideLam, notInsideLam, oneBranch, notOneBranch,
46         
47         -- ** The SpecInfo type
48         SpecInfo(..),
49         emptySpecInfo,
50         isEmptySpecInfo, specInfoFreeVars,
51         specInfoRules, seqSpecInfo, setSpecInfoHead,
52         specInfo, setSpecInfo,
53
54         -- ** The CAFInfo type
55         CafInfo(..),
56         ppCafInfo, mayHaveCafRefs,
57         cafInfo, setCafInfo,
58
59         -- ** The LBVarInfo type
60         LBVarInfo(..),
61         noLBVarInfo, hasNoLBVarInfo,
62         lbvarInfo, setLBVarInfo,
63
64         -- ** Tick-box Info
65         TickBoxOp(..), TickBoxId,
66     ) where
67
68 import CoreSyn
69
70 import Class
71 import PrimOp
72 import Name
73 import VarSet
74 import BasicTypes
75 import DataCon
76 import TyCon
77 import ForeignCall
78 import Demand
79 import Outputable       
80 import Module
81 import FastString
82
83 import Data.Maybe
84
85 -- infixl so you can say (id `set` a `set` b)
86 infixl  1 `setSpecInfo`,
87           `setArityInfo`,
88           `setInlinePragInfo`,
89           `setUnfoldingInfo`,
90           `setLBVarInfo`,
91           `setOccInfo`,
92           `setCafInfo`,
93           `setStrictnessInfo`,
94           `setDemandInfo`
95 \end{code}
96
97 %************************************************************************
98 %*                                                                      *
99                      IdDetails
100 %*                                                                      *
101 %************************************************************************
102
103 \begin{code}
104 -- | The 'IdDetails' of an 'Id' give stable, and necessary, 
105 -- information about the Id. 
106 data IdDetails
107   = VanillaId   
108
109   -- | The 'Id' for a record selector
110   | RecSelId                 
111     { sel_tycon   :: TyCon      -- ^ For a data type family, this is the /instance/ 'TyCon'
112                                 --   not the family 'TyCon'
113     , sel_naughty :: Bool       -- True <=> a "naughty" selector which can't actually exist, for example @x@ in:
114                                 --    data T = forall a. MkT { x :: a }
115     }                           -- See Note [Naughty record selectors] in TcTyClsDecls
116
117   | DataConWorkId DataCon       -- ^ The 'Id' is for a data constructor /worker/
118   | DataConWrapId DataCon       -- ^ The 'Id' is for a data constructor /wrapper/
119                                 
120                                 -- [the only reasons we need to know is so that
121                                 --  a) to support isImplicitId
122                                 --  b) when desugaring a RecordCon we can get 
123                                 --     from the Id back to the data con]
124
125   | ClassOpId Class             -- ^ The 'Id' is an superclass selector or class operation of a class
126
127   | PrimOpId PrimOp             -- ^ The 'Id' is for a primitive operator
128   | FCallId ForeignCall         -- ^ The 'Id' is for a foreign call
129
130   | TickBoxOpId TickBoxOp       -- ^ The 'Id' is for a HPC tick box (both traditional and binary)
131
132   | DFunId Int Bool             -- ^ A dictionary function.
133        -- Int = the number of "silent" arguments to the dfun
134        --       e.g.  class D a => C a where ...
135        --             instance C a => C [a]
136        --       has is_silent = 1, because the dfun
137        --       has type  dfun :: (D a, C a) => C [a]
138        --       See the DFun Superclass Invariant in TcInstDcls
139        --
140        -- Bool = True <=> the class has only one method, so may be
141        --                  implemented with a newtype, so it might be bad
142        --                  to be strict on this dictionary
143
144 instance Outputable IdDetails where
145     ppr = pprIdDetails
146
147 pprIdDetails :: IdDetails -> SDoc
148 pprIdDetails VanillaId = empty
149 pprIdDetails other     = brackets (pp other)
150  where
151    pp VanillaId         = panic "pprIdDetails"
152    pp (DataConWorkId _) = ptext (sLit "DataCon")
153    pp (DataConWrapId _) = ptext (sLit "DataConWrapper")
154    pp (ClassOpId {})    = ptext (sLit "ClassOp")
155    pp (PrimOpId _)      = ptext (sLit "PrimOp")
156    pp (FCallId _)       = ptext (sLit "ForeignCall")
157    pp (TickBoxOpId _)   = ptext (sLit "TickBoxOp")
158    pp (DFunId ns nt)    = ptext (sLit "DFunId")
159                              <> ppWhen (ns /= 0) (brackets (int ns))
160                              <> ppWhen nt (ptext (sLit "(nt)"))
161    pp (RecSelId { sel_naughty = is_naughty })
162                          = brackets $ ptext (sLit "RecSel") 
163                             <> ppWhen is_naughty (ptext (sLit "(naughty)"))
164 \end{code}
165
166
167 %************************************************************************
168 %*                                                                      *
169 \subsection{The main IdInfo type}
170 %*                                                                      *
171 %************************************************************************
172
173 \begin{code}
174 -- | An 'IdInfo' gives /optional/ information about an 'Id'.  If
175 -- present it never lies, but it may not be present, in which case there
176 -- is always a conservative assumption which can be made.
177 -- 
178 -- Two 'Id's may have different info even though they have the same
179 -- 'Unique' (and are hence the same 'Id'); for example, one might lack
180 -- the properties attached to the other.
181 -- 
182 -- The 'IdInfo' gives information about the value, or definition, of the
183 -- 'Id'.  It does not contain information about the 'Id''s usage,
184 -- except for 'demandInfo' and 'lbvarInfo'.
185 data IdInfo
186   = IdInfo {
187         arityInfo       :: !ArityInfo,          -- ^ 'Id' arity
188         specInfo        :: SpecInfo,            -- ^ Specialisations of the 'Id's function which exist
189                                                 -- See Note [Specialisations and RULES in IdInfo]
190         unfoldingInfo   :: Unfolding,           -- ^ The 'Id's unfolding
191         cafInfo         :: CafInfo,             -- ^ 'Id' CAF info
192         lbvarInfo       :: LBVarInfo,           -- ^ Info about a lambda-bound variable, if the 'Id' is one
193         inlinePragInfo  :: InlinePragma,        -- ^ Any inline pragma atached to the 'Id'
194         occInfo         :: OccInfo,             -- ^ How the 'Id' occurs in the program
195
196         strictnessInfo :: Maybe StrictSig,      -- ^ Id strictness information. Reason for Maybe: 
197                                                 -- the DmdAnal phase needs to know whether
198                                                 -- this is the first visit, so it can assign botSig.
199                                                 -- Other customers want topSig.  So @Nothing@ is good.
200
201         demandInfo        :: Maybe Demand       -- ^ Id demand information. Similarly we want to know 
202                                                 -- if there's no known demand yet, for when we are looking
203                                                 -- for CPR info
204     }
205
206 -- | Just evaluate the 'IdInfo' to WHNF
207 seqIdInfo :: IdInfo -> ()
208 seqIdInfo (IdInfo {}) = ()
209
210 -- | Evaluate all the fields of the 'IdInfo' that are generally demanded by the
211 -- compiler
212 megaSeqIdInfo :: IdInfo -> ()
213 megaSeqIdInfo info
214   = seqSpecInfo (specInfo info)                 `seq`
215
216 -- Omitting this improves runtimes a little, presumably because
217 -- some unfoldings are not calculated at all
218 --    seqUnfolding (unfoldingInfo info)         `seq`
219
220     seqDemandInfo (demandInfo info)     `seq`
221     seqStrictnessInfo (strictnessInfo info) `seq`
222
223     seqCaf (cafInfo info)                       `seq`
224     seqLBVar (lbvarInfo info)                   `seq`
225     seqOccInfo (occInfo info) 
226
227 seqStrictnessInfo :: Maybe StrictSig -> ()
228 seqStrictnessInfo Nothing = ()
229 seqStrictnessInfo (Just ty) = seqStrictSig ty
230
231 seqDemandInfo :: Maybe Demand -> ()
232 seqDemandInfo Nothing    = ()
233 seqDemandInfo (Just dmd) = seqDemand dmd
234 \end{code}
235
236 Setters
237
238 \begin{code}
239 setSpecInfo :: IdInfo -> SpecInfo -> IdInfo
240 setSpecInfo       info sp = sp `seq` info { specInfo = sp }
241 setInlinePragInfo :: IdInfo -> InlinePragma -> IdInfo
242 setInlinePragInfo info pr = pr `seq` info { inlinePragInfo = pr }
243 setOccInfo :: IdInfo -> OccInfo -> IdInfo
244 setOccInfo        info oc = oc `seq` info { occInfo = oc }
245         -- Try to avoid spack leaks by seq'ing
246
247 setUnfoldingInfoLazily :: IdInfo -> Unfolding -> IdInfo
248 setUnfoldingInfoLazily info uf  -- Lazy variant to avoid looking at the
249   =                             -- unfolding of an imported Id unless necessary
250     info { unfoldingInfo = uf } -- (In this case the demand-zapping is redundant.)
251
252 setUnfoldingInfo :: IdInfo -> Unfolding -> IdInfo
253 setUnfoldingInfo info uf 
254   = -- We don't seq the unfolding, as we generate intermediate
255     -- unfoldings which are just thrown away, so evaluating them is a
256     -- waste of time.
257     -- seqUnfolding uf `seq`
258     info { unfoldingInfo = uf }
259
260 setArityInfo :: IdInfo -> ArityInfo -> IdInfo
261 setArityInfo      info ar  = info { arityInfo = ar  }
262 setCafInfo :: IdInfo -> CafInfo -> IdInfo
263 setCafInfo        info caf = info { cafInfo = caf }
264
265 setLBVarInfo :: IdInfo -> LBVarInfo -> IdInfo
266 setLBVarInfo      info lb = {-lb `seq`-} info { lbvarInfo = lb }
267
268 setDemandInfo :: IdInfo -> Maybe Demand -> IdInfo
269 setDemandInfo     info dd = dd `seq` info { demandInfo = dd }
270
271 setStrictnessInfo :: IdInfo -> Maybe StrictSig -> IdInfo
272 setStrictnessInfo info dd = dd `seq` info { strictnessInfo = dd }
273 \end{code}
274
275
276 \begin{code}
277 -- | Basic 'IdInfo' that carries no useful information whatsoever
278 vanillaIdInfo :: IdInfo
279 vanillaIdInfo 
280   = IdInfo {
281             cafInfo             = vanillaCafInfo,
282             arityInfo           = unknownArity,
283             specInfo            = emptySpecInfo,
284             unfoldingInfo       = noUnfolding,
285             lbvarInfo           = NoLBVarInfo,
286             inlinePragInfo      = defaultInlinePragma,
287             occInfo             = NoOccInfo,
288             demandInfo  = Nothing,
289             strictnessInfo   = Nothing
290            }
291
292 -- | More informative 'IdInfo' we can use when we know the 'Id' has no CAF references
293 noCafIdInfo :: IdInfo
294 noCafIdInfo  = vanillaIdInfo `setCafInfo`    NoCafRefs
295         -- Used for built-in type Ids in MkId.
296 \end{code}
297
298
299 %************************************************************************
300 %*                                                                      *
301 \subsection[arity-IdInfo]{Arity info about an @Id@}
302 %*                                                                      *
303 %************************************************************************
304
305 For locally-defined Ids, the code generator maintains its own notion
306 of their arities; so it should not be asking...  (but other things
307 besides the code-generator need arity info!)
308
309 \begin{code}
310 -- | An 'ArityInfo' of @n@ tells us that partial application of this 
311 -- 'Id' to up to @n-1@ value arguments does essentially no work.
312 --
313 -- That is not necessarily the same as saying that it has @n@ leading 
314 -- lambdas, because coerces may get in the way.
315 --
316 -- The arity might increase later in the compilation process, if
317 -- an extra lambda floats up to the binding site.
318 type ArityInfo = Arity
319
320 -- | It is always safe to assume that an 'Id' has an arity of 0
321 unknownArity :: Arity
322 unknownArity = 0 :: Arity
323
324 ppArityInfo :: Int -> SDoc
325 ppArityInfo 0 = empty
326 ppArityInfo n = hsep [ptext (sLit "Arity"), int n]
327 \end{code}
328
329 %************************************************************************
330 %*                                                                      *
331 \subsection{Inline-pragma information}
332 %*                                                                      *
333 %************************************************************************
334
335 \begin{code}
336 -- | Tells when the inlining is active.
337 -- When it is active the thing may be inlined, depending on how
338 -- big it is.
339 --
340 -- If there was an @INLINE@ pragma, then as a separate matter, the
341 -- RHS will have been made to look small with a Core inline 'Note'
342 --
343 -- The default 'InlinePragInfo' is 'AlwaysActive', so the info serves
344 -- entirely as a way to inhibit inlining until we want it
345 type InlinePragInfo = InlinePragma
346 \end{code}
347
348
349 %************************************************************************
350 %*                                                                      *
351                Strictness
352 %*                                                                      *
353 %************************************************************************
354
355 \begin{code}
356 pprStrictness :: Maybe StrictSig -> SDoc
357 pprStrictness Nothing    = empty
358 pprStrictness (Just sig) = ppr sig
359 \end{code}
360
361
362 %************************************************************************
363 %*                                                                      *
364         SpecInfo
365 %*                                                                      *
366 %************************************************************************
367
368 Note [Specialisations and RULES in IdInfo]
369 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
370 Generally speaking, a GlobalIdshas an *empty* SpecInfo.  All their
371 RULES are contained in the globally-built rule-base.  In principle,
372 one could attach the to M.f the RULES for M.f that are defined in M.
373 But we don't do that for instance declarations and so we just treat
374 them all uniformly.
375
376 The EXCEPTION is PrimOpIds, which do have rules in their IdInfo. That is
377 jsut for convenience really.
378
379 However, LocalIds may have non-empty SpecInfo.  We treat them 
380 differently because:
381   a) they might be nested, in which case a global table won't work
382   b) the RULE might mention free variables, which we use to keep things alive
383
384 In TidyPgm, when the LocalId becomes a GlobalId, its RULES are stripped off
385 and put in the global list.
386
387 \begin{code}
388 -- | Records the specializations of this 'Id' that we know about
389 -- in the form of rewrite 'CoreRule's that target them
390 data SpecInfo 
391   = SpecInfo 
392         [CoreRule] 
393         VarSet          -- Locally-defined free vars of *both* LHS and RHS 
394                         -- of rules.  I don't think it needs to include the
395                         -- ru_fn though.
396                         -- Note [Rule dependency info] in OccurAnal
397
398 -- | Assume that no specilizations exist: always safe
399 emptySpecInfo :: SpecInfo
400 emptySpecInfo = SpecInfo [] emptyVarSet
401
402 isEmptySpecInfo :: SpecInfo -> Bool
403 isEmptySpecInfo (SpecInfo rs _) = null rs
404
405 -- | Retrieve the locally-defined free variables of both the left and
406 -- right hand sides of the specialization rules
407 specInfoFreeVars :: SpecInfo -> VarSet
408 specInfoFreeVars (SpecInfo _ fvs) = fvs
409
410 specInfoRules :: SpecInfo -> [CoreRule]
411 specInfoRules (SpecInfo rules _) = rules
412
413 -- | Change the name of the function the rule is keyed on on all of the 'CoreRule's
414 setSpecInfoHead :: Name -> SpecInfo -> SpecInfo
415 setSpecInfoHead fn (SpecInfo rules fvs)
416   = SpecInfo (map (setRuleIdName fn) rules) fvs
417
418 seqSpecInfo :: SpecInfo -> ()
419 seqSpecInfo (SpecInfo rules fvs) = seqRules rules `seq` seqVarSet fvs
420 \end{code}
421
422 %************************************************************************
423 %*                                                                      *
424 \subsection[CG-IdInfo]{Code generator-related information}
425 %*                                                                      *
426 %************************************************************************
427
428 \begin{code}
429 -- CafInfo is used to build Static Reference Tables (see simplStg/SRT.lhs).
430
431 -- | Records whether an 'Id' makes Constant Applicative Form references
432 data CafInfo 
433         = MayHaveCafRefs                -- ^ Indicates that the 'Id' is for either:
434                                         --
435                                         -- 1. A function or static constructor
436                                         --    that refers to one or more CAFs, or
437                                         --
438                                         -- 2. A real live CAF
439
440         | NoCafRefs                     -- ^ A function or static constructor
441                                         -- that refers to no CAFs.
442         deriving (Eq, Ord)
443
444 -- | Assumes that the 'Id' has CAF references: definitely safe
445 vanillaCafInfo :: CafInfo
446 vanillaCafInfo = MayHaveCafRefs
447
448 mayHaveCafRefs :: CafInfo -> Bool
449 mayHaveCafRefs  MayHaveCafRefs = True
450 mayHaveCafRefs _               = False
451
452 seqCaf :: CafInfo -> ()
453 seqCaf c = c `seq` ()
454
455 instance Outputable CafInfo where
456    ppr = ppCafInfo
457
458 ppCafInfo :: CafInfo -> SDoc
459 ppCafInfo NoCafRefs = ptext (sLit "NoCafRefs")
460 ppCafInfo MayHaveCafRefs = empty
461 \end{code}
462
463 %************************************************************************
464 %*                                                                      *
465 \subsection[lbvar-IdInfo]{Lambda-bound var info about an @Id@}
466 %*                                                                      *
467 %************************************************************************
468
469 \begin{code}
470 -- | If the 'Id' is a lambda-bound variable then it may have lambda-bound
471 -- variable info. Sometimes we know whether the lambda binding this variable
472 -- is a \"one-shot\" lambda; that is, whether it is applied at most once.
473 --
474 -- This information may be useful in optimisation, as computations may
475 -- safely be floated inside such a lambda without risk of duplicating
476 -- work.
477 data LBVarInfo = NoLBVarInfo            -- ^ No information
478                | IsOneShotLambda        -- ^ The lambda is applied at most once).
479
480 -- | It is always safe to assume that an 'Id' has no lambda-bound variable information
481 noLBVarInfo :: LBVarInfo
482 noLBVarInfo = NoLBVarInfo
483
484 hasNoLBVarInfo :: LBVarInfo -> Bool
485 hasNoLBVarInfo NoLBVarInfo     = True
486 hasNoLBVarInfo IsOneShotLambda = False
487
488 seqLBVar :: LBVarInfo -> ()
489 seqLBVar l = l `seq` ()
490
491 pprLBVarInfo :: LBVarInfo -> SDoc
492 pprLBVarInfo NoLBVarInfo     = empty
493 pprLBVarInfo IsOneShotLambda = ptext (sLit "OneShot")
494
495 instance Outputable LBVarInfo where
496     ppr = pprLBVarInfo
497
498 instance Show LBVarInfo where
499     showsPrec p c = showsPrecSDoc p (ppr c)
500 \end{code}
501
502
503 %************************************************************************
504 %*                                                                      *
505 \subsection{Bulk operations on IdInfo}
506 %*                                                                      *
507 %************************************************************************
508
509 \begin{code}
510 -- | This is used to remove information on lambda binders that we have
511 -- setup as part of a lambda group, assuming they will be applied all at once,
512 -- but turn out to be part of an unsaturated lambda as in e.g:
513 --
514 -- > (\x1. \x2. e) arg1
515 zapLamInfo :: IdInfo -> Maybe IdInfo
516 zapLamInfo info@(IdInfo {occInfo = occ, demandInfo = demand})
517   | is_safe_occ occ && is_safe_dmd demand
518   = Nothing
519   | otherwise
520   = Just (info {occInfo = safe_occ, demandInfo = Nothing})
521   where
522         -- The "unsafe" occ info is the ones that say I'm not in a lambda
523         -- because that might not be true for an unsaturated lambda
524     is_safe_occ (OneOcc in_lam _ _) = in_lam
525     is_safe_occ _other              = True
526
527     safe_occ = case occ of
528                  OneOcc _ once int_cxt -> OneOcc insideLam once int_cxt
529                  _other                -> occ
530
531     is_safe_dmd Nothing    = True
532     is_safe_dmd (Just dmd) = not (isStrictDmd dmd)
533 \end{code}
534
535 \begin{code}
536 -- | Remove demand info on the 'IdInfo' if it is present, otherwise return @Nothing@
537 zapDemandInfo :: IdInfo -> Maybe IdInfo
538 zapDemandInfo info@(IdInfo {demandInfo = dmd})
539   | isJust dmd = Just (info {demandInfo = Nothing})
540   | otherwise  = Nothing
541 \end{code}
542
543 \begin{code}
544 zapFragileInfo :: IdInfo -> Maybe IdInfo
545 -- ^ Zap info that depends on free variables
546 zapFragileInfo info 
547   = Just (info `setSpecInfo` emptySpecInfo
548                `setUnfoldingInfo` noUnfolding
549                `setOccInfo` zapFragileOcc occ)
550   where
551     occ = occInfo info
552 \end{code}
553
554 %************************************************************************
555 %*                                                                      *
556 \subsection{TickBoxOp}
557 %*                                                                      *
558 %************************************************************************
559
560 \begin{code}
561 type TickBoxId = Int
562
563 -- | Tick box for Hpc-style coverage
564 data TickBoxOp 
565    = TickBox Module {-# UNPACK #-} !TickBoxId
566
567 instance Outputable TickBoxOp where
568     ppr (TickBox mod n)         = ptext (sLit "tick") <+> ppr (mod,n)
569 \end{code}