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 )
19 import NewDemand ( Demand(..), DmdResult(..), Demands(..) )
20 import MkId ( realWorldPrimId, voidArgId, mkRuntimeErrorApp, rUNTIME_ERROR_ID,
21 mkUnpackCase, mkProductBox )
22 import TysWiredIn ( tupleCon )
24 import Coercion ( mkSymCoercion, splitNewTypeRepCo_maybe )
25 import BasicTypes ( Boxity(..) )
26 import Var ( Var, isId )
29 import Util ( zipWithEqual, notNull )
31 import List ( zipWith4 )
35 %************************************************************************
37 \subsection[mkWrapperAndWorker]{@mkWrapperAndWorker@}
39 %************************************************************************
41 Here's an example. The original function is:
44 g :: forall a . Int -> [a] -> a
52 From this, we want to produce:
54 -- wrapper (an unfolding)
55 g :: forall a . Int -> [a] -> a
60 -- call the worker; don't forget the type args!
63 $wg :: forall a . Int# -> [a] -> a
65 $wg = /\ a -> \ x# ys ->
69 case x of -- note: body of g moved intact
74 Something we have to be careful about: Here's an example:
77 -- "f" strictness: U(P)U(P)
78 f (I# a) (I# b) = a +# b
80 g = f -- "g" strictness same as "f"
83 \tr{f} will get a worker all nice and friendly-like; that's good.
84 {\em But we don't want a worker for \tr{g}}, even though it has the
85 same strictness as \tr{f}. Doing so could break laziness, at best.
87 Consequently, we insist that the number of strictness-info items is
88 exactly the same as the number of lambda-bound arguments. (This is
89 probably slightly paranoid, but OK in practice.) If it isn't the
90 same, we ``revise'' the strictness info, so that we won't propagate
91 the unusable strictness-info into the interfaces.
94 %************************************************************************
96 \subsection{The worker wrapper core}
98 %************************************************************************
100 @mkWwBodies@ is called when doing the worker/wrapper split inside a module.
103 mkWwBodies :: Type -- Type of original function
104 -> [Demand] -- Strictness of original function
105 -> DmdResult -- Info about function result
106 -> [Bool] -- One-shot-ness of the function
107 -> UniqSM ([Demand], -- Demands for worker (value) args
108 Id -> CoreExpr, -- Wrapper body, lacking only the worker Id
109 CoreExpr -> CoreExpr) -- Worker body, lacking the original function rhs
111 -- wrap_fn_args E = \x y -> E
112 -- work_fn_args E = E x y
114 -- wrap_fn_str E = case x of { (a,b) ->
115 -- case a of { (a1,a2) ->
117 -- work_fn_str E = \a2 a2 b y ->
118 -- let a = (a1,a2) in
122 mkWwBodies fun_ty demands res_info one_shots = do
123 (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs fun_ty demands one_shots'
124 (work_args, wrap_fn_str, work_fn_str) <- mkWWstr wrap_args
125 let (work_lam_args, work_call_args) = do mkWorkerArgs work_args res_ty
126 -- Don't do CPR if the worker doesn't have any value arguments
127 -- Then the worker is just a constant, so we don't want to unbox it.
128 (wrap_fn_cpr, work_fn_cpr, _cpr_res_ty)
129 <- if any isId work_args then
130 mkWWcpr res_ty res_info
132 return (id, id, res_ty)
134 return ([idNewDemandInfo v | v <- work_call_args, isId v],
135 Note InlineMe . wrap_fn_args . wrap_fn_cpr . wrap_fn_str . applyToVars work_call_args . Var,
136 mkLams work_lam_args. work_fn_str . work_fn_cpr . work_fn_args)
137 -- We use an INLINE unconditionally, even if the wrapper turns out to be
138 -- something trivial like
140 -- f = __inline__ (coerce T fw)
141 -- The point is to propagate the coerce to f's call sites, so even though
142 -- f's RHS is now trivial (size 1) we still want the __inline__ to prevent
143 -- fw from being inlined into f's RHS
145 one_shots' = one_shots ++ repeat False
149 %************************************************************************
151 \subsection{Making wrapper args}
153 %************************************************************************
155 During worker-wrapper stuff we may end up with an unlifted thing
156 which we want to let-bind without losing laziness. So we
157 add a void argument. E.g.
159 f = /\a -> \x y z -> E::Int# -- E does not mention x,y,z
161 fw = /\ a -> \void -> E
162 f = /\ a -> \x y z -> fw realworld
164 We use the state-token type which generates no code.
167 mkWorkerArgs :: [Var]
168 -> Type -- Type of body
169 -> ([Var], -- Lambda bound args
170 [Var]) -- Args at call site
171 mkWorkerArgs args res_ty
172 | any isId args || not (isUnLiftedType res_ty)
175 = (args ++ [voidArgId], args ++ [realWorldPrimId])
179 %************************************************************************
181 \subsection{Coercion stuff}
183 %************************************************************************
186 We really want to "look through" coerces.
187 Reason: I've seen this situation:
189 let f = coerce T (\s -> E)
195 If only we w/w'd f, we'd get
196 let f = coerce T (\s -> fw s)
200 Now we'll inline f to get
208 Now we'll see that fw has arity 1, and will arity expand
209 the \x to get what we want.
212 -- mkWWargs is driven off the function type and arity.
213 -- It chomps bites off foralls, arrows, newtypes
214 -- and keeps repeating that until it's satisfied the supplied arity
218 -> [Bool] -- True for a one-shot arg; ** may be infinite **
219 -> UniqSM ([Var], -- Wrapper args
220 CoreExpr -> CoreExpr, -- Wrapper fn
221 CoreExpr -> CoreExpr, -- Worker fn
222 Type) -- Type of wrapper body
224 mkWWargs fun_ty demands one_shots
225 | Just (rep_ty, co) <- splitNewTypeRepCo_maybe fun_ty = do
226 -- The newtype case is for when the function has
227 -- a recursive newtype after the arrow (rare)
228 -- We check for arity >= 0 to avoid looping in the case
229 -- of a function whose type is, in effect, infinite
230 -- [Arity is driven by looking at the term, not just the type.]
232 -- It's also important when we have a function returning (say) a pair
233 -- wrapped in a recursive newtype, at least if CPR analysis can look
234 -- through such newtypes, which it probably can since they are
236 (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs rep_ty demands one_shots
238 \ e -> Cast (wrap_fn_args e) (mkSymCoercion co),
239 \ e -> work_fn_args (Cast e co),
241 | notNull demands = do
242 wrap_uniqs <- getUniquesM
244 (tyvars, tau) = splitForAllTys fun_ty
245 (arg_tys, body_ty) = splitFunTys tau
247 n_demands = length demands
248 n_arg_tys = length arg_tys
249 n_args = n_demands `min` n_arg_tys
251 new_fun_ty = mkFunTys (drop n_demands arg_tys) body_ty
252 new_demands = drop n_arg_tys demands
253 new_one_shots = drop n_args one_shots
255 val_args = zipWith4 mk_wrap_arg wrap_uniqs arg_tys demands one_shots
256 wrap_args = tyvars ++ val_args
257 {- ASSERT( notNull tyvars || notNull arg_tys ) -}
258 if (null tyvars) && (null arg_tys) then
259 pprTrace "mkWWargs" (ppr fun_ty $$ ppr demands)
260 return ([], id, id, fun_ty)
263 (more_wrap_args, wrap_fn_args, work_fn_args, res_ty) <-
264 mkWWargs new_fun_ty new_demands new_one_shots
266 return (wrap_args ++ more_wrap_args,
267 mkLams wrap_args . wrap_fn_args,
268 work_fn_args . applyToVars wrap_args,
272 = return ([], id, id, fun_ty)
275 applyToVars :: [Var] -> CoreExpr -> CoreExpr
276 applyToVars vars fn = mkVarApps fn vars
278 mk_wrap_arg :: Unique -> Type -> NewDemand.Demand -> Bool -> Id
279 mk_wrap_arg uniq ty dmd one_shot
280 = set_one_shot one_shot (setIdNewDemandInfo (mkSysLocal FSLIT("w") uniq ty) dmd)
282 set_one_shot True id = setOneShotLambda id
283 set_one_shot False id = id
287 %************************************************************************
289 \subsection{Strictness stuff}
291 %************************************************************************
294 mkWWstr :: [Var] -- Wrapper args; have their demand info on them
295 -- *Includes type variables*
296 -> UniqSM ([Var], -- Worker args
297 CoreExpr -> CoreExpr, -- Wrapper body, lacking the worker call
298 -- and without its lambdas
299 -- This fn adds the unboxing
301 CoreExpr -> CoreExpr) -- Worker body, lacking the original body of the function,
302 -- and lacking its lambdas.
303 -- This fn does the reboxing
305 = return ([], nop_fn, nop_fn)
307 mkWWstr (arg : args) = do
308 (args1, wrap_fn1, work_fn1) <- mkWWstr_one arg
309 (args2, wrap_fn2, work_fn2) <- mkWWstr args
310 return (args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2)
312 ----------------------
313 -- mkWWstr_one wrap_arg = (work_args, wrap_fn, work_fn)
314 -- * wrap_fn assumes wrap_arg is in scope,
315 -- brings into scope work_args (via cases)
316 -- * work_fn assumes work_args are in scope, a
317 -- brings into scope wrap_arg (via lets)
318 mkWWstr_one :: Var -> UniqSM ([Var], CoreExpr -> CoreExpr, CoreExpr -> CoreExpr)
321 = return ([arg], nop_fn, nop_fn)
324 = case idNewDemandInfo arg of
326 -- Absent case. We don't deal with absence for unlifted types,
327 -- though, because it's not so easy to manufacture a placeholder
328 -- We'll see if this turns out to be a problem
329 Abs | not (isUnLiftedType (idType arg)) ->
330 return ([], nop_fn, mk_absent_let arg)
334 | Just (_arg_tycon, _tycon_arg_tys, data_con, inst_con_arg_tys)
335 <- deepSplitProductType_maybe (idType arg)
336 -> do uniqs <- getUniquesM
338 unpk_args = zipWith mk_ww_local uniqs inst_con_arg_tys
339 unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs
340 unbox_fn = mkUnpackCase (sanitiseCaseBndr arg) (Var arg) unpk_args data_con
341 rebox_fn = Let (NonRec arg con_app)
342 con_app = mkProductBox unpk_args (idType arg)
343 (worker_args, wrap_fn, work_fn) <- mkWWstr unpk_args_w_ds
344 return (worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn)
345 -- Don't pass the arg, rebox instead
347 -- `seq` demand; evaluate in wrapper in the hope
348 -- of dropping seqs in the worker
351 arg_w_unf = arg `setIdUnfolding` evaldUnfolding
352 -- Tell the worker arg that it's sure to be evaluated
353 -- so that internal seqs can be dropped
355 return ([arg_w_unf], mk_seq_case arg, nop_fn)
356 -- Pass the arg, anyway, even if it is in theory discarded
359 -- x gets a (Eval (Poly Abs)) demand, but if we fail to pass it to the worker
360 -- we ABSOLUTELY MUST record that x is evaluated in the wrapper.
362 -- f x y = x `seq` fw y
363 -- fw y = let x{Evald} = error "oops" in (x `seq` y)
364 -- If we don't pin on the "Evald" flag, the seq doesn't disappear, and
365 -- we end up evaluating the absent thunk.
366 -- But the Evald flag is pretty weird, and I worry that it might disappear
367 -- during simplification, so for now I've just nuked this whole case
370 _other_demand -> return ([arg], nop_fn, nop_fn)
373 -- If the wrapper argument is a one-shot lambda, then
374 -- so should (all) the corresponding worker arguments be
375 -- This bites when we do w/w on a case join point
376 set_worker_arg_info worker_arg demand = set_one_shot (setIdNewDemandInfo worker_arg demand)
378 set_one_shot | isOneShotLambda arg = setOneShotLambda
379 | otherwise = \x -> x
381 ----------------------
382 nop_fn :: CoreExpr -> CoreExpr
387 %************************************************************************
389 \subsection{CPR stuff}
391 %************************************************************************
394 @mkWWcpr@ takes the worker/wrapper pair produced from the strictness
395 info and adds in the CPR transformation. The worker returns an
396 unboxed tuple containing non-CPR components. The wrapper takes this
397 tuple and re-produces the correct structured output.
399 The non-CPR results appear ordered in the unboxed tuple as if by a
400 left-to-right traversal of the result structure.
404 mkWWcpr :: Type -- function body type
405 -> DmdResult -- CPR analysis results
406 -> UniqSM (CoreExpr -> CoreExpr, -- New wrapper
407 CoreExpr -> CoreExpr, -- New worker
408 Type) -- Type of worker's body
410 mkWWcpr body_ty RetCPR
411 | not (isClosedAlgType body_ty)
413 text "mkWWcpr: non-algebraic or open body type" <+> ppr body_ty )
414 return (id, id, body_ty)
416 | n_con_args == 1 && isUnLiftedType con_arg_ty1 = do
417 -- Special case when there is a single result of unlifted type
419 -- Wrapper: case (..call worker..) of x -> C x
420 -- Worker: case ( ..body.. ) of C x -> x
421 (work_uniq : arg_uniq : _) <- getUniquesM
423 work_wild = mk_ww_local work_uniq body_ty
424 arg = mk_ww_local arg_uniq con_arg_ty1
425 con_app = mkProductBox [arg] body_ty
427 return (\ wkr_call -> Case wkr_call (arg) (exprType con_app) [(DEFAULT, [], con_app)],
428 \ body -> workerCase (work_wild) body [arg] data_con (Var arg),
431 | otherwise = do -- The general case
432 -- Wrapper: case (..call worker..) of (# a, b #) -> C a b
433 -- Worker: case ( ...body... ) of C a b -> (# a, b #)
436 (wrap_wild : work_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : body_ty : con_arg_tys)
437 arg_vars = map Var args
438 ubx_tup_con = tupleCon Unboxed n_con_args
439 ubx_tup_ty = exprType ubx_tup_app
440 ubx_tup_app = mkConApp ubx_tup_con (map Type con_arg_tys ++ arg_vars)
441 con_app = mkProductBox args body_ty
443 return (\ wkr_call -> Case wkr_call (wrap_wild) (exprType con_app) [(DataAlt ubx_tup_con, args, con_app)],
444 \ body -> workerCase (work_wild) body args data_con ubx_tup_app,
447 (_arg_tycon, _tycon_arg_tys, data_con, con_arg_tys) = deepSplitProductType "mkWWcpr" body_ty
448 n_con_args = length con_arg_tys
449 con_arg_ty1 = head con_arg_tys
451 mkWWcpr body_ty _other -- No CPR info
452 = return (id, id, body_ty)
454 -- If the original function looked like
455 -- f = \ x -> _scc_ "foo" E
457 -- then we want the CPR'd worker to look like
458 -- \ x -> _scc_ "foo" (case E of I# x -> x)
459 -- and definitely not
460 -- \ x -> case (_scc_ "foo" E) of I# x -> x)
462 -- This transform doesn't move work or allocation
463 -- from one cost centre to another
464 workerCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
465 workerCase bndr (Note (SCC cc) e) args con body = Note (SCC cc) (mkUnpackCase bndr e args con body)
466 workerCase bndr e args con body = mkUnpackCase bndr e args con body
470 %************************************************************************
472 \subsection{Utilities}
474 %************************************************************************
478 mk_absent_let :: Id -> CoreExpr -> CoreExpr
479 mk_absent_let arg body
480 | not (isUnLiftedType arg_ty)
481 = Let (NonRec arg abs_rhs) body
483 = panic "WwLib: haven't done mk_absent_let for primitives yet"
486 abs_rhs = mkRuntimeErrorApp rUNTIME_ERROR_ID arg_ty msg
487 msg = "Oops! Entered absent arg " ++ showSDocDebug (ppr arg <+> ppr (idType arg))
489 mk_seq_case :: Id -> CoreExpr -> CoreExpr
490 mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) (exprType body) [(DEFAULT, [], body)]
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
503 mk_ww_local :: Unique -> Type -> Id
504 mk_ww_local uniq ty = mkSysLocal FSLIT("ww") uniq ty