54875d7fabc7a87c96f05c04f0b1912e4ae5bb8a
[ghc-hetmet.git] / ghc / compiler / codeGen / CgClosure.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1995
3 %
4 \section[CgClosure]{Code generation for closures}
5
6 This module provides the support code for @StgToAbstractC@ to deal
7 with {\em closures} on the RHSs of let(rec)s.  See also
8 @CgCon@, which deals with constructors.
9
10 \begin{code}
11 #include "HsVersions.h"
12
13 module CgClosure ( cgTopRhsClosure, cgRhsClosure ) where
14
15 import Ubiq{-uitous-}
16 import CgLoop2          ( cgExpr, cgSccExpr )
17
18 import CgMonad
19 import AbsCSyn
20 import StgSyn
21
22 import AbsCUtils        ( mkAbstractCs, getAmodeRep )
23 import CgBindery        ( getCAddrMode, getArgAmodes,
24                           getCAddrModeAndInfo, bindNewToNode,
25                           bindNewToAStack, bindNewToBStack,
26                           bindNewToReg, bindArgsToRegs,
27                           stableAmodeIdInfo, heapIdInfo
28                         )
29 import CgCompInfo       ( spARelToInt, spBRelToInt )
30 import CgUpdate         ( pushUpdateFrame )
31 import CgHeapery        ( allocDynClosure, heapCheck
32 #ifdef GRAN
33                           , fetchAndReschedule  -- HWL
34 #endif
35                         )
36 import CgRetConv        ( mkLiveRegsMask,
37                           ctrlReturnConvAlg, dataReturnConvAlg, 
38                           CtrlReturnConvention(..), DataReturnConvention(..)
39                         )
40 import CgStackery       ( getFinalStackHW, mkVirtStkOffsets,
41                           adjustRealSps
42                         )
43 import CgUsages         ( getVirtSps, setRealAndVirtualSps,
44                           getSpARelOffset, getSpBRelOffset,
45                           getHpRelOffset
46                         )
47 import CLabel           ( mkClosureLabel, mkConUpdCodePtrVecLabel,
48                           mkStdUpdCodePtrVecLabel, mkStdUpdVecTblLabel,
49                           mkErrorStdEntryLabel, mkRednCountsLabel
50                         )
51 import ClosureInfo      -- lots and lots of stuff
52 import CmdLineOpts      ( opt_EmitArityChecks, opt_ForConcurrent )
53 import CostCentre       ( useCurrentCostCentre, currentOrSubsumedCosts,
54                           noCostCentreAttached, costsAreSubsumed,
55                           isCafCC, overheadCostCentre
56                         )
57 import HeapOffs         ( VirtualHeapOffset(..) )
58 import Id               ( idType, idPrimRep, 
59                           showId, getIdStrictness, dataConTag,
60                           emptyIdSet,
61                           GenId{-instance Outputable-}
62                         )
63 import ListSetOps       ( minusList )
64 import Maybes           ( maybeToBool )
65 import PprStyle         ( PprStyle(..) )
66 import PprType          ( GenType{-instance Outputable-}, TyCon{-ditto-} )
67 import Pretty           ( prettyToUn, ppBesides, ppChar, ppPStr )
68 import PrimRep          ( isFollowableRep, PrimRep(..) )
69 import TyCon            ( isPrimTyCon, tyConDataCons )
70 import Unpretty         ( uppShow )
71 import Util             ( isIn, panic, pprPanic, assertPanic )
72
73 myWrapperMaybe = panic "CgClosure.myWrapperMaybe (ToDo)"
74 showTypeCategory = panic "CgClosure.showTypeCategory (ToDo)"
75 getWrapperArgTypeCategories = panic "CgClosure.getWrapperArgTypeCategories (ToDo)"
76 \end{code}
77
78 %********************************************************
79 %*                                                      *
80 \subsection[closures-no-free-vars]{Top-level closures}
81 %*                                                      *
82 %********************************************************
83
84 For closures bound at top level, allocate in static space.
85 They should have no free variables.
86
87 \begin{code}
88 cgTopRhsClosure :: Id
89                 -> CostCentre   -- Optional cost centre annotation
90                 -> StgBinderInfo
91                 -> [Id]         -- Args
92                 -> StgExpr
93                 -> LambdaFormInfo
94                 -> FCode (Id, CgIdInfo)
95
96 cgTopRhsClosure name cc binder_info args body lf_info
97   =     -- LAY OUT THE OBJECT
98     let
99         closure_info = layOutStaticNoFVClosure name lf_info
100     in
101
102         -- GENERATE THE INFO TABLE (IF NECESSARY)
103     forkClosureBody (closureCodeBody binder_info closure_info
104                                          cc args body)
105                                                         `thenC`
106
107         -- BUILD VAP INFO TABLES IF NECESSARY
108         -- Don't build Vap info tables etc for
109         -- a function whose result is an unboxed type,
110         -- because we can never have thunks with such a type.
111     (if closureReturnsUnboxedType closure_info then
112         nopC
113     else
114         let
115             bind_the_fun = addBindC name cg_id_info     -- It's global!
116         in
117         cgVapInfoTables True {- Top level -} bind_the_fun binder_info name args lf_info
118     ) `thenC`
119
120         -- BUILD THE OBJECT (IF NECESSARY)
121     (if staticClosureRequired name binder_info lf_info
122      then
123         let
124             cost_centre = mkCCostCentre cc
125         in
126         absC (CStaticClosure
127                 closure_label   -- Labelled with the name on lhs of defn
128                 closure_info
129                 cost_centre
130                 [])             -- No fields
131      else
132         nopC
133     ) `thenC`
134
135     returnFC (name, cg_id_info)
136   where
137     closure_label = mkClosureLabel name
138     cg_id_info    = stableAmodeIdInfo name (CLbl closure_label PtrRep) lf_info
139 \end{code}
140
141 %********************************************************
142 %*                                                      *
143 \subsection[non-top-level-closures]{Non top-level closures}
144 %*                                                      *
145 %********************************************************
146
147 For closures with free vars, allocate in heap.
148
149 ===================== OLD PROBABLY OUT OF DATE COMMENTS =============
150
151 -- Closures which (a) have no fvs and (b) have some args (i.e.
152 -- combinator functions), are allocated statically, just as if they
153 -- were top-level closures.  We can't get a space leak that way
154 -- (because they are HNFs) and it saves allocation.
155
156 -- Lexical Scoping: Problem
157 -- These top level function closures will be inherited, possibly
158 -- to a different cost centre scope set before entering.
159
160 -- Evaluation Scoping: ok as already in HNF
161
162 -- Should rely on floating mechanism to achieve this floating to top level.
163 -- As let floating will avoid floating which breaks cost centre attribution
164 -- everything will be OK.
165
166 -- Disabled: because it breaks lexical-scoped cost centre semantics.
167 -- cgRhsClosure binder cc bi [] upd_flag args@(_:_) body
168 --  = cgTopRhsClosure binder cc bi upd_flag args body
169
170 ===================== END OF OLD PROBABLY OUT OF DATE COMMENTS =============
171
172 \begin{code}
173 cgRhsClosure    :: Id
174                 -> CostCentre   -- Optional cost centre annotation
175                 -> StgBinderInfo
176                 -> [Id]         -- Free vars
177                 -> [Id]         -- Args
178                 -> StgExpr
179                 -> LambdaFormInfo
180                 -> FCode (Id, CgIdInfo)
181
182 cgRhsClosure binder cc binder_info fvs args body lf_info
183   | maybeToBool maybe_std_thunk         -- AHA!  A STANDARD-FORM THUNK
184   -- ToDo: check non-primitiveness (ASSERT)
185   = (
186         -- LAY OUT THE OBJECT
187     getArgAmodes std_thunk_payload              `thenFC` \ amodes ->
188     let
189         (closure_info, amodes_w_offsets)
190           = layOutDynClosure binder getAmodeRep amodes lf_info
191
192         (use_cc, blame_cc) = chooseDynCostCentres cc args fvs body
193     in
194         -- BUILD THE OBJECT
195     allocDynClosure closure_info use_cc blame_cc amodes_w_offsets
196     )
197                 `thenFC` \ heap_offset ->
198
199         -- RETURN
200     returnFC (binder, heapIdInfo binder heap_offset lf_info)
201
202   where
203     maybe_std_thunk        = getStandardFormThunkInfo lf_info
204     Just std_thunk_payload = maybe_std_thunk
205 \end{code}
206
207 Here's the general case.
208 \begin{code}
209 cgRhsClosure binder cc binder_info fvs args body lf_info
210   = (
211         -- LAY OUT THE OBJECT
212         --
213         -- If the binder is itself a free variable, then don't store
214         -- it in the closure.  Instead, just bind it to Node on entry.
215         -- NB we can be sure that Node will point to it, because we
216         -- havn't told mkClosureLFInfo about this; so if the binder
217         -- *was* a free var of its RHS, mkClosureLFInfo thinks it *is*
218         -- stored in the closure itself, so it will make sure that
219         -- Node points to it...
220     let
221         is_elem        = isIn "cgRhsClosure"
222
223         binder_is_a_fv = binder `is_elem` fvs
224         reduced_fvs    = if binder_is_a_fv
225                          then fvs `minusList` [binder]
226                          else fvs
227     in
228     mapFCs getCAddrModeAndInfo reduced_fvs      `thenFC` \ amodes_and_info ->
229     let
230         fvs_w_amodes_and_info         = reduced_fvs `zip` amodes_and_info
231
232         closure_info :: ClosureInfo
233         bind_details :: [((Id, (CAddrMode, LambdaFormInfo)), VirtualHeapOffset)]
234
235         (closure_info, bind_details)
236           = layOutDynClosure binder get_kind fvs_w_amodes_and_info lf_info
237
238         bind_fv ((id, (_, lf_info)), offset) = bindNewToNode id offset lf_info
239
240         amodes_w_offsets = [(amode,offset) | ((_, (amode,_)), offset) <- bind_details]
241
242         get_kind (id, amode_and_info) = idPrimRep id
243     in
244         -- BUILD ITS INFO TABLE AND CODE
245     forkClosureBody (
246                 -- Bind the fvs
247             mapCs bind_fv bind_details `thenC`
248
249                 -- Bind the binder itself, if it is a free var
250             (if binder_is_a_fv then
251                 bindNewToReg binder node lf_info
252             else
253                 nopC)                                   `thenC`
254
255                 -- Compile the body
256             closureCodeBody binder_info closure_info cc args body
257     )   `thenC`
258
259         -- BUILD VAP INFO TABLES IF NECESSARY
260         -- Don't build Vap info tables etc for
261         -- a function whose result is an unboxed type,
262         -- because we can never have thunks with such a type.
263     (if closureReturnsUnboxedType closure_info then
264         nopC
265     else
266         cgVapInfoTables False {- Not top level -} nopC binder_info binder args lf_info
267     ) `thenC`
268
269         -- BUILD THE OBJECT
270     let
271         (use_cc, blame_cc) = chooseDynCostCentres cc args fvs body
272     in
273     allocDynClosure closure_info use_cc blame_cc amodes_w_offsets
274     )           `thenFC` \ heap_offset ->
275
276         -- RETURN
277     returnFC (binder, heapIdInfo binder heap_offset lf_info)
278 \end{code}
279
280 @cgVapInfoTables@ generates both Vap info tables, if they are required
281 at all.  It calls @cgVapInfoTable@ to generate each Vap info table,
282 along with its entry code.
283
284 \begin{code}
285 -- Don't generate Vap info tables for thunks; only for functions
286 cgVapInfoTables top_level perhaps_bind_the_fun binder_info fun [{- no args; a thunk! -}] lf_info
287   = nopC
288
289 cgVapInfoTables top_level perhaps_bind_the_fun binder_info fun args lf_info
290   =     -- BUILD THE STANDARD VAP-ENTRY STUFF IF NECESSARY
291     (if stdVapRequired binder_info then
292         cgVapInfoTable perhaps_bind_the_fun Updatable fun args fun_in_payload lf_info
293     else
294         nopC
295     )           `thenC`
296
297                 -- BUILD THE NO-UPDATE VAP-ENTRY STUFF IF NECESSARY
298     (if noUpdVapRequired binder_info then
299         cgVapInfoTable perhaps_bind_the_fun SingleEntry fun args fun_in_payload lf_info
300     else
301         nopC
302     )
303
304   where
305     fun_in_payload = not top_level
306
307 cgVapInfoTable perhaps_bind_the_fun upd_flag fun args fun_in_payload fun_lf_info
308   = let
309         -- The vap_entry_rhs is a manufactured STG expression which
310         -- looks like the RHS of any binding which is going to use the vap-entry
311         -- point of the function.  Each of these bindings will look like:
312         --
313         --      x = [a,b,c] \upd [] -> f a b c
314         --
315         -- If f is not top-level, then f is one of the free variables too,
316         -- hence "payload_ids" isn't the same as "arg_ids".
317         --
318         vap_entry_rhs = StgApp (StgVarArg fun) (map StgVarArg args) emptyIdSet
319                                                                         -- Empty live vars
320
321         arg_ids_w_info = [(name,mkLFArgument) | name <- args]
322         payload_ids_w_info | fun_in_payload = (fun,fun_lf_info) : arg_ids_w_info
323                            | otherwise      = arg_ids_w_info
324
325         payload_ids | fun_in_payload = fun : args               -- Sigh; needed for mkClosureLFInfo
326                     | otherwise      = args
327
328         vap_lf_info   = mkClosureLFInfo False {-not top level-} payload_ids
329                                         upd_flag [] vap_entry_rhs
330                 -- It's not top level, even if we're currently compiling a top-level
331                 -- function, because any VAP *use* of this function will be for a
332                 -- local thunk, thus
333                 --              let x = f p q   -- x isn't top level!
334                 --              in ...
335
336         get_kind (id, info) = idPrimRep id
337
338         payload_bind_details :: [((Id, LambdaFormInfo), VirtualHeapOffset)]
339         (closure_info, payload_bind_details) = layOutDynClosure
340                                                         fun
341                                                         get_kind payload_ids_w_info
342                                                         vap_lf_info
343                 -- The dodgy thing is that we use the "fun" as the
344                 -- Id to give to layOutDynClosure.  This Id gets embedded in
345                 -- the closure_info it returns.  But of course, the function doesn't
346                 -- have the right type to match the Vap closure.  Never mind,
347                 -- a hack in closureType spots the special case.  Otherwise that
348                 -- Id is just used for label construction, which is OK.
349
350         bind_fv ((id,lf_info), offset) = bindNewToNode id offset lf_info
351     in
352
353         -- BUILD ITS INFO TABLE AND CODE
354     forkClosureBody (
355
356                 -- Bind the fvs; if the fun is not in the payload, then bind_the_fun tells
357                 -- how to bind it.  If it is in payload it'll be bound by payload_bind_details.
358             perhaps_bind_the_fun                `thenC`
359             mapCs bind_fv payload_bind_details  `thenC`
360
361                 -- Generate the info table and code
362             closureCodeBody NoStgBinderInfo
363                             closure_info
364                             useCurrentCostCentre
365                             []  -- No args; it's a thunk
366                             vap_entry_rhs
367     )
368 \end{code}
369 %************************************************************************
370 %*                                                                      *
371 \subsection[code-for-closures]{The code for closures}
372 %*                                                                      *
373 %************************************************************************
374
375 \begin{code}
376 closureCodeBody :: StgBinderInfo
377                 -> ClosureInfo  -- Lots of information about this closure
378                 -> CostCentre   -- Optional cost centre attached to closure
379                 -> [Id]
380                 -> StgExpr
381                 -> Code
382 \end{code}
383
384 There are two main cases for the code for closures.  If there are {\em
385 no arguments}, then the closure is a thunk, and not in normal form.
386 So it should set up an update frame (if it is shared).  Also, it has
387 no argument satisfaction check, so fast and slow entry-point labels
388 are the same.
389
390 \begin{code}
391 closureCodeBody binder_info closure_info cc [] body
392   = -- thunks cannot have a primitive type!
393 #ifdef DEBUG
394     let
395         (has_tycon, tycon)
396           = case (closureType closure_info) of
397               Nothing       -> (False, panic "debug")
398               Just (tc,_,_) -> (True,  tc)
399     in
400     if has_tycon && isPrimTyCon tycon then
401         pprPanic "closureCodeBody:thunk:prim type!" (ppr PprDebug tycon)
402     else
403 #endif
404     getAbsC body_code   `thenFC` \ body_absC ->
405     moduleName          `thenFC` \ mod_name ->
406
407     absC (CClosureInfoAndCode closure_info body_absC Nothing
408                               stdUpd (cl_descr mod_name)
409                               (dataConLiveness closure_info))
410   where
411     cl_descr mod_name = closureDescription mod_name (closureId closure_info) [] body
412
413     body_addr   = CLbl (entryLabelFromCI closure_info) CodePtrRep
414     body_code   = profCtrC SLIT("ENT_THK") []                   `thenC`
415                   enterCostCentreCode closure_info cc IsThunk   `thenC`
416                   thunkWrapper closure_info (cgSccExpr body)
417
418     stdUpd      = CLbl mkErrorStdEntryLabel CodePtrRep
419 \end{code}
420
421 If there is {\em at least one argument}, then this closure is in
422 normal form, so there is no need to set up an update frame.  On the
423 other hand, we do have to check that there are enough args, and
424 perform an update if not!
425
426 The Macros for GrAnSim are produced at the beginning of the
427 argSatisfactionCheck (by calling fetchAndReschedule).  There info if
428 Node points to closure is available. -- HWL
429
430 \begin{code}
431 closureCodeBody binder_info closure_info cc all_args body
432   = getEntryConvention id lf_info
433                        (map idPrimRep all_args)         `thenFC` \ entry_conv ->
434     let
435         do_arity_chks = opt_EmitArityChecks
436         is_concurrent = opt_ForConcurrent
437
438         stg_arity = length all_args
439
440         -- Arg mapping for standard (slow) entry point; all args on stack
441         (spA_all_args, spB_all_args, all_bxd_w_offsets, all_ubxd_w_offsets)
442            = mkVirtStkOffsets
443                 0 0             -- Initial virtual SpA, SpB
444                 idPrimRep
445                 all_args
446
447         -- Arg mapping for the fast entry point; as many args as poss in
448         -- registers; the rest on the stack
449         --      arg_regs are the registers used for arg passing
450         --      stk_args are the args which are passed on the stack
451         --
452         arg_regs = case entry_conv of
453                 DirectEntry lbl arity regs -> regs
454                 ViaNode | is_concurrent    -> []
455                 other                      -> panic "closureCodeBody:arg_regs"
456
457         stk_args = drop (length arg_regs) all_args
458         (spA_stk_args, spB_stk_args, stk_bxd_w_offsets, stk_ubxd_w_offsets)
459           = mkVirtStkOffsets
460                 0 0             -- Initial virtual SpA, SpB
461                 idPrimRep
462                 stk_args
463
464         -- HWL; Note: empty list of live regs in slow entry code
465         -- Old version (reschedule combined with heap check);
466         -- see argSatisfactionCheck for new version
467         --slow_entry_code = forceHeapCheck [node] True slow_entry_code'
468         --                where node = VanillaReg PtrRep 1
469         --slow_entry_code = forceHeapCheck [] True slow_entry_code'
470
471         slow_entry_code
472           = profCtrC SLIT("ENT_FUN_STD") []                 `thenC`
473
474                 -- Bind args, and record expected position of stk ptrs
475             mapCs bindNewToAStack all_bxd_w_offsets         `thenC`
476             mapCs bindNewToBStack all_ubxd_w_offsets        `thenC`
477             setRealAndVirtualSps spA_all_args spB_all_args  `thenC`
478
479             argSatisfactionCheck closure_info all_args      `thenC`
480
481             -- OK, so there are enough args.  Now we need to stuff as
482             -- many of them in registers as the fast-entry code
483             -- expects Note that the zipWith will give up when it hits
484             -- the end of arg_regs.
485
486             mapFCs getCAddrMode all_args                    `thenFC` \ stk_amodes ->
487             absC (mkAbstractCs (zipWith assign_to_reg arg_regs stk_amodes)) `thenC`
488
489             -- Now adjust real stack pointers
490             adjustRealSps spA_stk_args spB_stk_args             `thenC`
491
492             -- set the arity checker, if asked
493             absC (
494                 if do_arity_chks
495                 then CMacroStmt SET_ARITY [mkIntCLit stg_arity]
496                 else AbsCNop
497             )                                                   `thenC`
498             absC (CFallThrough (CLbl fast_label CodePtrRep))
499
500         assign_to_reg reg_id amode = CAssign (CReg reg_id) amode
501
502         -- HWL
503         -- Old version (reschedule combined with heap check);
504         -- see argSatisfactionCheck for new version
505         -- fast_entry_code = forceHeapCheck [] True fast_entry_code'
506
507         fast_entry_code
508           = profCtrC SLIT("ENT_FUN_DIRECT") [
509                     CLbl (mkRednCountsLabel id) PtrRep,
510                     CString (_PK_ (showId PprDebug id)),
511                     mkIntCLit stg_arity,        -- total # of args
512                     mkIntCLit spA_stk_args,     -- # passed on A stk
513                     mkIntCLit spB_stk_args,     -- B stk (rest in regs)
514                     CString (_PK_ (map (showTypeCategory . idType) all_args)),
515                     CString (_PK_ (show_wrapper_name wrapper_maybe)),
516                     CString (_PK_ (show_wrapper_arg_kinds wrapper_maybe))
517                 ]                       `thenC`
518             absC (
519                 if do_arity_chks
520                 then CMacroStmt CHK_ARITY [mkIntCLit stg_arity]
521                 else AbsCNop
522             )                           `thenC`
523
524                 -- Bind args to regs/stack as appropriate, and
525                 -- record expected position of sps
526             bindArgsToRegs all_args arg_regs                `thenC`
527             mapCs bindNewToAStack stk_bxd_w_offsets         `thenC`
528             mapCs bindNewToBStack stk_ubxd_w_offsets        `thenC`
529             setRealAndVirtualSps spA_stk_args spB_stk_args  `thenC`
530
531                 -- Enter the closures cc, if required
532             enterCostCentreCode closure_info cc IsFunction  `thenC`
533
534                 -- Do the business
535             funWrapper closure_info arg_regs (cgExpr body)
536     in
537         -- Make a labelled code-block for the slow and fast entry code
538     forkAbsC (if slow_code_needed then slow_entry_code else absC AbsCNop)
539                                 `thenFC` \ slow_abs_c ->
540     forkAbsC fast_entry_code    `thenFC` \ fast_abs_c ->
541     moduleName                  `thenFC` \ mod_name ->
542
543         -- Now either construct the info table, or put the fast code in alone
544         -- (We never have slow code without an info table)
545     absC (
546       if info_table_needed then
547         CClosureInfoAndCode closure_info slow_abs_c (Just fast_abs_c)
548                         stdUpd (cl_descr mod_name)
549                         (dataConLiveness closure_info)
550       else
551         CCodeBlock fast_label fast_abs_c
552     )
553   where
554     lf_info = closureLFInfo closure_info
555
556     cl_descr mod_name = closureDescription mod_name id all_args body
557
558         -- Figure out what is needed and what isn't
559     slow_code_needed   = slowFunEntryCodeRequired id binder_info
560     info_table_needed  = funInfoTableRequired id binder_info lf_info
561
562         -- Manufacture labels
563     id         = closureId closure_info
564
565     fast_label = fastLabelFromCI closure_info
566
567     stdUpd = CLbl mkErrorStdEntryLabel CodePtrRep
568
569     wrapper_maybe = get_ultimate_wrapper Nothing id
570       where
571         get_ultimate_wrapper deflt x -- walk all the way up a "wrapper chain"
572           = case (myWrapperMaybe x) of
573               Nothing -> deflt
574               Just xx -> get_ultimate_wrapper (Just xx) xx
575
576     show_wrapper_name Nothing   = ""
577     show_wrapper_name (Just xx) = showId PprDebug xx
578
579     show_wrapper_arg_kinds Nothing   = ""
580     show_wrapper_arg_kinds (Just xx)
581       = case (getWrapperArgTypeCategories (idType xx) (getIdStrictness xx)) of
582           Nothing  -> ""
583           Just str -> str
584 \end{code}
585
586 For lexically scoped profiling we have to load the cost centre from
587 the closure entered, if the costs are not supposed to be inherited.
588 This is done immediately on entering the fast entry point.
589
590 Load current cost centre from closure, if not inherited.
591 Node is guaranteed to point to it, if profiling and not inherited.
592
593 \begin{code}
594 data IsThunk = IsThunk | IsFunction -- Bool-like, local
595
596 enterCostCentreCode :: ClosureInfo -> CostCentre -> IsThunk -> Code
597
598 enterCostCentreCode closure_info cc is_thunk
599   = costCentresFlag     `thenFC` \ profiling_on ->
600     if not profiling_on then
601         nopC
602     else -- down to business
603         ASSERT(not (noCostCentreAttached cc))
604
605         if costsAreSubsumed cc then
606             nopC
607
608         else if is_current_CC cc then -- fish the CC out of the closure,
609                                       -- where we put it when we alloc'd;
610                                       -- NB: chk defn of "is_current_CC"
611                                       -- if you go to change this! (WDP 94/12)
612             costCentresC
613                 (case is_thunk of
614                    IsThunk    -> SLIT("ENTER_CC_TCL")
615                    IsFunction -> SLIT("ENTER_CC_FCL"))
616                 [CReg node]
617
618         else if isCafCC cc then
619             costCentresC
620                 SLIT("ENTER_CC_CAF")
621                 [mkCCostCentre cc]
622
623         else -- we've got a "real" cost centre right here in our hands...
624             costCentresC
625                 (case is_thunk of
626                    IsThunk    -> SLIT("ENTER_CC_T")
627                    IsFunction -> SLIT("ENTER_CC_F"))
628                 [mkCCostCentre cc]
629   where
630     is_current_CC cc
631       = currentOrSubsumedCosts cc
632         -- but we've already ruled out "subsumed", so it must be "current"!
633 \end{code}
634
635 %************************************************************************
636 %*                                                                      *
637 \subsubsection[pre-closure-code-stuff]{Pre-closure-code code}
638 %*                                                                      *
639 %************************************************************************
640
641 The argument-satisfaction check code is placed after binding
642 the arguments to their stack locations. Hence, the virtual stack
643 pointer is pointing after all the args, and virtual offset 1 means
644 the base of frame and hence most distant arg.  Hence
645 virtual offset 0 is just beyond the most distant argument; the
646 relative offset of this word tells how many words of arguments
647 are expected.
648
649 \begin{code}
650 argSatisfactionCheck :: ClosureInfo -> [Id] -> Code
651
652 argSatisfactionCheck closure_info [] = nopC
653
654 argSatisfactionCheck closure_info args
655   = -- safest way to determine which stack last arg will be on:
656     -- look up CAddrMode that last arg is bound to;
657     -- getAmodeRep;
658     -- check isFollowableRep.
659
660     nodeMustPointToIt (closureLFInfo closure_info)      `thenFC` \ node_points ->
661
662 #ifdef GRAN
663     -- HWL:
664     -- absC (CMacroStmt GRAN_FETCH [])                  `thenC`
665     -- forceHeapCheck [] node_points (absC AbsCNop)     `thenC`
666     (if node_points
667         then fetchAndReschedule  [] node_points
668         else absC AbsCNop)                              `thenC`
669 #endif  {- GRAN -}
670
671     getCAddrMode (last args)                            `thenFC` \ last_amode ->
672
673     if (isFollowableRep (getAmodeRep last_amode)) then
674         getSpARelOffset 0       `thenFC` \ (SpARel spA off) ->
675         let
676             lit = mkIntCLit (spARelToInt spA off)
677         in
678         if node_points then
679             absC (CMacroStmt ARGS_CHK_A [lit])
680         else
681             absC (CMacroStmt ARGS_CHK_A_LOAD_NODE [lit, set_Node_to_this])
682     else
683         getSpBRelOffset 0       `thenFC` \ (SpBRel spB off) ->
684         let
685             lit = mkIntCLit (spBRelToInt spB off)
686         in
687         if node_points then
688             absC (CMacroStmt ARGS_CHK_B [lit])
689         else
690             absC (CMacroStmt ARGS_CHK_B_LOAD_NODE [lit, set_Node_to_this])
691   where
692     -- We must tell the arg-satis macro whether Node is pointing to
693     -- the closure or not.  If it isn't so pointing, then we give to
694     -- the macro the (static) address of the closure.
695
696     set_Node_to_this = CLbl (closureLabelFromCI closure_info) PtrRep
697 \end{code}
698
699 %************************************************************************
700 %*                                                                      *
701 \subsubsection[closure-code-wrappers]{Wrappers around closure code}
702 %*                                                                      *
703 %************************************************************************
704
705 \begin{code}
706 thunkWrapper:: ClosureInfo -> Code -> Code
707 thunkWrapper closure_info thunk_code
708   =     -- Stack and heap overflow checks
709     nodeMustPointToIt (closureLFInfo closure_info)      `thenFC` \ node_points ->
710
711 #ifdef GRAN
712     -- HWL insert macros for GrAnSim if node is live here
713     (if node_points
714        then fetchAndReschedule [] node_points
715        else absC AbsCNop)                               `thenC`
716 #endif  {- GRAN -}
717
718     stackCheck closure_info [] node_points (    -- stackCheck *encloses* the rest
719
720     -- Must be after stackCheck: if stchk fails new stack
721     -- space has to be allocated from the heap
722
723     heapCheck [] node_points (
724                                         -- heapCheck *encloses* the rest
725         -- The "[]" says there are no live argument registers
726
727         -- Overwrite with black hole if necessary
728     blackHoleIt closure_info                            `thenC`
729
730         -- Push update frame if necessary
731     setupUpdate closure_info (          -- setupUpdate *encloses* the rest
732         thunk_code
733     )))
734
735 funWrapper :: ClosureInfo       -- Closure whose code body this is
736            -> [MagicId]         -- List of argument registers (if any)
737            -> Code              -- Body of function being compiled
738            -> Code
739 funWrapper closure_info arg_regs fun_body
740   =     -- Stack overflow check
741     nodeMustPointToIt (closureLFInfo closure_info)      `thenFC` \ node_points ->
742     stackCheck closure_info arg_regs node_points (      -- stackCheck *encloses* the rest
743
744         -- Heap overflow check
745     heapCheck arg_regs node_points (
746                                         -- heapCheck *encloses* the rest
747
748         -- Finally, do the business
749     fun_body
750     ))
751 \end{code}
752
753 %************************************************************************
754 %*                                                                      *
755 \subsubsubsection[overflow-checks]{Stack and heap overflow wrappers}
756 %*                                                                      *
757 %************************************************************************
758
759 Assumption: virtual and real stack pointers are currently exactly aligned.
760
761 \begin{code}
762 stackCheck :: ClosureInfo
763            -> [MagicId]                 -- Live registers
764            -> Bool                      -- Node required to point after check?
765            -> Code
766            -> Code
767
768 stackCheck closure_info regs node_reqd code
769   = getFinalStackHW (\ aHw -> \ bHw ->  -- Both virtual stack offsets
770
771     getVirtSps          `thenFC` \ (vSpA, vSpB) ->
772
773     let a_headroom_reqd = aHw - vSpA    -- Virtual offsets are positive integers
774         b_headroom_reqd = bHw - vSpB
775     in
776
777     absC (if (a_headroom_reqd == 0 && b_headroom_reqd == 0) then
778                 AbsCNop
779           else
780                 CMacroStmt STK_CHK [mkIntCLit liveness_mask,
781                                     mkIntCLit a_headroom_reqd,
782                                     mkIntCLit b_headroom_reqd,
783                                     mkIntCLit vSpA,
784                                     mkIntCLit vSpB,
785                                     mkIntCLit (if returns_prim_type then 1 else 0),
786                                     mkIntCLit (if node_reqd         then 1 else 0)]
787          )
788         -- The test is *inside* the absC, to avoid black holes!
789
790     `thenC` code
791     )
792   where
793     all_regs = if node_reqd then node:regs else regs
794     liveness_mask = mkLiveRegsMask all_regs
795
796     returns_prim_type = closureReturnsUnboxedType closure_info
797 \end{code}
798
799 %************************************************************************
800 %*                                                                      *
801 \subsubsubsection[update-and-BHs]{Update and black-hole wrappers}
802 %*                                                                      *
803 %************************************************************************
804
805
806 \begin{code}
807 blackHoleIt :: ClosureInfo -> Code      -- Only called for thunks
808 blackHoleIt closure_info
809   = noBlackHolingFlag   `thenFC` \ no_black_holing ->
810
811     if (blackHoleOnEntry no_black_holing closure_info)
812     then
813         absC (if closureSingleEntry(closure_info) then
814                 CMacroStmt UPD_BH_SINGLE_ENTRY [CReg node]
815               else
816                 CMacroStmt UPD_BH_UPDATABLE [CReg node])
817         -- Node always points to it; see stg-details
818     else
819         nopC
820 \end{code}
821
822 \begin{code}
823 setupUpdate :: ClosureInfo -> Code -> Code      -- Only called for thunks
824         -- Nota Bene: this function does not change Node (even if it's a CAF),
825         -- so that the cost centre in the original closure can still be
826         -- extracted by a subsequent ENTER_CC_TCL
827
828 setupUpdate closure_info code
829  = if (closureUpdReqd closure_info) then
830         link_caf_if_needed      `thenFC` \ update_closure ->
831         pushUpdateFrame update_closure vector code
832    else
833         profCtrC SLIT("UPDF_OMITTED") [] `thenC`
834         code
835  where
836    link_caf_if_needed :: FCode CAddrMode        -- Returns amode for closure to be updated
837    link_caf_if_needed
838      = if not (isStaticClosure closure_info) then
839           returnFC (CReg node)
840        else
841
842           -- First we must allocate a black hole, and link the
843           -- CAF onto the CAF list
844
845                 -- Alloc black hole specifying CC_HDR(Node) as the cost centre
846                 --   Hack Warning: Using a CLitLit to get CAddrMode !
847           let
848               use_cc   = CLitLit SLIT("CC_HDR(R1.p)") PtrRep
849               blame_cc = use_cc
850           in
851           allocDynClosure (blackHoleClosureInfo closure_info) use_cc blame_cc []
852                                                         `thenFC` \ heap_offset ->
853           getHpRelOffset heap_offset                    `thenFC` \ hp_rel ->
854           let  amode = CAddr hp_rel
855           in
856           absC (CMacroStmt UPD_CAF [CReg node, amode])
857                                                         `thenC`
858           returnFC amode
859
860    closure_label = mkClosureLabel (closureId closure_info)
861
862    vector
863      = case (closureType closure_info) of
864         Nothing -> CReg StdUpdRetVecReg
865         Just (spec_tycon, _, spec_datacons) ->
866             case (ctrlReturnConvAlg spec_tycon) of
867               UnvectoredReturn 1 ->
868                 let
869                     spec_data_con = head spec_datacons
870                     only_tag = dataConTag spec_data_con
871
872                     direct = case (dataReturnConvAlg spec_data_con) of
873                         ReturnInRegs _ -> mkConUpdCodePtrVecLabel spec_tycon only_tag
874                         ReturnInHeap   -> mkStdUpdCodePtrVecLabel spec_tycon only_tag
875
876                     vectored = mkStdUpdVecTblLabel spec_tycon
877                 in
878                     CUnVecLbl direct vectored
879
880               UnvectoredReturn _ -> CReg StdUpdRetVecReg
881               VectoredReturn _   -> CLbl (mkStdUpdVecTblLabel spec_tycon) DataPtrRep
882 \end{code}
883
884 %************************************************************************
885 %*                                                                      *
886 \subsection[CgClosure-Description]{Profiling Closure Description.}
887 %*                                                                      *
888 %************************************************************************
889
890 For "global" data constructors the description is simply occurrence
891 name of the data constructor itself (see \ref{CgConTbls-info-tables}).
892
893 Otherwise it is determind by @closureDescription@ from the let
894 binding information.
895
896 \begin{code}
897 closureDescription :: FAST_STRING       -- Module
898                    -> Id                -- Id of closure binding
899                    -> [Id]              -- Args
900                    -> StgExpr   -- Body
901                    -> String
902
903         -- Not called for StgRhsCon which have global info tables built in
904         -- CgConTbls.lhs with a description generated from the data constructor
905
906 closureDescription mod_name name args body
907   = uppShow 0 (prettyToUn (
908         ppBesides [ppChar '<',
909                    ppPStr mod_name,
910                    ppChar '.',
911                    ppr PprDebug name,
912                    ppChar '>']))
913 \end{code}
914
915 \begin{code}
916 chooseDynCostCentres cc args fvs body
917   = let
918         use_cc -- cost-centre we record in the object
919           = if currentOrSubsumedCosts cc
920             then CReg CurCostCentre
921             else mkCCostCentre cc
922
923         blame_cc -- cost-centre on whom we blame the allocation
924           = case (args, fvs, body) of
925               ([], [just1], StgApp (StgVarArg fun) [{-no args-}] _)
926                 | just1 == fun
927                 -> mkCCostCentre overheadCostCentre
928               _ -> use_cc
929             -- if it's an utterly trivial RHS, then it must be
930             -- one introduced by boxHigherOrderArgs for profiling,
931             -- so we charge it to "OVERHEAD".
932     in
933     (use_cc, blame_cc)
934 \end{code}