Remove the (very) old strictness analyser
[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 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, idDemandInfo, setIdDemandInfo,
14                           isOneShotLambda, setOneShotLambda, setIdUnfolding,
15                           setIdInfo
16                         )
17 import IdInfo           ( vanillaIdInfo )
18 import DataCon
19 import Demand           ( Demand(..), DmdResult(..), Demands(..) ) 
20 import MkId             ( realWorldPrimId, voidArgId, mkRuntimeErrorApp, rUNTIME_ERROR_ID,
21                           mkUnpackCase, mkProductBox )
22 import TysWiredIn       ( tupleCon )
23 import Type
24 import Coercion         ( mkSymCoercion, splitNewTypeRepCo_maybe )
25 import BasicTypes       ( Boxity(..) )
26 import Var              ( Var )
27 import UniqSupply
28 import Unique
29 import Util             ( zipWithEqual )
30 import Outputable
31 import FastString
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   = do  { let arg_info = demands `zip` (one_shots ++ repeat False)
124         ; (wrap_args, wrap_fn_args, work_fn_args, res_ty) <- mkWWargs emptyTvSubst fun_ty arg_info
125         ; (work_args, wrap_fn_str,  work_fn_str) <- mkWWstr wrap_args
126
127         -- Don't do CPR if the worker doesn't have any value arguments
128         -- Then the worker is just a constant, so we don't want to unbox it.
129         ; (wrap_fn_cpr, work_fn_cpr,  _cpr_res_ty)
130                <- if any isId work_args then
131                      mkWWcpr res_ty res_info
132                   else
133                      return (id, id, res_ty)
134
135         ; let (work_lam_args, work_call_args) = mkWorkerArgs work_args res_ty
136         ; return ([idDemandInfo v | v <- work_call_args, isId v],
137                   wrap_fn_args . wrap_fn_cpr . wrap_fn_str . applyToVars work_call_args . Var,
138                   mkLams work_lam_args. work_fn_str . work_fn_cpr . work_fn_args) }
139         -- We use an INLINE unconditionally, even if the wrapper turns out to be
140         -- something trivial like
141         --      fw = ...
142         --      f = __inline__ (coerce T fw)
143         -- The point is to propagate the coerce to f's call sites, so even though
144         -- f's RHS is now trivial (size 1) we still want the __inline__ to prevent
145         -- fw from being inlined into f's RHS
146 \end{code}
147
148
149 %************************************************************************
150 %*                                                                      *
151 \subsection{Making wrapper args}
152 %*                                                                      *
153 %************************************************************************
154
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.
158
159         f = /\a -> \x y z -> E::Int#    -- E does not mention x,y,z
160 ==>
161         fw = /\ a -> \void -> E
162         f  = /\ a -> \x y z -> fw realworld
163
164 We use the state-token type which generates no code.
165
166 \begin{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)
173     = (args, args)
174     | otherwise 
175     = (args ++ [voidArgId], args ++ [realWorldPrimId])
176 \end{code}
177
178
179 %************************************************************************
180 %*                                                                      *
181 \subsection{Coercion stuff}
182 %*                                                                      *
183 %************************************************************************
184
185 We really want to "look through" coerces.
186 Reason: I've seen this situation:
187
188         let f = coerce T (\s -> E)
189         in \x -> case x of
190                     p -> coerce T' f
191                     q -> \s -> E2
192                     r -> coerce T' f
193
194 If only we w/w'd f, we'd get
195         let f = coerce T (\s -> fw s)
196             fw = \s -> E
197         in ...
198
199 Now we'll inline f to get
200
201         let fw = \s -> E
202         in \x -> case x of
203                     p -> fw
204                     q -> \s -> E2
205                     r -> fw
206
207 Now we'll see that fw has arity 1, and will arity expand
208 the \x to get what we want.
209
210 \begin{code}
211 -- mkWWargs just does eta expansion
212 -- 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
215
216 mkWWargs :: TvSubst             -- Freshening substitution to apply to the type
217                                 --   See Note [Freshen type variables]
218          -> Type                -- The type of the function
219          -> [(Demand,Bool)]     -- Demands and one-shot info for value arguments
220          -> UniqSM  ([Var],             -- Wrapper args
221                      CoreExpr -> CoreExpr,      -- Wrapper fn
222                      CoreExpr -> CoreExpr,      -- Worker fn
223                      Type)                      -- Type of wrapper body
224
225 mkWWargs subst fun_ty arg_info
226   | Just (rep_ty, co) <- splitNewTypeRepCo_maybe fun_ty
227         -- The newtype case is for when the function has
228         -- a recursive newtype after the arrow (rare)
229         -- We check for arity >= 0 to avoid looping in the case
230         -- of a function whose type is, in effect, infinite
231         -- [Arity is driven by looking at the term, not just the type.]
232         --
233         -- It's also important when we have a function returning (say) a pair
234         -- wrapped in a recursive newtype, at least if CPR analysis can look 
235         -- through such newtypes, which it probably can since they are 
236         -- simply coerces.
237         --
238         -- Note (Sept 08): This case applies even if demands is empty.
239         --                 I'm not quite sure why; perhaps it makes it
240         --                 easier for CPR
241   = do { (wrap_args, wrap_fn_args, work_fn_args, res_ty)
242             <-  mkWWargs subst rep_ty arg_info
243         ; return (wrap_args,
244                   \e -> Cast (wrap_fn_args e) (mkSymCoercion co),
245                   \e -> work_fn_args (Cast e co),
246                   res_ty) } 
247
248   | null arg_info
249   = return ([], id, id, substTy subst fun_ty)
250
251   | Just (tv, fun_ty') <- splitForAllTy_maybe fun_ty
252   = do  { let (subst', tv') = substTyVarBndr subst tv
253                 -- This substTyVarBndr clones the type variable when necy
254                 -- See Note [Freshen type variables]
255         ; (wrap_args, wrap_fn_args, work_fn_args, res_ty)
256              <- mkWWargs subst' fun_ty' arg_info
257         ; return (tv' : wrap_args,
258                   Lam tv' . wrap_fn_args,
259                   work_fn_args . (`App` Type (mkTyVarTy tv')),
260                   res_ty) }
261
262   | ((dmd,one_shot):arg_info') <- arg_info
263   , Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
264   = do  { uniq <- getUniqueM
265         ; let arg_ty' = substTy subst arg_ty
266               id = mk_wrap_arg uniq arg_ty' dmd one_shot
267         ; (wrap_args, wrap_fn_args, work_fn_args, res_ty)
268               <- mkWWargs subst fun_ty' arg_info'
269         ; return (id : wrap_args,
270                   Lam id . wrap_fn_args,
271                   work_fn_args . (`App` Var id),
272                   res_ty) }
273
274   | otherwise
275   = WARN( True, ppr fun_ty )                    -- Should not happen: if there is a demand
276     return ([], id, id, substTy subst fun_ty)   -- then there should be a function arrow
277
278 applyToVars :: [Var] -> CoreExpr -> CoreExpr
279 applyToVars vars fn = mkVarApps fn vars
280
281 mk_wrap_arg :: Unique -> Type -> Demand -> Bool -> Id
282 mk_wrap_arg uniq ty dmd one_shot 
283   = set_one_shot one_shot (setIdDemandInfo (mkSysLocal (fsLit "w") uniq ty) dmd)
284   where
285     set_one_shot True  id = setOneShotLambda id
286     set_one_shot False id = id
287 \end{code}
288
289 Note [Freshen type variables]
290 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
291 mkWWargs may be given a type like  (a~b) => <blah>
292 Which really means                 forall (co:a~b). <blah>
293 Because the name of the coercion variable, 'co', isn't mentioned in <blah>,
294 nested coercion foralls may all use the same variable; and sometimes do
295 see Var.mkWildCoVar.
296
297 However, when we do a worker/wrapper split, we must not use shadowed names,
298 else we'll get
299    f = /\ co /\co. fw co co
300 which is obviously wrong.  Actually, the same is true of type variables, which
301 can in principle shadow, within a type (e.g. forall a. a -> forall a. a->a).
302 But type variables *are* mentioned in <blah>, so we must substitute.
303
304 That's why we carry the TvSubst through mkWWargs
305         
306 %************************************************************************
307 %*                                                                      *
308 \subsection{Strictness stuff}
309 %*                                                                      *
310 %************************************************************************
311
312 \begin{code}
313 mkWWstr :: [Var]                                -- Wrapper args; have their demand info on them
314                                                 --  *Includes type variables*
315         -> UniqSM ([Var],                       -- Worker args
316                    CoreExpr -> CoreExpr,        -- Wrapper body, lacking the worker call
317                                                 -- and without its lambdas 
318                                                 -- This fn adds the unboxing
319                                 
320                    CoreExpr -> CoreExpr)        -- Worker body, lacking the original body of the function,
321                                                 -- and lacking its lambdas.
322                                                 -- This fn does the reboxing
323 mkWWstr []
324   = return ([], nop_fn, nop_fn)
325
326 mkWWstr (arg : args) = do
327     (args1, wrap_fn1, work_fn1) <- mkWWstr_one arg
328     (args2, wrap_fn2, work_fn2) <- mkWWstr args
329     return (args1 ++ args2, wrap_fn1 . wrap_fn2, work_fn1 . work_fn2)
330
331 ----------------------
332 -- mkWWstr_one wrap_arg = (work_args, wrap_fn, work_fn)
333 --   *  wrap_fn assumes wrap_arg is in scope,
334 --        brings into scope work_args (via cases)
335 --   * work_fn assumes work_args are in scope, a
336 --        brings into scope wrap_arg (via lets)
337 mkWWstr_one :: Var -> UniqSM ([Var], CoreExpr -> CoreExpr, CoreExpr -> CoreExpr)
338 mkWWstr_one arg
339   | isTyVar arg
340   = return ([arg],  nop_fn, nop_fn)
341
342   | otherwise
343   = case idDemandInfo arg of
344
345         -- Absent case.  We don't deal with absence for unlifted types,
346         -- though, because it's not so easy to manufacture a placeholder
347         -- We'll see if this turns out to be a problem
348       Abs | not (isUnLiftedType (idType arg)) ->
349         return ([], nop_fn, mk_absent_let arg) 
350
351         -- Unpack case
352       Eval (Prod cs)
353         | Just (_arg_tycon, _tycon_arg_tys, data_con, inst_con_arg_tys) 
354                 <- deepSplitProductType_maybe (idType arg)
355         -> do uniqs <- getUniquesM
356               let
357                 unpk_args      = zipWith mk_ww_local uniqs inst_con_arg_tys
358                 unpk_args_w_ds = zipWithEqual "mkWWstr" set_worker_arg_info unpk_args cs
359                 unbox_fn       = mkUnpackCase (sanitiseCaseBndr arg) (Var arg) unpk_args data_con
360                 rebox_fn       = Let (NonRec arg con_app) 
361                 con_app        = mkProductBox unpk_args (idType arg)
362               (worker_args, wrap_fn, work_fn) <- mkWWstr unpk_args_w_ds
363               return (worker_args, unbox_fn . wrap_fn, work_fn . rebox_fn) 
364                            -- Don't pass the arg, rebox instead
365
366         -- `seq` demand; evaluate in wrapper in the hope
367         -- of dropping seqs in the worker
368       Eval (Poly Abs)
369         -> let
370                 arg_w_unf = arg `setIdUnfolding` evaldUnfolding
371                 -- Tell the worker arg that it's sure to be evaluated
372                 -- so that internal seqs can be dropped
373            in
374            return ([arg_w_unf], mk_seq_case arg, nop_fn)
375                 -- Pass the arg, anyway, even if it is in theory discarded
376                 -- Consider
377                 --      f x y = x `seq` y
378                 -- x gets a (Eval (Poly Abs)) demand, but if we fail to pass it to the worker
379                 -- we ABSOLUTELY MUST record that x is evaluated in the wrapper.
380                 -- Something like:
381                 --      f x y = x `seq` fw y
382                 --      fw y = let x{Evald} = error "oops" in (x `seq` y)
383                 -- If we don't pin on the "Evald" flag, the seq doesn't disappear, and
384                 -- we end up evaluating the absent thunk.
385                 -- But the Evald flag is pretty weird, and I worry that it might disappear
386                 -- during simplification, so for now I've just nuked this whole case
387                         
388         -- Other cases
389       _other_demand -> return ([arg], nop_fn, nop_fn)
390
391   where
392         -- If the wrapper argument is a one-shot lambda, then
393         -- so should (all) the corresponding worker arguments be
394         -- This bites when we do w/w on a case join point
395     set_worker_arg_info worker_arg demand = set_one_shot (setIdDemandInfo worker_arg demand)
396
397     set_one_shot | isOneShotLambda arg = setOneShotLambda
398                  | otherwise           = \x -> x
399
400 ----------------------
401 nop_fn :: CoreExpr -> CoreExpr
402 nop_fn body = body
403 \end{code}
404
405
406 %************************************************************************
407 %*                                                                      *
408 \subsection{CPR stuff}
409 %*                                                                      *
410 %************************************************************************
411
412
413 @mkWWcpr@ takes the worker/wrapper pair produced from the strictness
414 info and adds in the CPR transformation.  The worker returns an
415 unboxed tuple containing non-CPR components.  The wrapper takes this
416 tuple and re-produces the correct structured output.
417
418 The non-CPR results appear ordered in the unboxed tuple as if by a
419 left-to-right traversal of the result structure.
420
421
422 \begin{code}
423 mkWWcpr :: Type                              -- function body type
424         -> DmdResult                         -- CPR analysis results
425         -> UniqSM (CoreExpr -> CoreExpr,             -- New wrapper 
426                    CoreExpr -> CoreExpr,             -- New worker
427                    Type)                        -- Type of worker's body 
428
429 mkWWcpr body_ty RetCPR
430     | not (isClosedAlgType body_ty)
431     = WARN( True, 
432             text "mkWWcpr: non-algebraic or open body type" <+> ppr body_ty )
433       return (id, id, body_ty)
434
435     | n_con_args == 1 && isUnLiftedType con_arg_ty1 = do
436         -- Special case when there is a single result of unlifted type
437         --
438         -- Wrapper:     case (..call worker..) of x -> C x
439         -- Worker:      case (   ..body..    ) of C x -> x
440       (work_uniq : arg_uniq : _) <- getUniquesM
441       let
442         work_wild = mk_ww_local work_uniq body_ty
443         arg       = mk_ww_local arg_uniq  con_arg_ty1
444         con_app   = mkProductBox [arg] body_ty
445
446       return (\ wkr_call -> Case wkr_call (arg) (exprType con_app) [(DEFAULT, [], con_app)],
447                 \ body     -> workerCase (work_wild) body [arg] data_con (Var arg),
448                 con_arg_ty1)
449
450     | otherwise = do    -- The general case
451         -- Wrapper: case (..call worker..) of (# a, b #) -> C a b
452         -- Worker:  case (   ...body...  ) of C a b -> (# a, b #)     
453       uniqs <- getUniquesM
454       let
455         (wrap_wild : work_wild : args) = zipWith mk_ww_local uniqs (ubx_tup_ty : body_ty : con_arg_tys)
456         arg_vars                       = map Var args
457         ubx_tup_con                    = tupleCon Unboxed n_con_args
458         ubx_tup_ty                     = exprType ubx_tup_app
459         ubx_tup_app                    = mkConApp ubx_tup_con (map Type con_arg_tys   ++ arg_vars)
460         con_app                        = mkProductBox args body_ty
461
462       return (\ wkr_call -> Case wkr_call (wrap_wild) (exprType con_app)  [(DataAlt ubx_tup_con, args, con_app)],
463                 \ body     -> workerCase (work_wild) body args data_con ubx_tup_app,
464                 ubx_tup_ty)
465     where
466       (_arg_tycon, _tycon_arg_tys, data_con, con_arg_tys) = deepSplitProductType "mkWWcpr" body_ty
467       n_con_args  = length con_arg_tys
468       con_arg_ty1 = head con_arg_tys
469
470 mkWWcpr body_ty _other          -- No CPR info
471     = return (id, id, body_ty)
472
473 -- If the original function looked like
474 --      f = \ x -> _scc_ "foo" E
475 --
476 -- then we want the CPR'd worker to look like
477 --      \ x -> _scc_ "foo" (case E of I# x -> x)
478 -- and definitely not
479 --      \ x -> case (_scc_ "foo" E) of I# x -> x)
480 --
481 -- This transform doesn't move work or allocation
482 -- from one cost centre to another
483 workerCase :: Id -> CoreExpr -> [Id] -> DataCon -> CoreExpr -> CoreExpr
484 workerCase bndr (Note (SCC cc) e) args con body = Note (SCC cc) (mkUnpackCase bndr e args con body)
485 workerCase bndr e args con body = mkUnpackCase bndr e args con body
486 \end{code}
487
488
489 %************************************************************************
490 %*                                                                      *
491 \subsection{Utilities}
492 %*                                                                      *
493 %************************************************************************
494
495
496 \begin{code}
497 mk_absent_let :: Id -> CoreExpr -> CoreExpr
498 mk_absent_let arg body
499   | not (isUnLiftedType arg_ty)
500   = Let (NonRec arg abs_rhs) body
501   | otherwise
502   = panic "WwLib: haven't done mk_absent_let for primitives yet"
503   where
504     arg_ty = idType arg
505     abs_rhs = mkRuntimeErrorApp rUNTIME_ERROR_ID arg_ty msg
506     msg     = "Oops!  Entered absent arg " ++ showSDocDebug (ppr arg <+> ppr (idType arg))
507
508 mk_seq_case :: Id -> CoreExpr -> CoreExpr
509 mk_seq_case arg body = Case (Var arg) (sanitiseCaseBndr arg) (exprType body) [(DEFAULT, [], body)]
510
511 sanitiseCaseBndr :: Id -> Id
512 -- The argument we are scrutinising has the right type to be
513 -- a case binder, so it's convenient to re-use it for that purpose.
514 -- But we *must* throw away all its IdInfo.  In particular, the argument
515 -- will have demand info on it, and that demand info may be incorrect for
516 -- the case binder.  e.g.       case ww_arg of ww_arg { I# x -> ... }
517 -- Quite likely ww_arg isn't used in '...'.  The case may get discarded
518 -- if the case binder says "I'm demanded".  This happened in a situation 
519 -- like         (x+y) `seq` ....
520 sanitiseCaseBndr id = id `setIdInfo` vanillaIdInfo
521
522 mk_ww_local :: Unique -> Type -> Id
523 mk_ww_local uniq ty = mkSysLocal (fsLit "ww") uniq ty
524 \end{code}