fff708237b2f4e825eb876f1d7df9a0213a0df97
[ghc-hetmet.git] / ghc / 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 module WorkWrap ( wwTopBinds, mkWrapper ) where
8
9 #include "HsVersions.h"
10
11 import CoreSyn
12 import CoreUnfold       ( certainlyWillInline )
13 import CoreLint         ( showPass, endPass )
14 import CoreUtils        ( exprType )
15 import Id               ( Id, idType, idNewStrictness, idArity, isOneShotLambda,
16                           setIdNewStrictness, zapIdNewStrictness, idInlinePragma, mkWorkerId,
17                           setIdWorkerInfo, idCprInfo, setInlinePragma )
18 import Type             ( Type )
19 import IdInfo           ( mkStrictnessInfo, noStrictnessInfo, StrictnessInfo(..),
20                           CprInfo(..), InlinePragInfo(..), isNeverInlinePrag,
21                           WorkerInfo(..)
22                         )
23 import NewDemand        ( Demand(..), StrictSig(..), DmdType(..), DmdResult(..), 
24                           mkTopDmdType, isBotRes, returnsCPR
25                         )
26 import UniqSupply       ( UniqSupply, initUs_, returnUs, thenUs, mapUs, getUniqueUs, UniqSM )
27 import BasicTypes       ( RecFlag(..), isNonRec )
28 import CmdLineOpts
29 import WwLib
30 import Outputable
31 \end{code}
32
33 We take Core bindings whose binders have:
34
35 \begin{enumerate}
36
37 \item Strictness attached (by the front-end of the strictness
38 analyser), and / or
39
40 \item Constructed Product Result information attached by the CPR
41 analysis pass.
42
43 \end{enumerate}
44
45 and we return some ``plain'' bindings which have been
46 worker/wrapper-ified, meaning: 
47
48 \begin{enumerate} 
49
50 \item Functions have been split into workers and wrappers where
51 appropriate.  If a function has both strictness and CPR properties
52 then only one worker/wrapper doing both transformations is produced;
53
54 \item Binders' @IdInfos@ have been updated to reflect the existence of
55 these workers/wrappers (this is where we get STRICTNESS and CPR pragma
56 info for exported values).
57 \end{enumerate}
58
59 \begin{code}
60
61 wwTopBinds :: DynFlags 
62            -> UniqSupply
63            -> [CoreBind]
64            -> IO [CoreBind]
65
66 wwTopBinds dflags us binds
67   = do {
68         showPass dflags "Worker Wrapper binds";
69
70         -- Create worker/wrappers, and mark binders with their
71         -- "strictness info" [which encodes their worker/wrapper-ness]
72         let { binds' = workersAndWrappers us binds };
73
74         endPass dflags "Worker Wrapper binds" 
75                 Opt_D_dump_worker_wrapper binds'
76     }
77 \end{code}
78
79
80 \begin{code}
81 workersAndWrappers :: UniqSupply -> [CoreBind] -> [CoreBind]
82
83 workersAndWrappers us top_binds
84   = initUs_ us $
85     mapUs wwBind top_binds `thenUs` \ top_binds' ->
86     returnUs (concat top_binds')
87 \end{code}
88
89 %************************************************************************
90 %*                                                                      *
91 \subsection[wwBind-wwExpr]{@wwBind@ and @wwExpr@}
92 %*                                                                      *
93 %************************************************************************
94
95 @wwBind@ works on a binding, trying each \tr{(binder, expr)} pair in
96 turn.  Non-recursive case first, then recursive...
97
98 \begin{code}
99 wwBind  :: CoreBind
100         -> UniqSM [CoreBind]    -- returns a WwBinding intermediate form;
101                                 -- the caller will convert to Expr/Binding,
102                                 -- as appropriate.
103
104 wwBind (NonRec binder rhs)
105   = wwExpr rhs                          `thenUs` \ new_rhs ->
106     tryWW NonRecursive binder new_rhs   `thenUs` \ new_pairs ->
107     returnUs [NonRec b e | (b,e) <- new_pairs]
108       -- Generated bindings must be non-recursive
109       -- because the original binding was.
110
111 wwBind (Rec pairs)
112   = mapUs do_one pairs          `thenUs` \ new_pairs ->
113     returnUs [Rec (concat new_pairs)]
114   where
115     do_one (binder, rhs) = wwExpr rhs   `thenUs` \ new_rhs ->
116                            tryWW Recursive binder new_rhs
117 \end{code}
118
119 @wwExpr@ basically just walks the tree, looking for appropriate
120 annotations that can be used. Remember it is @wwBind@ that does the
121 matching by looking for strict arguments of the correct type.
122 @wwExpr@ is a version that just returns the ``Plain'' Tree.
123
124 \begin{code}
125 wwExpr :: CoreExpr -> UniqSM CoreExpr
126
127 wwExpr e@(Type _)   = returnUs e
128 wwExpr e@(Var _)    = returnUs e
129 wwExpr e@(Lit _)    = returnUs e
130
131 wwExpr (Lam binder expr)
132   = wwExpr expr                 `thenUs` \ new_expr ->
133     returnUs (Lam binder new_expr)
134
135 wwExpr (App f a)
136   = wwExpr f                    `thenUs` \ new_f ->
137     wwExpr a                    `thenUs` \ new_a ->
138     returnUs (App new_f new_a)
139
140 wwExpr (Note note expr)
141   = wwExpr expr                 `thenUs` \ new_expr ->
142     returnUs (Note note new_expr)
143
144 wwExpr (Let bind expr)
145   = wwBind bind                 `thenUs` \ intermediate_bind ->
146     wwExpr expr                 `thenUs` \ new_expr ->
147     returnUs (mkLets intermediate_bind new_expr)
148
149 wwExpr (Case expr binder alts)
150   = wwExpr expr                         `thenUs` \ new_expr ->
151     mapUs ww_alt alts                   `thenUs` \ new_alts ->
152     returnUs (Case new_expr binder new_alts)
153   where
154     ww_alt (con, binders, rhs)
155       = wwExpr rhs                      `thenUs` \ new_rhs ->
156         returnUs (con, binders, new_rhs)
157 \end{code}
158
159 %************************************************************************
160 %*                                                                      *
161 \subsection[tryWW]{@tryWW@: attempt a worker/wrapper pair}
162 %*                                                                      *
163 %************************************************************************
164
165 @tryWW@ just accumulates arguments, converts strictness info from the
166 front-end into the proper form, then calls @mkWwBodies@ to do
167 the business.
168
169 We have to BE CAREFUL that we don't worker-wrapperize an Id that has
170 already been w-w'd!  (You can end up with several liked-named Ids
171 bouncing around at the same time---absolute mischief.)  So the
172 criterion we use is: if an Id already has an unfolding (for whatever
173 reason), then we don't w-w it.
174
175 The only reason this is monadised is for the unique supply.
176
177 \begin{code}
178 tryWW   :: RecFlag
179         -> Id                           -- The fn binder
180         -> CoreExpr                     -- The bound rhs; its innards
181                                         --   are already ww'd
182         -> UniqSM [(Id, CoreExpr)]      -- either *one* or *two* pairs;
183                                         -- if one, then no worker (only
184                                         -- the orig "wrapper" lives on);
185                                         -- if two, then a worker and a
186                                         -- wrapper.
187 tryWW is_rec fn_id rhs
188   | isNeverInlinePrag inline_prag
189         -- Don't split NOINLINE things, because they will never be inlined
190         -- Furthermore, zap the strictess info in the Id.  Why?  Because
191         -- the NOINLINE says "don't expose any of the inner workings at the call 
192         -- site" and the strictness is certainly an inner working.
193         --
194         -- More concretely, the demand analyser discovers the following strictness
195         -- for unsafePerformIO:  C(U(AV))
196         -- But then consider
197         --      unsafePerformIO (\s -> let r = f x in 
198         --                             case writeIORef v r s of (# s1, _ #) ->
199         --                             (# s1, r #)
200         -- The strictness analyser will find that the binding for r is strict,
201         -- (becuase of uPIO's strictness sig), and so it'll evaluate it before 
202         -- doing the writeIORef.  This actually makes tests/lib/should_run/memo002
203         -- get a deadlock!  
204         --
205         -- Solution: don't expose the strictness of unsafePerformIO.
206   = returnUs [ (zapIdNewStrictness fn_id, rhs) ]
207
208   |  arity == 0
209         -- Don't worker-wrapper thunks
210   || isNonRec is_rec && certainlyWillInline fn_id
211         -- No point in worker/wrappering a function that is going to be
212         -- INLINEd wholesale anyway.  If the strictness analyser is run
213         -- twice, this test also prevents wrappers (which are INLINEd)
214         -- from being re-done.
215         --      
216         -- It's very important to refrain from w/w-ing an INLINE function
217         -- If we do so by mistake we transform
218         --      f = __inline (\x -> E)
219         -- into
220         --      f = __inline (\x -> case x of (a,b) -> fw E)
221         --      fw = \ab -> (__inline (\x -> E)) (a,b)
222         -- and the original __inline now vanishes, so E is no longer
223         -- inside its __inline wrapper.  Death!  Disaster!
224   || not (worthSplitting strict_sig)
225         -- Strictness info suggests not to w/w
226   = returnUs [ (fn_id, rhs) ]
227
228   | otherwise           -- Do w/w split!
229   = WARN( arity /= length wrap_dmds, ppr fn_id <+> (ppr arity $$ ppr strict_sig) )
230         -- The arity should match the signature
231     mkWwBodies fun_ty wrap_dmds res_info one_shots      `thenUs` \ (work_demands, wrap_fn, work_fn) ->
232     getUniqueUs                                         `thenUs` \ work_uniq ->
233     let
234         work_rhs = work_fn rhs
235         work_id  = mkWorkerId work_uniq fn_id (exprType work_rhs) 
236                         `setInlinePragma` inline_prag
237                         `setIdNewStrictness` StrictSig (mkTopDmdType work_demands work_res_info)
238                                 -- Even though we may not be at top level, 
239                                 -- it's ok to give it an empty DmdEnv
240
241         wrap_rhs = wrap_fn work_id
242         wrap_id  = fn_id `setIdWorkerInfo`      HasWorker work_id arity
243                          `setInlinePragma`      NoInlinePragInfo        -- Zap any inline pragma;
244                                                                         -- Put it on the worker instead
245     in
246     returnUs ([(work_id, work_rhs), (wrap_id, wrap_rhs)])
247         -- Worker first, because wrapper mentions it
248         -- mkWwBodies has already built a wrap_rhs with an INLINE pragma wrapped around it
249   where
250     fun_ty = idType fn_id
251     arity  = idArity fn_id      -- The arity is set by the simplifier using exprEtaExpandArity
252                                 -- So it may be more than the number of top-level-visible lambdas
253
254     inline_prag = idInlinePragma fn_id
255     strict_sig  = idNewStrictness fn_id
256
257     StrictSig (DmdType _ wrap_dmds res_info) = strict_sig
258     work_res_info | isBotRes res_info = BotRes  -- Cpr stuff done by wrapper
259                   | otherwise         = TopRes
260
261     one_shots = get_one_shots rhs
262
263 -- If the original function has one-shot arguments, it is important to
264 -- make the wrapper and worker have corresponding one-shot arguments too.
265 -- Otherwise we spuriously float stuff out of case-expression join points,
266 -- which is very annoying.
267 get_one_shots (Lam b e)
268   | isId b    = isOneShotLambda b : get_one_shots e
269   | otherwise = get_one_shots e
270 get_one_shots (Note _ e) = get_one_shots e
271 get_one_shots other      = noOneShotInfo
272 \end{code}
273
274
275 %************************************************************************
276 %*                                                                      *
277 \subsection{Functions over Demands}
278 %*                                                                      *
279 %************************************************************************
280
281 \begin{code}
282 worthSplitting :: StrictSig -> Bool
283                 -- True <=> the wrapper would not be an identity function
284 worthSplitting (StrictSig (DmdType _ ds res))
285   = any worth_it ds || returnsCPR res
286         -- worthSplitting returns False for an empty list of demands,
287         -- and hence do_strict_ww is False if arity is zero
288
289         -- We used not to split if the result is bottom.
290         -- [Justification:  there's no efficiency to be gained.]
291         -- But it's sometimes bad not to make a wrapper.  Consider
292         --      fw = \x# -> let x = I# x# in case e of
293         --                                      p1 -> error_fn x
294         --                                      p2 -> error_fn x
295         --                                      p3 -> the real stuff
296         -- The re-boxing code won't go away unless error_fn gets a wrapper too.
297         -- [We don't do reboxing now, but in general it's better to pass 
298         --  an unboxed thing to f, and have it reboxed in the error cases....]
299   where
300     worth_it Abs          = True        -- Absent arg
301     worth_it (Seq _ _ ds) = True        -- Arg to evaluate
302     worth_it other        = False
303 \end{code}
304
305
306
307 %************************************************************************
308 %*                                                                      *
309 \subsection{The worker wrapper core}
310 %*                                                                      *
311 %************************************************************************
312
313 @mkWrapper@ is called when importing a function.  We have the type of 
314 the function and the name of its worker, and we want to make its body (the wrapper).
315
316 \begin{code}
317 mkWrapper :: Type               -- Wrapper type
318           -> StrictSig          -- Wrapper strictness info
319           -> UniqSM (Id -> CoreExpr)    -- Wrapper body, missing worker Id
320
321 mkWrapper fun_ty (StrictSig (DmdType _ demands res_info))
322   = mkWwBodies fun_ty demands res_info noOneShotInfo    `thenUs` \ (_, wrap_fn, _) ->
323     returnUs wrap_fn
324
325 noOneShotInfo = repeat False
326 \end{code}
327
328