1 -----------------------------------------------------------------------------
3 -- Stg to C--: heap management functions
5 -- (c) The University of Glasgow 2004-2006
7 -----------------------------------------------------------------------------
10 getVirtHp, setVirtHp, setRealHp,
11 getHpRelOffset, hpRel,
13 entryHeapCheck, altHeapCheck,
15 layOutDynConstr, layOutStaticConstr,
16 mkVirtHeapOffsets, mkStaticClosureFields, mkStaticClosure,
18 allocDynClosure, emitSetDynHdr
21 #include "HsVersions.h"
43 import FastString( LitString, mkFastString, sLit )
48 -----------------------------------------------------------
49 -- Layout of heap objects
50 -----------------------------------------------------------
52 layOutDynConstr, layOutStaticConstr
53 :: DataCon -> [(PrimRep, a)]
54 -> (ClosureInfo, [(a, VirtualHpOffset)])
55 -- No Void arguments in result
57 layOutDynConstr = layOutConstr False
58 layOutStaticConstr = layOutConstr True
60 layOutConstr :: Bool -> DataCon -> [(PrimRep, a)]
61 -> (ClosureInfo, [(a, VirtualHpOffset)])
62 layOutConstr is_static data_con args
63 = (mkConInfo is_static data_con tot_wds ptr_wds,
66 (tot_wds, -- #ptr_wds + #nonptr_wds
68 things_w_offsets) = mkVirtHeapOffsets False{-not a thunk-} args
71 -----------------------------------------------------------
72 -- Initialise dynamic heap objects
73 -----------------------------------------------------------
77 -> CmmExpr -- Cost Centre to stick in the object
78 -> CmmExpr -- Cost Centre to blame for this alloc
79 -- (usually the same; sometimes "OVERHEAD")
81 -> [(StgArg, VirtualHpOffset)] -- Offsets from start of the object
82 -- ie Info ptr has offset zero.
83 -- No void args in here
86 -- allocDynClosure allocates the thing in the heap,
87 -- and modifies the virtual Hp to account for this.
89 -- Note [Return a LocalReg]
90 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
91 -- allocDynClosure returns a LocalReg, not a (Hp+8) CmmExpr.
93 -- ...allocate object...
96 -- ...here obj is still valid,
97 -- but Hp+8 means something quite different...
100 allocDynClosure cl_info use_cc _blame_cc args_w_offsets
101 = do { virt_hp <- getVirtHp
103 -- SAY WHAT WE ARE ABOUT TO DO
104 ; tickyDynAlloc cl_info
105 ; profDynAlloc cl_info use_cc
106 -- ToDo: This is almost certainly wrong
107 -- We're ignoring blame_cc. But until we've
108 -- fixed the boxing hack in chooseDynCostCentres etc,
109 -- we're worried about making things worse by "fixing"
110 -- this part to use blame_cc!
112 -- FIND THE OFFSET OF THE INFO-PTR WORD
113 ; let info_offset = virt_hp + 1
114 -- info_offset is the VirtualHpOffset of the first
115 -- word of the new object
116 -- Remember, virtHp points to last allocated word,
117 -- ie 1 *before* the info-ptr word of new object.
119 info_ptr = CmmLit (CmmLabel (infoTableLabelFromCI cl_info))
121 -- ALLOCATE THE OBJECT
122 ; base <- getHpRelOffset info_offset
123 ; emit (mkComment $ mkFastString "allocDynClosure")
124 ; emitSetDynHdr base info_ptr use_cc
125 ; let (args, offsets) = unzip args_w_offsets
126 ; cmm_args <- mapM getArgAmode args -- No void args
127 ; hpStore base cmm_args offsets
129 -- BUMP THE VIRTUAL HEAP POINTER
130 ; setVirtHp (virt_hp + closureSize cl_info)
132 -- Assign to a temporary and return
133 -- Note [Return a LocalReg]
134 ; hp_rel <- getHpRelOffset info_offset
135 ; assignTemp hp_rel }
137 emitSetDynHdr :: CmmExpr -> CmmExpr -> CmmExpr -> FCode ()
138 emitSetDynHdr base info_ptr ccs
139 = hpStore base header [0..]
142 header = [info_ptr] ++ dynProfHdr ccs
143 -- ToDo: Gransim stuff
144 -- ToDo: Parallel stuff
147 hpStore :: CmmExpr -> [CmmExpr] -> [VirtualHpOffset] -> FCode ()
148 -- Store the item (expr,off) in base[off]
149 hpStore base vals offs
150 = emit (catAGraphs (zipWith mk_store vals offs))
152 mk_store val off = mkStore (cmmOffsetW base off) val
155 -----------------------------------------------------------
156 -- Layout of static closures
157 -----------------------------------------------------------
159 -- Make a static closure, adding on any extra padding needed for CAFs,
160 -- and adding a static link field if necessary.
162 mkStaticClosureFields
165 -> Bool -- Has CAF refs
166 -> [CmmLit] -- Payload
167 -> [CmmLit] -- The full closure
168 mkStaticClosureFields cl_info ccs caf_refs payload
169 = mkStaticClosure info_lbl ccs payload padding_wds
170 static_link_field saved_info_field
172 info_lbl = infoTableLabelFromCI cl_info
174 -- CAFs must have consistent layout, regardless of whether they
175 -- are actually updatable or not. The layout of a CAF is:
182 -- the static_link and saved_info fields must always be in the same
183 -- place. So we use closureNeedsUpdSpace rather than
184 -- closureUpdReqd here:
186 is_caf = closureNeedsUpdSpace cl_info
190 | otherwise = ASSERT(null payload) [mkIntCLit 0]
193 | is_caf || staticClosureNeedsLink cl_info = [static_link_value]
197 | is_caf = [mkIntCLit 0]
200 -- for a static constructor which has NoCafRefs, we set the
201 -- static link field to a non-zero value so the garbage
202 -- collector will ignore it.
204 | caf_refs = mkIntCLit 0
205 | otherwise = mkIntCLit 1
208 mkStaticClosure :: CLabel -> CostCentreStack -> [CmmLit]
209 -> [CmmLit] -> [CmmLit] -> [CmmLit] -> [CmmLit]
210 mkStaticClosure info_lbl ccs payload padding_wds static_link_field saved_info_field
211 = [CmmLabel info_lbl]
212 ++ variable_header_words
218 variable_header_words
224 -----------------------------------------------------------
225 -- Heap overflow checking
226 -----------------------------------------------------------
228 {- Note [Heap checks]
230 Heap checks come in various forms. We provide the following entry
231 points to the runtime system, all of which use the native C-- entry
234 * gc() performs garbage collection and returns
235 nothing to its caller
237 * A series of canned entry points like
239 where r is a pointer. This performs gc, and
240 then returns its argument r to its caller.
242 * A series of canned entry points like
244 where f is a function closure of arity 2
245 This performs garbage collection, keeping alive the
246 three argument ptrs, and then tail-calls f(x,y)
248 These are used in the following circumstances
250 * entryHeapCheck: Function entry
251 (a) With a canned GC entry sequence
252 f( f_clo, x:ptr, y:ptr ) {
257 jump gcfun_2p( f_clo, x, y ) }
258 Note the tail call to the garbage collector;
259 it should do no register shuffling
261 (b) No canned sequence
262 f( f_clo, x:ptr, y:ptr, ...etc... ) {
267 call gc() -- Needs an info table
270 * altHeapCheck: Immediately following an eval
272 case f x y of r { (p,q) -> rhs }
273 (a) With a canned sequence for the results of f
274 (which is the very common case since
275 all boxed cases return just one pointer
278 K: -- K needs an info table
286 Here, the info table needed by the call
287 to gc_1p should be the *same* as the
288 one for the call to f; the C-- optimiser
289 spots this sharing opportunity
291 (b) No canned sequence for results of f
292 Note second info table
294 (r1,r2,r3) = call f( x, y )
300 L: call gc() -- Extra info table here
303 * generalHeapCheck: Anywhere else
305 case branch *not* following eval,
307 Exactly the same as the previous case:
309 K: -- K needs an info table
318 --------------------------------------------------------------
319 -- A heap/stack check at a function or thunk entry point.
321 entryHeapCheck :: LocalReg -- Function
322 -> [LocalReg] -- Args (empty for thunk)
327 entryHeapCheck fun args srt code
328 = heapCheck gc_call code -- The 'fun' keeps relevant CAFs alive
331 | null args = mkJump (CmmReg (CmmGlobal GCEnter1)) [CmmReg (CmmLocal fun)]
332 | otherwise = case gc_lbl args of
333 Just lbl -> mkJump (CmmLit (CmmLabel (mkRtsCodeLabel lbl)))
334 (map (CmmReg . CmmLocal) (fun:args))
335 Nothing -> mkCmmCall generic_gc [] [] srt
337 gc_lbl :: [LocalReg] -> Maybe LitString
339 | isGcPtrType ty = Just (sLit "stg_gc_unpt_r1") -- "stg_gc_fun_1p"
340 | isFloatType ty = case width of
341 W32 -> Just (sLit "stg_gc_f1") -- "stg_gc_fun_f1"
342 W64 -> Just (sLit "stg_gc_d1") -- "stg_gc_fun_d1"
344 | otherwise = case width of
345 W32 -> Just (sLit "stg_gc_unbx_r1") -- "stg_gc_fun_unbx_r1"
346 W64 -> Just (sLit "stg_gc_l1") -- "stg_gc_fun_unbx_l1"
347 _other -> Nothing -- Narrow cases
349 ty = localRegType reg
352 gc_lbl regs = gc_lbl_ptrs (map (isGcPtrType . localRegType) regs)
354 gc_lbl_ptrs :: [Bool] -> Maybe LitString
355 -- JD: TEMPORARY -- UNTIL THOSE FUNCTIONS EXIST...
356 --gc_lbl_ptrs [True,True] = Just (sLit "stg_gc_fun_2p")
357 --gc_lbl_ptrs [True,True,True] = Just (sLit "stg_gc_fun_3p")
358 gc_lbl_ptrs _ = Nothing
361 altHeapCheck :: [LocalReg] -> C_SRT -> FCode a -> FCode a
362 altHeapCheck regs srt code
363 = heapCheck gc_call code
366 | null regs = mkCmmCall generic_gc [] [] srt
368 | Just gc_lbl <- rts_label regs -- Canned call
369 = mkCmmCall (CmmLit (CmmLabel (mkRtsCodeLabel gc_lbl)))
371 (map (CmmReg . CmmLocal) regs)
373 | otherwise -- No canned call, and non-empty live vars
374 = mkCmmCall generic_gc [] [] srt
377 | isGcPtrType ty = Just (sLit "stg_gc_unpt_r1")
378 | isFloatType ty = case width of
379 W32 -> Just (sLit "stg_gc_f1")
380 W64 -> Just (sLit "stg_gc_d1")
382 | otherwise = case width of
383 W32 -> Just (sLit "stg_gc_unbx_r1")
384 W64 -> Just (sLit "stg_gc_unbx_l1")
385 _other -> Nothing -- Narrow cases
387 ty = localRegType reg
390 rts_label _ = Nothing
393 generic_gc :: CmmExpr -- The generic GC procedure; no params, no resuls
394 generic_gc = CmmLit (CmmLabel (mkRtsCodeLabel (sLit "stg_gc_fun")))
396 -------------------------------
397 heapCheck :: CmmAGraph -> FCode a -> FCode a
399 = getHeapUsage $ \ hpHw ->
400 do { emit (do_checks hpHw do_gc)
401 -- Emit heap checks, but be sure to do it lazily so
402 -- that the conditionals on hpHw don't cause a black hole
403 ; tickyAllocHeap hpHw
404 ; doGranAllocate hpHw
408 do_checks :: WordOff -- Heap headroom
409 -> CmmAGraph -- What to do on failure
413 do_checks alloc do_gc
414 = withFreshLabel "gc" $ \ blk_id ->
415 mkLabel blk_id Nothing
416 <*> mkAssign hpReg bump_hp
417 <*> mkCmmIfThen hp_oflo
421 -- Bump heap pointer, and test for heap exhaustion
422 -- Note that we don't move the heap pointer unless the
423 -- stack check succeeds. Otherwise we might end up
424 -- with slop at the end of the current block, which can
425 -- confuse the LDV profiler.
427 alloc_lit = CmmLit (mkIntCLit (alloc*wORD_SIZE)) -- Bytes
428 bump_hp = cmmOffsetExprB (CmmReg hpReg) alloc_lit
430 -- Hp overflow if (Hp > HpLim)
431 -- (Hp has been incremented by now)
432 -- HpLim points to the LAST WORD of valid allocation space.
433 hp_oflo = CmmMachOp mo_wordUGt
434 [CmmReg hpReg, CmmReg (CmmGlobal HpLim)]
436 save_alloc = mkAssign (CmmGlobal HpAlloc) alloc_lit
440 {- Unboxed tuple alternatives and let-no-escapes (the two most annoying
441 constructs to generate code for!) For unboxed tuple returns, there
442 are an arbitrary number of possibly unboxed return values, some of
443 which will be in registers, and the others will be on the stack. We
444 always organise the stack-resident fields into pointers &
445 non-pointers, and pass the number of each to the heap check code. -}
448 :: [(Id, GlobalReg)] -- Live registers
449 -> WordOff -- no. of stack slots containing ptrs
450 -> WordOff -- no. of stack slots containing nonptrs
451 -> CmmAGraph -- code to insert in the failure path
455 unbxTupleHeapCheck regs ptrs nptrs fail_code code
456 -- We can't manage more than 255 pointers/non-pointers
457 -- in a generic heap check.
458 | ptrs > 255 || nptrs > 255 = panic "altHeapCheck"
460 = initHeapUsage $ \ hpHw -> do
461 { codeOnly $ do { do_checks 0 {- no stack check -} hpHw
462 full_fail_code rts_label
463 ; tickyAllocHeap hpHw }
467 full_fail_code = fail_code `plusStmts` oneStmt assign_liveness
468 assign_liveness = CmmAssign (CmmGlobal (VanillaReg 9)) -- Ho ho ho!
469 (CmmLit (mkWordCLit liveness))
470 liveness = mkRegLiveness regs ptrs nptrs
471 rts_label = CmmLit (CmmLabel (mkRtsCodeLabel (sLit "stg_gc_ut")))
474 {- Old Gransim comment -- I have no idea whether it still makes sense (SLPJ Sep07)
475 For GrAnSim the code for doing a heap check and doing a context switch
476 has been separated. Especially, the HEAP_CHK macro only performs a
477 heap check. THREAD_CONTEXT_SWITCH should be used for doing a context
478 switch. GRAN_FETCH_AND_RESCHEDULE must be put at the beginning of
479 every slow entry code in order to simulate the fetching of
480 closures. If fetching is necessary (i.e. current closure is not local)
481 then an automatic context switch is done. -}
484 When failing a check, we save a return address on the stack and
485 jump to a pre-compiled code fragment that saves the live registers
486 and returns to the scheduler.
488 The return address in most cases will be the beginning of the basic
489 block in which the check resides, since we need to perform the check
490 again on re-entry because someone else might have stolen the resource
493 %************************************************************************
495 Generic Heap/Stack Checks - used in the RTS
497 %************************************************************************
500 hpChkGen :: CmmExpr -> CmmExpr -> CmmExpr -> FCode ()
501 hpChkGen bytes liveness reentry
502 = do_checks' bytes True assigns stg_gc_gen
505 CmmAssign (CmmGlobal (VanillaReg 9)) liveness,
506 CmmAssign (CmmGlobal (VanillaReg 10)) reentry
509 -- a heap check where R1 points to the closure to enter on return, and
510 -- we want to assign to Sp[0] on failure (used in AutoApply.cmm:BUILD_PAP).
511 hpChkNodePointsAssignSp0 :: CmmExpr -> CmmExpr -> FCode ()
512 hpChkNodePointsAssignSp0 bytes sp0
513 = do_checks' bytes True assign stg_gc_enter1
514 where assign = oneStmt (CmmStore (CmmReg spReg) sp0)
516 stg_gc_gen = CmmLit (CmmLabel (mkRtsCodeLabel (sLit "stg_gc_gen")))