87f560b575900434f8dc43628c607224cacdab7b
[ghc-hetmet.git] / ghc / compiler / stranal / WorkWrap.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[WorkWrap]{Worker/wrapper-generating back-end of strictness analyser}
5
6 \begin{code}
7 module WorkWrap ( wwTopBinds, mkWrapper ) where
8
9 #include "HsVersions.h"
10
11 import CoreSyn
12 import CoreUnfold       ( Unfolding, certainlyWillInline )
13 import CmdLineOpts      ( opt_UF_CreationThreshold , opt_D_verbose_core2core, 
14                           opt_D_dump_worker_wrapper
15                         )
16 import CoreLint         ( beginPass, endPass )
17 import CoreUtils        ( exprType, exprArity, exprEtaExpandArity )
18 import DataCon          ( DataCon )
19 import MkId             ( mkWorkerId )
20 import Id               ( Id, idType, idStrictness, setIdArityInfo, isOneShotLambda,
21                           setIdStrictness, idInlinePragma, 
22                           setIdWorkerInfo, idCprInfo, setInlinePragma )
23 import VarSet
24 import Type             ( Type, isNewType, splitForAllTys, splitFunTys )
25 import IdInfo           ( mkStrictnessInfo, noStrictnessInfo, StrictnessInfo(..),
26                           CprInfo(..), exactArity, InlinePragInfo(..), isNeverInlinePrag,
27                           WorkerInfo(..)
28                         )
29 import Demand           ( Demand, wwLazy )
30 import SaLib
31 import UniqSupply       ( UniqSupply, initUs_, returnUs, thenUs, mapUs, getUniqueUs, UniqSM )
32 import UniqSet
33 import WwLib
34 import Outputable
35 \end{code}
36
37 We take Core bindings whose binders have:
38
39 \begin{enumerate}
40
41 \item Strictness attached (by the front-end of the strictness
42 analyser), and / or
43
44 \item Constructed Product Result information attached by the CPR
45 analysis pass.
46
47 \end{enumerate}
48
49 and we return some ``plain'' bindings which have been
50 worker/wrapper-ified, meaning: 
51
52 \begin{enumerate} 
53
54 \item Functions have been split into workers and wrappers where
55 appropriate.  If a function has both strictness and CPR properties
56 then only one worker/wrapper doing both transformations is produced;
57
58 \item Binders' @IdInfos@ have been updated to reflect the existence of
59 these workers/wrappers (this is where we get STRICTNESS and CPR pragma
60 info for exported values).
61 \end{enumerate}
62
63 \begin{code}
64
65 wwTopBinds :: UniqSupply
66              -> [CoreBind]
67              -> IO [CoreBind]
68
69 wwTopBinds us binds
70   = do {
71         beginPass "Worker Wrapper binds";
72
73         -- Create worker/wrappers, and mark binders with their
74         -- "strictness info" [which encodes their worker/wrapper-ness]
75         let { binds' = workersAndWrappers us binds };
76
77         endPass "Worker Wrapper binds" (opt_D_dump_worker_wrapper || 
78                                         opt_D_verbose_core2core) binds'
79     }
80 \end{code}
81
82
83 \begin{code}
84 workersAndWrappers :: UniqSupply -> [CoreBind] -> [CoreBind]
85
86 workersAndWrappers us top_binds
87   = initUs_ us $
88     mapUs wwBind top_binds `thenUs` \ top_binds' ->
89     returnUs (concat top_binds')
90 \end{code}
91
92 %************************************************************************
93 %*                                                                      *
94 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
95 %*                                                                      *
96 %************************************************************************
97
98 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
99 turn.  Non-recursive case first, then recursive...
100
101 \begin{code}
102 wwBind  :: CoreBind
103         -> UniqSM [CoreBind]    -- returns a WwBinding intermediate form;
104                                 -- the caller will convert to Expr/Binding,
105                                 -- as appropriate.
106
107 wwBind (NonRec binder rhs)
108   = wwExpr rhs                                          `thenUs` \ new_rhs ->
109     tryWW True {- non-recursive -} binder new_rhs       `thenUs` \ new_pairs ->
110     returnUs [NonRec b e | (b,e) <- new_pairs]
111       -- Generated bindings must be non-recursive
112       -- because the original binding was.
113
114 ------------------------------
115
116 wwBind (Rec pairs)
117   = mapUs do_one pairs          `thenUs` \ new_pairs ->
118     returnUs [Rec (concat new_pairs)]
119   where
120     do_one (binder, rhs) = wwExpr rhs   `thenUs` \ new_rhs ->
121                            tryWW False {- recursive -} binder new_rhs
122 \end{code}
123
124 @wwExpr@ basically just walks the tree, looking for appropriate
125 annotations that can be used. Remember it is @wwBind@ that does the
126 matching by looking for strict arguments of the correct type.
127 @wwExpr@ is a version that just returns the ``Plain'' Tree.
128
129 \begin{code}
130 wwExpr :: CoreExpr -> UniqSM CoreExpr
131
132 wwExpr e@(Type _)   = returnUs e
133 wwExpr e@(Var _)    = returnUs e
134 wwExpr e@(Lit _)    = returnUs e
135
136 wwExpr (Lam binder expr)
137   = wwExpr expr                 `thenUs` \ new_expr ->
138     returnUs (Lam binder new_expr)
139
140 wwExpr (App f a)
141   = wwExpr f                    `thenUs` \ new_f ->
142     wwExpr a                    `thenUs` \ new_a ->
143     returnUs (App new_f new_a)
144
145 wwExpr (Note note expr)
146   = wwExpr expr                 `thenUs` \ new_expr ->
147     returnUs (Note note new_expr)
148
149 wwExpr (Let bind expr)
150   = wwBind bind                 `thenUs` \ intermediate_bind ->
151     wwExpr expr                 `thenUs` \ new_expr ->
152     returnUs (mkLets intermediate_bind new_expr)
153
154 wwExpr (Case expr binder alts)
155   = wwExpr expr                         `thenUs` \ new_expr ->
156     mapUs ww_alt alts                   `thenUs` \ new_alts ->
157     returnUs (Case new_expr binder new_alts)
158   where
159     ww_alt (con, binders, rhs)
160       = wwExpr rhs                      `thenUs` \ new_rhs ->
161         returnUs (con, binders, new_rhs)
162 \end{code}
163
164 %************************************************************************
165 %*                                                                      *
166 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
167 %*                                                                      *
168 %************************************************************************
169
170 @tryWW@ just accumulates arguments, converts strictness info from the
171 front-end into the proper form, then calls @mkWwBodies@ to do
172 the business.
173
174 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
175 already been w-w'd!  (You can end up with several liked-named Ids
176 bouncing around at the same time---absolute mischief.)  So the
177 criterion we use is: if an Id already has an unfolding (for whatever
178 reason), then we don't w-w it.
179
180 The only reason this is monadised is for the unique supply.
181
182 \begin{code}
183 tryWW   :: Bool                         -- True <=> a non-recursive binding
184         -> Id                           -- The fn binder
185         -> CoreExpr                     -- The bound rhs; its innards
186                                         --   are already ww'd
187         -> UniqSM [(Id, CoreExpr)]      -- either *one* or *two* pairs;
188                                         -- if one, then no worker (only
189                                         -- the orig "wrapper" lives on);
190                                         -- if two, then a worker and a
191                                         -- wrapper.
192 tryWW non_rec fn_id rhs
193   | isNeverInlinePrag inline_prag
194   =     -- Don't split things that will never be inlined
195     returnUs [ (fn_id, rhs) ]
196
197   | non_rec && certainlyWillInline fn_id
198         -- No point in worker/wrappering something that is going to be
199         -- INLINEd wholesale anyway.  If the strictness analyser is run
200         -- twice, this test also prevents wrappers (which are INLINEd)
201         -- from being re-done.
202         --
203         -- OUT OF DATE NOTE, kept for info:
204         --   In this case we add an INLINE pragma to the RHS.  Why?
205         --   Because consider
206         --        f = \x -> g x x
207         --        g = \yz -> ...                -- And g is strict
208         --   Then f is small, so we don't w/w it.  But g is big, and we do, so
209         --   g's wrapper will get inlined in f's RHS, which makes f look big now.
210         --   So f doesn't get inlined, but it is strict and we have failed to w/w it.
211         -- It's out of date because now wrappers look very cheap 
212         -- even when they are inlined.
213   = returnUs [ (fn_id, rhs) ]
214
215   | not (do_strict_ww || do_cpr_ww || do_coerce_ww)
216   = returnUs [ (fn_id, rhs) ]
217
218   | otherwise           -- Do w/w split
219   = mkWwBodies fun_ty arity wrap_dmds result_bot one_shots cpr_info     `thenUs` \ (work_demands, wrap_fn, work_fn) ->
220     getUniqueUs                                                         `thenUs` \ work_uniq ->
221     let
222         work_rhs      = work_fn rhs
223         proto_work_id = mkWorkerId work_uniq fn_id (exprType work_rhs) 
224                         `setInlinePragma` inline_prag
225
226         work_id | has_strictness = proto_work_id `setIdStrictness` mkStrictnessInfo (work_demands, result_bot)
227                 | otherwise      = proto_work_id
228
229         wrap_arity = exprArity wrap_rhs         -- Might be greater than the current visible arity
230                                                 -- if the function returns bottom
231                                                 
232         wrap_rhs = wrap_fn work_id
233         wrap_id  = fn_id `setIdStrictness`      wrapper_strictness
234                          `setIdWorkerInfo`      HasWorker work_id wrap_arity
235                          `setIdArityInfo`       exactArity wrap_arity
236                          `setInlinePragma`      NoInlinePragInfo        -- Put it on the worker instead
237                 -- Add info to the wrapper:
238                 --      (a) we want to set its arity
239                 --      (b) we want to pin on its revised strictness info
240                 --      (c) we pin on its worker id 
241     in
242     returnUs ([(work_id, work_rhs), (wrap_id, wrap_rhs)])
243         -- Worker first, because wrapper mentions it
244         -- Arrange to inline the wrapper unconditionally
245   where
246     fun_ty = idType fn_id
247     arity  = exprEtaExpandArity rhs
248
249         -- Don't split something which is marked unconditionally NOINLINE
250     inline_prag  = idInlinePragma fn_id
251
252     strictness_info           = idStrictness fn_id
253     has_strictness            = case strictness_info of
254                                         StrictnessInfo _ _ -> True
255                                         NoStrictnessInfo   -> False
256     (arg_demands, result_bot) = case strictness_info of
257                                         StrictnessInfo d r -> (d,  r)
258                                         NoStrictnessInfo   -> ([], False)
259
260     wrap_dmds = setUnpackStrategy arg_demands
261     do_strict_ww = WARN( has_strictness && not result_bot && arity < length arg_demands && worthSplitting wrap_dmds result_bot, 
262                          text "Insufficient arity" <+> ppr fn_id <+> ppr arity <+> ppr arg_demands )
263                     (result_bot || arity >= length arg_demands) -- Only if there's enough visible arity
264                  &&                                             -- (else strictness info isn't valid)
265                                                                 -- 
266                     worthSplitting wrap_dmds result_bot         -- And it's useful
267         -- worthSplitting returns False for an empty list of demands,
268         -- and hence do_strict_ww is False if arity is zero
269         -- Also it's false if there is no strictness (arg_demands is [])
270
271     wrapper_strictness | has_strictness = mkStrictnessInfo (wrap_dmds, result_bot)
272                        | otherwise      = noStrictnessInfo
273
274         -------------------------------------------------------------
275     cpr_info  = idCprInfo fn_id
276     do_cpr_ww = arity > 0 &&
277                 case cpr_info of
278                         ReturnsCPR -> True
279                         other      -> False
280
281         -------------------------------------------------------------
282     do_coerce_ww = check_for_coerce arity fun_ty
283         -- We are willing to do a w/w even if the arity is zero.
284         --      x = coerce t E
285         -- ==>
286         --      x' = E
287         --      x  = coerce t x'
288
289         -------------------------------------------------------------
290     one_shots = get_one_shots rhs
291
292 -- See if there's a Coerce before we run out of arity;
293 -- if so, it's worth trying a w/w split.  Reason: we find
294 -- functions like       f = coerce (\s -> e)
295 --           and        g = \x -> coerce (\s -> e)
296 -- and they may have no useful strictness or cpr info, but if we
297 -- do the w/w thing we get rid of the coerces.  
298
299 check_for_coerce arity ty
300   = length arg_tys <= arity && isNewType res_ty
301         -- Don't look further than arity args, 
302         -- but if there are arity or fewer, see if there's
303         -- a newtype in the corner
304   where
305     (_, tau)          = splitForAllTys ty
306     (arg_tys, res_ty) = splitFunTys tau
307
308 -- If the original function has one-shot arguments, it is important to
309 -- make the wrapper and worker have corresponding one-shot arguments too.
310 -- Otherwise we spuriously float stuff out of case-expression join points,
311 -- which is very annoying.
312 get_one_shots (Lam b e)
313   | isId b    = isOneShotLambda b : get_one_shots e
314   | otherwise = get_one_shots e
315 get_one_shots (Note _ e) = get_one_shots e
316 get_one_shots other      = noOneShotInfo
317 \end{code}
318
319
320
321 %************************************************************************
322 %*                                                                      *
323 \subsection{The worker wrapper core}
324 %*                                                                      *
325 %************************************************************************
326
327 @mkWrapper@ is called when importing a function.  We have the type of 
328 the function and the name of its worker, and we want to make its body (the wrapper).
329
330 \begin{code}
331 mkWrapper :: Type               -- Wrapper type
332           -> Int                -- Arity
333           -> [Demand]           -- Wrapper strictness info
334           -> Bool               -- Function returns bottom
335           -> CprInfo            -- Wrapper cpr info
336           -> UniqSM (Id -> CoreExpr)    -- Wrapper body, missing worker Id
337
338 mkWrapper fun_ty arity demands res_bot cpr_info
339   = mkWwBodies fun_ty arity demands res_bot noOneShotInfo cpr_info      `thenUs` \ (_, wrap_fn, _) ->
340     returnUs wrap_fn
341
342 noOneShotInfo = repeat False
343 \end{code}
344
345