2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[WorkWrap]{Worker/wrapper-generating back-end of strictness analyser}
7 module WorkWrap ( wwTopBinds, mkWrapper ) where
9 #include "HsVersions.h"
12 import CoreUnfold ( certainlyWillInline )
13 import CoreLint ( showPass, endPass )
14 import CoreUtils ( exprType )
15 import Id ( Id, idType, idNewStrictness, idArity, isOneShotLambda,
16 setIdNewStrictness, zapIdNewStrictness, idInlinePragma, mkWorkerId,
17 setIdWorkerInfo, setInlinePragma )
19 import IdInfo ( InlinePragInfo(..), isNeverInlinePrag, WorkerInfo(..) )
20 import NewDemand ( Demand(..), StrictSig(..), DmdType(..), DmdResult(..),
21 mkTopDmdType, isBotRes, returnsCPR
23 import UniqSupply ( UniqSupply, initUs_, returnUs, thenUs, mapUs, getUniqueUs, UniqSM )
24 import BasicTypes ( RecFlag(..), isNonRec )
30 We take Core bindings whose binders have:
34 \item Strictness attached (by the front-end of the strictness
37 \item Constructed Product Result information attached by the CPR
42 and we return some ``plain'' bindings which have been
43 worker/wrapper-ified, meaning:
47 \item Functions have been split into workers and wrappers where
48 appropriate. If a function has both strictness and CPR properties
49 then only one worker/wrapper doing both transformations is produced;
51 \item Binders' @IdInfos@ have been updated to reflect the existence of
52 these workers/wrappers (this is where we get STRICTNESS and CPR pragma
53 info for exported values).
58 wwTopBinds :: DynFlags
63 wwTopBinds dflags us binds
65 showPass dflags "Worker Wrapper binds";
67 -- Create worker/wrappers, and mark binders with their
68 -- "strictness info" [which encodes their worker/wrapper-ness]
69 let { binds' = workersAndWrappers us binds };
71 endPass dflags "Worker Wrapper binds"
72 Opt_D_dump_worker_wrapper binds'
78 workersAndWrappers :: UniqSupply -> [CoreBind] -> [CoreBind]
80 workersAndWrappers us top_binds
82 mapUs wwBind top_binds `thenUs` \ top_binds' ->
83 returnUs (concat top_binds')
86 %************************************************************************
88 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
90 %************************************************************************
92 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
93 turn. Non-recursive case first, then recursive...
97 -> UniqSM [CoreBind] -- returns a WwBinding intermediate form;
98 -- the caller will convert to Expr/Binding,
101 wwBind (NonRec binder rhs)
102 = wwExpr rhs `thenUs` \ new_rhs ->
103 tryWW NonRecursive binder new_rhs `thenUs` \ new_pairs ->
104 returnUs [NonRec b e | (b,e) <- new_pairs]
105 -- Generated bindings must be non-recursive
106 -- because the original binding was.
109 = mapUs do_one pairs `thenUs` \ new_pairs ->
110 returnUs [Rec (concat new_pairs)]
112 do_one (binder, rhs) = wwExpr rhs `thenUs` \ new_rhs ->
113 tryWW Recursive binder new_rhs
116 @wwExpr@ basically just walks the tree, looking for appropriate
117 annotations that can be used. Remember it is @wwBind@ that does the
118 matching by looking for strict arguments of the correct type.
119 @wwExpr@ is a version that just returns the ``Plain'' Tree.
122 wwExpr :: CoreExpr -> UniqSM CoreExpr
124 wwExpr e@(Type _) = returnUs e
125 wwExpr e@(Var _) = returnUs e
126 wwExpr e@(Lit _) = returnUs e
128 wwExpr (Lam binder expr)
129 = wwExpr expr `thenUs` \ new_expr ->
130 returnUs (Lam binder new_expr)
133 = wwExpr f `thenUs` \ new_f ->
134 wwExpr a `thenUs` \ new_a ->
135 returnUs (App new_f new_a)
137 wwExpr (Note note expr)
138 = wwExpr expr `thenUs` \ new_expr ->
139 returnUs (Note note new_expr)
141 wwExpr (Let bind expr)
142 = wwBind bind `thenUs` \ intermediate_bind ->
143 wwExpr expr `thenUs` \ new_expr ->
144 returnUs (mkLets intermediate_bind new_expr)
146 wwExpr (Case expr binder alts)
147 = wwExpr expr `thenUs` \ new_expr ->
148 mapUs ww_alt alts `thenUs` \ new_alts ->
149 returnUs (Case new_expr binder new_alts)
151 ww_alt (con, binders, rhs)
152 = wwExpr rhs `thenUs` \ new_rhs ->
153 returnUs (con, binders, new_rhs)
156 %************************************************************************
158 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
160 %************************************************************************
162 @tryWW@ just accumulates arguments, converts strictness info from the
163 front-end into the proper form, then calls @mkWwBodies@ to do
166 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
167 already been w-w'd! (You can end up with several liked-named Ids
168 bouncing around at the same time---absolute mischief.) So the
169 criterion we use is: if an Id already has an unfolding (for whatever
170 reason), then we don't w-w it.
172 The only reason this is monadised is for the unique supply.
176 -> Id -- The fn binder
177 -> CoreExpr -- The bound rhs; its innards
179 -> UniqSM [(Id, CoreExpr)] -- either *one* or *two* pairs;
180 -- if one, then no worker (only
181 -- the orig "wrapper" lives on);
182 -- if two, then a worker and a
184 tryWW is_rec fn_id rhs
185 | isNeverInlinePrag inline_prag
186 -- Don't split NOINLINE things, because they will never be inlined
187 -- Furthermore, zap the strictess info in the Id. Why? Because
188 -- the NOINLINE says "don't expose any of the inner workings at the call
189 -- site" and the strictness is certainly an inner working.
191 -- More concretely, the demand analyser discovers the following strictness
192 -- for unsafePerformIO: C(U(AV))
194 -- unsafePerformIO (\s -> let r = f x in
195 -- case writeIORef v r s of (# s1, _ #) ->
197 -- The strictness analyser will find that the binding for r is strict,
198 -- (becuase of uPIO's strictness sig), and so it'll evaluate it before
199 -- doing the writeIORef. This actually makes tests/lib/should_run/memo002
202 -- Solution: don't expose the strictness of unsafePerformIO.
203 = returnUs [ (zapIdNewStrictness fn_id, rhs) ]
206 -- Don't worker-wrapper thunks
207 || isNonRec is_rec && certainlyWillInline fn_id
208 -- No point in worker/wrappering a function that is going to be
209 -- INLINEd wholesale anyway. If the strictness analyser is run
210 -- twice, this test also prevents wrappers (which are INLINEd)
211 -- from being re-done.
213 -- It's very important to refrain from w/w-ing an INLINE function
214 -- If we do so by mistake we transform
215 -- f = __inline (\x -> E)
217 -- f = __inline (\x -> case x of (a,b) -> fw E)
218 -- fw = \ab -> (__inline (\x -> E)) (a,b)
219 -- and the original __inline now vanishes, so E is no longer
220 -- inside its __inline wrapper. Death! Disaster!
221 || not (worthSplitting strict_sig)
222 -- Strictness info suggests not to w/w
223 = returnUs [ (fn_id, rhs) ]
225 | otherwise -- Do w/w split!
226 = WARN( arity /= length wrap_dmds, ppr fn_id <+> (ppr arity $$ ppr strict_sig) )
227 -- The arity should match the signature
228 mkWwBodies fun_ty wrap_dmds res_info one_shots `thenUs` \ (work_demands, wrap_fn, work_fn) ->
229 getUniqueUs `thenUs` \ work_uniq ->
231 work_rhs = work_fn rhs
232 work_id = mkWorkerId work_uniq fn_id (exprType work_rhs)
233 `setInlinePragma` inline_prag
234 `setIdNewStrictness` StrictSig (mkTopDmdType work_demands work_res_info)
235 -- Even though we may not be at top level,
236 -- it's ok to give it an empty DmdEnv
238 wrap_rhs = wrap_fn work_id
239 wrap_id = fn_id `setIdWorkerInfo` HasWorker work_id arity
240 `setInlinePragma` NoInlinePragInfo -- Zap any inline pragma;
241 -- Put it on the worker instead
243 returnUs ([(work_id, work_rhs), (wrap_id, wrap_rhs)])
244 -- Worker first, because wrapper mentions it
245 -- mkWwBodies has already built a wrap_rhs with an INLINE pragma wrapped around it
247 fun_ty = idType fn_id
248 arity = idArity fn_id -- The arity is set by the simplifier using exprEtaExpandArity
249 -- So it may be more than the number of top-level-visible lambdas
251 inline_prag = idInlinePragma fn_id
252 strict_sig = idNewStrictness fn_id
254 StrictSig (DmdType _ wrap_dmds res_info) = strict_sig
255 work_res_info | isBotRes res_info = BotRes -- Cpr stuff done by wrapper
258 one_shots = get_one_shots rhs
260 -- If the original function has one-shot arguments, it is important to
261 -- make the wrapper and worker have corresponding one-shot arguments too.
262 -- Otherwise we spuriously float stuff out of case-expression join points,
263 -- which is very annoying.
264 get_one_shots (Lam b e)
265 | isId b = isOneShotLambda b : get_one_shots e
266 | otherwise = get_one_shots e
267 get_one_shots (Note _ e) = get_one_shots e
268 get_one_shots other = noOneShotInfo
272 %************************************************************************
274 \subsection{Functions over Demands}
276 %************************************************************************
279 worthSplitting :: StrictSig -> Bool
280 -- True <=> the wrapper would not be an identity function
281 worthSplitting (StrictSig (DmdType _ ds res))
282 = any worth_it ds || returnsCPR res
283 -- worthSplitting returns False for an empty list of demands,
284 -- and hence do_strict_ww is False if arity is zero
286 -- We used not to split if the result is bottom.
287 -- [Justification: there's no efficiency to be gained.]
288 -- But it's sometimes bad not to make a wrapper. Consider
289 -- fw = \x# -> let x = I# x# in case e of
292 -- p3 -> the real stuff
293 -- The re-boxing code won't go away unless error_fn gets a wrapper too.
294 -- [We don't do reboxing now, but in general it's better to pass
295 -- an unboxed thing to f, and have it reboxed in the error cases....]
297 worth_it Abs = True -- Absent arg
298 worth_it (Seq _ ds) = True -- Arg to evaluate
299 worth_it other = False
304 %************************************************************************
306 \subsection{The worker wrapper core}
308 %************************************************************************
310 @mkWrapper@ is called when importing a function. We have the type of
311 the function and the name of its worker, and we want to make its body (the wrapper).
314 mkWrapper :: Type -- Wrapper type
315 -> StrictSig -- Wrapper strictness info
316 -> UniqSM (Id -> CoreExpr) -- Wrapper body, missing worker Id
318 mkWrapper fun_ty (StrictSig (DmdType _ demands res_info))
319 = mkWwBodies fun_ty demands res_info noOneShotInfo `thenUs` \ (_, wrap_fn, _) ->
322 noOneShotInfo = repeat False