[project @ 2001-10-24 08:33:25 by simonpj]
[ghc-hetmet.git] / ghc / compiler / stranal / WwLib.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[WwLib]{A library for the ``worker/wrapper'' back-end to the strictness analyser}
5
6 \begin{code}
7 module WwLib ( mkWwBodies, mkWWstr ) where
8
9 #include "HsVersions.h"
10
11 import CoreSyn
12 import CoreUtils        ( exprType )
13 import Id               ( Id, idType, mkSysLocal, idNewDemandInfo, setIdNewDemandInfo,
14                           isOneShotLambda, setOneShotLambda, setIdUnfolding,
15                           setIdInfo
16                         )
17 import IdInfo           ( vanillaIdInfo )
18 import DataCon          ( splitProductType_maybe, splitProductType )
19 import NewDemand        ( Demand(..), Keepity(..), DmdResult(..) ) 
20 import DmdAnal          ( both )
21 import PrelInfo         ( eRROR_CSTRING_ID )
22 import TysPrim          ( realWorldStatePrimTy )
23 import TysWiredIn       ( tupleCon )
24 import Type             ( Type, isUnLiftedType, mkFunTys,
25                           splitForAllTys, splitFunTys, splitNewType_maybe, isAlgType
26                         )
27 import Literal          ( Literal(MachStr) )
28 import BasicTypes       ( Boxity(..) )
29 import Var              ( Var, isId )
30 import UniqSupply       ( returnUs, thenUs, getUniqueUs, getUniquesUs, UniqSM )
31 import Util             ( zipWithEqual )
32 import Outputable
33 import List             ( zipWith4 )
34 \end{code}
35
36
37 %************************************************************************
38 %*                                                                      *
39 \subsection[mkWrapperAndWorker]{@mkWrapperAndWorker@}
40 %*                                                                      *
41 %************************************************************************
42
43 Here's an example.  The original function is:
44
45 \begin{verbatim}
46 g :: forall a . Int -> [a] -> a
47
48 g = /\ a -> \ x ys ->
49         case x of
50           0 -> head ys
51           _ -> head (tail ys)
52 \end{verbatim}
53
54 From this, we want to produce:
55 \begin{verbatim}
56 -- wrapper (an unfolding)
57 g :: forall a . Int -> [a] -> a
58
59 g = /\ a -> \ x ys ->
60         case x of
61           I# x# -> $wg a x# ys
62             -- call the worker; don't forget the type args!
63
64 -- worker
65 $wg :: forall a . Int# -> [a] -> a
66
67 $wg = /\ a -> \ x# ys ->
68         let
69             x = I# x#
70         in
71             case x of               -- note: body of g moved intact
72               0 -> head ys
73               _ -> head (tail ys)
74 \end{verbatim}
75
76 Something we have to be careful about:  Here's an example:
77
78 \begin{verbatim}
79 -- "f" strictness: U(P)U(P)
80 f (I# a) (I# b) = a +# b
81
82 g = f   -- "g" strictness same as "f"
83 \end{verbatim}
84
85 \tr{f} will get a worker all nice and friendly-like; that's good.
86 {\em But we don't want a worker for \tr{g}}, even though it has the
87 same strictness as \tr{f}.  Doing so could break laziness, at best.
88
89 Consequently, we insist that the number of strictness-info items is
90 exactly the same as the number of lambda-bound arguments.  (This is
91 probably slightly paranoid, but OK in practice.)  If it isn't the
92 same, we ``revise'' the strictness info, so that we won't propagate
93 the unusable strictness-info into the interfaces.
94
95
96 %************************************************************************
97 %*                                                                      *
98 \subsection{The worker wrapper core}
99 %*                                                                      *
100 %************************************************************************
101
102 @mkWwBodies@ is called when doing the worker/wrapper split inside a module.
103
104 \begin{code}
105 mkWwBodies :: Type                              -- Type of original function
106            -> [Demand]                          -- Strictness of original function
107            -> DmdResult                         -- Info about function result
108            -> [Bool]                            -- One-shot-ness of the function
109            -> UniqSM ([Demand],                 -- Demands for worker (value) args
110                       Id -> CoreExpr,           -- Wrapper body, lacking only the worker Id
111                       CoreExpr -> CoreExpr)     -- Worker body, lacking the original function rhs
112
113 -- wrap_fn_args E       = \x y -> E
114 -- work_fn_args E       = E x y
115
116 -- wrap_fn_str E        = case x of { (a,b) -> 
117 --                        case a of { (a1,a2) ->
118 --                        E a1 a2 b y }}
119 -- work_fn_str E        = \a2 a2 b y ->
120 --                        let a = (a1,a2) in
121 --                        let x = (a,b) in
122 --                        E
123
124 mkWwBodies fun_ty demands res_info one_shots
125   = mkWWargs fun_ty demands one_shots'  `thenUs` \ (wrap_args,   wrap_fn_args, work_fn_args, res_ty) ->
126     mkWWcpr res_ty res_info             `thenUs` \ (wrap_fn_cpr, work_fn_cpr,  cpr_res_ty) ->
127     mkWWstr wrap_args                   `thenUs` \ (work_args,   wrap_fn_str,  work_fn_str) ->
128     hackWorkArgs work_args cpr_res_ty   `thenUs` \ work_args' ->
129
130     returnUs ([idNewDemandInfo v | v <- work_args, isId v],
131               Note InlineMe . wrap_fn_args . wrap_fn_cpr . wrap_fn_str . applyToVars work_args' . Var,
132               mkLams work_args' . work_fn_str . work_fn_cpr . work_fn_args)
133         -- We use an INLINE unconditionally, even if the wrapper turns out to be
134         -- something trivial like
135         --      fw = ...
136         --      f = __inline__ (coerce T fw)
137         -- The point is to propagate the coerce to f's call sites, so even though
138         -- f's RHS is now trivial (size 1) we still want the __inline__ to prevent
139         -- fw from being inlined into f's RHS
140   where
141     one_shots' = one_shots ++ repeat False
142
143         -- Horrid special case.  If the worker would have no arguments, and the
144         -- function returns a primitive type value, that would make the worker into
145         -- an unboxed value.  We box it by passing a dummy void argument, thus:
146         --
147         --      f = /\abc. \xyz. fw abc void
148         --      fw = /\abc. \v. body
149         --
150         -- We use the state-token type which generates no code
151 hackWorkArgs work_args res_ty
152   | any isId work_args || not (isUnLiftedType res_ty) 
153   = returnUs work_args
154   | otherwise
155   = getUniqueUs                 `thenUs` \ void_arg_uniq ->
156     let
157         void_arg = mk_ww_local void_arg_uniq realWorldStatePrimTy
158     in
159     returnUs (work_args ++ [void_arg])
160 \end{code}
161
162
163 %************************************************************************
164 %*                                                                      *
165 \subsection{Coercion stuff}
166 %*                                                                      *
167 %************************************************************************
168
169
170 We really want to "look through" coerces.
171 Reason: I've seen this situation:
172
173         let f = coerce T (\s -> E)
174         in \x -> case x of
175                     p -> coerce T' f
176                     q -> \s -> E2
177                     r -> coerce T' f
178
179 If only we w/w'd f, we'd get
180         let f = coerce T (\s -> fw s)
181             fw = \s -> E
182         in ...
183
184 Now we'll inline f to get
185
186         let fw = \s -> E
187         in \x -> case x of
188                     p -> fw
189                     q -> \s -> E2
190                     r -> fw
191
192 Now we'll see that fw has arity 1, and will arity expand
193 the \x to get what we want.
194
195 \begin{code}
196 -- mkWWargs is driven off the function type and arity.
197 -- It chomps bites off foralls, arrows, newtypes
198 -- and keeps repeating that until it's satisfied the supplied arity
199
200 mkWWargs :: Type
201          -> [Demand]
202          -> [Bool]                      -- True for a one-shot arg; ** may be infinite **
203          -> UniqSM  ([Var],             -- Wrapper args
204                      CoreExpr -> CoreExpr,      -- Wrapper fn
205                      CoreExpr -> CoreExpr,      -- Worker fn
206                      Type)                      -- Type of wrapper body
207
208 mkWWargs fun_ty demands one_shots
209   | Just rep_ty <- splitNewType_maybe fun_ty
210         -- The newtype case is for when the function has
211         -- a recursive newtype after the arrow (rare)
212         -- We check for arity >= 0 to avoid looping in the case
213         -- of a function whose type is, in effect, infinite
214         -- [Arity is driven by looking at the term, not just the type.]
215         --
216         -- It's also important when we have a function returning (say) a pair
217         -- wrapped in a recursive newtype, at least if CPR analysis can look 
218         -- through such newtypes, which it probably can since they are 
219         -- simply coerces.
220   = mkWWargs rep_ty demands one_shots   `thenUs` \ (wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
221     returnUs (wrap_args,
222               Note (Coerce fun_ty rep_ty) . wrap_fn_args,
223               work_fn_args . Note (Coerce rep_ty fun_ty),
224               res_ty)
225
226   | not (null demands)
227   = getUniquesUs                `thenUs` \ wrap_uniqs ->
228     let
229       (tyvars, tau)             = splitForAllTys fun_ty
230       (arg_tys, body_ty)        = splitFunTys tau
231
232       n_demands = length demands
233       n_arg_tys = length arg_tys
234       n_args    = n_demands `min` n_arg_tys
235
236       new_fun_ty    = mkFunTys (drop n_demands arg_tys) body_ty
237       new_demands   = drop n_arg_tys demands
238       new_one_shots = drop n_args one_shots
239
240       val_args  = zipWith4 mk_wrap_arg wrap_uniqs arg_tys demands one_shots
241       wrap_args = tyvars ++ val_args
242     in
243 {-     ASSERT( not (null tyvars) || not (null arg_tys) ) -}
244     if (null tyvars) && (null arg_tys) then
245         pprTrace "mkWWargs" (ppr fun_ty $$ ppr demands) 
246                 returnUs ([], id, id, fun_ty)
247         else
248
249     mkWWargs new_fun_ty
250              new_demands
251              new_one_shots      `thenUs` \ (more_wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
252
253     returnUs (wrap_args ++ more_wrap_args,
254               mkLams wrap_args . wrap_fn_args,
255               work_fn_args . applyToVars wrap_args,
256               res_ty)
257
258   | otherwise
259   = returnUs ([], id, id, fun_ty)
260
261
262 applyToVars :: [Var] -> CoreExpr -> CoreExpr
263 applyToVars vars fn = mkVarApps fn vars
264
265 mk_wrap_arg uniq ty dmd one_shot 
266   = set_one_shot one_shot (setIdNewDemandInfo (mkSysLocal SLIT("w") uniq ty) dmd)
267   where
268     set_one_shot True  id = setOneShotLambda id
269     set_one_shot False id = id
270 \end{code}
271
272
273 %************************************************************************
274 %*                                                                      *
275 \subsection{Strictness stuff}
276 %*                                                                      *
277 %************************************************************************
278
279 \begin{code}
280 mkWWstr :: [Var]                                -- Wrapper args; have their demand info on them
281                                                 -- *Includes type variables*
282         -> UniqSM ([Var],                       -- Worker args
283                    CoreExpr -> CoreExpr,        -- Wrapper body, lacking the worker call
284                                                 -- and without its lambdas 
285                                                 -- This fn adds the unboxing
286                                 
287                    CoreExpr -> CoreExpr)        -- Worker body, lacking the original body of the function,
288                                                 -- and lacking its lambdas.
289                                                 -- This fn does the reboxing
290
291 ----------------------
292 nop_fn body = body
293
294 ----------------------
295 mkWWstr []
296   = returnUs ([], nop_fn, nop_fn)
297
298 mkWWstr (arg : args)
299   = mkWWstr_one arg             `thenUs` \ (args1, wrap_fn1, work_fn1) ->
300     mkWWstr args                `thenUs` \ (args2, wrap_fn2, work_fn2) ->
301     returnUs (args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2)
302
303
304 ----------------------
305 mkWWstr_one arg
306   | isTyVar arg
307   = returnUs ([arg],  nop_fn, nop_fn)
308
309   | otherwise
310   = case idNewDemandInfo arg of
311
312         -- Absent case.  We don't deal with absence for unlifted types,
313         -- though, because it's not so easy to manufacture a placeholder
314         -- We'll see if this turns out to be a problem
315       Abs | not (isUnLiftedType (idType arg)) ->
316         returnUs ([], nop_fn, mk_absent_let arg) 
317
318         -- Seq and keep
319       Seq _ []
320         -> let
321                 arg_w_unf = arg `setIdUnfolding` mkOtherCon []
322                 -- Tell the worker arg that it's sure to be evaluated
323                 -- so that internal seqs can be dropped
324            in
325            returnUs ([arg_w_unf], mk_seq_case arg, nop_fn)
326                 -- Pass the arg, anyway, even if it is in theory discarded
327                 -- Consider
328                 --      f x y = x `seq` y
329                 -- x gets a (Seq Drop []) demand, but if we fail to pass it to the worker
330                 -- we ABSOLUTELY MUST record that x is evaluated in the wrapper.
331                 -- Something like:
332                 --      f x y = x `seq` fw y
333                 --      fw y = let x{Evald} = error "oops" in (x `seq` y)
334                 -- If we don't pin on the "Evald" flag, the seq doesn't disappear, and
335                 -- we end up evaluating the absent thunk.
336                 -- But the Evald flag is pretty wierd, and I worry that it might disappear
337                 -- during simplification, so for now I've just nuked this whole case
338                         
339         -- Unpack case
340       Seq keep cs 
341         | Just (arg_tycon, tycon_arg_tys, data_con, inst_con_arg_tys) 
342                 <- splitProductType_maybe (idType arg)
343         -> getUniquesUs                 `thenUs` \ uniqs ->
344            let
345              unpk_args      = zipWith mk_ww_local uniqs inst_con_arg_tys
346              unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs'
347              unbox_fn       = mk_unpk_case arg unpk_args data_con arg_tycon
348              rebox_fn       = Let (NonRec arg con_app) 
349              con_app        = mkConApp data_con (map Type tycon_arg_tys ++ map Var unpk_args)
350
351              cs' = case keep of
352                         Keep -> map (DmdAnal.both Lazy) cs      -- Careful! Now we don't pass
353                                                                 -- the box, we must pass all the
354                                                                 -- components.   In effect
355                                                                 --      S(LA) -->  U(LL)
356                         Drop -> cs
357            in
358            mkWWstr unpk_args_w_ds               `thenUs` \ (worker_args, wrap_fn, work_fn) ->
359
360 --         case keep of
361 --           Keep -> returnUs (arg : worker_args, unbox_fn . wrap_fn, work_fn)
362 --                         -- Pass the arg, no need to rebox
363 --           Drop -> returnUs (worker_args,       unbox_fn . wrap_fn, work_fn . rebox_fn)
364 --                         -- Don't pass the arg, rebox instead
365 -- I used to be clever here, but consider
366 --      f n []     = n
367 --      f n (x:xs) = f (n+x) xs
368 -- Here n gets (Seq Keep [L]), but it's BAD BAD BAD to pass both n and n#
369 -- Needs more thought, but the simple thing to do is to accept the reboxing
370 -- stuff if there are any non-absent arguments (and that case is dealt with above):
371
372            returnUs (worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn)
373                            -- Don't pass the arg, rebox instead
374
375         | otherwise -> 
376            WARN( True, ppr arg )
377            returnUs ([arg], nop_fn, nop_fn)
378
379         -- Other cases
380       other_demand -> returnUs ([arg], nop_fn, nop_fn)
381
382   where
383         -- If the wrapper argument is a one-shot lambda, then
384         -- so should (all) the corresponding worker arguments be
385         -- This bites when we do w/w on a case join point
386     set_worker_arg_info worker_arg demand = set_one_shot (setIdNewDemandInfo worker_arg demand)
387
388     set_one_shot | isOneShotLambda arg = setOneShotLambda
389                  | otherwise           = \x -> x
390 \end{code}
391
392
393 %************************************************************************
394 %*                                                                      *
395 \subsection{CPR stuff}
396 %*                                                                      *
397 %************************************************************************
398
399
400 @mkWWcpr@ takes the worker/wrapper pair produced from the strictness
401 info and adds in the CPR transformation.  The worker returns an
402 unboxed tuple containing non-CPR components.  The wrapper takes this
403 tuple and re-produces the correct structured output.
404
405 The non-CPR results appear ordered in the unboxed tuple as if by a
406 left-to-right traversal of the result structure.
407
408
409 \begin{code}
410 mkWWcpr :: Type                              -- function body type
411         -> DmdResult                         -- CPR analysis results
412         -> UniqSM (CoreExpr -> CoreExpr,             -- New wrapper 
413                    CoreExpr -> CoreExpr,             -- New worker
414                    Type)                        -- Type of worker's body 
415
416 mkWWcpr body_ty RetCPR
417     | not (isAlgType body_ty)
418     = WARN( True, text "mkWWcpr: non-algebraic body type" <+> ppr body_ty )
419       returnUs (id, id, body_ty)
420
421     | n_con_args == 1 && isUnLiftedType con_arg_ty1
422         -- Special case when there is a single result of unlifted type
423     = getUniquesUs                      `thenUs` \ (work_uniq : arg_uniq : _) ->
424       let
425         work_wild = mk_ww_local work_uniq body_ty
426         arg       = mk_ww_local arg_uniq  con_arg_ty1
427       in
428       returnUs (\ wkr_call -> Case wkr_call arg [(DEFAULT, [], mkConApp data_con (map Type tycon_arg_tys ++ [Var arg]))],
429                 \ body     -> workerCase body work_wild [(DataAlt data_con, [arg], Var arg)],
430                 con_arg_ty1)
431
432     | otherwise         -- The general case
433     = getUniquesUs              `thenUs` \ uniqs ->
434       let
435         (wrap_wild : work_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : body_ty : con_arg_tys)
436         arg_vars                       = map Var args
437         ubx_tup_con                    = tupleCon Unboxed n_con_args
438         ubx_tup_ty                     = exprType ubx_tup_app
439         ubx_tup_app                    = mkConApp ubx_tup_con (map Type con_arg_tys   ++ arg_vars)
440         con_app                        = mkConApp data_con    (map Type tycon_arg_tys ++ arg_vars)
441       in
442       returnUs (\ wkr_call -> Case wkr_call wrap_wild [(DataAlt ubx_tup_con, args, con_app)],
443                 \ body     -> workerCase body work_wild [(DataAlt data_con,    args, ubx_tup_app)],
444                 ubx_tup_ty)
445     where
446       (_, tycon_arg_tys, data_con, con_arg_tys) = splitProductType "mkWWcpr" body_ty
447       n_con_args  = length con_arg_tys
448       con_arg_ty1 = head con_arg_tys
449
450 mkWWcpr body_ty other           -- No CPR info
451     = returnUs (id, id, body_ty)
452
453 -- If the original function looked like
454 --      f = \ x -> _scc_ "foo" E
455 --
456 -- then we want the CPR'd worker to look like
457 --      \ x -> _scc_ "foo" (case E of I# x -> x)
458 -- and definitely not
459 --      \ x -> case (_scc_ "foo" E) of I# x -> x)
460 --
461 -- This transform doesn't move work or allocation
462 -- from one cost centre to another
463
464 workerCase (Note (SCC cc) e) arg alts = Note (SCC cc) (Case e arg alts)
465 workerCase e                 arg alts = Case e arg alts
466 \end{code}
467
468
469 %************************************************************************
470 %*                                                                      *
471 \subsection{Utilities}
472 %*                                                                      *
473 %************************************************************************
474
475
476 \begin{code}
477 mk_absent_let arg body
478   | not (isUnLiftedType arg_ty)
479   = Let (NonRec arg abs_rhs) body
480   | otherwise
481   = panic "WwLib: haven't done mk_absent_let for primitives yet"
482   where
483     arg_ty = idType arg
484 --    abs_rhs = mkTyApps (Var aBSENT_ERROR_ID) [arg_ty]
485     abs_rhs = mkApps (Var eRROR_CSTRING_ID) [Type arg_ty, Lit (MachStr (_PK_ msg))] 
486     msg     = "Oops!  Entered absent arg " ++ showSDocDebug (ppr arg <+> ppr (idType arg))
487
488 mk_unpk_case arg unpk_args boxing_con boxing_tycon body
489         -- A data type
490   = Case (Var arg) 
491          (sanitiseCaseBndr arg)
492          [(DataAlt boxing_con, unpk_args, body)]
493
494 mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) [(DEFAULT, [], body)]
495
496 sanitiseCaseBndr :: Id -> Id
497 -- The argument we are scrutinising has the right type to be
498 -- a case binder, so it's convenient to re-use it for that purpose.
499 -- But we *must* throw away all its IdInfo.  In particular, the argument
500 -- will have demand info on it, and that demand info may be incorrect for
501 -- the case binder.  e.g.       case ww_arg of ww_arg { I# x -> ... }
502 -- Quite likely ww_arg isn't used in '...'.  The case may get discarded
503 -- if the case binder says "I'm demanded".  This happened in a situation 
504 -- like         (x+y) `seq` ....
505 sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo
506
507 mk_ww_local uniq ty = mkSysLocal SLIT("ww") uniq ty
508 \end{code}