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