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