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