[project @ 1999-04-08 15:46:12 by simonm]
[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 -> FAST_STRING        -- module name, group name
57         -> UniqSupply                   -- unique supply
58         -> [StgBinding]                 -- input
59         -> (CollectedCCs, [StgBinding])
60
61 stgMassageForProfiling mod_name grp_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 grp_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 grp_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         let new_ccs | isCurrentCCS prev_ccs = setCurrentCCS -- are we inside a lambda??
273                     | otherwise             = currentCCS
274         in
275         returnMM (StgRhsClosure new_ccs bi srt fv u args body')
276
277     do_rhs (StgRhsCon cc con args)
278       = returnMM (StgRhsCon currentCCS con args)
279 \end{code}
280
281 %************************************************************************
282 %*                                                                      *
283 \subsection{Boxing higher-order args}
284 %*                                                                      *
285 %************************************************************************
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 boxHigherOrderArgs almost_expr args
295   = getTopLevelIshIds           `thenMM` \ ids ->
296     mapAccumMM (do_arg ids) [] args     `thenMM` \ (let_bindings, new_args) ->
297     returnMM (foldr (mk_stg_let currentCCS) (almost_expr new_args) let_bindings)
298   where
299     ---------------
300     do_arg ids bindings atom@(StgConArg _) = returnMM (bindings, atom)
301
302     do_arg ids bindings atom@(StgVarArg old_var)
303       = let
304             var_type = idType old_var
305         in
306         if ( not (isLocallyDefinedName (idName old_var)) ||
307              elemVarSet old_var ids ) && isFunType var_type
308         then
309             -- make a trivial let-binding for the top-level function
310             getUniqueMM         `thenMM` \ uniq ->
311             let
312                 new_var = mkSysLocal SLIT("sf") uniq var_type
313             in
314             returnMM ( (new_var, old_var) : bindings, StgVarArg new_var )
315         else
316             returnMM (bindings, atom)
317
318     ---------------
319     mk_stg_let :: CostCentreStack -> (Id, Id) -> StgExpr -> StgExpr
320
321     mk_stg_let cc (new_var, old_var) body
322       = let
323             rhs_body    = StgApp old_var [{-args-}]
324             rhs_closure = StgRhsClosure cc stgArgOcc NoSRT [{-fvs-}] ReEntrant [{-args-}] rhs_body
325         in
326         StgLet (StgNonRec new_var rhs_closure) body
327       where
328         bOGUS_LVs = emptyUniqSet -- easier to print than: panic "mk_stg_let: LVs"
329
330 isFunType var_type 
331   = case splitForAllTys var_type of
332         (_, ty) -> case splitTyConApp_maybe ty of
333                         Just (tycon,_) | isFunTyCon tycon -> True
334                         _ -> False
335
336 \end{code}
337
338 %************************************************************************
339 %*                                                                      *
340 \subsection{Boring monad stuff for this}
341 %*                                                                      *
342 %************************************************************************
343
344 \begin{code}
345 type MassageM result
346   =  Module             -- module name
347   -> CostCentreStack    -- prevailing CostCentre
348                         -- if none, subsumedCosts at top-level
349                         -- useCurrentCostCentre at nested levels
350   -> UniqSupply
351   -> VarSet             -- toplevel-ish Ids for boxing
352   -> CollectedCCs
353   -> (CollectedCCs, result)
354
355 -- the initUs function also returns the final UniqueSupply and CollectedCCs
356
357 initMM :: Module        -- module name, which we may consult
358        -> UniqSupply
359        -> MassageM a
360        -> (CollectedCCs, a)
361
362 initMM mod_name init_us m = m mod_name noCCS init_us emptyVarSet ([],[],[])
363
364 thenMM  :: MassageM a -> (a -> MassageM b) -> MassageM b
365 thenMM_ :: MassageM a -> (MassageM b) -> MassageM b
366
367 thenMM expr cont mod scope_cc us ids ccs
368   = case splitUniqSupply us     of { (s1, s2) ->
369     case (expr mod scope_cc s1 ids ccs) of { (ccs2, result) ->
370     cont result mod scope_cc s2 ids ccs2 }}
371
372 thenMM_ expr cont mod scope_cc us ids ccs
373   = case splitUniqSupply us     of { (s1, s2) ->
374     case (expr mod scope_cc s1 ids ccs) of { (ccs2, _) ->
375     cont mod scope_cc s2 ids ccs2 }}
376
377 returnMM :: a -> MassageM a
378 returnMM result mod scope_cc us ids ccs = (ccs, result)
379
380 nopMM :: MassageM ()
381 nopMM mod scope_cc us ids ccs = (ccs, ())
382
383 mapMM :: (a -> MassageM b) -> [a] -> MassageM [b]
384 mapMM f [] = returnMM []
385 mapMM f (m:ms)
386   = f m         `thenMM` \ r  ->
387     mapMM f ms  `thenMM` \ rs ->
388     returnMM (r:rs)
389
390 mapAccumMM :: (acc -> x -> MassageM (acc, y)) -> acc -> [x] -> MassageM (acc, [y])
391 mapAccumMM f b [] = returnMM (b, [])
392 mapAccumMM f b (m:ms)
393   = f b m               `thenMM` \ (b2, r)  ->
394     mapAccumMM f b2 ms  `thenMM` \ (b3, rs) ->
395     returnMM (b3, r:rs)
396
397 getUniqueMM :: MassageM Unique
398 getUniqueMM mod scope_cc us ids ccs = (ccs, uniqFromSupply us)
399
400 addTopLevelIshId :: Id -> MassageM a -> MassageM a
401 addTopLevelIshId id scope mod scope_cc us ids ccs
402   | isCurrentCCS scope_cc = scope mod scope_cc us ids ccs
403   | otherwise             = scope mod scope_cc us (extendVarSet ids id) ccs
404
405 addTopLevelIshIds :: [Id] -> MassageM a -> MassageM a
406 addTopLevelIshIds [] cont = cont
407 addTopLevelIshIds (id:ids) cont 
408   = addTopLevelIshId id (addTopLevelIshIds ids cont)
409
410 getTopLevelIshIds :: MassageM VarSet
411 getTopLevelIshIds mod scope_cc us ids ccs = (ccs, ids)
412 \end{code}
413
414 The prevailing CCS is used to tell whether we're in a top-levelish
415 position, where top-levelish is defined as "not inside a lambda".
416 Prevailing CCs used to be used for something much more complicated,
417 I'm sure --SDM
418
419 \begin{code}
420 set_lambda_cc :: MassageM a -> MassageM a
421 set_lambda_cc action mod scope_cc us ids ccs
422   = action mod currentCCS us ids ccs
423
424 set_prevailing_cc :: CostCentreStack -> MassageM a -> MassageM a
425 set_prevailing_cc cc_to_set_to action mod scope_cc us ids ccs
426   = action mod cc_to_set_to us ids ccs
427
428 get_prevailing_cc :: MassageM CostCentreStack
429 get_prevailing_cc mod scope_cc us ids ccs = (ccs, scope_cc)
430 \end{code}
431
432 \begin{code}
433 collectCC :: CostCentre -> MassageM ()
434
435 collectCC cc mod_name scope_cc us ids (local_ccs, extern_ccs, ccss)
436   = ASSERT(not (noCCAttached cc))
437     if (cc `ccFromThisModule` mod_name) then
438         ((cc : local_ccs, extern_ccs, ccss), ())
439     else -- must declare it "extern"
440         ((local_ccs, cc : extern_ccs, ccss), ())
441
442 collectCCS :: CostCentreStack -> MassageM ()
443
444 collectCCS ccs mod_name scope_cc us ids (local_ccs, extern_ccs, ccss)
445   = ASSERT(not (noCCSAttached ccs))
446     ((local_ccs, extern_ccs, ccs : ccss), ())
447 \end{code}