[project @ 2000-03-08 17:48:24 by simonmar]
[ghc-hetmet.git] / ghc / compiler / profiling / SCCfinal.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[SCCfinal]{Modify and collect code generation for final STG program}
5
6 This is now a sort-of-normal STG-to-STG pass (WDP 94/06), run by stg2stg.
7
8 * Traverses the STG program collecting the cost centres. These are
9   required to declare the cost centres at the start of code
10   generation.
11
12   Note: because of cross-module unfolding, some of these cost centres
13   may be from other modules.  But will still have to give them
14   "extern" declarations.
15
16 * Puts on CAF cost-centres if the user has asked for individual CAF
17   cost-centres.
18
19 * Ditto for individual DICT cost-centres.
20
21 * Boxes top-level inherited functions passed as arguments.
22
23 * "Distributes" given cost-centres to all as-yet-unmarked RHSs.
24
25 \begin{code}
26 module SCCfinal ( stgMassageForProfiling ) where
27
28 #include "HsVersions.h"
29
30 import StgSyn
31
32 import CmdLineOpts      ( opt_AutoSccsOnIndividualCafs )
33 import CostCentre       -- lots of things
34 import Const            ( Con(..) )
35 import Id               ( Id, mkSysLocal, idType, idName )
36 import Module           ( Module )
37 import UniqSupply       ( uniqFromSupply, splitUniqSupply, UniqSupply )
38 import Unique           ( Unique )
39 import Type             ( splitForAllTys, splitTyConApp_maybe )
40 import TyCon            ( isFunTyCon )
41 import VarSet
42 import UniqSet
43 import Name             ( isLocallyDefinedName )
44 import Util             ( removeDups )
45 import Outputable       
46
47 infixr 9 `thenMM`, `thenMM_`
48 \end{code}
49
50 \begin{code}
51 type CollectedCCs = ([CostCentre],      -- locally defined ones
52                      [CostCentre],      -- ones needing "extern" decls
53                      [CostCentreStack]) -- singleton stacks (for CAFs)
54
55 stgMassageForProfiling
56         :: Module                       -- module name
57         -> UniqSupply                   -- unique supply
58         -> [StgBinding]                 -- input
59         -> (CollectedCCs, [StgBinding])
60
61 stgMassageForProfiling mod_name us stg_binds
62   = let
63         ((local_ccs, extern_ccs, cc_stacks),
64          stg_binds2)
65           = initMM mod_name us (do_top_bindings stg_binds)
66
67         (fixed_ccs, fixed_cc_stacks)
68           = if opt_AutoSccsOnIndividualCafs
69             then ([],[])  -- don't need "all CAFs" CC 
70                           -- (for Prelude, we use PreludeCC)
71             else ([all_cafs_cc], [all_cafs_ccs])
72
73         local_ccs_no_dups  = fst (removeDups cmpCostCentre local_ccs)
74         extern_ccs_no_dups = fst (removeDups cmpCostCentre extern_ccs)
75     in
76     ((fixed_ccs ++ local_ccs_no_dups, 
77       extern_ccs_no_dups, 
78       fixed_cc_stacks ++ cc_stacks), stg_binds2)
79   where
80
81     all_cafs_cc  = mkAllCafsCC mod_name
82     all_cafs_ccs = mkSingletonCCS all_cafs_cc
83
84     ----------
85     do_top_bindings :: [StgBinding] -> MassageM [StgBinding]
86
87     do_top_bindings [] = returnMM []
88
89     do_top_bindings (StgNonRec b rhs : bs) 
90       = do_top_rhs b rhs                `thenMM` \ rhs' ->
91         addTopLevelIshId b (
92            do_top_bindings bs `thenMM` \bs' ->
93            returnMM (StgNonRec b rhs' : bs')
94         )
95
96     do_top_bindings (StgRec pairs : bs)
97       = addTopLevelIshIds binders (
98            mapMM do_pair pairs          `thenMM` \ pairs2 ->
99            do_top_bindings bs `thenMM` \ bs' ->
100            returnMM (StgRec pairs2 : bs')
101         )
102       where
103         binders = map fst pairs
104         do_pair (b, rhs) 
105            = do_top_rhs b rhs   `thenMM` \ rhs2 ->
106              returnMM (b, rhs2)
107
108     ----------
109     do_top_rhs :: Id -> StgRhs -> MassageM StgRhs
110
111     do_top_rhs binder (StgRhsClosure _ bi srt fv u [] (StgSCC cc (StgCon (DataCon con) args _)))
112       | not (isSccCountCostCentre cc)
113         -- Trivial _scc_ around nothing but static data
114         -- Eliminate _scc_ ... and turn into StgRhsCon
115       = returnMM (StgRhsCon dontCareCCS con args)
116
117 {- Can't do this one with cost-centre stacks:  --SDM
118     do_top_rhs binder (StgRhsClosure no_cc bi srt fv u [] (StgSCC ty cc expr))
119       | (noCCSAttached no_cc || currentOrSubsumedCCS no_cc)
120         && not (isSccCountCostCentre cc)
121         -- Top level CAF without a cost centre attached
122         -- Attach and collect cc of trivial _scc_ in body
123       = collectCC cc                                    `thenMM_`
124         set_prevailing_cc cc (do_expr expr)             `thenMM`  \ expr' ->
125         returnMM (StgRhsClosure cc bi srt fv u [] expr')
126 -}
127
128     do_top_rhs binder (StgRhsClosure no_cc bi srt fv u [] body)
129       | noCCSAttached no_cc || currentOrSubsumedCCS no_cc
130         -- Top level CAF without a cost centre attached
131         -- Attach CAF cc (collect if individual CAF ccs)
132       = (if opt_AutoSccsOnIndividualCafs 
133                 then let cc = mkAutoCC binder mod_name CafCC
134                          ccs = mkSingletonCCS cc
135                      in
136                      collectCC  cc  `thenMM_`
137                      collectCCS ccs `thenMM_`
138                      returnMM ccs
139                 else 
140                      returnMM all_cafs_ccs)             `thenMM`  \ caf_ccs ->
141            set_prevailing_cc caf_ccs (do_expr body)     `thenMM`  \ body' ->
142            returnMM (StgRhsClosure caf_ccs bi srt fv u [] body')
143
144     do_top_rhs binder (StgRhsClosure cc bi srt fv u [] body)
145         -- Top level CAF with cost centre attached
146         -- Should this be a CAF cc ??? Does this ever occur ???
147       = pprPanic "SCCfinal: CAF with cc:" (ppr cc)
148
149 {- can't do this with cost-centre stacks:  --SDM
150     do_top_rhs binder (StgRhsClosure _ bi srt fv u args (StgSCC cc expr))
151       | not (isSccCountCostCentre cc)
152         -- Top level function with trivial _scc_ in body
153         -- Attach and collect cc of trivial _scc_
154       = collectCC cc                                    `thenMM_`
155         set_prevailing_cc cc (do_expr expr)             `thenMM` \ expr' ->
156         returnMM (StgRhsClosure cc bi srt fv u args expr')
157 -}
158
159     do_top_rhs binder (StgRhsClosure no_ccs bi srt fv u args body)
160         -- Top level function, probably subsumed
161       | noCCSAttached no_ccs
162       = set_lambda_cc (do_expr body)    `thenMM` \ body' ->
163         returnMM (StgRhsClosure subsumedCCS bi srt fv u args body')
164
165       | otherwise
166       = pprPanic "SCCfinal: CAF with cc:" (ppr no_ccs)
167
168     do_top_rhs binder (StgRhsCon ccs con args)
169         -- Top-level (static) data is not counted in heap
170         -- profiles; nor do we set CCCS from it; so we
171         -- just slam in dontCareCostCentre
172       = returnMM (StgRhsCon dontCareCCS con args)
173
174     ------
175     do_expr :: StgExpr -> MassageM StgExpr
176
177     do_expr (StgApp fn args)
178       = boxHigherOrderArgs (StgApp fn) args
179
180     do_expr (StgCon con args res_ty)
181       = boxHigherOrderArgs (\args -> StgCon con args res_ty) args
182
183     do_expr (StgSCC cc expr)    -- Ha, we found a cost centre!
184       = collectCC cc            `thenMM_`
185         do_expr expr            `thenMM` \ expr' ->
186         returnMM (StgSCC cc expr')
187
188     do_expr (StgCase expr fv1 fv2 bndr srt alts)
189       = do_expr expr            `thenMM` \ expr' ->
190         do_alts alts            `thenMM` \ alts' ->
191         returnMM (StgCase expr' fv1 fv2 bndr srt alts')
192       where
193         do_alts (StgAlgAlts ty alts def) 
194           = mapMM do_alt alts   `thenMM` \ alts' ->
195             do_deflt def        `thenMM` \ def' ->
196             returnMM (StgAlgAlts ty alts' def')
197           where
198             do_alt (id, bs, use_mask, e)
199               = do_expr e `thenMM` \ e' ->
200                 returnMM (id, bs, use_mask, e')
201
202         do_alts (StgPrimAlts ty alts def) 
203           = mapMM do_alt alts   `thenMM` \ alts' ->
204             do_deflt def        `thenMM` \ def' ->
205             returnMM (StgPrimAlts ty alts' def')
206           where
207             do_alt (l,e)
208               = do_expr e `thenMM` \ e' ->
209                 returnMM (l,e')
210
211         do_deflt StgNoDefault = returnMM StgNoDefault
212         do_deflt (StgBindDefault e) 
213           = do_expr e                   `thenMM` \ e' ->
214             returnMM (StgBindDefault e')
215
216     do_expr (StgLet b e)
217         = do_let b e `thenMM` \ (b,e) ->
218           returnMM (StgLet b e)
219
220     do_expr (StgLetNoEscape lvs1 lvs2 b e)
221         = do_let b e `thenMM` \ (b,e) ->
222           returnMM (StgLetNoEscape lvs1 lvs2 b e)
223
224     ----------------------------------
225
226     do_let (StgNonRec b rhs) e
227       = do_rhs rhs                      `thenMM` \ rhs' ->
228         addTopLevelIshId b (
229           do_expr e                     `thenMM` \ e' ->
230           returnMM (StgNonRec b rhs',e')
231         )
232
233     do_let (StgRec pairs) e
234       = addTopLevelIshIds binders (
235            mapMM do_pair pairs          `thenMM` \ pairs' ->
236            do_expr e                    `thenMM` \ e' ->
237            returnMM (StgRec pairs', e')
238         )
239       where
240         binders = map fst pairs
241         do_pair (b, rhs) 
242            = do_rhs rhs                 `thenMM` \ rhs2 ->
243              returnMM (b, rhs2)
244
245     ----------------------------------
246     do_rhs :: StgRhs -> MassageM StgRhs
247         -- We play much the same game as we did in do_top_rhs above;
248         -- but we don't have to worry about cafs etc.
249
250 {-
251     do_rhs (StgRhsClosure closure_cc bi srt fv u [] (StgSCC ty cc (StgCon (DataCon con) args _)))
252       | not (isSccCountCostCentre cc)
253       = collectCC cc `thenMM_`
254         returnMM (StgRhsCon cc con args)
255 -}
256
257 {-
258     do_rhs (StgRhsClosure _ bi srt fv u args (StgSCC ty cc expr))
259       | not (isSccCountCostCentre cc)
260       = collectCC cc                            `thenMM_`
261         set_prevailing_cc cc (do_expr expr)     `thenMM` \ expr' ->
262         returnMM (StgRhsClosure cc bi srt fv u args expr')
263 -}
264
265     do_rhs (StgRhsClosure cc bi srt fv u [] body)
266       = do_expr body                            `thenMM` \ body' ->
267         returnMM (StgRhsClosure currentCCS bi srt fv u [] body')
268
269     do_rhs (StgRhsClosure cc bi srt fv u args body)
270       = set_lambda_cc (do_expr body)            `thenMM` \ body' ->
271         get_prevailing_cc                       `thenMM` \ prev_ccs ->
272         returnMM (StgRhsClosure currentCCS bi srt fv u args body')
273
274     do_rhs (StgRhsCon cc con args)
275       = returnMM (StgRhsCon currentCCS con args)
276 \end{code}
277
278 %************************************************************************
279 %*                                                                      *
280 \subsection{Boxing higher-order args}
281 %*                                                                      *
282 %************************************************************************
283
284 Boxing is *turned off* at the moment, until we can figure out how to
285 do it properly in general.
286
287 \begin{code}
288 boxHigherOrderArgs
289     :: ([StgArg] -> StgExpr)
290                         -- An application lacking its arguments
291     -> [StgArg]         -- arguments which we might box
292     -> MassageM StgExpr
293
294 #ifndef PROF_DO_BOXING
295 boxHigherOrderArgs almost_expr args
296    = returnMM (almost_expr args)
297 #else
298 boxHigherOrderArgs almost_expr args
299   = getTopLevelIshIds           `thenMM` \ ids ->
300     mapAccumMM (do_arg ids) [] args     `thenMM` \ (let_bindings, new_args) ->
301     returnMM (foldr (mk_stg_let currentCCS) (almost_expr new_args) let_bindings)
302   where
303     ---------------
304     do_arg ids bindings atom@(StgConArg _) = returnMM (bindings, atom)
305
306     do_arg ids bindings atom@(StgVarArg old_var)
307       = let
308             var_type = idType old_var
309         in
310         if ( not (isLocallyDefinedName (idName old_var)) ||
311              elemVarSet old_var ids ) && isFunType var_type
312         then
313             -- make a trivial let-binding for the top-level function
314             getUniqueMM         `thenMM` \ uniq ->
315             let
316                 new_var = mkSysLocal SLIT("sf") uniq var_type
317             in
318             returnMM ( (new_var, old_var) : bindings, StgVarArg new_var )
319         else
320             returnMM (bindings, atom)
321
322     ---------------
323     mk_stg_let :: CostCentreStack -> (Id, Id) -> StgExpr -> StgExpr
324
325     mk_stg_let cc (new_var, old_var) body
326       = let
327             rhs_body    = StgApp old_var [{-args-}]
328             rhs_closure = StgRhsClosure cc stgArgOcc NoSRT [{-fvs-}] ReEntrant [{-args-}] rhs_body
329         in
330         StgLet (StgNonRec new_var rhs_closure) body
331       where
332         bOGUS_LVs = emptyUniqSet -- easier to print than: panic "mk_stg_let: LVs"
333
334 isFunType var_type 
335   = case splitForAllTys var_type of
336         (_, ty) -> case splitTyConApp_maybe ty of
337                         Just (tycon,_) | isFunTyCon tycon -> True
338                         _ -> False
339 #endif
340 \end{code}
341
342 %************************************************************************
343 %*                                                                      *
344 \subsection{Boring monad stuff for this}
345 %*                                                                      *
346 %************************************************************************
347
348 \begin{code}
349 type MassageM result
350   =  Module             -- module name
351   -> CostCentreStack    -- prevailing CostCentre
352                         -- if none, subsumedCosts at top-level
353                         -- useCurrentCostCentre at nested levels
354   -> UniqSupply
355   -> VarSet             -- toplevel-ish Ids for boxing
356   -> CollectedCCs
357   -> (CollectedCCs, result)
358
359 -- the initMM function also returns the final CollectedCCs
360
361 initMM :: Module        -- module name, which we may consult
362        -> UniqSupply
363        -> MassageM a
364        -> (CollectedCCs, a)
365
366 initMM mod_name init_us m = m mod_name noCCS init_us emptyVarSet ([],[],[])
367
368 thenMM  :: MassageM a -> (a -> MassageM b) -> MassageM b
369 thenMM_ :: MassageM a -> (MassageM b) -> MassageM b
370
371 thenMM expr cont mod scope_cc us ids ccs
372   = case splitUniqSupply us     of { (s1, s2) ->
373     case (expr mod scope_cc s1 ids ccs) of { (ccs2, result) ->
374     cont result mod scope_cc s2 ids ccs2 }}
375
376 thenMM_ expr cont mod scope_cc us ids ccs
377   = case splitUniqSupply us     of { (s1, s2) ->
378     case (expr mod scope_cc s1 ids ccs) of { (ccs2, _) ->
379     cont mod scope_cc s2 ids ccs2 }}
380
381 returnMM :: a -> MassageM a
382 returnMM result mod scope_cc us ids ccs = (ccs, result)
383
384 nopMM :: MassageM ()
385 nopMM mod scope_cc us ids ccs = (ccs, ())
386
387 mapMM :: (a -> MassageM b) -> [a] -> MassageM [b]
388 mapMM f [] = returnMM []
389 mapMM f (m:ms)
390   = f m         `thenMM` \ r  ->
391     mapMM f ms  `thenMM` \ rs ->
392     returnMM (r:rs)
393
394 mapAccumMM :: (acc -> x -> MassageM (acc, y)) -> acc -> [x] -> MassageM (acc, [y])
395 mapAccumMM f b [] = returnMM (b, [])
396 mapAccumMM f b (m:ms)
397   = f b m               `thenMM` \ (b2, r)  ->
398     mapAccumMM f b2 ms  `thenMM` \ (b3, rs) ->
399     returnMM (b3, r:rs)
400
401 getUniqueMM :: MassageM Unique
402 getUniqueMM mod scope_cc us ids ccs = (ccs, uniqFromSupply us)
403
404 addTopLevelIshId :: Id -> MassageM a -> MassageM a
405 addTopLevelIshId id scope mod scope_cc us ids ccs
406   | isCurrentCCS scope_cc = scope mod scope_cc us ids ccs
407   | otherwise             = scope mod scope_cc us (extendVarSet ids id) ccs
408
409 addTopLevelIshIds :: [Id] -> MassageM a -> MassageM a
410 addTopLevelIshIds [] cont = cont
411 addTopLevelIshIds (id:ids) cont 
412   = addTopLevelIshId id (addTopLevelIshIds ids cont)
413
414 getTopLevelIshIds :: MassageM VarSet
415 getTopLevelIshIds mod scope_cc us ids ccs = (ccs, ids)
416 \end{code}
417
418 The prevailing CCS is used to tell whether we're in a top-levelish
419 position, where top-levelish is defined as "not inside a lambda".
420 Prevailing CCs used to be used for something much more complicated,
421 I'm sure --SDM
422
423 \begin{code}
424 set_lambda_cc :: MassageM a -> MassageM a
425 set_lambda_cc action mod scope_cc us ids ccs
426   = action mod currentCCS us ids ccs
427
428 set_prevailing_cc :: CostCentreStack -> MassageM a -> MassageM a
429 set_prevailing_cc cc_to_set_to action mod scope_cc us ids ccs
430   = action mod cc_to_set_to us ids ccs
431
432 get_prevailing_cc :: MassageM CostCentreStack
433 get_prevailing_cc mod scope_cc us ids ccs = (ccs, scope_cc)
434 \end{code}
435
436 \begin{code}
437 collectCC :: CostCentre -> MassageM ()
438
439 collectCC cc mod_name scope_cc us ids (local_ccs, extern_ccs, ccss)
440   = ASSERT(not (noCCAttached cc))
441     if (cc `ccFromThisModule` mod_name) then
442         ((cc : local_ccs, extern_ccs, ccss), ())
443     else -- must declare it "extern"
444         ((local_ccs, cc : extern_ccs, ccss), ())
445
446 collectCCS :: CostCentreStack -> MassageM ()
447
448 collectCCS ccs mod_name scope_cc us ids (local_ccs, extern_ccs, ccss)
449   = ASSERT(not (noCCSAttached ccs))
450     ((local_ccs, extern_ccs, ccs : ccss), ())
451 \end{code}