Add (a) CoreM monad, (b) new Annotations feature
[ghc-hetmet.git] / compiler / stranal / WorkWrap.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[WorkWrap]{Worker/wrapper-generating back-end of 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 WorkWrap ( wwTopBinds, mkWrapper ) where
15
16 #include "HsVersions.h"
17
18 import CoreSyn
19 import CoreUnfold       ( certainlyWillInline )
20 import CoreLint         ( showPass, endPass )
21 import CoreUtils        ( exprType, exprIsHNF, exprArity )
22 import Id               ( Id, idType, isOneShotLambda, 
23                           setIdNewStrictness, mkWorkerId,
24                           setIdWorkerInfo, setInlinePragma,
25                           setIdArity, idInfo )
26 import MkId             ( lazyIdKey, lazyIdUnfolding )
27 import Type             ( Type )
28 import IdInfo           ( WorkerInfo(..), arityInfo,
29                           newDemandInfo, newStrictnessInfo, unfoldingInfo, inlinePragInfo
30                         )
31 import NewDemand        ( Demand(..), StrictSig(..), DmdType(..), DmdResult(..), 
32                           Demands(..), mkTopDmdType, isBotRes, returnsCPR, topSig, isAbsent
33                         )
34 import UniqSupply
35 import Unique           ( hasKey )
36 import BasicTypes       ( RecFlag(..), isNonRec, isNeverActive )
37 import VarEnv           ( isEmptyVarEnv )
38 import Maybes           ( orElse )
39 import WwLib
40 import Util             ( lengthIs, notNull )
41 import Outputable
42 import MonadUtils
43 \end{code}
44
45 We take Core bindings whose binders have:
46
47 \begin{enumerate}
48
49 \item Strictness attached (by the front-end of the strictness
50 analyser), and / or
51
52 \item Constructed Product Result information attached by the CPR
53 analysis pass.
54
55 \end{enumerate}
56
57 and we return some ``plain'' bindings which have been
58 worker/wrapper-ified, meaning: 
59
60 \begin{enumerate} 
61
62 \item Functions have been split into workers and wrappers where
63 appropriate.  If a function has both strictness and CPR properties
64 then only one worker/wrapper doing both transformations is produced;
65
66 \item Binders' @IdInfos@ have been updated to reflect the existence of
67 these workers/wrappers (this is where we get STRICTNESS and CPR pragma
68 info for exported values).
69 \end{enumerate}
70
71 \begin{code}
72 wwTopBinds :: UniqSupply -> [CoreBind] -> [CoreBind]
73
74 wwTopBinds us top_binds
75   = initUs_ us $ do
76     top_binds' <- mapM wwBind top_binds
77     return (concat top_binds')
78 \end{code}
79
80 %************************************************************************
81 %*                                                                      *
82 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
83 %*                                                                      *
84 %************************************************************************
85
86 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
87 turn.  Non-recursive case first, then recursive...
88
89 \begin{code}
90 wwBind  :: CoreBind
91         -> UniqSM [CoreBind]    -- returns a WwBinding intermediate form;
92                                 -- the caller will convert to Expr/Binding,
93                                 -- as appropriate.
94
95 wwBind (NonRec binder rhs) = do
96     new_rhs <- wwExpr rhs
97     new_pairs <- tryWW NonRecursive binder new_rhs
98     return [NonRec b e | (b,e) <- new_pairs]
99       -- Generated bindings must be non-recursive
100       -- because the original binding was.
101
102 wwBind (Rec pairs)
103   = return . Rec <$> concatMapM do_one pairs
104   where
105     do_one (binder, rhs) = do new_rhs <- wwExpr rhs
106                               tryWW Recursive binder new_rhs
107 \end{code}
108
109 @wwExpr@ basically just walks the tree, looking for appropriate
110 annotations that can be used. Remember it is @wwBind@ that does the
111 matching by looking for strict arguments of the correct type.
112 @wwExpr@ is a version that just returns the ``Plain'' Tree.
113
114 \begin{code}
115 wwExpr :: CoreExpr -> UniqSM CoreExpr
116
117 wwExpr e@(Type _)             = return e
118 wwExpr e@(Lit _)              = return e
119 wwExpr e@(Note InlineMe expr) = return e
120         -- Don't w/w inside InlineMe's
121
122 wwExpr e@(Var v)
123   | v `hasKey` lazyIdKey = return lazyIdUnfolding
124   | otherwise            = return e
125         -- HACK alert: Inline 'lazy' after strictness analysis
126         -- (but not inside InlineMe's)
127
128 wwExpr (Lam binder expr)
129   = Lam binder <$> wwExpr expr
130
131 wwExpr (App f a)
132   = App <$> wwExpr f <*> wwExpr a
133
134 wwExpr (Note note expr)
135   = Note note <$> wwExpr expr
136
137 wwExpr (Cast expr co) = do
138     new_expr <- wwExpr expr
139     return (Cast new_expr co)
140
141 wwExpr (Let bind expr)
142   = mkLets <$> wwBind bind <*> wwExpr expr
143
144 wwExpr (Case expr binder ty alts) = do
145     new_expr <- wwExpr expr
146     new_alts <- mapM ww_alt alts
147     return (Case new_expr binder ty new_alts)
148   where
149     ww_alt (con, binders, rhs) = do
150         new_rhs <- wwExpr rhs
151         return (con, binders, new_rhs)
152 \end{code}
153
154 %************************************************************************
155 %*                                                                      *
156 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
157 %*                                                                      *
158 %************************************************************************
159
160 @tryWW@ just accumulates arguments, converts strictness info from the
161 front-end into the proper form, then calls @mkWwBodies@ to do
162 the business.
163
164 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
165 already been w-w'd!  (You can end up with several liked-named Ids
166 bouncing around at the same time---absolute mischief.)  So the
167 criterion we use is: if an Id already has an unfolding (for whatever
168 reason), then we don't w-w it.
169
170 The only reason this is monadised is for the unique supply.
171
172 Note [Don't w/w inline things]
173 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
174 It's very important to refrain from w/w-ing an INLINE function
175 If we do so by mistake we transform
176         f = __inline (\x -> E)
177 into
178         f = __inline (\x -> case x of (a,b) -> fw E)
179         fw = \ab -> (__inline (\x -> E)) (a,b)
180 and the original __inline now vanishes, so E is no longer
181 inside its __inline wrapper.  Death!  Disaster!
182
183 Furthermore, if the programmer has marked something as INLINE, 
184 we may lose by w/w'ing it.
185
186 If the strictness analyser is run twice, this test also prevents
187 wrappers (which are INLINEd) from being re-done.
188
189 Notice that we refrain from w/w'ing an INLINE function even if it is
190 in a recursive group.  It might not be the loop breaker.  (We could
191 test for loop-breaker-hood, but I'm not sure that ever matters.)
192
193 \begin{code}
194 tryWW   :: RecFlag
195         -> Id                           -- The fn binder
196         -> CoreExpr                     -- The bound rhs; its innards
197                                         --   are already ww'd
198         -> UniqSM [(Id, CoreExpr)]      -- either *one* or *two* pairs;
199                                         -- if one, then no worker (only
200                                         -- the orig "wrapper" lives on);
201                                         -- if two, then a worker and a
202                                         -- wrapper.
203 tryWW is_rec fn_id rhs
204   |  -- isNonRec is_rec &&      -- Now omitted: see Note [Don't w/w inline things]
205      certainlyWillInline unfolding
206
207   || isNeverActive inline_prag
208         -- No point in worker/wrappering if the thing is never inlined!
209         -- Because the no-inline prag will prevent the wrapper ever
210         -- being inlined at a call site. 
211   = return [ (new_fn_id, rhs) ]
212
213   | is_thunk && worthSplittingThunk maybe_fn_dmd res_info
214   = ASSERT2( isNonRec is_rec, ppr new_fn_id )   -- The thunk must be non-recursive
215     splitThunk new_fn_id rhs
216
217   | is_fun && worthSplittingFun wrap_dmds res_info
218   = splitFun new_fn_id fn_info wrap_dmds res_info inline_prag rhs
219
220   | otherwise
221   = return [ (new_fn_id, rhs) ]
222
223   where
224     fn_info      = idInfo fn_id
225     maybe_fn_dmd = newDemandInfo fn_info
226     unfolding    = unfoldingInfo fn_info
227     inline_prag  = inlinePragInfo fn_info
228
229         -- In practice it always will have a strictness 
230         -- signature, even if it's a uninformative one
231     strict_sig  = newStrictnessInfo fn_info `orElse` topSig
232     StrictSig (DmdType env wrap_dmds res_info) = strict_sig
233
234         -- new_fn_id has the DmdEnv zapped.  
235         --      (a) it is never used again
236         --      (b) it wastes space
237         --      (c) it becomes incorrect as things are cloned, because
238         --          we don't push the substitution into it
239     new_fn_id | isEmptyVarEnv env = fn_id
240               | otherwise         = fn_id `setIdNewStrictness` 
241                                      StrictSig (mkTopDmdType wrap_dmds res_info)
242
243     is_fun    = notNull wrap_dmds
244     is_thunk  = not is_fun && not (exprIsHNF rhs)
245
246 ---------------------
247 splitFun fn_id fn_info wrap_dmds res_info inline_prag rhs
248   = WARN( not (wrap_dmds `lengthIs` arity), ppr fn_id <+> (ppr arity $$ ppr wrap_dmds $$ ppr res_info) ) 
249     (do {
250         -- The arity should match the signature
251       (work_demands, wrap_fn, work_fn) <- mkWwBodies fun_ty wrap_dmds res_info one_shots
252     ; work_uniq <- getUniqueM
253     ; let
254         work_rhs = work_fn rhs
255         work_id  = mkWorkerId work_uniq fn_id (exprType work_rhs) 
256                         `setInlinePragma` inline_prag
257                                 -- Any inline pragma (which sets when inlining is active) 
258                                 -- on the original function is duplicated on the worker and wrapper
259                                 -- It *matters* that the pragma stays on the wrapper
260                                 -- It seems sensible to have it on the worker too, although we
261                                 -- can't think of a compelling reason. (In ptic, INLINE things are 
262                                 -- not w/wd)
263                         `setIdNewStrictness` StrictSig (mkTopDmdType work_demands work_res_info)
264                                 -- Even though we may not be at top level, 
265                                 -- it's ok to give it an empty DmdEnv
266                         `setIdArity` (exprArity work_rhs)
267                                 -- Set the arity so that the Core Lint check that the 
268                                 -- arity is consistent with the demand type goes through
269
270         wrap_rhs = wrap_fn work_id
271         wrap_id  = fn_id `setIdWorkerInfo` HasWorker work_id arity
272
273     ; return ([(work_id, work_rhs), (wrap_id, wrap_rhs)]) })
274         -- Worker first, because wrapper mentions it
275         -- mkWwBodies has already built a wrap_rhs with an INLINE pragma wrapped around it
276   where
277     fun_ty = idType fn_id
278
279     arity  = arityInfo fn_info  -- The arity is set by the simplifier using exprEtaExpandArity
280                                 -- So it may be more than the number of top-level-visible lambdas
281
282     work_res_info | isBotRes res_info = BotRes  -- Cpr stuff done by wrapper
283                   | otherwise         = TopRes
284
285     one_shots = get_one_shots rhs
286
287 -- If the original function has one-shot arguments, it is important to
288 -- make the wrapper and worker have corresponding one-shot arguments too.
289 -- Otherwise we spuriously float stuff out of case-expression join points,
290 -- which is very annoying.
291 get_one_shots (Lam b e)
292   | isIdVar b = isOneShotLambda b : get_one_shots e
293   | otherwise = get_one_shots e
294 get_one_shots (Note _ e) = get_one_shots e
295 get_one_shots other      = noOneShotInfo
296 \end{code}
297
298 Thunk splitting
299 ~~~~~~~~~~~~~~~
300 Suppose x is used strictly (never mind whether it has the CPR
301 property).  
302
303       let
304         x* = x-rhs
305       in body
306
307 splitThunk transforms like this:
308
309       let
310         x* = case x-rhs of { I# a -> I# a }
311       in body
312
313 Now simplifier will transform to
314
315       case x-rhs of 
316         I# a -> let x* = I# a 
317                 in body
318
319 which is what we want. Now suppose x-rhs is itself a case:
320
321         x-rhs = case e of { T -> I# a; F -> I# b }
322
323 The join point will abstract over a, rather than over (which is
324 what would have happened before) which is fine.
325
326 Notice that x certainly has the CPR property now!
327
328 In fact, splitThunk uses the function argument w/w splitting 
329 function, so that if x's demand is deeper (say U(U(L,L),L))
330 then the splitting will go deeper too.
331
332 \begin{code}
333 -- splitThunk converts the *non-recursive* binding
334 --      x = e
335 -- into
336 --      x = let x = e
337 --          in case x of 
338 --               I# y -> let x = I# y in x }
339 -- See comments above. Is it not beautifully short?
340
341 splitThunk fn_id rhs = do
342     (_, wrap_fn, work_fn) <- mkWWstr [fn_id]
343     return [ (fn_id, Let (NonRec fn_id rhs) (wrap_fn (work_fn (Var fn_id)))) ]
344 \end{code}
345
346
347 %************************************************************************
348 %*                                                                      *
349 \subsection{Functions over Demands}
350 %*                                                                      *
351 %************************************************************************
352
353 \begin{code}
354 worthSplittingFun :: [Demand] -> DmdResult -> Bool
355                 -- True <=> the wrapper would not be an identity function
356 worthSplittingFun ds res
357   = any worth_it ds || returnsCPR res
358         -- worthSplitting returns False for an empty list of demands,
359         -- and hence do_strict_ww is False if arity is zero and there is no CPR
360   -- See Note [Worker-wrapper for bottoming functions]
361   where
362     worth_it Abs              = True    -- Absent arg
363     worth_it (Eval (Prod ds)) = True    -- Product arg to evaluate
364     worth_it other            = False
365
366 worthSplittingThunk :: Maybe Demand     -- Demand on the thunk
367                     -> DmdResult        -- CPR info for the thunk
368                     -> Bool
369 worthSplittingThunk maybe_dmd res
370   = worth_it maybe_dmd || returnsCPR res
371   where
372         -- Split if the thing is unpacked
373     worth_it (Just (Eval (Prod ds))) = not (all isAbsent ds)
374     worth_it other                   = False
375 \end{code}
376
377 Note [Worker-wrapper for bottoming functions]
378 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
379 We used not to split if the result is bottom.
380 [Justification:  there's no efficiency to be gained.]
381
382 But it's sometimes bad not to make a wrapper.  Consider
383         fw = \x# -> let x = I# x# in case e of
384                                         p1 -> error_fn x
385                                         p2 -> error_fn x
386                                         p3 -> the real stuff
387 The re-boxing code won't go away unless error_fn gets a wrapper too.
388 [We don't do reboxing now, but in general it's better to pass an
389 unboxed thing to f, and have it reboxed in the error cases....]
390
391
392 %************************************************************************
393 %*                                                                      *
394 \subsection{The worker wrapper core}
395 %*                                                                      *
396 %************************************************************************
397
398 @mkWrapper@ is called when importing a function.  We have the type of 
399 the function and the name of its worker, and we want to make its body (the wrapper).
400
401 \begin{code}
402 mkWrapper :: Type               -- Wrapper type
403           -> StrictSig          -- Wrapper strictness info
404           -> UniqSM (Id -> CoreExpr)    -- Wrapper body, missing worker Id
405
406 mkWrapper fun_ty (StrictSig (DmdType _ demands res_info)) = do
407     (_, wrap_fn, _) <- mkWwBodies fun_ty demands res_info noOneShotInfo
408     return wrap_fn
409
410 noOneShotInfo = repeat False
411 \end{code}