2d60dd21b984c82d266fa7294026ee9e9464d9ae
[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, mkWorkerArgs ) 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(..), DmdResult(..), Demands(..) ) 
20 import DmdAnal          ( both )
21 import MkId             ( realWorldPrimId, voidArgId, 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     let
129         (work_lam_args, work_call_args) = mkWorkerArgs work_args cpr_res_ty
130     in
131     returnUs ([idNewDemandInfo v | v <- work_args, isId v],
132               Note InlineMe . wrap_fn_args . wrap_fn_cpr . wrap_fn_str . applyToVars work_call_args . Var,
133               mkLams work_lam_args . work_fn_str . work_fn_cpr . work_fn_args)
134         -- We use an INLINE unconditionally, even if the wrapper turns out to be
135         -- something trivial like
136         --      fw = ...
137         --      f = __inline__ (coerce T fw)
138         -- The point is to propagate the coerce to f's call sites, so even though
139         -- f's RHS is now trivial (size 1) we still want the __inline__ to prevent
140         -- fw from being inlined into f's RHS
141   where
142     one_shots' = one_shots ++ repeat False
143 \end{code}
144
145
146 %************************************************************************
147 %*                                                                      *
148 \subsection{Making wrapper args}
149 %*                                                                      *
150 %************************************************************************
151
152 During worker-wrapper stuff we may end up with an unlifted thing
153 which we want to let-bind without losing laziness.  So we
154 add a void argument.  E.g.
155
156         f = /\a -> \x y z -> E::Int#    -- E does not mentione x,y,z
157 ==>
158         fw = /\ a -> \void -> E
159         f  = /\ a -> \x y z -> fw realworld
160
161 We use the state-token type which generates no code.
162
163 \begin{code}
164 mkWorkerArgs :: [Var]
165              -> Type    -- Type of body
166              -> ([Var], -- Lambda bound args
167                  [Var]) -- Args at call site
168 mkWorkerArgs args res_ty
169     | any isId args || not (isUnLiftedType res_ty)
170     = (args, args)
171     | otherwise 
172     = (args ++ [voidArgId], args ++ [realWorldPrimId])
173 \end{code}
174
175
176 %************************************************************************
177 %*                                                                      *
178 \subsection{Coercion stuff}
179 %*                                                                      *
180 %************************************************************************
181
182
183 We really want to "look through" coerces.
184 Reason: I've seen this situation:
185
186         let f = coerce T (\s -> E)
187         in \x -> case x of
188                     p -> coerce T' f
189                     q -> \s -> E2
190                     r -> coerce T' f
191
192 If only we w/w'd f, we'd get
193         let f = coerce T (\s -> fw s)
194             fw = \s -> E
195         in ...
196
197 Now we'll inline f to get
198
199         let fw = \s -> E
200         in \x -> case x of
201                     p -> fw
202                     q -> \s -> E2
203                     r -> fw
204
205 Now we'll see that fw has arity 1, and will arity expand
206 the \x to get what we want.
207
208 \begin{code}
209 -- mkWWargs is driven off the function type and arity.
210 -- It chomps bites off foralls, arrows, newtypes
211 -- and keeps repeating that until it's satisfied the supplied arity
212
213 mkWWargs :: Type
214          -> [Demand]
215          -> [Bool]                      -- True for a one-shot arg; ** may be infinite **
216          -> UniqSM  ([Var],             -- Wrapper args
217                      CoreExpr -> CoreExpr,      -- Wrapper fn
218                      CoreExpr -> CoreExpr,      -- Worker fn
219                      Type)                      -- Type of wrapper body
220
221 mkWWargs fun_ty demands one_shots
222   | Just rep_ty <- splitNewType_maybe fun_ty
223         -- The newtype case is for when the function has
224         -- a recursive newtype after the arrow (rare)
225         -- We check for arity >= 0 to avoid looping in the case
226         -- of a function whose type is, in effect, infinite
227         -- [Arity is driven by looking at the term, not just the type.]
228         --
229         -- It's also important when we have a function returning (say) a pair
230         -- wrapped in a recursive newtype, at least if CPR analysis can look 
231         -- through such newtypes, which it probably can since they are 
232         -- simply coerces.
233   = mkWWargs rep_ty demands one_shots   `thenUs` \ (wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
234     returnUs (wrap_args,
235               Note (Coerce fun_ty rep_ty) . wrap_fn_args,
236               work_fn_args . Note (Coerce rep_ty fun_ty),
237               res_ty)
238
239   | not (null demands)
240   = getUniquesUs                `thenUs` \ wrap_uniqs ->
241     let
242       (tyvars, tau)             = splitForAllTys fun_ty
243       (arg_tys, body_ty)        = splitFunTys tau
244
245       n_demands = length demands
246       n_arg_tys = length arg_tys
247       n_args    = n_demands `min` n_arg_tys
248
249       new_fun_ty    = mkFunTys (drop n_demands arg_tys) body_ty
250       new_demands   = drop n_arg_tys demands
251       new_one_shots = drop n_args one_shots
252
253       val_args  = zipWith4 mk_wrap_arg wrap_uniqs arg_tys demands one_shots
254       wrap_args = tyvars ++ val_args
255     in
256 {-     ASSERT( not (null tyvars) || not (null arg_tys) ) -}
257     if (null tyvars) && (null arg_tys) then
258         pprTrace "mkWWargs" (ppr fun_ty $$ ppr demands) 
259                 returnUs ([], id, id, fun_ty)
260         else
261
262     mkWWargs new_fun_ty
263              new_demands
264              new_one_shots      `thenUs` \ (more_wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
265
266     returnUs (wrap_args ++ more_wrap_args,
267               mkLams wrap_args . wrap_fn_args,
268               work_fn_args . applyToVars wrap_args,
269               res_ty)
270
271   | otherwise
272   = returnUs ([], id, id, fun_ty)
273
274
275 applyToVars :: [Var] -> CoreExpr -> CoreExpr
276 applyToVars vars fn = mkVarApps fn vars
277
278 mk_wrap_arg uniq ty dmd one_shot 
279   = set_one_shot one_shot (setIdNewDemandInfo (mkSysLocal SLIT("w") uniq ty) dmd)
280   where
281     set_one_shot True  id = setOneShotLambda id
282     set_one_shot False id = id
283 \end{code}
284
285
286 %************************************************************************
287 %*                                                                      *
288 \subsection{Strictness stuff}
289 %*                                                                      *
290 %************************************************************************
291
292 \begin{code}
293 mkWWstr :: [Var]                                -- Wrapper args; have their demand info on them
294                                                 -- *Includes type variables*
295         -> UniqSM ([Var],                       -- Worker args
296                    CoreExpr -> CoreExpr,        -- Wrapper body, lacking the worker call
297                                                 -- and without its lambdas 
298                                                 -- This fn adds the unboxing
299                                 
300                    CoreExpr -> CoreExpr)        -- Worker body, lacking the original body of the function,
301                                                 -- and lacking its lambdas.
302                                                 -- This fn does the reboxing
303
304 ----------------------
305 nop_fn body = body
306
307 ----------------------
308 mkWWstr []
309   = returnUs ([], nop_fn, nop_fn)
310
311 mkWWstr (arg : args)
312   = mkWWstr_one arg             `thenUs` \ (args1, wrap_fn1, work_fn1) ->
313     mkWWstr args                `thenUs` \ (args2, wrap_fn2, work_fn2) ->
314     returnUs (args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2)
315
316
317 ----------------------
318 -- mkWWstr_one wrap_arg = (work_args, wrap_fn, work_fn)
319 --   *  wrap_fn assumes wrap_arg is in scope,
320 --        brings into scope work_args (via cases)
321 --   * work_fn assumes work_args are in scope, a
322 --        brings into scope wrap_arg (via lets)
323
324 mkWWstr_one arg
325   | isTyVar arg
326   = returnUs ([arg],  nop_fn, nop_fn)
327
328   | otherwise
329   = case idNewDemandInfo arg of
330
331         -- Absent case.  We don't deal with absence for unlifted types,
332         -- though, because it's not so easy to manufacture a placeholder
333         -- We'll see if this turns out to be a problem
334       Abs | not (isUnLiftedType (idType arg)) ->
335         returnUs ([], nop_fn, mk_absent_let arg) 
336
337         -- Unpack case
338       Eval (Prod cs)
339         | Just (arg_tycon, tycon_arg_tys, data_con, inst_con_arg_tys) 
340                 <- splitProductType_maybe (idType arg)
341         -> getUniquesUs                 `thenUs` \ uniqs ->
342            let
343              unpk_args      = zipWith mk_ww_local uniqs inst_con_arg_tys
344              unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs
345              unbox_fn       = mk_unpk_case arg unpk_args data_con arg_tycon
346              rebox_fn       = Let (NonRec arg con_app) 
347              con_app        = mkConApp data_con (map Type tycon_arg_tys ++ map Var unpk_args)
348            in
349            mkWWstr unpk_args_w_ds               `thenUs` \ (worker_args, wrap_fn, work_fn) ->
350            returnUs (worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn)
351                            -- Don't pass the arg, rebox instead
352
353         -- `seq` demand; evaluate in wrapper in the hope
354         -- of dropping seqs in the worker
355       Eval (Poly Abs)
356         -> let
357                 arg_w_unf = arg `setIdUnfolding` mkOtherCon []
358                 -- Tell the worker arg that it's sure to be evaluated
359                 -- so that internal seqs can be dropped
360            in
361            returnUs ([arg_w_unf], mk_seq_case arg, nop_fn)
362                 -- Pass the arg, anyway, even if it is in theory discarded
363                 -- Consider
364                 --      f x y = x `seq` y
365                 -- x gets a (Seq Drop []) demand, but if we fail to pass it to the worker
366                 -- we ABSOLUTELY MUST record that x is evaluated in the wrapper.
367                 -- Something like:
368                 --      f x y = x `seq` fw y
369                 --      fw y = let x{Evald} = error "oops" in (x `seq` y)
370                 -- If we don't pin on the "Evald" flag, the seq doesn't disappear, and
371                 -- we end up evaluating the absent thunk.
372                 -- But the Evald flag is pretty weird, and I worry that it might disappear
373                 -- during simplification, so for now I've just nuked this whole case
374                         
375         -- Other cases
376       other_demand -> returnUs ([arg], nop_fn, nop_fn)
377
378   where
379         -- If the wrapper argument is a one-shot lambda, then
380         -- so should (all) the corresponding worker arguments be
381         -- This bites when we do w/w on a case join point
382     set_worker_arg_info worker_arg demand = set_one_shot (setIdNewDemandInfo worker_arg demand)
383
384     set_one_shot | isOneShotLambda arg = setOneShotLambda
385                  | otherwise           = \x -> x
386 \end{code}
387
388
389 %************************************************************************
390 %*                                                                      *
391 \subsection{CPR stuff}
392 %*                                                                      *
393 %************************************************************************
394
395
396 @mkWWcpr@ takes the worker/wrapper pair produced from the strictness
397 info and adds in the CPR transformation.  The worker returns an
398 unboxed tuple containing non-CPR components.  The wrapper takes this
399 tuple and re-produces the correct structured output.
400
401 The non-CPR results appear ordered in the unboxed tuple as if by a
402 left-to-right traversal of the result structure.
403
404
405 \begin{code}
406 mkWWcpr :: Type                              -- function body type
407         -> DmdResult                         -- CPR analysis results
408         -> UniqSM (CoreExpr -> CoreExpr,             -- New wrapper 
409                    CoreExpr -> CoreExpr,             -- New worker
410                    Type)                        -- Type of worker's body 
411
412 mkWWcpr body_ty RetCPR
413     | not (isAlgType body_ty)
414     = WARN( True, text "mkWWcpr: non-algebraic body type" <+> ppr body_ty )
415       returnUs (id, id, body_ty)
416
417     | n_con_args == 1 && isUnLiftedType con_arg_ty1
418         -- Special case when there is a single result of unlifted type
419     = getUniquesUs                      `thenUs` \ (work_uniq : arg_uniq : _) ->
420       let
421         work_wild = mk_ww_local work_uniq body_ty
422         arg       = mk_ww_local arg_uniq  con_arg_ty1
423       in
424       returnUs (\ wkr_call -> Case wkr_call arg [(DEFAULT, [], mkConApp data_con (map Type tycon_arg_tys ++ [Var arg]))],
425                 \ body     -> workerCase body work_wild [(DataAlt data_con, [arg], Var arg)],
426                 con_arg_ty1)
427
428     | otherwise         -- The general case
429     = getUniquesUs              `thenUs` \ uniqs ->
430       let
431         (wrap_wild : work_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : body_ty : con_arg_tys)
432         arg_vars                       = map Var args
433         ubx_tup_con                    = tupleCon Unboxed n_con_args
434         ubx_tup_ty                     = exprType ubx_tup_app
435         ubx_tup_app                    = mkConApp ubx_tup_con (map Type con_arg_tys   ++ arg_vars)
436         con_app                        = mkConApp data_con    (map Type tycon_arg_tys ++ arg_vars)
437       in
438       returnUs (\ wkr_call -> Case wkr_call wrap_wild [(DataAlt ubx_tup_con, args, con_app)],
439                 \ body     -> workerCase body work_wild [(DataAlt data_con,    args, ubx_tup_app)],
440                 ubx_tup_ty)
441     where
442       (_, tycon_arg_tys, data_con, con_arg_tys) = splitProductType "mkWWcpr" body_ty
443       n_con_args  = length con_arg_tys
444       con_arg_ty1 = head con_arg_tys
445
446 mkWWcpr body_ty other           -- No CPR info
447     = returnUs (id, id, body_ty)
448
449 -- If the original function looked like
450 --      f = \ x -> _scc_ "foo" E
451 --
452 -- then we want the CPR'd worker to look like
453 --      \ x -> _scc_ "foo" (case E of I# x -> x)
454 -- and definitely not
455 --      \ x -> case (_scc_ "foo" E) of I# x -> x)
456 --
457 -- This transform doesn't move work or allocation
458 -- from one cost centre to another
459
460 workerCase (Note (SCC cc) e) arg alts = Note (SCC cc) (Case e arg alts)
461 workerCase e                 arg alts = Case e arg alts
462 \end{code}
463
464
465 %************************************************************************
466 %*                                                                      *
467 \subsection{Utilities}
468 %*                                                                      *
469 %************************************************************************
470
471
472 \begin{code}
473 mk_absent_let arg body
474   | not (isUnLiftedType arg_ty)
475   = Let (NonRec arg abs_rhs) body
476   | otherwise
477   = panic "WwLib: haven't done mk_absent_let for primitives yet"
478   where
479     arg_ty = idType arg
480 --    abs_rhs = mkTyApps (Var aBSENT_ERROR_ID) [arg_ty]
481     abs_rhs = mkApps (Var eRROR_CSTRING_ID) [Type arg_ty, Lit (MachStr (_PK_ msg))] 
482     msg     = "Oops!  Entered absent arg " ++ showSDocDebug (ppr arg <+> ppr (idType arg))
483
484 mk_unpk_case arg unpk_args boxing_con boxing_tycon body
485         -- A data type
486   = Case (Var arg) 
487          (sanitiseCaseBndr arg)
488          [(DataAlt boxing_con, unpk_args, body)]
489
490 mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) [(DEFAULT, [], body)]
491
492 sanitiseCaseBndr :: Id -> Id
493 -- The argument we are scrutinising has the right type to be
494 -- a case binder, so it's convenient to re-use it for that purpose.
495 -- But we *must* throw away all its IdInfo.  In particular, the argument
496 -- will have demand info on it, and that demand info may be incorrect for
497 -- the case binder.  e.g.       case ww_arg of ww_arg { I# x -> ... }
498 -- Quite likely ww_arg isn't used in '...'.  The case may get discarded
499 -- if the case binder says "I'm demanded".  This happened in a situation 
500 -- like         (x+y) `seq` ....
501 sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo
502
503 mk_ww_local uniq ty = mkSysLocal SLIT("ww") uniq ty
504 \end{code}