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