9bf57b1cb497399d49abdb715f4e82a259850dbe
[ghc.git] / compiler / codeGen / StgCmmBind.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Stg to C-- code generation: bindings
4 --
5 -- (c) The University of Glasgow 2004-2006
6 --
7 -----------------------------------------------------------------------------
8
9 {-# OPTIONS -fno-warn-tabs #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and
12 -- detab the module (please do the detabbing in a separate patch). See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
14 -- for details
15
16 module StgCmmBind (
17 cgTopRhsClosure,
18 cgBind,
19 emitBlackHoleCode,
20 pushUpdateFrame
21 ) where
22
23 #include "HsVersions.h"
24
25 import StgCmmExpr
26 import StgCmmMonad
27 import StgCmmEnv
28 import StgCmmCon
29 import StgCmmHeap
30 import StgCmmProf
31 import StgCmmTicky
32 import StgCmmGran
33 import StgCmmLayout
34 import StgCmmUtils
35 import StgCmmClosure
36 import StgCmmForeign (emitPrimCall)
37
38 import MkGraph
39 import CoreSyn ( AltCon(..) )
40 import SMRep
41 import Cmm
42 import CmmUtils
43 import CLabel
44 import StgSyn
45 import CostCentre
46 import Id
47 import Control.Monad
48 import Name
49 import Module
50 import ListSetOps
51 import Util
52 import BasicTypes
53 import Constants
54 import Outputable
55 import FastString
56 import Maybes
57 import DynFlags
58 import StaticFlags
59
60 ------------------------------------------------------------------------
61 -- Top-level bindings
62 ------------------------------------------------------------------------
63
64 -- For closures bound at top level, allocate in static space.
65 -- They should have no free variables.
66
67 cgTopRhsClosure :: Id
68 -> CostCentreStack -- Optional cost centre annotation
69 -> StgBinderInfo
70 -> UpdateFlag
71 -> SRT
72 -> [Id] -- Args
73 -> StgExpr
74 -> FCode CgIdInfo
75
76 cgTopRhsClosure id ccs _ upd_flag srt args body = do
77 { -- LAY OUT THE OBJECT
78 let name = idName id
79 ; lf_info <- mkClosureLFInfo id TopLevel [] upd_flag args
80 ; srt_info <- getSRTInfo srt
81 ; mod_name <- getModuleName
82 ; let descr = closureDescription mod_name name
83 closure_info = mkClosureInfo True id lf_info 0 0 srt_info descr
84 closure_label = mkLocalClosureLabel name (idCafInfo id)
85 cg_id_info = litIdInfo id lf_info (CmmLabel closure_label)
86 caffy = idCafInfo id
87 info_tbl = mkCmmInfo closure_info -- XXX short-cut
88 closure_rep = mkStaticClosureFields info_tbl ccs caffy []
89
90 -- BUILD THE OBJECT, AND GENERATE INFO TABLE (IF NECESSARY)
91 ; emitDataLits closure_label closure_rep
92 ; let fv_details :: [(NonVoid Id, VirtualHpOffset)]
93 (_, _, fv_details) = mkVirtHeapOffsets (isLFThunk lf_info)
94 (addIdReps [])
95 -- Don't drop the non-void args until the closure info has been made
96 ; forkClosureBody (closureCodeBody True id closure_info ccs
97 (nonVoidIds args) (length args) body fv_details)
98
99 ; returnFC cg_id_info }
100
101 ------------------------------------------------------------------------
102 -- Non-top-level bindings
103 ------------------------------------------------------------------------
104
105 cgBind :: StgBinding -> FCode ()
106 cgBind (StgNonRec name rhs)
107 = do { ((info, init), body) <- getCodeR $ cgRhs name rhs
108 ; addBindC (cg_id info) info
109 ; emit (init <*> body) }
110
111 cgBind (StgRec pairs)
112 = do { ((new_binds, inits), body) <- getCodeR $ fixC (\ new_binds_inits ->
113 do { addBindsC $ fst new_binds_inits -- avoid premature deconstruction
114 ; liftM unzip $ listFCs [ cgRhs b e | (b,e) <- pairs ] })
115 ; addBindsC new_binds
116 ; emit (catAGraphs inits <*> body) }
117
118 {- Recursive let-bindings are tricky.
119 Consider the following pseudocode:
120 let x = \_ -> ... y ...
121 y = \_ -> ... z ...
122 z = \_ -> ... x ...
123 in ...
124 For each binding, we need to allocate a closure, and each closure must
125 capture the address of the other closures.
126 We want to generate the following C-- code:
127 // Initialization Code
128 x = hp - 24; // heap address of x's closure
129 y = hp - 40; // heap address of x's closure
130 z = hp - 64; // heap address of x's closure
131 // allocate and initialize x
132 m[hp-8] = ...
133 m[hp-16] = y // the closure for x captures y
134 m[hp-24] = x_info;
135 // allocate and initialize y
136 m[hp-32] = z; // the closure for y captures z
137 m[hp-40] = y_info;
138 // allocate and initialize z
139 ...
140
141 For each closure, we must generate not only the code to allocate and
142 initialize the closure itself, but also some Initialization Code that
143 sets a variable holding the closure pointer.
144 The complication here is that we don't know the heap offsets a priori,
145 which has two consequences:
146 1. we need a fixpoint
147 2. we can't trivially separate the Initialization Code from the
148 code that compiles the right-hand-sides
149
150 Note: We don't need this complication with let-no-escapes, because
151 in that case, the names are bound to labels in the environment,
152 and we don't need to emit any code to witness that binding.
153 -}
154
155 --------------------
156 cgRhs :: Id -> StgRhs -> FCode (CgIdInfo, CmmAGraph)
157 -- The Id is passed along so a binding can be set up
158 -- The returned values are the binding for the environment
159 -- and the Initialization Code that witnesses the binding
160
161 cgRhs name (StgRhsCon cc con args)
162 = buildDynCon name cc con args
163
164 cgRhs name (StgRhsClosure cc bi fvs upd_flag srt args body)
165 = mkRhsClosure name cc bi (nonVoidIds fvs) upd_flag srt args body
166
167 ------------------------------------------------------------------------
168 -- Non-constructor right hand sides
169 ------------------------------------------------------------------------
170
171 mkRhsClosure :: Id -> CostCentreStack -> StgBinderInfo
172 -> [NonVoid Id] -- Free vars
173 -> UpdateFlag -> SRT
174 -> [Id] -- Args
175 -> StgExpr
176 -> FCode (CgIdInfo, CmmAGraph)
177
178 {- mkRhsClosure looks for two special forms of the right-hand side:
179 a) selector thunks
180 b) AP thunks
181
182 If neither happens, it just calls mkClosureLFInfo. You might think
183 that mkClosureLFInfo should do all this, but it seems wrong for the
184 latter to look at the structure of an expression
185
186 Note [Selectors]
187 ~~~~~~~~~~~~~~~~
188 We look at the body of the closure to see if it's a selector---turgid,
189 but nothing deep. We are looking for a closure of {\em exactly} the
190 form:
191
192 ... = [the_fv] \ u [] ->
193 case the_fv of
194 con a_1 ... a_n -> a_i
195
196 Note [Ap thunks]
197 ~~~~~~~~~~~~~~~~
198 A more generic AP thunk of the form
199
200 x = [ x_1...x_n ] \.. [] -> x_1 ... x_n
201
202 A set of these is compiled statically into the RTS, so we just use
203 those. We could extend the idea to thunks where some of the x_i are
204 global ids (and hence not free variables), but this would entail
205 generating a larger thunk. It might be an option for non-optimising
206 compilation, though.
207
208 We only generate an Ap thunk if all the free variables are pointers,
209 for semi-obvious reasons.
210
211 -}
212
213 ---------- Note [Selectors] ------------------
214 mkRhsClosure bndr cc bi
215 [NonVoid the_fv] -- Just one free var
216 upd_flag -- Updatable thunk
217 _srt
218 [] -- A thunk
219 body@(StgCase (StgApp scrutinee [{-no args-}])
220 _ _ _ _ -- ignore uniq, etc.
221 (AlgAlt _)
222 [(DataAlt _, params, _use_mask,
223 (StgApp selectee [{-no args-}]))])
224 | the_fv == scrutinee -- Scrutinee is the only free variable
225 && maybeToBool maybe_offset -- Selectee is a component of the tuple
226 && offset_into_int <= mAX_SPEC_SELECTEE_SIZE -- Offset is small enough
227 = -- NOT TRUE: ASSERT(is_single_constructor)
228 -- The simplifier may have statically determined that the single alternative
229 -- is the only possible case and eliminated the others, even if there are
230 -- other constructors in the datatype. It's still ok to make a selector
231 -- thunk in this case, because we *know* which constructor the scrutinee
232 -- will evaluate to.
233 --
234 -- srt is discarded; it must be empty
235 cgStdThunk bndr cc bi body lf_info [StgVarArg the_fv]
236 where
237 lf_info = mkSelectorLFInfo bndr offset_into_int
238 (isUpdatable upd_flag)
239 (_, _, params_w_offsets) = mkVirtConstrOffsets (addIdReps params)
240 -- Just want the layout
241 maybe_offset = assocMaybe params_w_offsets (NonVoid selectee)
242 Just the_offset = maybe_offset
243 offset_into_int = the_offset - fixedHdrSize
244
245 ---------- Note [Ap thunks] ------------------
246 mkRhsClosure bndr cc bi
247 fvs
248 upd_flag
249 _srt
250 [] -- No args; a thunk
251 body@(StgApp fun_id args)
252
253 | args `lengthIs` (arity-1)
254 && all (isGcPtrRep . idPrimRep . stripNV) fvs
255 && isUpdatable upd_flag
256 && arity <= mAX_SPEC_AP_SIZE
257 && not opt_SccProfilingOn -- not when profiling: we don't want to
258 -- lose information about this particular
259 -- thunk (e.g. its type) (#949)
260
261 -- Ha! an Ap thunk
262 = cgStdThunk bndr cc bi body lf_info payload
263 where
264 lf_info = mkApLFInfo bndr upd_flag arity
265 -- the payload has to be in the correct order, hence we can't
266 -- just use the fvs.
267 payload = StgVarArg fun_id : args
268 arity = length fvs
269
270 ---------- Default case ------------------
271 mkRhsClosure bndr cc _ fvs upd_flag srt args body
272 = do { -- LAY OUT THE OBJECT
273 -- If the binder is itself a free variable, then don't store
274 -- it in the closure. Instead, just bind it to Node on entry.
275 -- NB we can be sure that Node will point to it, because we
276 -- haven't told mkClosureLFInfo about this; so if the binder
277 -- _was_ a free var of its RHS, mkClosureLFInfo thinks it *is*
278 -- stored in the closure itself, so it will make sure that
279 -- Node points to it...
280 ; let
281 is_elem = isIn "cgRhsClosure"
282 bndr_is_a_fv = (NonVoid bndr) `is_elem` fvs
283 reduced_fvs | bndr_is_a_fv = fvs `minusList` [NonVoid bndr]
284 | otherwise = fvs
285
286
287 -- MAKE CLOSURE INFO FOR THIS CLOSURE
288 ; lf_info <- mkClosureLFInfo bndr NotTopLevel fvs upd_flag args
289 ; mod_name <- getModuleName
290 ; c_srt <- getSRTInfo srt
291 ; let name = idName bndr
292 descr = closureDescription mod_name name
293 fv_details :: [(NonVoid Id, VirtualHpOffset)]
294 (tot_wds, ptr_wds, fv_details)
295 = mkVirtHeapOffsets (isLFThunk lf_info)
296 (addIdReps (map stripNV reduced_fvs))
297 closure_info = mkClosureInfo False -- Not static
298 bndr lf_info tot_wds ptr_wds
299 c_srt descr
300
301 -- BUILD ITS INFO TABLE AND CODE
302 ; forkClosureBody $
303 -- forkClosureBody: (a) ensure that bindings in here are not seen elsewhere
304 -- (b) ignore Sequel from context; use empty Sequel
305 -- And compile the body
306 closureCodeBody False bndr closure_info cc (nonVoidIds args)
307 (length args) body fv_details
308
309 -- BUILD THE OBJECT
310 -- ; (use_cc, blame_cc) <- chooseDynCostCentres cc args body
311 ; let use_cc = curCCS; blame_cc = curCCS
312 ; emit (mkComment $ mkFastString "calling allocDynClosure")
313 ; let toVarArg (NonVoid a, off) = (NonVoid (StgVarArg a), off)
314 ; let info_tbl = mkCmmInfo closure_info
315 ; (tmp, init) <- allocDynClosure info_tbl lf_info use_cc blame_cc
316 (map toVarArg fv_details)
317
318 -- RETURN
319 ; regIdInfo bndr lf_info tmp init }
320
321 -- Use with care; if used inappropriately, it could break invariants.
322 stripNV :: NonVoid a -> a
323 stripNV (NonVoid a) = a
324
325 -------------------------
326 cgStdThunk
327 :: Id
328 -> CostCentreStack -- Optional cost centre annotation
329 -> StgBinderInfo -- XXX: not used??
330 -> StgExpr
331 -> LambdaFormInfo
332 -> [StgArg] -- payload
333 -> FCode (CgIdInfo, CmmAGraph)
334
335 cgStdThunk bndr _cc _bndr_info _body lf_info payload
336 = do -- AHA! A STANDARD-FORM THUNK
337 { -- LAY OUT THE OBJECT
338 mod_name <- getModuleName
339 ; let (tot_wds, ptr_wds, payload_w_offsets)
340 = mkVirtHeapOffsets (isLFThunk lf_info) (addArgReps payload)
341
342 descr = closureDescription mod_name (idName bndr)
343 closure_info = mkClosureInfo False -- Not static
344 bndr lf_info tot_wds ptr_wds
345 NoC_SRT -- No SRT for a std-form closure
346 descr
347
348 -- ; (use_cc, blame_cc) <- chooseDynCostCentres cc [{- no args-}] body
349 ; let use_cc = curCCS; blame_cc = curCCS
350
351 -- BUILD THE OBJECT
352 ; let info_tbl = mkCmmInfo closure_info
353 ; (tmp, init) <- allocDynClosure info_tbl lf_info
354 use_cc blame_cc payload_w_offsets
355
356 -- RETURN
357 ; regIdInfo bndr lf_info tmp init }
358
359 mkClosureLFInfo :: Id -- The binder
360 -> TopLevelFlag -- True of top level
361 -> [NonVoid Id] -- Free vars
362 -> UpdateFlag -- Update flag
363 -> [Id] -- Args
364 -> FCode LambdaFormInfo
365 mkClosureLFInfo bndr top fvs upd_flag args
366 | null args = return (mkLFThunk (idType bndr) top (map stripNV fvs) upd_flag)
367 | otherwise = do { arg_descr <- mkArgDescr (idName bndr) args
368 ; return (mkLFReEntrant top (map stripNV fvs) args arg_descr) }
369
370
371 ------------------------------------------------------------------------
372 -- The code for closures}
373 ------------------------------------------------------------------------
374
375 closureCodeBody :: Bool -- whether this is a top-level binding
376 -> Id -- the closure's name
377 -> ClosureInfo -- Lots of information about this closure
378 -> CostCentreStack -- Optional cost centre attached to closure
379 -> [NonVoid Id] -- incoming args to the closure
380 -> Int -- arity, including void args
381 -> StgExpr
382 -> [(NonVoid Id, VirtualHpOffset)] -- the closure's free vars
383 -> FCode ()
384
385 {- There are two main cases for the code for closures.
386
387 * If there are *no arguments*, then the closure is a thunk, and not in
388 normal form. So it should set up an update frame (if it is
389 shared). NB: Thunks cannot have a primitive type!
390
391 * If there is *at least one* argument, then this closure is in
392 normal form, so there is no need to set up an update frame.
393
394 The Macros for GrAnSim are produced at the beginning of the
395 argSatisfactionCheck (by calling fetchAndReschedule).
396 There info if Node points to closure is available. -- HWL -}
397
398 closureCodeBody top_lvl bndr cl_info cc args arity body fv_details
399 | length args == 0 -- No args i.e. thunk
400 = emitClosureProcAndInfoTable top_lvl bndr lf_info info_tbl [] $
401 \(_, node, _) -> thunkCode cl_info fv_details cc node arity body
402 where
403 lf_info = closureLFInfo cl_info
404 info_tbl = mkCmmInfo cl_info
405
406 closureCodeBody top_lvl bndr cl_info _cc args arity body fv_details
407 = ASSERT( length args > 0 )
408 do { -- Allocate the global ticky counter,
409 -- and establish the ticky-counter
410 -- label for this block
411 ; dflags <- getDynFlags
412 ; let platform = targetPlatform dflags
413 ticky_ctr_lbl = closureRednCountsLabel platform cl_info
414 ; emitTickyCounter cl_info (map stripNV args)
415 ; setTickyCtrLabel ticky_ctr_lbl $ do
416
417 ; let
418 lf_info = closureLFInfo cl_info
419 info_tbl = mkCmmInfo cl_info
420
421 -- Emit the main entry code
422 ; emitClosureProcAndInfoTable top_lvl bndr lf_info info_tbl args $
423 \(offset, node, arg_regs) -> do
424 -- Emit slow-entry code (for entering a closure through a PAP)
425 { mkSlowEntryCode cl_info arg_regs
426
427 ; let lf_info = closureLFInfo cl_info
428 node_points = nodeMustPointToIt lf_info
429 node' = if node_points then Just node else Nothing
430 ; tickyEnterFun cl_info
431 ; whenC node_points (ldvEnterClosure cl_info)
432 ; granYield arg_regs node_points
433
434 -- Main payload
435 ; entryHeapCheck cl_info offset node' arity arg_regs $ do
436 { fv_bindings <- mapM bind_fv fv_details
437 -- Load free vars out of closure *after*
438 -- heap check, to reduce live vars over check
439 ; if node_points then load_fvs node lf_info fv_bindings
440 else return ()
441 ; cgExpr body }}
442 }
443
444 -- A function closure pointer may be tagged, so we
445 -- must take it into account when accessing the free variables.
446 bind_fv :: (NonVoid Id, VirtualHpOffset) -> FCode (LocalReg, WordOff)
447 bind_fv (id, off) = do { reg <- rebindToReg id; return (reg, off) }
448
449 load_fvs :: LocalReg -> LambdaFormInfo -> [(LocalReg, WordOff)] -> FCode ()
450 load_fvs node lf_info = mapCs (\ (reg, off) ->
451 emit $ mkTaggedObjectLoad reg node off tag)
452 where tag = lfDynTag lf_info
453
454 -----------------------------------------
455 -- The "slow entry" code for a function. This entry point takes its
456 -- arguments on the stack. It loads the arguments into registers
457 -- according to the calling convention, and jumps to the function's
458 -- normal entry point. The function's closure is assumed to be in
459 -- R1/node.
460 --
461 -- The slow entry point is used for unknown calls: eg. stg_PAP_entry
462
463 mkSlowEntryCode :: ClosureInfo -> [LocalReg] -> FCode ()
464 -- If this function doesn't have a specialised ArgDescr, we need
465 -- to generate the function's arg bitmap and slow-entry code.
466 -- Here, we emit the slow-entry code.
467 mkSlowEntryCode _ [] = panic "entering a closure with no arguments?"
468 mkSlowEntryCode cl_info arg_regs -- function closure is already in `Node'
469 | Just (_, ArgGen _) <- closureFunInfo cl_info
470 = do dflags <- getDynFlags
471 let platform = targetPlatform dflags
472 slow_lbl = closureSlowEntryLabel platform cl_info
473 fast_lbl = closureLocalEntryLabel platform cl_info
474 -- mkDirectJump does not clobber `Node' containing function closure
475 jump = mkDirectJump (mkLblExpr fast_lbl)
476 (map (CmmReg . CmmLocal) arg_regs)
477 initUpdFrameOff
478 emitProcWithConvention Slow CmmNonInfoTable slow_lbl arg_regs jump
479 | otherwise = return ()
480
481 -----------------------------------------
482 thunkCode :: ClosureInfo -> [(NonVoid Id, VirtualHpOffset)] -> CostCentreStack
483 -> LocalReg -> Int -> StgExpr -> FCode ()
484 thunkCode cl_info fv_details _cc node arity body
485 = do { let node_points = nodeMustPointToIt (closureLFInfo cl_info)
486 node' = if node_points then Just node else Nothing
487 ; tickyEnterThunk cl_info
488 ; ldvEnterClosure cl_info -- NB: Node always points when profiling
489 ; granThunk node_points
490
491 -- Heap overflow check
492 ; entryHeapCheck cl_info 0 node' arity [] $ do
493 { -- Overwrite with black hole if necessary
494 -- but *after* the heap-overflow check
495 ; whenC (blackHoleOnEntry cl_info && node_points)
496 (blackHoleIt cl_info)
497
498 -- Push update frame
499 ; setupUpdate cl_info node $
500 -- We only enter cc after setting up update so
501 -- that cc of enclosing scope will be recorded
502 -- in update frame CAF/DICT functions will be
503 -- subsumed by this enclosing cc
504 do { enterCostCentreThunk (CmmReg nodeReg)
505 ; let lf_info = closureLFInfo cl_info
506 ; fv_bindings <- mapM bind_fv fv_details
507 ; load_fvs node lf_info fv_bindings
508 ; cgExpr body }}}
509
510
511 ------------------------------------------------------------------------
512 -- Update and black-hole wrappers
513 ------------------------------------------------------------------------
514
515 blackHoleIt :: ClosureInfo -> FCode ()
516 -- Only called for closures with no args
517 -- Node points to the closure
518 blackHoleIt closure_info = emitBlackHoleCode (closureSingleEntry closure_info)
519
520 emitBlackHoleCode :: Bool -> FCode ()
521 emitBlackHoleCode is_single_entry = do
522 dflags <- getDynFlags
523
524 -- Eager blackholing is normally disabled, but can be turned on with
525 -- -feager-blackholing. When it is on, we replace the info pointer
526 -- of the thunk with stg_EAGER_BLACKHOLE_info on entry.
527
528 -- If we wanted to do eager blackholing with slop filling, we'd need
529 -- to do it at the *end* of a basic block, otherwise we overwrite
530 -- the free variables in the thunk that we still need. We have a
531 -- patch for this from Andy Cheadle, but not incorporated yet. --SDM
532 -- [6/2004]
533 --
534 -- Previously, eager blackholing was enabled when ticky-ticky was
535 -- on. But it didn't work, and it wasn't strictly necessary to bring
536 -- back minimal ticky-ticky, so now EAGER_BLACKHOLING is
537 -- unconditionally disabled. -- krc 1/2007
538
539 -- Note the eager-blackholing check is here rather than in blackHoleOnEntry,
540 -- because emitBlackHoleCode is called from CmmParse.
541
542 let eager_blackholing = not opt_SccProfilingOn
543 && dopt Opt_EagerBlackHoling dflags
544 -- Profiling needs slop filling (to support LDV
545 -- profiling), so currently eager blackholing doesn't
546 -- work with profiling.
547
548 whenC eager_blackholing $ do
549 tickyBlackHole (not is_single_entry)
550 emit (mkStore (cmmOffsetW (CmmReg nodeReg) fixedHdrSize)
551 (CmmReg (CmmGlobal CurrentTSO)))
552 emitPrimCall [] MO_WriteBarrier []
553 emit (mkStore (CmmReg nodeReg) (CmmReg (CmmGlobal EagerBlackholeInfo)))
554
555 setupUpdate :: ClosureInfo -> LocalReg -> FCode () -> FCode ()
556 -- Nota Bene: this function does not change Node (even if it's a CAF),
557 -- so that the cost centre in the original closure can still be
558 -- extracted by a subsequent enterCostCentre
559 setupUpdate closure_info node body
560 | closureReEntrant closure_info
561 = body
562
563 | not (isStaticClosure closure_info)
564 = if not (closureUpdReqd closure_info)
565 then do tickyUpdateFrameOmitted; body
566 else do
567 tickyPushUpdateFrame
568 --dflags <- getDynFlags
569 let es = [CmmReg (CmmLocal node), mkLblExpr mkUpdInfoLabel]
570 --if not opt_SccProfilingOn && dopt Opt_EagerBlackHoling dflags
571 -- then pushUpdateFrame es body -- XXX black hole
572 -- else pushUpdateFrame es body
573 pushUpdateFrame es body
574
575 | otherwise -- A static closure
576 = do { tickyUpdateBhCaf closure_info
577
578 ; if closureUpdReqd closure_info
579 then do -- Blackhole the (updatable) CAF:
580 { upd_closure <- link_caf True
581 ; pushUpdateFrame [CmmReg (CmmLocal upd_closure),
582 mkLblExpr mkUpdInfoLabel] body } -- XXX black hole
583 else do {tickyUpdateFrameOmitted; body}
584 }
585
586 -----------------------------------------------------------------------------
587 -- Setting up update frames
588
589 -- Push the update frame on the stack in the Entry area,
590 -- leaving room for the return address that is already
591 -- at the old end of the area.
592 pushUpdateFrame :: [CmmExpr] -> FCode () -> FCode ()
593 pushUpdateFrame es body
594 = do -- [EZY] I'm not sure if we need to special-case for BH too
595 updfr <- getUpdFrameOff
596 offset <- foldM push updfr es
597 withUpdFrameOff offset body
598 where push off e =
599 do emit (mkStore (CmmStackSlot (CallArea Old) base) e)
600 return base
601 where base = off + widthInBytes (cmmExprWidth e)
602
603 -----------------------------------------------------------------------------
604 -- Entering a CAF
605 --
606 -- When a CAF is first entered, it creates a black hole in the heap,
607 -- and updates itself with an indirection to this new black hole.
608 --
609 -- We update the CAF with an indirection to a newly-allocated black
610 -- hole in the heap. We also set the blocking queue on the newly
611 -- allocated black hole to be empty.
612 --
613 -- Why do we make a black hole in the heap when we enter a CAF?
614 --
615 -- - for a generational garbage collector, which needs a fast
616 -- test for whether an updatee is in an old generation or not
617 --
618 -- - for the parallel system, which can implement updates more
619 -- easily if the updatee is always in the heap. (allegedly).
620 --
621 -- When debugging, we maintain a separate CAF list so we can tell when
622 -- a CAF has been garbage collected.
623
624 -- newCAF must be called before the itbl ptr is overwritten, since
625 -- newCAF records the old itbl ptr in order to do CAF reverting
626 -- (which Hugs needs to do in order that combined mode works right.)
627 --
628
629 -- ToDo [Feb 04] This entire link_caf nonsense could all be moved
630 -- into the "newCAF" RTS procedure, which we call anyway, including
631 -- the allocation of the black-hole indirection closure.
632 -- That way, code size would fall, the CAF-handling code would
633 -- be closer together, and the compiler wouldn't need to know
634 -- about off_indirectee etc.
635
636 link_caf :: Bool -- True <=> updatable, False <=> single-entry
637 -> FCode LocalReg -- Returns amode for closure to be updated
638 -- To update a CAF we must allocate a black hole, link the CAF onto the
639 -- CAF list, then update the CAF to point to the fresh black hole.
640 -- This function returns the address of the black hole, so it can be
641 -- updated with the new value when available. The reason for all of this
642 -- is that we only want to update dynamic heap objects, not static ones,
643 -- so that generational GC is easier.
644 link_caf _is_upd = do
645 { -- Alloc black hole specifying CC_HDR(Node) as the cost centre
646 ; let use_cc = costCentreFrom (CmmReg nodeReg)
647 blame_cc = use_cc
648 tso = CmmReg (CmmGlobal CurrentTSO)
649
650 ; (hp_rel, init) <- allocDynClosureCmm cafBlackHoleInfoTable mkLFBlackHole
651 use_cc blame_cc [(tso,fixedHdrSize)]
652 ; emit init
653
654 -- Call the RTS function newCAF to add the CAF to the CafList
655 -- so that the garbage collector can find them
656 -- This must be done *before* the info table pointer is overwritten,
657 -- because the old info table ptr is needed for reversion
658 ; ret <- newTemp bWord
659 ; emitRtsCallGen [(ret,NoHint)] rtsPackageId (fsLit "newCAF")
660 [ (CmmReg (CmmGlobal BaseReg), AddrHint),
661 (CmmReg nodeReg, AddrHint),
662 (CmmReg (CmmLocal hp_rel), AddrHint) ]
663 (Just [node]) False
664 -- node is live, so save it.
665
666 -- see Note [atomic CAF entry] in rts/sm/Storage.c
667 ; emit $ mkCmmIfThen
668 (CmmMachOp mo_wordEq [ CmmReg (CmmLocal ret), CmmLit zeroCLit]) $
669 -- re-enter R1. Doing this directly is slightly dodgy; we're
670 -- assuming lots of things, like the stack pointer hasn't
671 -- moved since we entered the CAF.
672 let target = entryCode (closureInfoPtr (CmmReg nodeReg)) in
673 mkJump target [] 0
674
675 ; return hp_rel }
676
677 ------------------------------------------------------------------------
678 -- Profiling
679 ------------------------------------------------------------------------
680
681 -- For "global" data constructors the description is simply occurrence
682 -- name of the data constructor itself. Otherwise it is determined by
683 -- @closureDescription@ from the let binding information.
684
685 closureDescription :: Module -- Module
686 -> Name -- Id of closure binding
687 -> String
688 -- Not called for StgRhsCon which have global info tables built in
689 -- CgConTbls.lhs with a description generated from the data constructor
690 closureDescription mod_name name
691 = showSDocDump (char '<' <>
692 (if isExternalName name
693 then ppr name -- ppr will include the module name prefix
694 else pprModule mod_name <> char '.' <> ppr name) <>
695 char '>')
696 -- showSDocDump, because we want to see the unique on the Name.
697