[project @ 2001-07-23 16:16:47 by sof]
[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, 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   |  arity == 0
189         -- Don't worker-wrapper thunks
190   || isNeverInlinePrag inline_prag
191         -- Don't split things that will never be inlined
192   || isNonRec is_rec && certainlyWillInline fn_id
193         -- No point in worker/wrappering a function that is going to be
194         -- INLINEd wholesale anyway.  If the strictness analyser is run
195         -- twice, this test also prevents wrappers (which are INLINEd)
196         -- from being re-done.
197         --      
198         -- It's very important to refrain from w/w-ing an INLINE function
199         -- If we do so by mistake we transform
200         --      f = __inline (\x -> E)
201         -- into
202         --      f = __inline (\x -> case x of (a,b) -> fw E)
203         --      fw = \ab -> (__inline (\x -> E)) (a,b)
204         -- and the original __inline now vanishes, so E is no longer
205         -- inside its __inline wrapper.  Death!  Disaster!
206   || not (worthSplitting strict_sig)
207         -- Strictness info suggests not to w/w
208   = returnUs [ (fn_id, rhs) ]
209
210   | otherwise           -- Do w/w split!
211   = WARN( arity /= length wrap_dmds, ppr fn_id <+> (ppr arity $$ ppr strict_sig) )
212         -- The arity should match the signature
213     mkWwBodies fun_ty wrap_dmds res_info one_shots      `thenUs` \ (work_demands, wrap_fn, work_fn) ->
214     getUniqueUs                                         `thenUs` \ work_uniq ->
215     let
216         work_rhs = work_fn rhs
217         work_id  = mkWorkerId work_uniq fn_id (exprType work_rhs) 
218                         `setInlinePragma` inline_prag
219                         `setIdNewStrictness` StrictSig (mkTopDmdType work_demands work_res_info)
220                                 -- Even though we may not be at top level, 
221                                 -- it's ok to give it an empty DmdEnv
222
223         wrap_rhs = wrap_fn work_id
224         wrap_id  = fn_id `setIdWorkerInfo`      HasWorker work_id arity
225                          `setInlinePragma`      NoInlinePragInfo        -- Zap any inline pragma;
226                                                                         -- Put it on the worker instead
227     in
228     returnUs ([(work_id, work_rhs), (wrap_id, wrap_rhs)])
229         -- Worker first, because wrapper mentions it
230         -- mkWwBodies has already built a wrap_rhs with an INLINE pragma wrapped around it
231   where
232     fun_ty = idType fn_id
233     arity  = idArity fn_id      -- The arity is set by the simplifier using exprEtaExpandArity
234                                 -- So it may be more than the number of top-level-visible lambdas
235
236     inline_prag = idInlinePragma fn_id
237     strict_sig  = idNewStrictness fn_id
238
239     StrictSig (DmdType _ wrap_dmds res_info) = strict_sig
240     work_res_info | isBotRes res_info = BotRes  -- Cpr stuff done by wrapper
241                   | otherwise         = TopRes
242
243     one_shots = get_one_shots rhs
244
245 -- If the original function has one-shot arguments, it is important to
246 -- make the wrapper and worker have corresponding one-shot arguments too.
247 -- Otherwise we spuriously float stuff out of case-expression join points,
248 -- which is very annoying.
249 get_one_shots (Lam b e)
250   | isId b    = isOneShotLambda b : get_one_shots e
251   | otherwise = get_one_shots e
252 get_one_shots (Note _ e) = get_one_shots e
253 get_one_shots other      = noOneShotInfo
254 \end{code}
255
256
257 %************************************************************************
258 %*                                                                      *
259 \subsection{Functions over Demands}
260 %*                                                                      *
261 %************************************************************************
262
263 \begin{code}
264 worthSplitting :: StrictSig -> Bool
265                 -- True <=> the wrapper would not be an identity function
266 worthSplitting (StrictSig (DmdType _ ds res))
267   = any worth_it ds || returnsCPR res
268         -- worthSplitting returns False for an empty list of demands,
269         -- and hence do_strict_ww is False if arity is zero
270
271         -- We used not to split if the result is bottom.
272         -- [Justification:  there's no efficiency to be gained.]
273         -- But it's sometimes bad not to make a wrapper.  Consider
274         --      fw = \x# -> let x = I# x# in case e of
275         --                                      p1 -> error_fn x
276         --                                      p2 -> error_fn x
277         --                                      p3 -> the real stuff
278         -- The re-boxing code won't go away unless error_fn gets a wrapper too.
279         -- [We don't do reboxing now, but in general it's better to pass 
280         --  an unboxed thing to f, and have it reboxed in the error cases....]
281   where
282     worth_it Abs          = True        -- Absent arg
283     worth_it (Seq _ _ ds) = True        -- Arg to evaluate
284     worth_it other        = False
285 \end{code}
286
287
288
289 %************************************************************************
290 %*                                                                      *
291 \subsection{The worker wrapper core}
292 %*                                                                      *
293 %************************************************************************
294
295 @mkWrapper@ is called when importing a function.  We have the type of 
296 the function and the name of its worker, and we want to make its body (the wrapper).
297
298 \begin{code}
299 mkWrapper :: Type               -- Wrapper type
300           -> StrictSig          -- Wrapper strictness info
301           -> UniqSM (Id -> CoreExpr)    -- Wrapper body, missing worker Id
302
303 mkWrapper fun_ty (StrictSig (DmdType _ demands res_info))
304   = mkWwBodies fun_ty demands res_info noOneShotInfo    `thenUs` \ (_, wrap_fn, _) ->
305     returnUs wrap_fn
306
307 noOneShotInfo = repeat False
308 \end{code}
309
310