2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[WwLib]{A library for the ``worker/wrapper'' back-end to the strictness analyser}
7 module WwLib ( mkWwBodies, mkWWstr, mkWorkerArgs ) where
9 #include "HsVersions.h"
12 import CoreUtils ( exprType )
13 import Id ( Id, idType, mkSysLocal, idNewDemandInfo, setIdNewDemandInfo,
14 isOneShotLambda, setOneShotLambda, setIdUnfolding,
17 import IdInfo ( vanillaIdInfo )
18 import DataCon ( splitProductType_maybe, splitProductType )
19 import NewDemand ( Demand(..), DmdResult(..), Demands(..) )
20 import MkId ( realWorldPrimId, voidArgId, mkRuntimeErrorApp, rUNTIME_ERROR_ID )
21 import TysWiredIn ( tupleCon )
22 import Type ( Type, isUnLiftedType, mkFunTys,
23 splitForAllTys, splitFunTys, splitRecNewType_maybe, isAlgType
25 import BasicTypes ( Boxity(..) )
26 import Var ( Var, isId )
27 import UniqSupply ( returnUs, thenUs, getUniquesUs, UniqSM )
28 import Util ( zipWithEqual, notNull )
30 import List ( zipWith4 )
34 %************************************************************************
36 \subsection[mkWrapperAndWorker]{@mkWrapperAndWorker@}
38 %************************************************************************
40 Here's an example. The original function is:
43 g :: forall a . Int -> [a] -> a
51 From this, we want to produce:
53 -- wrapper (an unfolding)
54 g :: forall a . Int -> [a] -> a
59 -- call the worker; don't forget the type args!
62 $wg :: forall a . Int# -> [a] -> a
64 $wg = /\ a -> \ x# ys ->
68 case x of -- note: body of g moved intact
73 Something we have to be careful about: Here's an example:
76 -- "f" strictness: U(P)U(P)
77 f (I# a) (I# b) = a +# b
79 g = f -- "g" strictness same as "f"
82 \tr{f} will get a worker all nice and friendly-like; that's good.
83 {\em But we don't want a worker for \tr{g}}, even though it has the
84 same strictness as \tr{f}. Doing so could break laziness, at best.
86 Consequently, we insist that the number of strictness-info items is
87 exactly the same as the number of lambda-bound arguments. (This is
88 probably slightly paranoid, but OK in practice.) If it isn't the
89 same, we ``revise'' the strictness info, so that we won't propagate
90 the unusable strictness-info into the interfaces.
93 %************************************************************************
95 \subsection{The worker wrapper core}
97 %************************************************************************
99 @mkWwBodies@ is called when doing the worker/wrapper split inside a module.
102 mkWwBodies :: Type -- Type of original function
103 -> [Demand] -- Strictness of original function
104 -> DmdResult -- Info about function result
105 -> [Bool] -- One-shot-ness of the function
106 -> UniqSM ([Demand], -- Demands for worker (value) args
107 Id -> CoreExpr, -- Wrapper body, lacking only the worker Id
108 CoreExpr -> CoreExpr) -- Worker body, lacking the original function rhs
110 -- wrap_fn_args E = \x y -> E
111 -- work_fn_args E = E x y
113 -- wrap_fn_str E = case x of { (a,b) ->
114 -- case a of { (a1,a2) ->
116 -- work_fn_str E = \a2 a2 b y ->
117 -- let a = (a1,a2) in
121 mkWwBodies fun_ty demands res_info one_shots
122 = mkWWargs fun_ty demands one_shots' `thenUs` \ (wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
123 mkWWstr wrap_args `thenUs` \ (work_args, wrap_fn_str, work_fn_str) ->
125 (work_lam_args, work_call_args) = mkWorkerArgs work_args res_ty
127 -- Don't do CPR if the worker doesn't have any value arguments
128 -- Then the worker is just a constant, so we don't want to unbox it.
129 (if any isId work_args then
130 mkWWcpr res_ty res_info
132 returnUs (id, id, res_ty)
133 ) `thenUs` \ (wrap_fn_cpr, work_fn_cpr, cpr_res_ty) ->
135 returnUs ([idNewDemandInfo v | v <- work_args, isId v],
136 Note InlineMe . wrap_fn_args . wrap_fn_cpr . wrap_fn_str . applyToVars work_call_args . Var,
137 mkLams work_lam_args. work_fn_str . work_fn_cpr . work_fn_args)
138 -- We use an INLINE unconditionally, even if the wrapper turns out to be
139 -- something trivial like
141 -- f = __inline__ (coerce T fw)
142 -- The point is to propagate the coerce to f's call sites, so even though
143 -- f's RHS is now trivial (size 1) we still want the __inline__ to prevent
144 -- fw from being inlined into f's RHS
146 one_shots' = one_shots ++ repeat False
150 %************************************************************************
152 \subsection{Making wrapper args}
154 %************************************************************************
156 During worker-wrapper stuff we may end up with an unlifted thing
157 which we want to let-bind without losing laziness. So we
158 add a void argument. E.g.
160 f = /\a -> \x y z -> E::Int# -- E does not mention x,y,z
162 fw = /\ a -> \void -> E
163 f = /\ a -> \x y z -> fw realworld
165 We use the state-token type which generates no code.
168 mkWorkerArgs :: [Var]
169 -> Type -- Type of body
170 -> ([Var], -- Lambda bound args
171 [Var]) -- Args at call site
172 mkWorkerArgs args res_ty
173 | any isId args || not (isUnLiftedType res_ty)
176 = (args ++ [voidArgId], args ++ [realWorldPrimId])
180 %************************************************************************
182 \subsection{Coercion stuff}
184 %************************************************************************
187 We really want to "look through" coerces.
188 Reason: I've seen this situation:
190 let f = coerce T (\s -> E)
196 If only we w/w'd f, we'd get
197 let f = coerce T (\s -> fw s)
201 Now we'll inline f to get
209 Now we'll see that fw has arity 1, and will arity expand
210 the \x to get what we want.
213 -- mkWWargs is driven off the function type and arity.
214 -- It chomps bites off foralls, arrows, newtypes
215 -- and keeps repeating that until it's satisfied the supplied arity
219 -> [Bool] -- True for a one-shot arg; ** may be infinite **
220 -> UniqSM ([Var], -- Wrapper args
221 CoreExpr -> CoreExpr, -- Wrapper fn
222 CoreExpr -> CoreExpr, -- Worker fn
223 Type) -- Type of wrapper body
225 mkWWargs fun_ty demands one_shots
226 | Just rep_ty <- splitRecNewType_maybe fun_ty
227 -- The newtype case is for when the function has
228 -- a recursive newtype after the arrow (rare)
229 -- We check for arity >= 0 to avoid looping in the case
230 -- of a function whose type is, in effect, infinite
231 -- [Arity is driven by looking at the term, not just the type.]
233 -- It's also important when we have a function returning (say) a pair
234 -- wrapped in a recursive newtype, at least if CPR analysis can look
235 -- through such newtypes, which it probably can since they are
237 = mkWWargs rep_ty demands one_shots `thenUs` \ (wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
239 Note (Coerce fun_ty rep_ty) . wrap_fn_args,
240 work_fn_args . Note (Coerce rep_ty fun_ty),
244 = getUniquesUs `thenUs` \ wrap_uniqs ->
246 (tyvars, tau) = splitForAllTys fun_ty
247 (arg_tys, body_ty) = splitFunTys tau
249 n_demands = length demands
250 n_arg_tys = length arg_tys
251 n_args = n_demands `min` n_arg_tys
253 new_fun_ty = mkFunTys (drop n_demands arg_tys) body_ty
254 new_demands = drop n_arg_tys demands
255 new_one_shots = drop n_args one_shots
257 val_args = zipWith4 mk_wrap_arg wrap_uniqs arg_tys demands one_shots
258 wrap_args = tyvars ++ val_args
260 {- ASSERT( notNull tyvars || notNull arg_tys ) -}
261 if (null tyvars) && (null arg_tys) then
262 pprTrace "mkWWargs" (ppr fun_ty $$ ppr demands)
263 returnUs ([], id, id, fun_ty)
268 new_one_shots `thenUs` \ (more_wrap_args, wrap_fn_args, work_fn_args, res_ty) ->
270 returnUs (wrap_args ++ more_wrap_args,
271 mkLams wrap_args . wrap_fn_args,
272 work_fn_args . applyToVars wrap_args,
276 = returnUs ([], id, id, fun_ty)
279 applyToVars :: [Var] -> CoreExpr -> CoreExpr
280 applyToVars vars fn = mkVarApps fn vars
282 mk_wrap_arg uniq ty dmd one_shot
283 = set_one_shot one_shot (setIdNewDemandInfo (mkSysLocal FSLIT("w") uniq ty) dmd)
285 set_one_shot True id = setOneShotLambda id
286 set_one_shot False id = id
290 %************************************************************************
292 \subsection{Strictness stuff}
294 %************************************************************************
297 mkWWstr :: [Var] -- Wrapper args; have their demand info on them
298 -- *Includes type variables*
299 -> UniqSM ([Var], -- Worker args
300 CoreExpr -> CoreExpr, -- Wrapper body, lacking the worker call
301 -- and without its lambdas
302 -- This fn adds the unboxing
304 CoreExpr -> CoreExpr) -- Worker body, lacking the original body of the function,
305 -- and lacking its lambdas.
306 -- This fn does the reboxing
308 ----------------------
311 ----------------------
313 = returnUs ([], nop_fn, nop_fn)
316 = mkWWstr_one arg `thenUs` \ (args1, wrap_fn1, work_fn1) ->
317 mkWWstr args `thenUs` \ (args2, wrap_fn2, work_fn2) ->
318 returnUs (args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2)
321 ----------------------
322 -- mkWWstr_one wrap_arg = (work_args, wrap_fn, work_fn)
323 -- * wrap_fn assumes wrap_arg is in scope,
324 -- brings into scope work_args (via cases)
325 -- * work_fn assumes work_args are in scope, a
326 -- brings into scope wrap_arg (via lets)
330 = returnUs ([arg], nop_fn, nop_fn)
333 = case idNewDemandInfo arg of
335 -- Absent case. We don't deal with absence for unlifted types,
336 -- though, because it's not so easy to manufacture a placeholder
337 -- We'll see if this turns out to be a problem
338 Abs | not (isUnLiftedType (idType arg)) ->
339 returnUs ([], nop_fn, mk_absent_let arg)
343 | Just (arg_tycon, tycon_arg_tys, data_con, inst_con_arg_tys)
344 <- splitProductType_maybe (idType arg)
345 -> getUniquesUs `thenUs` \ uniqs ->
347 unpk_args = zipWith mk_ww_local uniqs inst_con_arg_tys
348 unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs
349 unbox_fn = mk_unpk_case arg unpk_args data_con arg_tycon
350 rebox_fn = Let (NonRec arg con_app)
351 con_app = mkConApp data_con (map Type tycon_arg_tys ++ map Var unpk_args)
353 mkWWstr unpk_args_w_ds `thenUs` \ (worker_args, wrap_fn, work_fn) ->
354 returnUs (worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn)
355 -- Don't pass the arg, rebox instead
357 -- `seq` demand; evaluate in wrapper in the hope
358 -- of dropping seqs in the worker
361 arg_w_unf = arg `setIdUnfolding` mkOtherCon []
362 -- Tell the worker arg that it's sure to be evaluated
363 -- so that internal seqs can be dropped
365 returnUs ([arg_w_unf], mk_seq_case arg, nop_fn)
366 -- Pass the arg, anyway, even if it is in theory discarded
369 -- x gets a (Eval (Poly Abs)) demand, but if we fail to pass it to the worker
370 -- we ABSOLUTELY MUST record that x is evaluated in the wrapper.
372 -- f x y = x `seq` fw y
373 -- fw y = let x{Evald} = error "oops" in (x `seq` y)
374 -- If we don't pin on the "Evald" flag, the seq doesn't disappear, and
375 -- we end up evaluating the absent thunk.
376 -- But the Evald flag is pretty weird, and I worry that it might disappear
377 -- during simplification, so for now I've just nuked this whole case
380 other_demand -> returnUs ([arg], nop_fn, nop_fn)
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)
388 set_one_shot | isOneShotLambda arg = setOneShotLambda
389 | otherwise = \x -> x
393 %************************************************************************
395 \subsection{CPR stuff}
397 %************************************************************************
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.
405 The non-CPR results appear ordered in the unboxed tuple as if by a
406 left-to-right traversal of the result structure.
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
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)
421 | n_con_args == 1 && isUnLiftedType con_arg_ty1
422 -- Special case when there is a single result of unlifted type
424 -- Wrapper: case (..call worker..) of x -> C x
425 -- Worker: case ( ..body.. ) of C x -> x
426 = getUniquesUs `thenUs` \ (work_uniq : arg_uniq : _) ->
428 work_wild = mk_ww_local work_uniq body_ty
429 arg = mk_ww_local arg_uniq con_arg_ty1
430 con_app = mkConApp data_con (map Type tycon_arg_tys ++ [Var arg])
432 returnUs (\ wkr_call -> Case wkr_call arg [(DEFAULT, [], con_app)],
433 \ body -> workerCase body work_wild [(DataAlt data_con, [arg], Var arg)],
436 | otherwise -- The general case
437 -- Wrapper: case (..call worker..) of (# a, b #) -> C a b
438 -- Worker: case ( ...body... ) of C a b -> (# a, b #)
439 = getUniquesUs `thenUs` \ uniqs ->
441 (wrap_wild : work_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : body_ty : con_arg_tys)
442 arg_vars = map Var args
443 ubx_tup_con = tupleCon Unboxed n_con_args
444 ubx_tup_ty = exprType ubx_tup_app
445 ubx_tup_app = mkConApp ubx_tup_con (map Type con_arg_tys ++ arg_vars)
446 con_app = mkConApp data_con (map Type tycon_arg_tys ++ arg_vars)
448 returnUs (\ wkr_call -> Case wkr_call wrap_wild [(DataAlt ubx_tup_con, args, con_app)],
449 \ body -> workerCase body work_wild [(DataAlt data_con, args, ubx_tup_app)],
452 (_, tycon_arg_tys, data_con, con_arg_tys) = splitProductType "mkWWcpr" body_ty
453 n_con_args = length con_arg_tys
454 con_arg_ty1 = head con_arg_tys
456 mkWWcpr body_ty other -- No CPR info
457 = returnUs (id, id, body_ty)
459 -- If the original function looked like
460 -- f = \ x -> _scc_ "foo" E
462 -- then we want the CPR'd worker to look like
463 -- \ x -> _scc_ "foo" (case E of I# x -> x)
464 -- and definitely not
465 -- \ x -> case (_scc_ "foo" E) of I# x -> x)
467 -- This transform doesn't move work or allocation
468 -- from one cost centre to another
470 workerCase (Note (SCC cc) e) arg alts = Note (SCC cc) (Case e arg alts)
471 workerCase e arg alts = Case e arg alts
475 %************************************************************************
477 \subsection{Utilities}
479 %************************************************************************
483 mk_absent_let arg body
484 | not (isUnLiftedType arg_ty)
485 = Let (NonRec arg abs_rhs) body
487 = panic "WwLib: haven't done mk_absent_let for primitives yet"
490 abs_rhs = mkRuntimeErrorApp rUNTIME_ERROR_ID arg_ty msg
491 msg = "Oops! Entered absent arg " ++ showSDocDebug (ppr arg <+> ppr (idType arg))
493 mk_unpk_case arg unpk_args boxing_con boxing_tycon body
496 (sanitiseCaseBndr arg)
497 [(DataAlt boxing_con, unpk_args, body)]
499 mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) [(DEFAULT, [], body)]
501 sanitiseCaseBndr :: Id -> Id
502 -- The argument we are scrutinising has the right type to be
503 -- a case binder, so it's convenient to re-use it for that purpose.
504 -- But we *must* throw away all its IdInfo. In particular, the argument
505 -- will have demand info on it, and that demand info may be incorrect for
506 -- the case binder. e.g. case ww_arg of ww_arg { I# x -> ... }
507 -- Quite likely ww_arg isn't used in '...'. The case may get discarded
508 -- if the case binder says "I'm demanded". This happened in a situation
509 -- like (x+y) `seq` ....
510 sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo
512 mk_ww_local uniq ty = mkSysLocal FSLIT("ww") uniq ty