Module header tidyup, phase 1
[ghc-hetmet.git] / compiler / codeGen / ClosureInfo.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The Univserity of Glasgow 1992-2004
4 %
5
6         Data structures which describe closures, and
7         operations over those data structures
8
9                 Nothing monadic in here
10
11 Much of the rationale for these things is in the ``details'' part of
12 the STG paper.
13
14 \begin{code}
15 module ClosureInfo (
16         ClosureInfo, LambdaFormInfo, SMRep,     -- all abstract
17         StandardFormInfo, 
18
19         ArgDescr(..), Liveness(..), 
20         C_SRT(..), needsSRT,
21
22         mkLFThunk, mkLFReEntrant, mkConLFInfo, mkSelectorLFInfo,
23         mkApLFInfo, mkLFImported, mkLFArgument, mkLFLetNoEscape,
24
25         mkClosureInfo, mkConInfo,
26
27         closureSize, closureNonHdrSize,
28         closureGoodStuffSize, closurePtrsSize,
29         slopSize, 
30
31         closureName, infoTableLabelFromCI,
32         closureLabelFromCI, closureSRT,
33         closureLFInfo, isLFThunk,closureSMRep, closureUpdReqd, 
34         closureNeedsUpdSpace, closureIsThunk,
35         closureSingleEntry, closureReEntrant, isConstrClosure_maybe,
36         closureFunInfo, isStandardFormThunk, isKnownFun,
37
38         enterIdLabel, enterLocalIdLabel, enterReturnPtLabel,
39
40         nodeMustPointToIt, 
41         CallMethod(..), getCallMethod,
42
43         blackHoleOnEntry,
44
45         staticClosureRequired,
46         getClosureType,
47
48         isToplevClosure,
49         closureValDescr, closureTypeDescr,      -- profiling
50
51         isStaticClosure,
52         cafBlackHoleClosureInfo, seCafBlackHoleClosureInfo,
53
54         staticClosureNeedsLink,
55     ) where
56
57 #include "../includes/MachDeps.h"
58 #include "HsVersions.h"
59
60 import StgSyn
61 import SMRep
62
63 import CLabel
64
65 import Packages
66 import PackageConfig
67 import StaticFlags
68 import Id
69 import DataCon
70 import Name
71 import OccName
72 import Type
73 import TypeRep
74 import TcType
75 import TyCon
76 import BasicTypes
77 import FastString
78 import Outputable
79 import Constants
80 \end{code}
81
82
83 %************************************************************************
84 %*                                                                      *
85 \subsection[ClosureInfo-datatypes]{Data types for closure information}
86 %*                                                                      *
87 %************************************************************************
88
89 Information about a closure, from the code generator's point of view.
90
91 A ClosureInfo decribes the info pointer of a closure.  It has
92 enough information 
93   a) to construct the info table itself
94   b) to allocate a closure containing that info pointer (i.e.
95         it knows the info table label)
96
97 We make a ClosureInfo for
98         - each let binding (both top level and not)
99         - each data constructor (for its shared static and
100                 dynamic info tables)
101
102 \begin{code}
103 data ClosureInfo
104   = ClosureInfo {
105         closureName   :: !Name,           -- The thing bound to this closure
106         closureLFInfo :: !LambdaFormInfo, -- NOTE: not an LFCon (see below)
107         closureSMRep  :: !SMRep,          -- representation used by storage mgr
108         closureSRT    :: !C_SRT,          -- What SRT applies to this closure
109         closureType   :: !Type,           -- Type of closure (ToDo: remove)
110         closureDescr  :: !String          -- closure description (for profiling)
111     }
112
113   -- Constructor closures don't have a unique info table label (they use
114   -- the constructor's info table), and they don't have an SRT.
115   | ConInfo {
116         closureCon       :: !DataCon,
117         closureSMRep     :: !SMRep,
118         closureDllCon    :: !Bool       -- is in a separate DLL
119     }
120
121 -- C_SRT is what StgSyn.SRT gets translated to... 
122 -- we add a label for the table, and expect only the 'offset/length' form
123
124 data C_SRT = NoC_SRT
125            | C_SRT !CLabel !WordOff !StgHalfWord {-bitmap or escape-}
126
127 needsSRT :: C_SRT -> Bool
128 needsSRT NoC_SRT       = False
129 needsSRT (C_SRT _ _ _) = True
130 \end{code}
131
132 %************************************************************************
133 %*                                                                      *
134 \subsubsection[LambdaFormInfo-datatype]{@LambdaFormInfo@: source-derivable info}
135 %*                                                                      *
136 %************************************************************************
137
138 Information about an identifier, from the code generator's point of
139 view.  Every identifier is bound to a LambdaFormInfo in the
140 environment, which gives the code generator enough info to be able to
141 tail call or return that identifier.
142
143 Note that a closure is usually bound to an identifier, so a
144 ClosureInfo contains a LambdaFormInfo.
145
146 \begin{code}
147 data LambdaFormInfo
148   = LFReEntrant         -- Reentrant closure (a function)
149         TopLevelFlag    -- True if top level
150         !Int            -- Arity. Invariant: always > 0
151         !Bool           -- True <=> no fvs
152         ArgDescr        -- Argument descriptor (should reall be in ClosureInfo)
153
154   | LFCon               -- A saturated constructor application
155         DataCon         -- The constructor
156
157   | LFThunk             -- Thunk (zero arity)
158         TopLevelFlag
159         !Bool           -- True <=> no free vars
160         !Bool           -- True <=> updatable (i.e., *not* single-entry)
161         StandardFormInfo
162         !Bool           -- True <=> *might* be a function type
163
164   | LFUnknown           -- Used for function arguments and imported things.
165                         --  We know nothing about  this closure.  Treat like
166                         -- updatable "LFThunk"...
167                         -- Imported things which we do know something about use
168                         -- one of the other LF constructors (eg LFReEntrant for
169                         -- known functions)
170         !Bool           -- True <=> *might* be a function type
171
172   | LFLetNoEscape       -- See LetNoEscape module for precise description of
173                         -- these "lets".
174         !Int            -- arity;
175
176   | LFBlackHole         -- Used for the closures allocated to hold the result
177                         -- of a CAF.  We want the target of the update frame to
178                         -- be in the heap, so we make a black hole to hold it.
179         CLabel          -- Flavour (info label, eg CAF_BLACKHOLE_info).
180
181
182 -------------------------
183 -- An ArgDsecr describes the argument pattern of a function
184
185 data ArgDescr
186   = ArgSpec             -- Fits one of the standard patterns
187         !Int            -- RTS type identifier ARG_P, ARG_N, ...
188
189   | ArgGen              -- General case
190         Liveness        -- Details about the arguments
191
192
193 -------------------------
194 -- We represent liveness bitmaps as a Bitmap (whose internal
195 -- representation really is a bitmap).  These are pinned onto case return
196 -- vectors to indicate the state of the stack for the garbage collector.
197 -- 
198 -- In the compiled program, liveness bitmaps that fit inside a single
199 -- word (StgWord) are stored as a single word, while larger bitmaps are
200 -- stored as a pointer to an array of words. 
201
202 data Liveness
203   = SmallLiveness       -- Liveness info that fits in one word
204         StgWord         -- Here's the bitmap
205
206   | BigLiveness         -- Liveness info witha a multi-word bitmap
207         CLabel          -- Label for the bitmap
208
209
210 -------------------------
211 -- StandardFormInfo tells whether this thunk has one of 
212 -- a small number of standard forms
213
214 data StandardFormInfo
215   = NonStandardThunk
216         -- Not of of the standard forms
217
218   | SelectorThunk
219         -- A SelectorThunk is of form
220         --      case x of
221         --             con a1,..,an -> ak
222         -- and the constructor is from a single-constr type.
223        WordOff                  -- 0-origin offset of ak within the "goods" of 
224                         -- constructor (Recall that the a1,...,an may be laid
225                         -- out in the heap in a non-obvious order.)
226
227   | ApThunk 
228         -- An ApThunk is of form
229         --      x1 ... xn
230         -- The code for the thunk just pushes x2..xn on the stack and enters x1.
231         -- There are a few of these (for 1 <= n <= MAX_SPEC_AP_SIZE) pre-compiled
232         -- in the RTS to save space.
233         Int             -- Arity, n
234 \end{code}
235
236 %************************************************************************
237 %*                                                                      *
238 \subsection[ClosureInfo-construction]{Functions which build LFInfos}
239 %*                                                                      *
240 %************************************************************************
241
242 \begin{code}
243 mkLFReEntrant :: TopLevelFlag   -- True of top level
244               -> [Id]           -- Free vars
245               -> [Id]           -- Args
246               -> ArgDescr       -- Argument descriptor
247               -> LambdaFormInfo
248
249 mkLFReEntrant top fvs args arg_descr 
250   = LFReEntrant top (length args) (null fvs) arg_descr
251
252 mkLFThunk thunk_ty top fvs upd_flag
253   = ASSERT( not (isUpdatable upd_flag) || not (isUnLiftedType thunk_ty) )
254     LFThunk top (null fvs) 
255             (isUpdatable upd_flag)
256             NonStandardThunk 
257             (might_be_a_function thunk_ty)
258
259 might_be_a_function :: Type -> Bool
260 might_be_a_function ty
261   | Just (tc,_) <- splitTyConApp_maybe (repType ty), 
262     not (isFunTyCon tc)  && not (isAbstractTyCon tc) = False
263         -- don't forget to check for abstract types, which might
264         -- be functions too.
265   | otherwise = True
266 \end{code}
267
268 @mkConLFInfo@ is similar, for constructors.
269
270 \begin{code}
271 mkConLFInfo :: DataCon -> LambdaFormInfo
272 mkConLFInfo con = LFCon con
273
274 mkSelectorLFInfo id offset updatable
275   = LFThunk NotTopLevel False updatable (SelectorThunk offset) 
276         (might_be_a_function (idType id))
277
278 mkApLFInfo id upd_flag arity
279   = LFThunk NotTopLevel (arity == 0) (isUpdatable upd_flag) (ApThunk arity)
280         (might_be_a_function (idType id))
281 \end{code}
282
283 Miscellaneous LF-infos.
284
285 \begin{code}
286 mkLFArgument id = LFUnknown (might_be_a_function (idType id))
287
288 mkLFLetNoEscape = LFLetNoEscape
289
290 mkLFImported :: Id -> LambdaFormInfo
291 mkLFImported id
292   = case idArity id of
293       n | n > 0 -> LFReEntrant TopLevel n True (panic "arg_descr")  -- n > 0
294       other -> mkLFArgument id -- Not sure of exact arity
295 \end{code}
296
297 \begin{code}
298 isLFThunk :: LambdaFormInfo -> Bool
299 isLFThunk (LFThunk _ _ _ _ _)  = True
300 isLFThunk (LFBlackHole _)      = True
301         -- return True for a blackhole: this function is used to determine
302         -- whether to use the thunk header in SMP mode, and a blackhole
303         -- must have one.
304 isLFThunk _ = False
305 \end{code}
306
307 %************************************************************************
308 %*                                                                      *
309         Building ClosureInfos
310 %*                                                                      *
311 %************************************************************************
312
313 \begin{code}
314 mkClosureInfo :: Bool           -- Is static
315               -> Id
316               -> LambdaFormInfo 
317               -> Int -> Int     -- Total and pointer words
318               -> C_SRT
319               -> String         -- String descriptor
320               -> ClosureInfo
321 mkClosureInfo is_static id lf_info tot_wds ptr_wds srt_info descr
322   = ClosureInfo { closureName = name, 
323                   closureLFInfo = lf_info,
324                   closureSMRep = sm_rep, 
325                   closureSRT = srt_info,
326                   closureType = idType id,
327                   closureDescr = descr }
328   where
329     name   = idName id
330     sm_rep = chooseSMRep is_static lf_info tot_wds ptr_wds
331
332 mkConInfo :: PackageId
333           -> Bool       -- Is static
334           -> DataCon    
335           -> Int -> Int -- Total and pointer words
336           -> ClosureInfo
337 mkConInfo this_pkg is_static data_con tot_wds ptr_wds
338    = ConInfo {  closureSMRep = sm_rep,
339                 closureCon = data_con,
340                 closureDllCon = isDllName this_pkg (dataConName data_con) }
341   where
342     sm_rep = chooseSMRep is_static (mkConLFInfo data_con) tot_wds ptr_wds
343 \end{code}
344
345 %************************************************************************
346 %*                                                                      *
347 \subsection[ClosureInfo-sizes]{Functions about closure {\em sizes}}
348 %*                                                                      *
349 %************************************************************************
350
351 \begin{code}
352 closureSize :: ClosureInfo -> WordOff
353 closureSize cl_info = hdr_size + closureNonHdrSize cl_info
354   where hdr_size  | closureIsThunk cl_info = thunkHdrSize
355                   | otherwise              = fixedHdrSize
356         -- All thunks use thunkHdrSize, even if they are non-updatable.
357         -- this is because we don't have separate closure types for
358         -- updatable vs. non-updatable thunks, so the GC can't tell the
359         -- difference.  If we ever have significant numbers of non-
360         -- updatable thunks, it might be worth fixing this.
361
362 closureNonHdrSize :: ClosureInfo -> WordOff
363 closureNonHdrSize cl_info
364   = tot_wds + computeSlopSize tot_wds cl_info
365   where
366     tot_wds = closureGoodStuffSize cl_info
367
368 closureGoodStuffSize :: ClosureInfo -> WordOff
369 closureGoodStuffSize cl_info
370   = let (ptrs, nonptrs) = sizes_from_SMRep (closureSMRep cl_info)
371     in  ptrs + nonptrs
372
373 closurePtrsSize :: ClosureInfo -> WordOff
374 closurePtrsSize cl_info
375   = let (ptrs, _) = sizes_from_SMRep (closureSMRep cl_info)
376     in  ptrs
377
378 -- not exported:
379 sizes_from_SMRep :: SMRep -> (WordOff,WordOff)
380 sizes_from_SMRep (GenericRep _ ptrs nonptrs _)   = (ptrs, nonptrs)
381 sizes_from_SMRep BlackHoleRep                    = (0, 0)
382 \end{code}
383
384 Computing slop size.  WARNING: this looks dodgy --- it has deep
385 knowledge of what the storage manager does with the various
386 representations...
387
388 Slop Requirements: every thunk gets an extra padding word in the
389 header, which takes the the updated value.
390
391 \begin{code}
392 slopSize cl_info = computeSlopSize payload_size cl_info
393   where payload_size = closureGoodStuffSize cl_info
394
395 computeSlopSize :: WordOff -> ClosureInfo -> WordOff
396 computeSlopSize payload_size cl_info
397   = max 0 (minPayloadSize smrep updatable - payload_size)
398   where
399         smrep        = closureSMRep cl_info
400         updatable    = closureNeedsUpdSpace cl_info
401
402 -- we leave space for an update if either (a) the closure is updatable
403 -- or (b) it is a static thunk.  This is because a static thunk needs
404 -- a static link field in a predictable place (after the slop), regardless
405 -- of whether it is updatable or not.
406 closureNeedsUpdSpace (ClosureInfo { closureLFInfo = 
407                                         LFThunk TopLevel _ _ _ _ }) = True
408 closureNeedsUpdSpace cl_info = closureUpdReqd cl_info
409
410 minPayloadSize :: SMRep -> Bool -> WordOff
411 minPayloadSize smrep updatable
412   = case smrep of
413         BlackHoleRep                            -> min_upd_size
414         GenericRep _ _ _ _      | updatable     -> min_upd_size
415         GenericRep True _ _ _                   -> 0 -- static
416         GenericRep False _ _ _                  -> mIN_PAYLOAD_SIZE
417           --       ^^^^^___ dynamic
418   where
419    min_upd_size =
420         ASSERT(mIN_PAYLOAD_SIZE <= sIZEOF_StgSMPThunkHeader)
421         0       -- check that we already have enough
422                 -- room for mIN_SIZE_NonUpdHeapObject,
423                 -- due to the extra header word in SMP
424 \end{code}
425
426 %************************************************************************
427 %*                                                                      *
428 \subsection[SMreps]{Choosing SM reps}
429 %*                                                                      *
430 %************************************************************************
431
432 \begin{code}
433 chooseSMRep
434         :: Bool                 -- True <=> static closure
435         -> LambdaFormInfo
436         -> WordOff -> WordOff   -- Tot wds, ptr wds
437         -> SMRep
438
439 chooseSMRep is_static lf_info tot_wds ptr_wds
440   = let
441          nonptr_wds   = tot_wds - ptr_wds
442          closure_type = getClosureType is_static ptr_wds lf_info
443     in
444     GenericRep is_static ptr_wds nonptr_wds closure_type        
445
446 -- We *do* get non-updatable top-level thunks sometimes.  eg. f = g
447 -- gets compiled to a jump to g (if g has non-zero arity), instead of
448 -- messing around with update frames and PAPs.  We set the closure type
449 -- to FUN_STATIC in this case.
450
451 getClosureType :: Bool -> WordOff -> LambdaFormInfo -> ClosureType
452 getClosureType is_static ptr_wds lf_info
453   = case lf_info of
454         LFCon con | is_static && ptr_wds == 0   -> ConstrNoCaf
455                   | otherwise                   -> Constr
456         LFReEntrant _ _ _ _                     -> Fun
457         LFThunk _ _ _ (SelectorThunk _) _       -> ThunkSelector
458         LFThunk _ _ _ _ _                       -> Thunk
459         _ -> panic "getClosureType"
460 \end{code}
461
462 %************************************************************************
463 %*                                                                      *
464 \subsection[ClosureInfo-4-questions]{Four major questions about @ClosureInfo@}
465 %*                                                                      *
466 %************************************************************************
467
468 Be sure to see the stg-details notes about these...
469
470 \begin{code}
471 nodeMustPointToIt :: LambdaFormInfo -> Bool
472 nodeMustPointToIt (LFReEntrant top _ no_fvs _)
473   = not no_fvs ||   -- Certainly if it has fvs we need to point to it
474     isNotTopLevel top
475                     -- If it is not top level we will point to it
476                     --   We can have a \r closure with no_fvs which
477                     --   is not top level as special case cgRhsClosure
478                     --   has been dissabled in favour of let floating
479
480                 -- For lex_profiling we also access the cost centre for a
481                 -- non-inherited function i.e. not top level
482                 -- the  not top  case above ensures this is ok.
483
484 nodeMustPointToIt (LFCon _) = True
485
486         -- Strictly speaking, the above two don't need Node to point
487         -- to it if the arity = 0.  But this is a *really* unlikely
488         -- situation.  If we know it's nil (say) and we are entering
489         -- it. Eg: let x = [] in x then we will certainly have inlined
490         -- x, since nil is a simple atom.  So we gain little by not
491         -- having Node point to known zero-arity things.  On the other
492         -- hand, we do lose something; Patrick's code for figuring out
493         -- when something has been updated but not entered relies on
494         -- having Node point to the result of an update.  SLPJ
495         -- 27/11/92.
496
497 nodeMustPointToIt (LFThunk _ no_fvs updatable NonStandardThunk _)
498   = updatable || not no_fvs || opt_SccProfilingOn
499           -- For the non-updatable (single-entry case):
500           --
501           -- True if has fvs (in which case we need access to them, and we
502           --                should black-hole it)
503           -- or profiling (in which case we need to recover the cost centre
504           --             from inside it)
505
506 nodeMustPointToIt (LFThunk _ no_fvs updatable some_standard_form_thunk _)
507   = True  -- Node must point to any standard-form thunk
508
509 nodeMustPointToIt (LFUnknown _)     = True
510 nodeMustPointToIt (LFBlackHole _)   = True    -- BH entry may require Node to point
511 nodeMustPointToIt (LFLetNoEscape _) = False 
512 \end{code}
513
514 The entry conventions depend on the type of closure being entered,
515 whether or not it has free variables, and whether we're running
516 sequentially or in parallel.
517
518 \begin{tabular}{lllll}
519 Closure Characteristics & Parallel & Node Req'd & Argument Passing & Enter Via \\
520 Unknown                         & no & yes & stack      & node \\
521 Known fun ($\ge$ 1 arg), no fvs         & no & no  & registers  & fast entry (enough args) \\
522 \ & \ & \ & \                                           & slow entry (otherwise) \\
523 Known fun ($\ge$ 1 arg), fvs    & no & yes & registers  & fast entry (enough args) \\
524 0 arg, no fvs @\r,\s@           & no & no  & n/a        & direct entry \\
525 0 arg, no fvs @\u@              & no & yes & n/a        & node \\
526 0 arg, fvs @\r,\s@              & no & yes & n/a        & direct entry \\
527 0 arg, fvs @\u@                 & no & yes & n/a        & node \\
528
529 Unknown                         & yes & yes & stack     & node \\
530 Known fun ($\ge$ 1 arg), no fvs         & yes & no  & registers & fast entry (enough args) \\
531 \ & \ & \ & \                                           & slow entry (otherwise) \\
532 Known fun ($\ge$ 1 arg), fvs    & yes & yes & registers & node \\
533 0 arg, no fvs @\r,\s@           & yes & no  & n/a       & direct entry \\
534 0 arg, no fvs @\u@              & yes & yes & n/a       & node \\
535 0 arg, fvs @\r,\s@              & yes & yes & n/a       & node \\
536 0 arg, fvs @\u@                 & yes & yes & n/a       & node\\
537 \end{tabular}
538
539 When black-holing, single-entry closures could also be entered via node
540 (rather than directly) to catch double-entry.
541
542 \begin{code}
543 data CallMethod
544   = EnterIt                             -- no args, not a function
545
546   | JumpToIt CLabel                     -- no args, not a function, but we
547                                         -- know what its entry code is
548
549   | ReturnIt                            -- it's a function, but we have
550                                         -- zero args to apply to it, so just
551                                         -- return it.
552
553   | ReturnCon DataCon                   -- It's a data constructor, just return it
554
555   | SlowCall                            -- Unknown fun, or known fun with
556                                         -- too few args.
557
558   | DirectEntry                         -- Jump directly, with args in regs
559         CLabel                          --   The code label
560         Int                             --   Its arity
561
562 getCallMethod :: PackageId
563               -> Name           -- Function being applied
564               -> LambdaFormInfo -- Its info
565               -> Int            -- Number of available arguments
566               -> CallMethod
567
568 getCallMethod this_pkg name lf_info n_args
569   | nodeMustPointToIt lf_info && opt_Parallel
570   =     -- If we're parallel, then we must always enter via node.  
571         -- The reason is that the closure may have been         
572         -- fetched since we allocated it.
573     EnterIt
574
575 getCallMethod this_pkg name (LFReEntrant _ arity _ _) n_args
576   | n_args == 0    = ASSERT( arity /= 0 )
577                      ReturnIt   -- No args at all
578   | n_args < arity = SlowCall   -- Not enough args
579   | otherwise      = DirectEntry (enterIdLabel this_pkg name) arity
580
581 getCallMethod this_pkg name (LFCon con) n_args
582   = ASSERT( n_args == 0 )
583     ReturnCon con
584
585 getCallMethod this_pkg name (LFThunk _ _ updatable std_form_info is_fun) n_args
586   | is_fun      -- Must always "call" a function-typed 
587   = SlowCall    -- thing, cannot just enter it [in eval/apply, the entry code
588                 -- is the fast-entry code]
589
590   | updatable || opt_DoTickyProfiling  -- to catch double entry
591       {- OLD: || opt_SMP
592          I decided to remove this, because in SMP mode it doesn't matter
593          if we enter the same thunk multiple times, so the optimisation
594          of jumping directly to the entry code is still valid.  --SDM
595         -}
596   = ASSERT( n_args == 0 ) EnterIt
597
598   | otherwise   -- Jump direct to code for single-entry thunks
599   = ASSERT( n_args == 0 )
600     JumpToIt (thunkEntryLabel this_pkg name std_form_info updatable)
601
602 getCallMethod this_pkg name (LFUnknown True) n_args
603   = SlowCall -- might be a function
604
605 getCallMethod this_pkg name (LFUnknown False) n_args
606   = ASSERT2 ( n_args == 0, ppr name <+> ppr n_args ) 
607     EnterIt -- Not a function
608
609 getCallMethod this_pkg name (LFBlackHole _) n_args
610   = SlowCall    -- Presumably the black hole has by now
611                 -- been updated, but we don't know with
612                 -- what, so we slow call it
613
614 getCallMethod this_pkg name (LFLetNoEscape 0) n_args
615   = JumpToIt (enterReturnPtLabel (nameUnique name))
616
617 getCallMethod this_pkg name (LFLetNoEscape arity) n_args
618   | n_args == arity = DirectEntry (enterReturnPtLabel (nameUnique name)) arity
619   | otherwise = pprPanic "let-no-escape: " (ppr name <+> ppr arity)
620
621 blackHoleOnEntry :: ClosureInfo -> Bool
622 -- Static closures are never themselves black-holed.
623 -- Updatable ones will be overwritten with a CAFList cell, which points to a 
624 -- black hole;
625 -- Single-entry ones have no fvs to plug, and we trust they don't form part 
626 -- of a loop.
627
628 blackHoleOnEntry ConInfo{} = False
629 blackHoleOnEntry (ClosureInfo { closureLFInfo = lf_info, closureSMRep = rep })
630   | isStaticRep rep
631   = False       -- Never black-hole a static closure
632
633   | otherwise
634   = case lf_info of
635         LFReEntrant _ _ _ _       -> False
636         LFLetNoEscape _           -> False
637         LFThunk _ no_fvs updatable _ _
638           -> if updatable
639              then not opt_OmitBlackHoling
640              else opt_DoTickyProfiling || not no_fvs
641                   -- the former to catch double entry,
642                   -- and the latter to plug space-leaks.  KSW/SDM 1999-04.
643
644         other -> panic "blackHoleOnEntry"       -- Should never happen
645
646 isStandardFormThunk :: LambdaFormInfo -> Bool
647 isStandardFormThunk (LFThunk _ _ _ (SelectorThunk _) _) = True
648 isStandardFormThunk (LFThunk _ _ _ (ApThunk _) _)       = True
649 isStandardFormThunk other_lf_info                       = False
650
651 isKnownFun :: LambdaFormInfo -> Bool
652 isKnownFun (LFReEntrant _ _ _ _) = True
653 isKnownFun (LFLetNoEscape _) = True
654 isKnownFun _ = False
655 \end{code}
656
657 -----------------------------------------------------------------------------
658 SRT-related stuff
659
660 \begin{code}
661 staticClosureNeedsLink :: ClosureInfo -> Bool
662 -- A static closure needs a link field to aid the GC when traversing
663 -- the static closure graph.  But it only needs such a field if either
664 --      a) it has an SRT
665 --      b) it's a constructor with one or more pointer fields
666 -- In case (b), the constructor's fields themselves play the role
667 -- of the SRT.
668 staticClosureNeedsLink (ClosureInfo { closureSRT = srt })
669   = needsSRT srt
670 staticClosureNeedsLink (ConInfo { closureSMRep = sm_rep, closureCon = con })
671   = not (isNullaryRepDataCon con) && not_nocaf_constr
672   where
673     not_nocaf_constr = 
674         case sm_rep of 
675            GenericRep _ _ _ ConstrNoCaf -> False
676            _other                       -> True
677 \end{code}
678
679 Avoiding generating entries and info tables
680 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
681 At present, for every function we generate all of the following,
682 just in case.  But they aren't always all needed, as noted below:
683
684 [NB1: all of this applies only to *functions*.  Thunks always
685 have closure, info table, and entry code.]
686
687 [NB2: All are needed if the function is *exported*, just to play safe.]
688
689
690 * Fast-entry code  ALWAYS NEEDED
691
692 * Slow-entry code
693         Needed iff (a) we have any un-saturated calls to the function
694         OR         (b) the function is passed as an arg
695         OR         (c) we're in the parallel world and the function has free vars
696                         [Reason: in parallel world, we always enter functions
697                         with free vars via the closure.]
698
699 * The function closure
700         Needed iff (a) we have any un-saturated calls to the function
701         OR         (b) the function is passed as an arg
702         OR         (c) if the function has free vars (ie not top level)
703
704   Why case (a) here?  Because if the arg-satis check fails,
705   UpdatePAP stuffs a pointer to the function closure in the PAP.
706   [Could be changed; UpdatePAP could stuff in a code ptr instead,
707    but doesn't seem worth it.]
708
709   [NB: these conditions imply that we might need the closure
710   without the slow-entry code.  Here's how.
711
712         f x y = let g w = ...x..y..w...
713                 in
714                 ...(g t)...
715
716   Here we need a closure for g which contains x and y,
717   but since the calls are all saturated we just jump to the
718   fast entry point for g, with R1 pointing to the closure for g.]
719
720
721 * Standard info table
722         Needed iff (a) we have any un-saturated calls to the function
723         OR         (b) the function is passed as an arg
724         OR         (c) the function has free vars (ie not top level)
725
726         NB.  In the sequential world, (c) is only required so that the function closure has
727         an info table to point to, to keep the storage manager happy.
728         If (c) alone is true we could fake up an info table by choosing
729         one of a standard family of info tables, whose entry code just
730         bombs out.
731
732         [NB In the parallel world (c) is needed regardless because
733         we enter functions with free vars via the closure.]
734
735         If (c) is retained, then we'll sometimes generate an info table
736         (for storage mgr purposes) without slow-entry code.  Then we need
737         to use an error label in the info table to substitute for the absent
738         slow entry code.
739
740 \begin{code}
741 staticClosureRequired
742         :: Name
743         -> StgBinderInfo
744         -> LambdaFormInfo
745         -> Bool
746 staticClosureRequired binder bndr_info
747                       (LFReEntrant top_level _ _ _)     -- It's a function
748   = ASSERT( isTopLevel top_level )
749         -- Assumption: it's a top-level, no-free-var binding
750         not (satCallsOnly bndr_info)
751
752 staticClosureRequired binder other_binder_info other_lf_info = True
753 \end{code}
754
755 %************************************************************************
756 %*                                                                      *
757 \subsection[ClosureInfo-misc-funs]{Misc functions about @ClosureInfo@, etc.}
758 %*                                                                      *
759 %************************************************************************
760
761 \begin{code}
762
763 isStaticClosure :: ClosureInfo -> Bool
764 isStaticClosure cl_info = isStaticRep (closureSMRep cl_info)
765
766 closureUpdReqd :: ClosureInfo -> Bool
767 closureUpdReqd ClosureInfo{ closureLFInfo = lf_info } = lfUpdatable lf_info
768 closureUpdReqd ConInfo{} = False
769
770 lfUpdatable :: LambdaFormInfo -> Bool
771 lfUpdatable (LFThunk _ _ upd _ _)  = upd
772 lfUpdatable (LFBlackHole _)        = True
773         -- Black-hole closures are allocated to receive the results of an
774         -- alg case with a named default... so they need to be updated.
775 lfUpdatable _ = False
776
777 closureIsThunk :: ClosureInfo -> Bool
778 closureIsThunk ClosureInfo{ closureLFInfo = lf_info } = isLFThunk lf_info
779 closureIsThunk ConInfo{} = False
780
781 closureSingleEntry :: ClosureInfo -> Bool
782 closureSingleEntry (ClosureInfo { closureLFInfo = LFThunk _ _ upd _ _}) = not upd
783 closureSingleEntry other_closure = False
784
785 closureReEntrant :: ClosureInfo -> Bool
786 closureReEntrant (ClosureInfo { closureLFInfo = LFReEntrant _ _ _ _ }) = True
787 closureReEntrant other_closure = False
788
789 isConstrClosure_maybe :: ClosureInfo -> Maybe DataCon
790 isConstrClosure_maybe (ConInfo { closureCon = data_con }) = Just data_con
791 isConstrClosure_maybe _                                   = Nothing
792
793 closureFunInfo :: ClosureInfo -> Maybe (Int, ArgDescr)
794 closureFunInfo (ClosureInfo { closureLFInfo = LFReEntrant _ arity _ arg_desc})
795   = Just (arity, arg_desc)
796 closureFunInfo _
797   = Nothing
798 \end{code}
799
800 \begin{code}
801 isToplevClosure :: ClosureInfo -> Bool
802 isToplevClosure (ClosureInfo { closureLFInfo = lf_info })
803   = case lf_info of
804       LFReEntrant TopLevel _ _ _ -> True
805       LFThunk TopLevel _ _ _ _   -> True
806       other -> False
807 isToplevClosure _ = False
808 \end{code}
809
810 Label generation.
811
812 \begin{code}
813 infoTableLabelFromCI :: ClosureInfo -> CLabel
814 infoTableLabelFromCI (ClosureInfo { closureName = name,
815                                     closureLFInfo = lf_info, 
816                                     closureSMRep = rep })
817   = case lf_info of
818         LFBlackHole info -> info
819
820         LFThunk _ _ upd_flag (SelectorThunk offset) _ -> 
821                 mkSelectorInfoLabel upd_flag offset
822
823         LFThunk _ _ upd_flag (ApThunk arity) _ -> 
824                 mkApInfoTableLabel upd_flag arity
825
826         LFThunk{}      -> mkLocalInfoTableLabel name
827
828         LFReEntrant _ _ _ _ -> mkLocalInfoTableLabel name
829
830         other -> panic "infoTableLabelFromCI"
831
832 infoTableLabelFromCI (ConInfo { closureCon = con, 
833                                 closureSMRep = rep,
834                                 closureDllCon = dll })
835   | isStaticRep rep = mkStaticInfoTableLabel  name dll
836   | otherwise       = mkConInfoTableLabel     name dll
837   where
838     name = dataConName con
839
840 -- ClosureInfo for a closure (as opposed to a constructor) is always local
841 closureLabelFromCI (ClosureInfo { closureName = nm }) = mkLocalClosureLabel nm
842 closureLabelFromCI _ = panic "closureLabelFromCI"
843
844 -- thunkEntryLabel is a local help function, not exported.  It's used from both
845 -- entryLabelFromCI and getCallMethod.
846
847 thunkEntryLabel this_pkg thunk_id (ApThunk arity) is_updatable
848   = enterApLabel is_updatable arity
849 thunkEntryLabel this_pkg thunk_id (SelectorThunk offset) upd_flag
850   = enterSelectorLabel upd_flag offset
851 thunkEntryLabel this_pkg thunk_id _ is_updatable
852   = enterIdLabel this_pkg thunk_id
853
854 enterApLabel is_updatable arity
855   | tablesNextToCode = mkApInfoTableLabel is_updatable arity
856   | otherwise        = mkApEntryLabel is_updatable arity
857
858 enterSelectorLabel upd_flag offset
859   | tablesNextToCode = mkSelectorInfoLabel upd_flag offset
860   | otherwise        = mkSelectorEntryLabel upd_flag offset
861
862 enterIdLabel this_pkg id
863   | tablesNextToCode = mkInfoTableLabel this_pkg id
864   | otherwise        = mkEntryLabel this_pkg id
865
866 enterLocalIdLabel id
867   | tablesNextToCode = mkLocalInfoTableLabel id
868   | otherwise        = mkLocalEntryLabel id
869
870 enterReturnPtLabel name
871   | tablesNextToCode = mkReturnInfoLabel name
872   | otherwise        = mkReturnPtLabel name
873 \end{code}
874
875
876 We need a black-hole closure info to pass to @allocDynClosure@ when we
877 want to allocate the black hole on entry to a CAF.  These are the only
878 ways to build an LFBlackHole, maintaining the invariant that it really
879 is a black hole and not something else.
880
881 \begin{code}
882 cafBlackHoleClosureInfo (ClosureInfo { closureName = nm,
883                                        closureType = ty })
884   = ClosureInfo { closureName   = nm,
885                   closureLFInfo = LFBlackHole mkCAFBlackHoleInfoTableLabel,
886                   closureSMRep  = BlackHoleRep,
887                   closureSRT    = NoC_SRT,
888                   closureType   = ty,
889                   closureDescr  = "" }
890 cafBlackHoleClosureInfo _ = panic "cafBlackHoleClosureInfo"
891
892 seCafBlackHoleClosureInfo (ClosureInfo { closureName = nm,
893                                          closureType = ty })
894   = ClosureInfo { closureName   = nm,
895                   closureLFInfo = LFBlackHole mkSECAFBlackHoleInfoTableLabel,
896                   closureSMRep  = BlackHoleRep,
897                   closureSRT    = NoC_SRT,
898                   closureType   = ty,
899                   closureDescr  = ""  }
900 seCafBlackHoleClosureInfo _ = panic "seCafBlackHoleClosureInfo"
901 \end{code}
902
903 %************************************************************************
904 %*                                                                      *
905 \subsection[ClosureInfo-Profiling-funs]{Misc functions about for profiling info.}
906 %*                                                                      *
907 %************************************************************************
908
909 Profiling requires two pieces of information to be determined for
910 each closure's info table --- description and type.
911
912 The description is stored directly in the @CClosureInfoTable@ when the
913 info table is built.
914
915 The type is determined from the type information stored with the @Id@
916 in the closure info using @closureTypeDescr@.
917
918 \begin{code}
919 closureValDescr, closureTypeDescr :: ClosureInfo -> String
920 closureValDescr (ClosureInfo {closureDescr = descr}) 
921   = descr
922 closureValDescr (ConInfo {closureCon = con})
923   = occNameString (getOccName con)
924
925 closureTypeDescr (ClosureInfo { closureType = ty })
926   = getTyDescription ty
927 closureTypeDescr (ConInfo { closureCon = data_con })
928   = occNameString (getOccName (dataConTyCon data_con))
929
930 getTyDescription :: Type -> String
931 getTyDescription ty
932   = case (tcSplitSigmaTy ty) of { (_, _, tau_ty) ->
933     case tau_ty of
934       TyVarTy _              -> "*"
935       AppTy fun _            -> getTyDescription fun
936       FunTy _ res            -> '-' : '>' : fun_result res
937       TyConApp tycon _       -> getOccString tycon
938       NoteTy (FTVNote _) ty  -> getTyDescription ty
939       PredTy sty             -> getPredTyDescription sty
940       ForAllTy _ ty          -> getTyDescription ty
941     }
942   where
943     fun_result (FunTy _ res) = '>' : fun_result res
944     fun_result other         = getTyDescription other
945
946 getPredTyDescription (ClassP cl tys) = getOccString cl
947 getPredTyDescription (IParam ip ty)  = getOccString (ipNameName ip)
948 \end{code}
949
950