e6319898db041ba7662eba5eb9967c7964636fab
[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 -- Return False only if we are *sure* it's a data type
261 -- Look through newtypes etc as much as poss
262 might_be_a_function ty
263   = case splitTyConApp_maybe (repType ty) of
264         Just (tc, _) -> not (isDataTyCon tc)
265         Nothing      -> 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      -- *Might* be a function, so we must "call" it (which is always safe)
587   = SlowCall    -- We cannot just enter it [in eval/apply, the entry code
588                 -- is the fast-entry code]
589
590   -- Since is_fun is False, we are *definitely* looking at a data value
591   | updatable || opt_DoTickyProfiling  -- to catch double entry
592       {- OLD: || opt_SMP
593          I decided to remove this, because in SMP mode it doesn't matter
594          if we enter the same thunk multiple times, so the optimisation
595          of jumping directly to the entry code is still valid.  --SDM
596         -}
597   = ASSERT2( n_args == 0, ppr name ) EnterIt
598
599   | otherwise   -- Jump direct to code for single-entry thunks
600   = ASSERT( n_args == 0 )
601     JumpToIt (thunkEntryLabel this_pkg name std_form_info updatable)
602
603 getCallMethod this_pkg name (LFUnknown True) n_args
604   = SlowCall -- might be a function
605
606 getCallMethod this_pkg name (LFUnknown False) n_args
607   = ASSERT2 ( n_args == 0, ppr name <+> ppr n_args ) 
608     EnterIt -- Not a function
609
610 getCallMethod this_pkg name (LFBlackHole _) n_args
611   = SlowCall    -- Presumably the black hole has by now
612                 -- been updated, but we don't know with
613                 -- what, so we slow call it
614
615 getCallMethod this_pkg name (LFLetNoEscape 0) n_args
616   = JumpToIt (enterReturnPtLabel (nameUnique name))
617
618 getCallMethod this_pkg name (LFLetNoEscape arity) n_args
619   | n_args == arity = DirectEntry (enterReturnPtLabel (nameUnique name)) arity
620   | otherwise = pprPanic "let-no-escape: " (ppr name <+> ppr arity)
621
622 blackHoleOnEntry :: ClosureInfo -> Bool
623 -- Static closures are never themselves black-holed.
624 -- Updatable ones will be overwritten with a CAFList cell, which points to a 
625 -- black hole;
626 -- Single-entry ones have no fvs to plug, and we trust they don't form part 
627 -- of a loop.
628
629 blackHoleOnEntry ConInfo{} = False
630 blackHoleOnEntry (ClosureInfo { closureLFInfo = lf_info, closureSMRep = rep })
631   | isStaticRep rep
632   = False       -- Never black-hole a static closure
633
634   | otherwise
635   = case lf_info of
636         LFReEntrant _ _ _ _       -> False
637         LFLetNoEscape _           -> False
638         LFThunk _ no_fvs updatable _ _
639           -> if updatable
640              then not opt_OmitBlackHoling
641              else opt_DoTickyProfiling || not no_fvs
642                   -- the former to catch double entry,
643                   -- and the latter to plug space-leaks.  KSW/SDM 1999-04.
644
645         other -> panic "blackHoleOnEntry"       -- Should never happen
646
647 isStandardFormThunk :: LambdaFormInfo -> Bool
648 isStandardFormThunk (LFThunk _ _ _ (SelectorThunk _) _) = True
649 isStandardFormThunk (LFThunk _ _ _ (ApThunk _) _)       = True
650 isStandardFormThunk other_lf_info                       = False
651
652 isKnownFun :: LambdaFormInfo -> Bool
653 isKnownFun (LFReEntrant _ _ _ _) = True
654 isKnownFun (LFLetNoEscape _) = True
655 isKnownFun _ = False
656 \end{code}
657
658 -----------------------------------------------------------------------------
659 SRT-related stuff
660
661 \begin{code}
662 staticClosureNeedsLink :: ClosureInfo -> Bool
663 -- A static closure needs a link field to aid the GC when traversing
664 -- the static closure graph.  But it only needs such a field if either
665 --      a) it has an SRT
666 --      b) it's a constructor with one or more pointer fields
667 -- In case (b), the constructor's fields themselves play the role
668 -- of the SRT.
669 staticClosureNeedsLink (ClosureInfo { closureSRT = srt })
670   = needsSRT srt
671 staticClosureNeedsLink (ConInfo { closureSMRep = sm_rep, closureCon = con })
672   = not (isNullaryRepDataCon con) && not_nocaf_constr
673   where
674     not_nocaf_constr = 
675         case sm_rep of 
676            GenericRep _ _ _ ConstrNoCaf -> False
677            _other                       -> True
678 \end{code}
679
680 Avoiding generating entries and info tables
681 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
682 At present, for every function we generate all of the following,
683 just in case.  But they aren't always all needed, as noted below:
684
685 [NB1: all of this applies only to *functions*.  Thunks always
686 have closure, info table, and entry code.]
687
688 [NB2: All are needed if the function is *exported*, just to play safe.]
689
690
691 * Fast-entry code  ALWAYS NEEDED
692
693 * Slow-entry code
694         Needed iff (a) we have any un-saturated calls to the function
695         OR         (b) the function is passed as an arg
696         OR         (c) we're in the parallel world and the function has free vars
697                         [Reason: in parallel world, we always enter functions
698                         with free vars via the closure.]
699
700 * The function closure
701         Needed iff (a) we have any un-saturated calls to the function
702         OR         (b) the function is passed as an arg
703         OR         (c) if the function has free vars (ie not top level)
704
705   Why case (a) here?  Because if the arg-satis check fails,
706   UpdatePAP stuffs a pointer to the function closure in the PAP.
707   [Could be changed; UpdatePAP could stuff in a code ptr instead,
708    but doesn't seem worth it.]
709
710   [NB: these conditions imply that we might need the closure
711   without the slow-entry code.  Here's how.
712
713         f x y = let g w = ...x..y..w...
714                 in
715                 ...(g t)...
716
717   Here we need a closure for g which contains x and y,
718   but since the calls are all saturated we just jump to the
719   fast entry point for g, with R1 pointing to the closure for g.]
720
721
722 * Standard info table
723         Needed iff (a) we have any un-saturated calls to the function
724         OR         (b) the function is passed as an arg
725         OR         (c) the function has free vars (ie not top level)
726
727         NB.  In the sequential world, (c) is only required so that the function closure has
728         an info table to point to, to keep the storage manager happy.
729         If (c) alone is true we could fake up an info table by choosing
730         one of a standard family of info tables, whose entry code just
731         bombs out.
732
733         [NB In the parallel world (c) is needed regardless because
734         we enter functions with free vars via the closure.]
735
736         If (c) is retained, then we'll sometimes generate an info table
737         (for storage mgr purposes) without slow-entry code.  Then we need
738         to use an error label in the info table to substitute for the absent
739         slow entry code.
740
741 \begin{code}
742 staticClosureRequired
743         :: Name
744         -> StgBinderInfo
745         -> LambdaFormInfo
746         -> Bool
747 staticClosureRequired binder bndr_info
748                       (LFReEntrant top_level _ _ _)     -- It's a function
749   = ASSERT( isTopLevel top_level )
750         -- Assumption: it's a top-level, no-free-var binding
751         not (satCallsOnly bndr_info)
752
753 staticClosureRequired binder other_binder_info other_lf_info = True
754 \end{code}
755
756 %************************************************************************
757 %*                                                                      *
758 \subsection[ClosureInfo-misc-funs]{Misc functions about @ClosureInfo@, etc.}
759 %*                                                                      *
760 %************************************************************************
761
762 \begin{code}
763
764 isStaticClosure :: ClosureInfo -> Bool
765 isStaticClosure cl_info = isStaticRep (closureSMRep cl_info)
766
767 closureUpdReqd :: ClosureInfo -> Bool
768 closureUpdReqd ClosureInfo{ closureLFInfo = lf_info } = lfUpdatable lf_info
769 closureUpdReqd ConInfo{} = False
770
771 lfUpdatable :: LambdaFormInfo -> Bool
772 lfUpdatable (LFThunk _ _ upd _ _)  = upd
773 lfUpdatable (LFBlackHole _)        = True
774         -- Black-hole closures are allocated to receive the results of an
775         -- alg case with a named default... so they need to be updated.
776 lfUpdatable _ = False
777
778 closureIsThunk :: ClosureInfo -> Bool
779 closureIsThunk ClosureInfo{ closureLFInfo = lf_info } = isLFThunk lf_info
780 closureIsThunk ConInfo{} = False
781
782 closureSingleEntry :: ClosureInfo -> Bool
783 closureSingleEntry (ClosureInfo { closureLFInfo = LFThunk _ _ upd _ _}) = not upd
784 closureSingleEntry other_closure = False
785
786 closureReEntrant :: ClosureInfo -> Bool
787 closureReEntrant (ClosureInfo { closureLFInfo = LFReEntrant _ _ _ _ }) = True
788 closureReEntrant other_closure = False
789
790 isConstrClosure_maybe :: ClosureInfo -> Maybe DataCon
791 isConstrClosure_maybe (ConInfo { closureCon = data_con }) = Just data_con
792 isConstrClosure_maybe _                                   = Nothing
793
794 closureFunInfo :: ClosureInfo -> Maybe (Int, ArgDescr)
795 closureFunInfo (ClosureInfo { closureLFInfo = LFReEntrant _ arity _ arg_desc})
796   = Just (arity, arg_desc)
797 closureFunInfo _
798   = Nothing
799 \end{code}
800
801 \begin{code}
802 isToplevClosure :: ClosureInfo -> Bool
803 isToplevClosure (ClosureInfo { closureLFInfo = lf_info })
804   = case lf_info of
805       LFReEntrant TopLevel _ _ _ -> True
806       LFThunk TopLevel _ _ _ _   -> True
807       other -> False
808 isToplevClosure _ = False
809 \end{code}
810
811 Label generation.
812
813 \begin{code}
814 infoTableLabelFromCI :: ClosureInfo -> CLabel
815 infoTableLabelFromCI (ClosureInfo { closureName = name,
816                                     closureLFInfo = lf_info, 
817                                     closureSMRep = rep })
818   = case lf_info of
819         LFBlackHole info -> info
820
821         LFThunk _ _ upd_flag (SelectorThunk offset) _ -> 
822                 mkSelectorInfoLabel upd_flag offset
823
824         LFThunk _ _ upd_flag (ApThunk arity) _ -> 
825                 mkApInfoTableLabel upd_flag arity
826
827         LFThunk{}      -> mkLocalInfoTableLabel name
828
829         LFReEntrant _ _ _ _ -> mkLocalInfoTableLabel name
830
831         other -> panic "infoTableLabelFromCI"
832
833 infoTableLabelFromCI (ConInfo { closureCon = con, 
834                                 closureSMRep = rep,
835                                 closureDllCon = dll })
836   | isStaticRep rep = mkStaticInfoTableLabel  name dll
837   | otherwise       = mkConInfoTableLabel     name dll
838   where
839     name = dataConName con
840
841 -- ClosureInfo for a closure (as opposed to a constructor) is always local
842 closureLabelFromCI (ClosureInfo { closureName = nm }) = mkLocalClosureLabel nm
843 closureLabelFromCI _ = panic "closureLabelFromCI"
844
845 -- thunkEntryLabel is a local help function, not exported.  It's used from both
846 -- entryLabelFromCI and getCallMethod.
847
848 thunkEntryLabel this_pkg thunk_id (ApThunk arity) is_updatable
849   = enterApLabel is_updatable arity
850 thunkEntryLabel this_pkg thunk_id (SelectorThunk offset) upd_flag
851   = enterSelectorLabel upd_flag offset
852 thunkEntryLabel this_pkg thunk_id _ is_updatable
853   = enterIdLabel this_pkg thunk_id
854
855 enterApLabel is_updatable arity
856   | tablesNextToCode = mkApInfoTableLabel is_updatable arity
857   | otherwise        = mkApEntryLabel is_updatable arity
858
859 enterSelectorLabel upd_flag offset
860   | tablesNextToCode = mkSelectorInfoLabel upd_flag offset
861   | otherwise        = mkSelectorEntryLabel upd_flag offset
862
863 enterIdLabel this_pkg id
864   | tablesNextToCode = mkInfoTableLabel this_pkg id
865   | otherwise        = mkEntryLabel this_pkg id
866
867 enterLocalIdLabel id
868   | tablesNextToCode = mkLocalInfoTableLabel id
869   | otherwise        = mkLocalEntryLabel id
870
871 enterReturnPtLabel name
872   | tablesNextToCode = mkReturnInfoLabel name
873   | otherwise        = mkReturnPtLabel name
874 \end{code}
875
876
877 We need a black-hole closure info to pass to @allocDynClosure@ when we
878 want to allocate the black hole on entry to a CAF.  These are the only
879 ways to build an LFBlackHole, maintaining the invariant that it really
880 is a black hole and not something else.
881
882 \begin{code}
883 cafBlackHoleClosureInfo (ClosureInfo { closureName = nm,
884                                        closureType = ty })
885   = ClosureInfo { closureName   = nm,
886                   closureLFInfo = LFBlackHole mkCAFBlackHoleInfoTableLabel,
887                   closureSMRep  = BlackHoleRep,
888                   closureSRT    = NoC_SRT,
889                   closureType   = ty,
890                   closureDescr  = "" }
891 cafBlackHoleClosureInfo _ = panic "cafBlackHoleClosureInfo"
892
893 seCafBlackHoleClosureInfo (ClosureInfo { closureName = nm,
894                                          closureType = ty })
895   = ClosureInfo { closureName   = nm,
896                   closureLFInfo = LFBlackHole mkSECAFBlackHoleInfoTableLabel,
897                   closureSMRep  = BlackHoleRep,
898                   closureSRT    = NoC_SRT,
899                   closureType   = ty,
900                   closureDescr  = ""  }
901 seCafBlackHoleClosureInfo _ = panic "seCafBlackHoleClosureInfo"
902 \end{code}
903
904 %************************************************************************
905 %*                                                                      *
906 \subsection[ClosureInfo-Profiling-funs]{Misc functions about for profiling info.}
907 %*                                                                      *
908 %************************************************************************
909
910 Profiling requires two pieces of information to be determined for
911 each closure's info table --- description and type.
912
913 The description is stored directly in the @CClosureInfoTable@ when the
914 info table is built.
915
916 The type is determined from the type information stored with the @Id@
917 in the closure info using @closureTypeDescr@.
918
919 \begin{code}
920 closureValDescr, closureTypeDescr :: ClosureInfo -> String
921 closureValDescr (ClosureInfo {closureDescr = descr}) 
922   = descr
923 closureValDescr (ConInfo {closureCon = con})
924   = occNameString (getOccName con)
925
926 closureTypeDescr (ClosureInfo { closureType = ty })
927   = getTyDescription ty
928 closureTypeDescr (ConInfo { closureCon = data_con })
929   = occNameString (getOccName (dataConTyCon data_con))
930
931 getTyDescription :: Type -> String
932 getTyDescription ty
933   = case (tcSplitSigmaTy ty) of { (_, _, tau_ty) ->
934     case tau_ty of
935       TyVarTy _              -> "*"
936       AppTy fun _            -> getTyDescription fun
937       FunTy _ res            -> '-' : '>' : fun_result res
938       TyConApp tycon _       -> getOccString tycon
939       NoteTy (FTVNote _) ty  -> getTyDescription ty
940       PredTy sty             -> getPredTyDescription sty
941       ForAllTy _ ty          -> getTyDescription ty
942     }
943   where
944     fun_result (FunTy _ res) = '>' : fun_result res
945     fun_result other         = getTyDescription other
946
947 getPredTyDescription (ClassP cl tys) = getOccString cl
948 getPredTyDescription (IParam ip ty)  = getOccString (ipNameName ip)
949 \end{code}
950
951