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