[project @ 2001-05-03 08:08:12 by simonpj]
[ghc-hetmet.git] / ghc / compiler / basicTypes / IdInfo.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[IdInfo]{@IdInfos@: Non-essential information about @Ids@}
5
6 (And a pretty good illustration of quite a few things wrong with
7 Haskell. [WDP 94/11])
8
9 \begin{code}
10 module IdInfo (
11         GlobalIdDetails(..), notGlobalId,       -- Not abstract
12
13         IdInfo,         -- Abstract
14         vanillaIdInfo, noCafNoTyGenIdInfo,
15         seqIdInfo, megaSeqIdInfo,
16
17         -- Zapping
18         zapLamInfo, zapDemandInfo,
19         shortableIdInfo, copyIdInfo,
20
21         -- Arity
22         ArityInfo(..),
23         exactArity, atLeastArity, unknownArity, hasArity,
24         arityInfo, setArityInfo, ppArityInfo, arityLowerBound,
25
26         -- Strictness; imported from Demand
27         StrictnessInfo(..),
28         mkStrictnessInfo, noStrictnessInfo,
29         ppStrictnessInfo,isBottomingStrictness, 
30         strictnessInfo, setStrictnessInfo,      
31
32         -- Usage generalisation
33         TyGenInfo(..),
34         tyGenInfo, setTyGenInfo,
35         noTyGenInfo, isNoTyGenInfo, ppTyGenInfo, tyGenInfoString,
36
37         -- Worker
38         WorkerInfo(..), workerExists, wrapperArity, workerId,
39         workerInfo, setWorkerInfo, ppWorkerInfo,
40
41         -- Unfolding
42         unfoldingInfo, setUnfoldingInfo, 
43
44         -- DemandInfo
45         demandInfo, setDemandInfo, 
46
47         -- Inline prags
48         InlinePragInfo(..), 
49         inlinePragInfo, setInlinePragInfo, pprInlinePragInfo,
50         isNeverInlinePrag, neverInlinePrag,
51
52         -- Occurrence info
53         OccInfo(..), isFragileOcc, isDeadOcc, isLoopBreaker,
54         InsideLam, OneBranch, insideLam, notInsideLam, oneBranch, notOneBranch,
55         occInfo, setOccInfo, 
56
57         -- Specialisation
58         specInfo, setSpecInfo,
59
60         -- CG info
61         CgInfo(..), cgInfo, setCgInfo,  cgMayHaveCafRefs, pprCgInfo,
62         cgArity, cgCafInfo, vanillaCgInfo,
63         CgInfoEnv, lookupCgInfo,
64         setCgArity,
65
66         -- CAF info
67         CafInfo(..), ppCafInfo, setCafInfo, mayHaveCafRefs,
68
69         -- Constructed Product Result Info
70         CprInfo(..), cprInfo, setCprInfo, ppCprInfo, noCprInfo,
71
72         -- Lambda-bound variable info
73         LBVarInfo(..), lbvarInfo, setLBVarInfo, noLBVarInfo, hasNoLBVarInfo
74     ) where
75
76 #include "HsVersions.h"
77
78
79 import CoreSyn
80 import Type             ( Type, usOnce )
81 import PrimOp           ( PrimOp )
82 import NameEnv          ( NameEnv, lookupNameEnv )
83 import Name             ( Name )
84 import Var              ( Id )
85 import BasicTypes       ( OccInfo(..), isFragileOcc, isDeadOcc, seqOccInfo, isLoopBreaker,
86                           InsideLam, insideLam, notInsideLam, 
87                           OneBranch, oneBranch, notOneBranch,
88                           Arity
89                         )
90 import DataCon          ( DataCon )
91 import FieldLabel       ( FieldLabel )
92 import Type             ( usOnce, usMany )
93 import Demand           -- Lots of stuff
94 import Outputable       
95 import Util             ( seqList )
96
97 infixl  1 `setDemandInfo`,
98           `setTyGenInfo`,
99           `setStrictnessInfo`,
100           `setSpecInfo`,
101           `setArityInfo`,
102           `setInlinePragInfo`,
103           `setUnfoldingInfo`,
104           `setCprInfo`,
105           `setWorkerInfo`,
106           `setLBVarInfo`,
107           `setOccInfo`,
108           `setCgInfo`,
109           `setCafInfo`,
110           `setCgArity`
111         -- infixl so you can say (id `set` a `set` b)
112 \end{code}
113
114 %************************************************************************
115 %*                                                                      *
116 \subsection{GlobalIdDetails
117 %*                                                                      *
118 %************************************************************************
119
120 This type is here (rather than in Id.lhs) mainly because there's 
121 an IdInfo.hi-boot, but no Id.hi-boot, and GlobalIdDetails is imported
122 (recursively) by Var.lhs.
123
124 \begin{code}
125 data GlobalIdDetails
126   = VanillaGlobal               -- Imported from elsewhere, a default method Id.
127
128   | RecordSelId FieldLabel      -- The Id for a record selector
129   | DataConId DataCon           -- The Id for a data constructor *worker*
130   | DataConWrapId DataCon       -- The Id for a data constructor *wrapper*
131                                 -- [the only reasons we need to know is so that
132                                 --  a) we can  suppress printing a definition in the interface file
133                                 --  b) when typechecking a pattern we can get from the
134                                 --     Id back to the data con]
135
136   | PrimOpId PrimOp             -- The Id for a primitive operator
137
138   | NotGlobalId                 -- Used as a convenient extra return value from globalIdDetails
139     
140 notGlobalId = NotGlobalId
141
142 instance Outputable GlobalIdDetails where
143     ppr NotGlobalId       = ptext SLIT("[***NotGlobalId***]")
144     ppr VanillaGlobal     = ptext SLIT("[GlobalId]")
145     ppr (DataConId _)     = ptext SLIT("[DataCon]")
146     ppr (DataConWrapId _) = ptext SLIT("[DataConWrapper]")
147     ppr (PrimOpId _)      = ptext SLIT("[PrimOp]")
148     ppr (RecordSelId _)   = ptext SLIT("[RecSel]")
149 \end{code}
150
151
152 %************************************************************************
153 %*                                                                      *
154 \subsection{The main IdInfo type}
155 %*                                                                      *
156 %************************************************************************
157
158 An @IdInfo@ gives {\em optional} information about an @Id@.  If
159 present it never lies, but it may not be present, in which case there
160 is always a conservative assumption which can be made.
161
162 Two @Id@s may have different info even though they have the same
163 @Unique@ (and are hence the same @Id@); for example, one might lack
164 the properties attached to the other.
165
166 The @IdInfo@ gives information about the value, or definition, of the
167 @Id@.  It does {\em not} contain information about the @Id@'s usage
168 (except for @DemandInfo@? ToDo). (@lbvarInfo@ is also a marginal
169 case.  KSW 1999-04).
170
171 \begin{code}
172 data IdInfo
173   = IdInfo {
174         arityInfo       :: ArityInfo,           -- Its arity
175         demandInfo      :: Demand,              -- Whether or not it is definitely demanded
176         specInfo        :: CoreRules,           -- Specialisations of this function which exist
177         tyGenInfo       :: TyGenInfo,           -- Restrictions on usage-generalisation of this Id
178         strictnessInfo  :: StrictnessInfo,      -- Strictness properties
179         workerInfo      :: WorkerInfo,          -- Pointer to Worker Function
180         unfoldingInfo   :: Unfolding,           -- Its unfolding
181         cgInfo          :: CgInfo,              -- Code generator info (arity, CAF info)
182         cprInfo         :: CprInfo,             -- Function always constructs a product result
183         lbvarInfo       :: LBVarInfo,           -- Info about a lambda-bound variable
184         inlinePragInfo  :: InlinePragInfo,      -- Inline pragma
185         occInfo         :: OccInfo              -- How it occurs
186     }
187
188 seqIdInfo :: IdInfo -> ()
189 seqIdInfo (IdInfo {}) = ()
190
191 megaSeqIdInfo :: IdInfo -> ()
192 megaSeqIdInfo info
193   = seqArity (arityInfo info)                   `seq`
194     seqDemand (demandInfo info)                 `seq`
195     seqRules (specInfo info)                    `seq`
196     seqTyGenInfo (tyGenInfo info)               `seq`
197     seqStrictnessInfo (strictnessInfo info)     `seq`
198     seqWorker (workerInfo info)                 `seq`
199
200 --    seqUnfolding (unfoldingInfo info) `seq`
201 -- Omitting this improves runtimes a little, presumably because
202 -- some unfoldings are not calculated at all
203
204 -- CgInfo is involved in a loop, so we have to be careful not to seq it
205 -- too early.
206 --    seqCg (cgInfo info)                       `seq`
207     seqCpr (cprInfo info)               `seq`
208     seqLBVar (lbvarInfo info)           `seq`
209     seqOccInfo (occInfo info) 
210 \end{code}
211
212 Setters
213
214 \begin{code}
215 setWorkerInfo     info wk = wk `seq` info { workerInfo = wk }
216 setSpecInfo       info sp = PSEQ sp (info { specInfo = sp })
217 setTyGenInfo      info tg = tg `seq` info { tyGenInfo = tg }
218 setInlinePragInfo info pr = pr `seq` info { inlinePragInfo = pr }
219 setOccInfo        info oc = oc `seq` info { occInfo = oc }
220 setStrictnessInfo info st = st `seq` info { strictnessInfo = st }
221         -- Try to avoid spack leaks by seq'ing
222
223 setUnfoldingInfo  info uf 
224   | isEvaldUnfolding uf && isStrict (demandInfo info)
225         -- If the unfolding is a value, the demand info may
226         -- go pear-shaped, so we nuke it.  Example:
227         --      let x = (a,b) in
228         --      case x of (p,q) -> h p q x
229         -- Here x is certainly demanded. But after we've nuked
230         -- the case, we'll get just
231         --      let x = (a,b) in h a b x
232         -- and now x is not demanded (I'm assuming h is lazy)
233         -- This really happens.  The solution here is a bit ad hoc...
234   = info { unfoldingInfo = uf, demandInfo = wwLazy }
235
236   | otherwise
237         -- We do *not* seq on the unfolding info, For some reason, doing so 
238         -- actually increases residency significantly. 
239   = info { unfoldingInfo = uf }
240
241 setDemandInfo     info dd = info { demandInfo = dd }
242 setArityInfo      info ar = info { arityInfo = ar  }
243 setCgInfo         info cg = info { cgInfo = cg }
244 setCprInfo        info cp = info { cprInfo = cp }
245 setLBVarInfo      info lb = info { lbvarInfo = lb }
246 \end{code}
247
248
249 \begin{code}
250 vanillaIdInfo :: IdInfo
251 vanillaIdInfo 
252   = IdInfo {
253             cgInfo              = noCgInfo,
254             arityInfo           = UnknownArity,
255             demandInfo          = wwLazy,
256             specInfo            = emptyCoreRules,
257             tyGenInfo           = noTyGenInfo,
258             workerInfo          = NoWorker,
259             strictnessInfo      = NoStrictnessInfo,
260             unfoldingInfo       = noUnfolding,
261             cprInfo             = NoCPRInfo,
262             lbvarInfo           = NoLBVarInfo,
263             inlinePragInfo      = NoInlinePragInfo,
264             occInfo             = NoOccInfo
265            }
266
267 noCafNoTyGenIdInfo = vanillaIdInfo `setTyGenInfo` TyGenNever
268                                    `setCgInfo`    (CgInfo 0 NoCafRefs)
269         -- Used for built-in type Ids in MkId.
270         -- Many built-in things have fixed types, so we shouldn't
271         -- run around generalising them
272 \end{code}
273
274
275 %************************************************************************
276 %*                                                                      *
277 \subsection[arity-IdInfo]{Arity info about an @Id@}
278 %*                                                                      *
279 %************************************************************************
280
281 For locally-defined Ids, the code generator maintains its own notion
282 of their arities; so it should not be asking...  (but other things
283 besides the code-generator need arity info!)
284
285 \begin{code}
286 data ArityInfo
287   = UnknownArity        -- No idea
288
289   | ArityExactly Arity  -- Arity is exactly this.  We use this when importing a
290                         -- function; it's already been compiled and we know its
291                         -- arity for sure.
292
293   | ArityAtLeast Arity  -- A partial application of this Id to up to n-1 value arguments
294                         -- does essentially no work.  That is not necessarily the
295                         -- same as saying that it has n leading lambdas, because coerces
296                         -- may get in the way.
297
298                         -- functions in the module being compiled.  Their arity
299                         -- might increase later in the compilation process, if
300                         -- an extra lambda floats up to the binding site.
301   deriving( Eq )
302
303 seqArity :: ArityInfo -> ()
304 seqArity a = arityLowerBound a `seq` ()
305
306 exactArity   = ArityExactly
307 atLeastArity = ArityAtLeast
308 unknownArity = UnknownArity
309
310 arityLowerBound :: ArityInfo -> Arity
311 arityLowerBound UnknownArity     = 0
312 arityLowerBound (ArityAtLeast n) = n
313 arityLowerBound (ArityExactly n) = n
314
315 hasArity :: ArityInfo -> Bool
316 hasArity UnknownArity = False
317 hasArity other        = True
318
319 ppArityInfo UnknownArity         = empty
320 ppArityInfo (ArityExactly arity) = hsep [ptext SLIT("ArityExactly"), int arity]
321 ppArityInfo (ArityAtLeast arity) = hsep [ptext SLIT("ArityAtLeast"), int arity]
322 \end{code}
323
324 %************************************************************************
325 %*                                                                      *
326 \subsection{Inline-pragma information}
327 %*                                                                      *
328 %************************************************************************
329
330 \begin{code}
331 data InlinePragInfo
332   = NoInlinePragInfo
333   | IMustNotBeINLINEd Bool              -- True <=> came from an INLINE prag, False <=> came from a NOINLINE prag
334                       (Maybe Int)       -- Phase number from pragma, if any
335   deriving( Eq )
336         -- The True, Nothing case doesn't need to be recorded
337
338         -- SEE COMMENTS WITH CoreUnfold.blackListed on the
339         -- exact significance of the IMustNotBeINLINEd pragma
340
341 isNeverInlinePrag :: InlinePragInfo -> Bool
342 isNeverInlinePrag (IMustNotBeINLINEd _ Nothing) = True
343 isNeverInlinePrag other                         = False
344
345 neverInlinePrag :: InlinePragInfo
346 neverInlinePrag = IMustNotBeINLINEd True{-should be False? --SDM -} Nothing
347
348 instance Outputable InlinePragInfo where
349   -- This is now parsed in interface files
350   ppr NoInlinePragInfo = empty
351   ppr other_prag       = ptext SLIT("__U") <> pprInlinePragInfo other_prag
352
353 pprInlinePragInfo NoInlinePragInfo                   = empty
354 pprInlinePragInfo (IMustNotBeINLINEd True Nothing)   = empty
355 pprInlinePragInfo (IMustNotBeINLINEd True (Just n))  = brackets (int n)
356 pprInlinePragInfo (IMustNotBeINLINEd False Nothing)  = brackets (char '!')
357 pprInlinePragInfo (IMustNotBeINLINEd False (Just n)) = brackets (char '!' <> int n)
358                                                         
359 instance Show InlinePragInfo where
360   showsPrec p prag = showsPrecSDoc p (ppr prag)
361 \end{code}
362
363
364 %************************************************************************
365 %*                                                                    *
366 \subsection[TyGen-IdInfo]{Type generalisation info about an @Id@}
367 %*                                                                    *
368 %************************************************************************
369
370 Certain passes (notably usage inference) may change the type of an
371 identifier, modifying all in-scope uses of that identifier
372 appropriately to maintain type safety.
373
374 However, some identifiers must not have their types changed in this
375 way, because their types are conjured up in the front end of the
376 compiler rather than being read from the interface file.  Default
377 methods, dictionary functions, record selectors, and others are in
378 this category.  (see comment at TcClassDcl.tcClassSig).
379
380 To indicate this property, such identifiers are marked TyGenNever.
381
382 Furthermore, if the usage inference generates a usage-specialised
383 variant of a function, we must NOT re-infer a fully-generalised type
384 at the next inference.  This finer property is indicated by a
385 TyGenUInfo on the identifier.
386
387 \begin{code}
388 data TyGenInfo
389   = NoTyGenInfo              -- no restriction on type generalisation
390
391   | TyGenUInfo [Maybe Type]  -- restrict generalisation of this Id to
392                              -- preserve specified usage annotations
393
394   | TyGenNever               -- never generalise the type of this Id
395
396   deriving ( Eq )
397 \end{code}
398
399 For TyGenUInfo, the list has one entry for each usage annotation on
400 the type of the Id, in left-to-right pre-order (annotations come
401 before the type they annotate).  Nothing means no restriction; Just
402 usOnce or Just usMany forces that annotation to that value.  Other
403 usage annotations are illegal.
404
405 \begin{code}
406 seqTyGenInfo :: TyGenInfo -> ()
407 seqTyGenInfo  NoTyGenInfo    = ()
408 seqTyGenInfo (TyGenUInfo us) = seqList us ()
409 seqTyGenInfo  TyGenNever     = ()
410
411 noTyGenInfo :: TyGenInfo
412 noTyGenInfo = NoTyGenInfo
413
414 isNoTyGenInfo :: TyGenInfo -> Bool
415 isNoTyGenInfo NoTyGenInfo = True
416 isNoTyGenInfo _           = False
417
418 -- NB: There's probably no need to write this information out to the interface file.
419 -- Why?  Simply because imported identifiers never get their types re-inferred.
420 -- But it's definitely nice to see in dumps, it for debugging purposes.
421
422 ppTyGenInfo :: TyGenInfo -> SDoc
423 ppTyGenInfo  NoTyGenInfo    = empty
424 ppTyGenInfo (TyGenUInfo us) = ptext SLIT("__G") <+> text (tyGenInfoString us)
425 ppTyGenInfo  TyGenNever     = ptext SLIT("__G N")
426
427 tyGenInfoString us = map go us
428   where go  Nothing               = 'x'  -- for legibility, choose
429         go (Just u) | u == usOnce = '1'  -- chars with identity
430                     | u == usMany = 'M'  -- Z-encoding.
431         go other = pprPanic "IdInfo.tyGenInfoString: unexpected annotation" (ppr other)
432
433 instance Outputable TyGenInfo where
434   ppr = ppTyGenInfo
435
436 instance Show TyGenInfo where
437   showsPrec p c = showsPrecSDoc p (ppr c)
438 \end{code}
439
440
441 %************************************************************************
442 %*                                                                      *
443 \subsection[worker-IdInfo]{Worker info about an @Id@}
444 %*                                                                      *
445 %************************************************************************
446
447 If this Id has a worker then we store a reference to it. Worker
448 functions are generated by the worker/wrapper pass.  This uses
449 information from the strictness and CPR analyses.
450
451 There might not be a worker, even for a strict function, because:
452 (a) the function might be small enough to inline, so no need 
453     for w/w split
454 (b) the strictness info might be "SSS" or something, so no w/w split.
455
456 Sometimes the arity of a wrapper changes from the original arity from
457 which it was generated, so we always emit the "original" arity into
458 the interface file, as part of the worker info.
459
460 How can this happen?  Sometimes we get
461         f = coerce t (\x y -> $wf x y)
462 at the moment of w/w split; but the eta reducer turns it into
463         f = coerce t $wf
464 which is perfectly fine except that the exposed arity so far as
465 the code generator is concerned (zero) differs from the arity
466 when we did the split (2).  
467
468 All this arises because we use 'arity' to mean "exactly how many
469 top level lambdas are there" in interface files; but during the
470 compilation of this module it means "how many things can I apply
471 this to".
472
473 \begin{code}
474
475 data WorkerInfo = NoWorker
476                 | HasWorker Id Arity
477         -- The Arity is the arity of the *wrapper* at the moment of the
478         -- w/w split. See comments in MkIface.ifaceId, with the 'Worker' code.
479
480 seqWorker :: WorkerInfo -> ()
481 seqWorker (HasWorker id _) = id `seq` ()
482 seqWorker NoWorker         = ()
483
484 ppWorkerInfo NoWorker            = empty
485 ppWorkerInfo (HasWorker wk_id _) = ptext SLIT("__P") <+> ppr wk_id
486
487 workerExists :: WorkerInfo -> Bool
488 workerExists NoWorker        = False
489 workerExists (HasWorker _ _) = True
490
491 workerId :: WorkerInfo -> Id
492 workerId (HasWorker id _) = id
493
494 wrapperArity :: WorkerInfo -> Arity
495 wrapperArity (HasWorker _ a) = a
496 \end{code}
497
498
499 %************************************************************************
500 %*                                                                      *
501 \subsection[CG-IdInfo]{Code generator-related information}
502 %*                                                                      *
503 %************************************************************************
504
505 CgInfo encapsulates calling-convention information produced by the code 
506 generator.  It is pasted into the IdInfo of each emitted Id by CoreTidy,
507 but only as a thunk --- the information is only actually produced further
508 downstream, by the code generator.
509
510 \begin{code}
511 data CgInfo = CgInfo 
512                 !Arity          -- Exact arity for calling purposes
513                 !CafInfo
514
515 cgArity   (CgInfo arity _)    = arity
516 cgCafInfo (CgInfo _ caf_info) = caf_info
517
518 setCafInfo info caf_info = 
519   case cgInfo info of { CgInfo arity _  -> 
520         info `setCgInfo` CgInfo arity caf_info }
521
522 setCgArity info arity = 
523   case cgInfo info of { CgInfo _ caf_info  -> 
524         info `setCgInfo` CgInfo arity caf_info }
525
526         -- Used for local Ids, which shouldn't need any CgInfo
527 noCgInfo = panic "noCgInfo!"
528
529 cgMayHaveCafRefs (CgInfo _ caf_info) = mayHaveCafRefs caf_info
530
531 seqCg c = c `seq` ()  -- fields are strict anyhow
532
533 vanillaCgInfo = CgInfo 0 MayHaveCafRefs         -- Definitely safe
534
535 -- CafInfo is used to build Static Reference Tables (see simplStg/SRT.lhs).
536
537 data CafInfo 
538         = MayHaveCafRefs                -- either:
539                                         -- (1) A function or static constructor
540                                         --     that refers to one or more CAFs,
541                                         -- (2) A real live CAF
542
543         | NoCafRefs                     -- A function or static constructor
544                                         -- that refers to no CAFs.
545
546 mayHaveCafRefs  MayHaveCafRefs = True
547 mayHaveCafRefs _               = False
548
549 seqCaf c = c `seq` ()
550
551 pprCgInfo (CgInfo arity caf_info) = ppArity arity <+> ppCafInfo caf_info
552
553 ppArity 0 = empty
554 ppArity n = hsep [ptext SLIT("__A"), int n]
555
556 ppCafInfo NoCafRefs = ptext SLIT("__C")
557 ppCafInfo MayHaveCafRefs = empty
558 \end{code}
559
560 \begin{code}
561 type CgInfoEnv = NameEnv CgInfo
562
563 lookupCgInfo :: NameEnv CgInfo -> Name -> CgInfo
564 lookupCgInfo env n = case lookupNameEnv env n of
565                         Just info -> info
566                         Nothing   -> pprTrace "Urk! Not in CgInfo env" (ppr n) vanillaCgInfo
567 \end{code}
568
569
570 %************************************************************************
571 %*                                                                      *
572 \subsection[cpr-IdInfo]{Constructed Product Result info about an @Id@}
573 %*                                                                      *
574 %************************************************************************
575
576 If the @Id@ is a function then it may have CPR info. A CPR analysis
577 phase detects whether:
578
579 \begin{enumerate}
580 \item
581 The function's return value has a product type, i.e. an algebraic  type 
582 with a single constructor. Examples of such types are tuples and boxed
583 primitive values.
584 \item
585 The function always 'constructs' the value that it is returning.  It
586 must do this on every path through,  and it's OK if it calls another
587 function which constructs the result.
588 \end{enumerate}
589
590 If this is the case then we store a template which tells us the
591 function has the CPR property and which components of the result are
592 also CPRs.   
593
594 \begin{code}
595 data CprInfo
596   = NoCPRInfo
597   | ReturnsCPR  -- Yes, this function returns a constructed product
598                 -- Implicitly, this means "after the function has been applied
599                 -- to all its arguments", so the worker/wrapper builder in 
600                 -- WwLib.mkWWcpr checks that that it is indeed saturated before
601                 -- making use of the CPR info
602
603         -- We used to keep nested info about sub-components, but
604         -- we never used it so I threw it away
605 \end{code}
606
607 \begin{code}
608 seqCpr :: CprInfo -> ()
609 seqCpr ReturnsCPR = ()
610 seqCpr NoCPRInfo  = ()
611
612 noCprInfo       = NoCPRInfo
613
614 ppCprInfo NoCPRInfo  = empty
615 ppCprInfo ReturnsCPR = ptext SLIT("__M")
616
617 instance Outputable CprInfo where
618     ppr = ppCprInfo
619
620 instance Show CprInfo where
621     showsPrec p c = showsPrecSDoc p (ppr c)
622 \end{code}
623
624
625 %************************************************************************
626 %*                                                                      *
627 \subsection[lbvar-IdInfo]{Lambda-bound var info about an @Id@}
628 %*                                                                      *
629 %************************************************************************
630
631 If the @Id@ is a lambda-bound variable then it may have lambda-bound
632 var info.  The usage analysis (UsageSP) detects whether the lambda
633 binding this var is a ``one-shot'' lambda; that is, whether it is
634 applied at most once.
635
636 This information may be useful in optimisation, as computations may
637 safely be floated inside such a lambda without risk of duplicating
638 work.
639
640 \begin{code}
641 data LBVarInfo
642   = NoLBVarInfo
643
644   | LBVarInfo Type              -- The lambda that binds this Id has this usage
645                                 --   annotation (i.e., if ==usOnce, then the
646                                 --   lambda is applied at most once).
647                                 -- The annotation's kind must be `$'
648                                 -- HACK ALERT! placing this info here is a short-term hack,
649                                 --   but it minimises changes to the rest of the compiler.
650                                 --   Hack agreed by SLPJ/KSW 1999-04.
651
652 seqLBVar l = l `seq` ()
653 \end{code}
654
655 \begin{code}
656 hasNoLBVarInfo NoLBVarInfo = True
657 hasNoLBVarInfo other       = False
658
659 noLBVarInfo = NoLBVarInfo
660
661 -- not safe to print or parse LBVarInfo because it is not really a
662 -- property of the definition, but a property of the context.
663 pprLBVarInfo NoLBVarInfo     = empty
664 pprLBVarInfo (LBVarInfo u)   | u == usOnce
665                              = getPprStyle $ \ sty ->
666                                if ifaceStyle sty
667                                then empty
668                                else ptext SLIT("OneShot")
669                              | otherwise
670                              = empty
671
672 instance Outputable LBVarInfo where
673     ppr = pprLBVarInfo
674
675 instance Show LBVarInfo where
676     showsPrec p c = showsPrecSDoc p (ppr c)
677 \end{code}
678
679
680 %************************************************************************
681 %*                                                                      *
682 \subsection{Bulk operations on IdInfo}
683 %*                                                                      *
684 %************************************************************************
685
686 @zapLamInfo@ is used for lambda binders that turn out to to be
687 part of an unsaturated lambda
688
689 \begin{code}
690 zapLamInfo :: IdInfo -> Maybe IdInfo
691 zapLamInfo info@(IdInfo {occInfo = occ, demandInfo = demand})
692   | is_safe_occ && not (isStrict demand)
693   = Nothing
694   | otherwise
695   = Just (info {occInfo = safe_occ,
696                 demandInfo = wwLazy})
697   where
698         -- The "unsafe" occ info is the ones that say I'm not in a lambda
699         -- because that might not be true for an unsaturated lambda
700     is_safe_occ = case occ of
701                         OneOcc in_lam once -> in_lam
702                         other              -> True
703
704     safe_occ = case occ of
705                  OneOcc _ once -> OneOcc insideLam once
706                  other         -> occ
707 \end{code}
708
709 \begin{code}
710 zapDemandInfo :: IdInfo -> Maybe IdInfo
711 zapDemandInfo info@(IdInfo {demandInfo = demand})
712   | not (isStrict demand) = Nothing
713   | otherwise             = Just (info {demandInfo = wwLazy})
714 \end{code}
715
716
717 copyIdInfo is used when shorting out a top-level binding
718         f_local = BIG
719         f = f_local
720 where f is exported.  We are going to swizzle it around to
721         f = BIG
722         f_local = f
723
724 BUT (a) we must be careful about messing up rules
725     (b) we must ensure f's IdInfo ends up right
726
727 (a) Messing up the rules
728 ~~~~~~~~~~~~~~~~~~~~
729 The example that went bad on me was this one:
730         
731     iterate :: (a -> a) -> a -> [a]
732     iterate = iterateList
733     
734     iterateFB c f x = x `c` iterateFB c f (f x)
735     iterateList f x =  x : iterateList f (f x)
736     
737     {-# RULES
738     "iterate"   forall f x.     iterate f x = build (\c _n -> iterateFB c f x)
739     "iterateFB"                 iterateFB (:) = iterateList
740      #-}
741
742 This got shorted out to:
743
744     iterateList :: (a -> a) -> a -> [a]
745     iterateList = iterate
746     
747     iterateFB c f x = x `c` iterateFB c f (f x)
748     iterate f x =  x : iterate f (f x)
749     
750     {-# RULES
751     "iterate"   forall f x.     iterate f x = build (\c _n -> iterateFB c f x)
752     "iterateFB"                 iterateFB (:) = iterate
753      #-}
754
755 And now we get an infinite loop in the rule system 
756         iterate f x -> build (\cn -> iterateFB c f x)
757                     -> iterateFB (:) f x
758                     -> iterate f x
759
760 Tiresome solution: don't do shorting out if f has rewrite rules.
761 Hence shortableIdInfo.
762
763 (b) Keeping the IdInfo right
764 ~~~~~~~~~~~~~~~~~~~~~~~~
765 We want to move strictness/worker info from f_local to f, but keep the rest.
766 Hence copyIdInfo.
767
768 \begin{code}
769 shortableIdInfo :: IdInfo -> Bool
770 shortableIdInfo info = isEmptyCoreRules (specInfo info)
771
772 copyIdInfo :: IdInfo    -- f_local
773            -> IdInfo    -- f (the exported one)
774            -> IdInfo    -- New info for f
775 copyIdInfo f_local f = f { strictnessInfo = strictnessInfo f_local,
776                            workerInfo     = workerInfo     f_local,
777                            cprInfo        = cprInfo        f_local
778                           }
779 \end{code}