636f170aae3ae908b45fcabc14cebe1d500d2cab
[ghc-hetmet.git] / ghc / compiler / stgSyn / CoreToStg.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[CoreToStg]{Converts Core to STG Syntax}
5
6 And, as we have the info in hand, we may convert some lets to
7 let-no-escapes.
8
9 \begin{code}
10 module CoreToStg ( coreToStg, coreExprToStg ) where
11
12 #include "HsVersions.h"
13
14 import CoreSyn
15 import CoreUtils
16 import StgSyn
17
18 import Type
19 import TyCon            ( isAlgTyCon )
20 import Literal
21 import Id
22 import Var              ( Var, globalIdDetails, varType )
23 #ifdef ILX
24 import MkId             ( unsafeCoerceId )
25 #endif
26 import IdInfo
27 import DataCon
28 import CostCentre       ( noCCS )
29 import VarSet
30 import VarEnv
31 import Maybes           ( maybeToBool )
32 import Name             ( getOccName, isExternalName, nameOccName )
33 import OccName          ( occNameUserString, occNameFS )
34 import BasicTypes       ( Arity )
35 import CmdLineOpts      ( DynFlags, opt_RuntimeTypes )
36 import Outputable
37
38 infixr 9 `thenLne`
39 \end{code}
40
41 %************************************************************************
42 %*                                                                      *
43 \subsection[live-vs-free-doc]{Documentation}
44 %*                                                                      *
45 %************************************************************************
46
47 (There is other relevant documentation in codeGen/CgLetNoEscape.)
48
49 The actual Stg datatype is decorated with {\em live variable}
50 information, as well as {\em free variable} information.  The two are
51 {\em not} the same.  Liveness is an operational property rather than a
52 semantic one.  A variable is live at a particular execution point if
53 it can be referred to {\em directly} again.  In particular, a dead
54 variable's stack slot (if it has one):
55 \begin{enumerate}
56 \item
57 should be stubbed to avoid space leaks, and
58 \item
59 may be reused for something else.
60 \end{enumerate}
61
62 There ought to be a better way to say this.  Here are some examples:
63 \begin{verbatim}
64         let v = [q] \[x] -> e
65         in
66         ...v...  (but no q's)
67 \end{verbatim}
68
69 Just after the `in', v is live, but q is dead.  If the whole of that
70 let expression was enclosed in a case expression, thus:
71 \begin{verbatim}
72         case (let v = [q] \[x] -> e in ...v...) of
73                 alts[...q...]
74 \end{verbatim}
75 (ie @alts@ mention @q@), then @q@ is live even after the `in'; because
76 we'll return later to the @alts@ and need it.
77
78 Let-no-escapes make this a bit more interesting:
79 \begin{verbatim}
80         let-no-escape v = [q] \ [x] -> e
81         in
82         ...v...
83 \end{verbatim}
84 Here, @q@ is still live at the `in', because @v@ is represented not by
85 a closure but by the current stack state.  In other words, if @v@ is
86 live then so is @q@.  Furthermore, if @e@ mentions an enclosing
87 let-no-escaped variable, then {\em its} free variables are also live
88 if @v@ is.
89
90 %************************************************************************
91 %*                                                                      *
92 \subsection[caf-info]{Collecting live CAF info}
93 %*                                                                      *
94 %************************************************************************
95
96 In this pass we also collect information on which CAFs are live for 
97 constructing SRTs (see SRT.lhs).  
98
99 A top-level Id has CafInfo, which is
100
101         - MayHaveCafRefs, if it may refer indirectly to
102           one or more CAFs, or
103         - NoCafRefs if it definitely doesn't
104
105 The CafInfo has already been calculated during the CoreTidy pass.
106
107 During CoreToStg, we then pin onto each binding and case expression, a
108 list of Ids which represents the "live" CAFs at that point.  The meaning
109 of "live" here is the same as for live variables, see above (which is
110 why it's convenient to collect CAF information here rather than elsewhere).
111
112 The later SRT pass takes these lists of Ids and uses them to construct
113 the actual nested SRTs, and replaces the lists of Ids with (offset,length)
114 pairs.
115
116
117 Interaction of let-no-escape with SRTs   [Sept 01]
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
119 Consider
120
121         let-no-escape x = ...caf1...caf2...
122         in
123         ...x...x...x...
124
125 where caf1,caf2 are CAFs.  Since x doesn't have a closure, we 
126 build SRTs just as if x's defn was inlined at each call site, and
127 that means that x's CAF refs get duplicated in the overall SRT.
128
129 This is unlike ordinary lets, in which the CAF refs are not duplicated.
130
131 We could fix this loss of (static) sharing by making a sort of pseudo-closure
132 for x, solely to put in the SRTs lower down.
133
134
135 %************************************************************************
136 %*                                                                      *
137 \subsection[binds-StgVarInfo]{Setting variable info: top-level, binds, RHSs}
138 %*                                                                      *
139 %************************************************************************
140
141 \begin{code}
142 coreToStg :: DynFlags -> [CoreBind] -> IO [StgBinding]
143 coreToStg dflags pgm
144   = return pgm'
145   where (_, _, pgm') = coreTopBindsToStg emptyVarEnv pgm
146
147 coreExprToStg :: CoreExpr -> StgExpr
148 coreExprToStg expr 
149   = new_expr where (new_expr,_,_) = initLne emptyVarEnv (coreToStgExpr expr)
150
151
152 coreTopBindsToStg
153     :: IdEnv HowBound           -- environment for the bindings
154     -> [CoreBind]
155     -> (IdEnv HowBound, FreeVarsInfo, [StgBinding])
156
157 coreTopBindsToStg env [] = (env, emptyFVInfo, [])
158 coreTopBindsToStg env (b:bs)
159   = (env2, fvs2, b':bs')
160   where
161         -- env accumulates down the list of binds, fvs accumulates upwards
162         (env1, fvs2, b' ) = coreTopBindToStg env fvs1 b
163         (env2, fvs1, bs') = coreTopBindsToStg env1 bs
164
165
166 coreTopBindToStg
167         :: IdEnv HowBound
168         -> FreeVarsInfo         -- Info about the body
169         -> CoreBind
170         -> (IdEnv HowBound, FreeVarsInfo, StgBinding)
171
172 coreTopBindToStg env body_fvs (NonRec id rhs)
173   = let 
174         env'      = extendVarEnv env id how_bound
175         how_bound = LetBound TopLet (manifestArity rhs)
176
177         (stg_rhs, fvs', lv_info) = 
178             initLne env (
179               coreToTopStgRhs body_fvs (id,rhs) `thenLne` \ (stg_rhs, fvs') ->
180               freeVarsToLiveVars fvs'           `thenLne` \ lv_info ->
181               returnLne (stg_rhs, fvs', lv_info)
182            )
183         
184         bind = StgNonRec (mkSRT lv_info) id stg_rhs
185     in
186     ASSERT2(manifestArity rhs == stgRhsArity stg_rhs, ppr id)
187     ASSERT2(consistentCafInfo id bind, ppr id)
188 --    WARN(not (consistent caf_info bind), ppr id <+> ppr cafs <+> ppCafInfo caf_info)
189     (env', fvs' `unionFVInfo` body_fvs, bind)
190
191 coreTopBindToStg env body_fvs (Rec pairs)
192   = let 
193         (binders, rhss) = unzip pairs
194
195         extra_env' = [ (b, LetBound TopLet (manifestArity rhs))
196                      | (b, rhs) <- pairs ]
197         env' = extendVarEnvList env extra_env'
198
199         (stg_rhss, fvs', lv_info)
200           = initLne env' (
201                mapAndUnzipLne (coreToTopStgRhs body_fvs) pairs
202                                                 `thenLne` \ (stg_rhss, fvss') ->
203                let fvs' = unionFVInfos fvss' in
204                freeVarsToLiveVars fvs'                  `thenLne` \ lv_info ->
205                returnLne (stg_rhss, fvs', lv_info)
206            )
207
208         bind = StgRec (mkSRT lv_info) (zip binders stg_rhss)
209     in
210     ASSERT2(and [manifestArity rhs == stgRhsArity stg_rhs | (rhs,stg_rhs) <- rhss `zip` stg_rhss], ppr binders)
211     ASSERT2(consistentCafInfo (head binders) bind, ppr binders)
212 --    WARN(not (consistent caf_info bind), ppr binders <+> ppr cafs <+> ppCafInfo caf_info)
213     (env', fvs' `unionFVInfo` body_fvs, bind)
214
215 #ifdef DEBUG
216 -- Assertion helper: this checks that the CafInfo on the Id matches
217 -- what CoreToStg has figured out about the binding's SRT.  The
218 -- CafInfo will be exact in all cases except when CorePrep has
219 -- floated out a binding, in which case it will be approximate.
220 consistentCafInfo id bind
221   | occNameFS (nameOccName (idName id)) == FSLIT("sat")
222   = id_marked_caffy || not binding_is_caffy
223   | otherwise
224   = id_marked_caffy == binding_is_caffy
225   where
226         id_marked_caffy  = mayHaveCafRefs (idCafInfo id)
227         binding_is_caffy = stgBindHasCafRefs bind
228 #endif
229 \end{code}
230
231 \begin{code}
232 coreToTopStgRhs
233         :: FreeVarsInfo         -- Free var info for the scope of the binding
234         -> (Id,CoreExpr)
235         -> LneM (StgRhs, FreeVarsInfo)
236
237 coreToTopStgRhs scope_fv_info (bndr, rhs)
238   = coreToStgExpr rhs           `thenLne` \ (new_rhs, rhs_fvs, _) ->
239     returnLne (mkTopStgRhs upd rhs_fvs bndr_info new_rhs, rhs_fvs)
240   where
241     bndr_info = lookupFVInfo scope_fv_info bndr
242
243     upd  | rhsIsNonUpd rhs = SingleEntry
244          | otherwise       = Updatable
245
246 mkTopStgRhs :: UpdateFlag -> FreeVarsInfo -> StgBinderInfo -> StgExpr -> StgRhs
247
248 mkTopStgRhs upd rhs_fvs binder_info (StgLam _ bndrs body)
249   = StgRhsClosure noCCS binder_info
250                   (getFVs rhs_fvs)               
251                   ReEntrant
252                   bndrs body
253         
254 mkTopStgRhs upd rhs_fvs binder_info (StgConApp con args)
255   | not (isUpdatable upd) -- StgConApps can be updatable (see isCrossDllConApp)
256   = StgRhsCon noCCS con args
257
258 mkTopStgRhs upd rhs_fvs binder_info rhs
259   = StgRhsClosure noCCS binder_info
260                   (getFVs rhs_fvs)               
261                   upd
262                   [] rhs
263 \end{code}
264
265
266 -- ---------------------------------------------------------------------------
267 -- Expressions
268 -- ---------------------------------------------------------------------------
269
270 \begin{code}
271 coreToStgExpr
272         :: CoreExpr
273         -> LneM (StgExpr,       -- Decorated STG expr
274                  FreeVarsInfo,  -- Its free vars (NB free, not live)
275                  EscVarsSet)    -- Its escapees, a subset of its free vars;
276                                 -- also a subset of the domain of the envt
277                                 -- because we are only interested in the escapees
278                                 -- for vars which might be turned into
279                                 -- let-no-escaped ones.
280 \end{code}
281
282 The second and third components can be derived in a simple bottom up pass, not
283 dependent on any decisions about which variables will be let-no-escaped or
284 not.  The first component, that is, the decorated expression, may then depend
285 on these components, but it in turn is not scrutinised as the basis for any
286 decisions.  Hence no black holes.
287
288 \begin{code}
289 coreToStgExpr (Lit l) = returnLne (StgLit l, emptyFVInfo, emptyVarSet)
290 coreToStgExpr (Var v) = coreToStgApp Nothing v []
291
292 coreToStgExpr expr@(App _ _)
293   = coreToStgApp Nothing f args
294   where
295     (f, args) = myCollectArgs expr
296
297 coreToStgExpr expr@(Lam _ _)
298   = let
299         (args, body) = myCollectBinders expr 
300         args'        = filterStgBinders args
301     in
302     extendVarEnvLne [ (a, LambdaBound) | a <- args' ] $
303     coreToStgExpr body  `thenLne` \ (body, body_fvs, body_escs) ->
304     let
305         fvs             = args' `minusFVBinders` body_fvs
306         escs            = body_escs `delVarSetList` args'
307         result_expr | null args' = body
308                     | otherwise  = StgLam (exprType expr) args' body
309     in
310     returnLne (result_expr, fvs, escs)
311
312 coreToStgExpr (Note (SCC cc) expr)
313   = coreToStgExpr expr          `thenLne` ( \ (expr2, fvs, escs) ->
314     returnLne (StgSCC cc expr2, fvs, escs) )
315
316 #ifdef ILX
317 -- For ILX, convert (__coerce__ to_ty from_ty e) 
318 --          into    (coerce to_ty from_ty e)
319 -- where coerce is real function
320 coreToStgExpr (Note (Coerce to_ty from_ty) expr)
321   = coreToStgExpr (mkApps (Var unsafeCoerceId) 
322                           [Type from_ty, Type to_ty, expr])
323 #endif
324
325 coreToStgExpr (Note other_note expr)
326   = coreToStgExpr expr
327
328 -- Cases require a little more real work.
329
330 coreToStgExpr (Case scrut bndr alts)
331   = extendVarEnvLne [(bndr, LambdaBound)]       (
332          mapAndUnzip3Lne vars_alt alts  `thenLne` \ (alts2, fvs_s, escs_s) ->
333          returnLne ( mkStgAlts (idType bndr) alts2,
334                      unionFVInfos fvs_s,
335                      unionVarSets escs_s )
336     )                                   `thenLne` \ (alts2, alts_fvs, alts_escs) ->
337     let
338         -- Determine whether the default binder is dead or not
339         -- This helps the code generator to avoid generating an assignment
340         -- for the case binder (is extremely rare cases) ToDo: remove.
341         bndr' | bndr `elementOfFVInfo` alts_fvs = bndr
342               | otherwise                       = bndr `setIdOccInfo` IAmDead
343
344         -- Don't consider the default binder as being 'live in alts',
345         -- since this is from the point of view of the case expr, where
346         -- the default binder is not free.
347         alts_fvs_wo_bndr  = bndr `minusFVBinder` alts_fvs
348         alts_escs_wo_bndr = alts_escs `delVarSet` bndr
349     in
350
351     freeVarsToLiveVars alts_fvs_wo_bndr         `thenLne` \ alts_lv_info ->
352
353         -- We tell the scrutinee that everything 
354         -- live in the alts is live in it, too.
355     setVarsLiveInCont alts_lv_info (
356         coreToStgExpr scrut       `thenLne` \ (scrut2, scrut_fvs, scrut_escs) ->
357         freeVarsToLiveVars scrut_fvs `thenLne` \ scrut_lv_info ->
358         returnLne (scrut2, scrut_fvs, scrut_escs, scrut_lv_info)
359       )    
360                 `thenLne` \ (scrut2, scrut_fvs, scrut_escs, scrut_lv_info) ->
361
362     returnLne (
363       StgCase scrut2 (getLiveVars scrut_lv_info)
364                      (getLiveVars alts_lv_info)
365                      bndr'
366                      (mkSRT alts_lv_info)
367                      alts2,
368       scrut_fvs `unionFVInfo` alts_fvs_wo_bndr,
369       alts_escs_wo_bndr `unionVarSet` getFVSet scrut_fvs
370                 -- You might think we should have scrut_escs, not 
371                 -- (getFVSet scrut_fvs), but actually we can't call, and 
372                 -- then return from, a let-no-escape thing.
373       )
374   where
375     vars_alt (con, binders, rhs)
376       = let     -- Remove type variables
377             binders' = filterStgBinders binders
378         in      
379         extendVarEnvLne [(b, LambdaBound) | b <- binders']      $
380         coreToStgExpr rhs       `thenLne` \ (rhs2, rhs_fvs, rhs_escs) ->
381         let
382                 -- Records whether each param is used in the RHS
383             good_use_mask = [ b `elementOfFVInfo` rhs_fvs | b <- binders' ]
384         in
385         returnLne ( (con, binders', good_use_mask, rhs2),
386                     binders' `minusFVBinders` rhs_fvs,
387                     rhs_escs `delVarSetList` binders' )
388                 -- ToDo: remove the delVarSet;
389                 -- since escs won't include any of these binders
390 \end{code}
391
392 Lets not only take quite a bit of work, but this is where we convert
393 then to let-no-escapes, if we wish.
394
395 (Meanwhile, we don't expect to see let-no-escapes...)
396 \begin{code}
397 coreToStgExpr (Let bind body)
398   = fixLne (\ ~(_, _, _, no_binder_escapes) ->
399         coreToStgLet no_binder_escapes bind body
400     )                           `thenLne` \ (new_let, fvs, escs, _) ->
401
402     returnLne (new_let, fvs, escs)
403 \end{code}
404
405 \begin{code}
406 mkStgAlts scrut_ty orig_alts
407  | is_prim_case = StgPrimAlts (tyConAppTyCon scrut_ty) prim_alts deflt
408  | otherwise    = StgAlgAlts  maybe_tycon              alg_alts  deflt
409   where
410     is_prim_case = isUnLiftedType scrut_ty && not (isUnboxedTupleType scrut_ty)
411
412     prim_alts    = [(lit, rhs)             | (LitAlt lit, _, _, rhs)        <- other_alts]
413     alg_alts     = [(con, bndrs, use, rhs) | (DataAlt con, bndrs, use, rhs) <- other_alts]
414
415     (other_alts, deflt) 
416         = case orig_alts of     -- DEFAULT is always first if it's there at all
417             (DEFAULT, _, _, rhs) : other_alts -> (other_alts, StgBindDefault rhs)
418             other                             -> (orig_alts,  StgNoDefault)
419
420     maybe_tycon = case alg_alts of 
421                         -- Get the tycon from the data con
422                         (dc, _, _, _) : _rest -> Just (dataConTyCon dc)
423
424                         -- Otherwise just do your best
425                         [] -> case splitTyConApp_maybe (repType scrut_ty) of
426                                 Just (tc,_) | isAlgTyCon tc -> Just tc
427                                 _other                      -> Nothing
428 \end{code}
429
430
431 -- ---------------------------------------------------------------------------
432 -- Applications
433 -- ---------------------------------------------------------------------------
434
435 \begin{code}
436 coreToStgApp
437          :: Maybe UpdateFlag            -- Just upd <=> this application is
438                                         -- the rhs of a thunk binding
439                                         --      x = [...] \upd [] -> the_app
440                                         -- with specified update flag
441         -> Id                           -- Function
442         -> [CoreArg]                    -- Arguments
443         -> LneM (StgExpr, FreeVarsInfo, EscVarsSet)
444
445 coreToStgApp maybe_thunk_body f args
446   = coreToStgArgs args          `thenLne` \ (args', args_fvs) ->
447     lookupVarLne f              `thenLne` \ how_bound ->
448
449     let
450         n_val_args       = valArgCount args
451         not_letrec_bound = not (isLetBound how_bound)
452         fun_fvs          
453           = let fvs = singletonFVInfo f how_bound fun_occ in
454             -- e.g. (f :: a -> int) (x :: a) 
455             -- Here the free variables are "f", "x" AND the type variable "a"
456             -- coreToStgArgs will deal with the arguments recursively
457             if opt_RuntimeTypes then
458               fvs `unionFVInfo` tyvarFVInfo (tyVarsOfType (varType f))
459             else fvs
460
461         -- Mostly, the arity info of a function is in the fn's IdInfo
462         -- But new bindings introduced by CoreSat may not have no
463         -- arity info; it would do us no good anyway.  For example:
464         --      let f = \ab -> e in f
465         -- No point in having correct arity info for f!
466         -- Hence the hasArity stuff below.
467         -- NB: f_arity is only consulted for LetBound things
468         f_arity   = stgArity f how_bound
469         saturated = f_arity <= n_val_args
470
471         fun_occ 
472          | not_letrec_bound         = noBinderInfo      -- Uninteresting variable
473          | f_arity > 0 && saturated = stgSatOcc -- Saturated or over-saturated function call
474          | otherwise                = stgUnsatOcc       -- Unsaturated function or thunk
475
476         fun_escs
477          | not_letrec_bound      = emptyVarSet  -- Only letrec-bound escapees are interesting
478          | f_arity == n_val_args = emptyVarSet  -- A function *or thunk* with an exactly
479                                                 -- saturated call doesn't escape
480                                                 -- (let-no-escape applies to 'thunks' too)
481
482          | otherwise         = unitVarSet f     -- Inexact application; it does escape
483
484         -- At the moment of the call:
485
486         --  either the function is *not* let-no-escaped, in which case
487         --         nothing is live except live_in_cont
488         --      or the function *is* let-no-escaped in which case the
489         --         variables it uses are live, but still the function
490         --         itself is not.  PS.  In this case, the function's
491         --         live vars should already include those of the
492         --         continuation, but it does no harm to just union the
493         --         two regardless.
494
495         res_ty = exprType (mkApps (Var f) args)
496         app = case globalIdDetails f of
497                 DataConWorkId dc | saturated -> StgConApp dc args'
498                 PrimOpId op                  -> ASSERT( saturated )
499                                                 StgOpApp (StgPrimOp op) args' res_ty
500                 FCallId call     -> ASSERT( saturated )
501                                     StgOpApp (StgFCallOp call (idUnique f)) args' res_ty
502                 _other           -> StgApp f args'
503
504     in
505     returnLne (
506         app,
507         fun_fvs  `unionFVInfo` args_fvs,
508         fun_escs `unionVarSet` (getFVSet args_fvs)
509                                 -- All the free vars of the args are disqualified
510                                 -- from being let-no-escaped.
511     )
512
513
514
515 -- ---------------------------------------------------------------------------
516 -- Argument lists
517 -- This is the guy that turns applications into A-normal form
518 -- ---------------------------------------------------------------------------
519
520 coreToStgArgs :: [CoreArg] -> LneM ([StgArg], FreeVarsInfo)
521 coreToStgArgs []
522   = returnLne ([], emptyFVInfo)
523
524 coreToStgArgs (Type ty : args)  -- Type argument
525   = coreToStgArgs args  `thenLne` \ (args', fvs) ->
526     if opt_RuntimeTypes then
527         returnLne (StgTypeArg ty : args', fvs `unionFVInfo` tyvarFVInfo (tyVarsOfType ty))
528     else
529     returnLne (args', fvs)
530
531 coreToStgArgs (arg : args)      -- Non-type argument
532   = coreToStgArgs args  `thenLne` \ (stg_args, args_fvs) ->
533     coreToStgExpr arg   `thenLne` \ (arg', arg_fvs, escs) ->
534     let
535         fvs = args_fvs `unionFVInfo` arg_fvs
536         stg_arg = case arg' of
537                        StgApp v []      -> StgVarArg v
538                        StgConApp con [] -> StgVarArg (dataConWorkId con)
539                        StgLit lit       -> StgLitArg lit
540                        _                -> pprPanic "coreToStgArgs" (ppr arg)
541     in
542     returnLne (stg_arg : stg_args, fvs)
543
544
545 -- ---------------------------------------------------------------------------
546 -- The magic for lets:
547 -- ---------------------------------------------------------------------------
548
549 coreToStgLet
550          :: Bool        -- True <=> yes, we are let-no-escaping this let
551          -> CoreBind    -- bindings
552          -> CoreExpr    -- body
553          -> LneM (StgExpr,      -- new let
554                   FreeVarsInfo, -- variables free in the whole let
555                   EscVarsSet,   -- variables that escape from the whole let
556                   Bool)         -- True <=> none of the binders in the bindings
557                                 -- is among the escaping vars
558
559 coreToStgLet let_no_escape bind body
560   = fixLne (\ ~(_, _, _, _, _, rec_body_fvs, _, _) ->
561
562         -- Do the bindings, setting live_in_cont to empty if
563         -- we ain't in a let-no-escape world
564         getVarsLiveInCont               `thenLne` \ live_in_cont ->
565         setVarsLiveInCont (if let_no_escape 
566                                 then live_in_cont 
567                                 else emptyLiveInfo)
568                           (vars_bind rec_body_fvs bind)
569             `thenLne` \ ( bind2, bind_fvs, bind_escs, bind_lv_info, env_ext) ->
570
571         -- Do the body
572         extendVarEnvLne env_ext (
573           coreToStgExpr body          `thenLne` \(body2, body_fvs, body_escs) ->
574           freeVarsToLiveVars body_fvs `thenLne` \ body_lv_info ->
575
576           returnLne (bind2, bind_fvs, bind_escs, getLiveVars bind_lv_info,
577                      body2, body_fvs, body_escs, getLiveVars body_lv_info)
578         )
579
580     ) `thenLne` (\ (bind2, bind_fvs, bind_escs, bind_lvs, 
581                     body2, body_fvs, body_escs, body_lvs) ->
582
583
584         -- Compute the new let-expression
585     let
586         new_let | let_no_escape = StgLetNoEscape live_in_whole_let bind_lvs bind2 body2
587                 | otherwise     = StgLet bind2 body2
588
589         free_in_whole_let
590           = binders `minusFVBinders` (bind_fvs `unionFVInfo` body_fvs)
591
592         live_in_whole_let
593           = bind_lvs `unionVarSet` (body_lvs `delVarSetList` binders)
594
595         real_bind_escs = if let_no_escape then
596                             bind_escs
597                          else
598                             getFVSet bind_fvs
599                             -- Everything escapes which is free in the bindings
600
601         let_escs = (real_bind_escs `unionVarSet` body_escs) `delVarSetList` binders
602
603         all_escs = bind_escs `unionVarSet` body_escs    -- Still includes binders of
604                                                         -- this let(rec)
605
606         no_binder_escapes = isEmptyVarSet (set_of_binders `intersectVarSet` all_escs)
607
608 #ifdef DEBUG
609         -- Debugging code as requested by Andrew Kennedy
610         checked_no_binder_escapes
611                 | not no_binder_escapes && any is_join_var binders
612                 = pprTrace "Interesting!  A join var that isn't let-no-escaped" (ppr binders)
613                   False
614                 | otherwise = no_binder_escapes
615 #else
616         checked_no_binder_escapes = no_binder_escapes
617 #endif
618                             
619                 -- Mustn't depend on the passed-in let_no_escape flag, since
620                 -- no_binder_escapes is used by the caller to derive the flag!
621     in
622     returnLne (
623         new_let,
624         free_in_whole_let,
625         let_escs,
626         checked_no_binder_escapes
627     ))
628   where
629     set_of_binders = mkVarSet binders
630     binders        = bindersOf bind
631
632     mk_binding bind_lv_info binder rhs
633         = (binder, LetBound (NestedLet live_vars) (manifestArity rhs))
634         where
635            live_vars | let_no_escape = addLiveVar bind_lv_info binder
636                      | otherwise     = unitLiveVar binder
637                 -- c.f. the invariant on NestedLet
638
639     vars_bind :: FreeVarsInfo           -- Free var info for body of binding
640               -> CoreBind
641               -> LneM (StgBinding,
642                        FreeVarsInfo, 
643                        EscVarsSet,        -- free vars; escapee vars
644                        LiveInfo,          -- Vars and CAFs live in binding
645                        [(Id, HowBound)])  -- extension to environment
646                                          
647
648     vars_bind body_fvs (NonRec binder rhs)
649       = coreToStgRhs body_fvs (binder,rhs)
650                                 `thenLne` \ (rhs2, bind_fvs, escs) ->
651
652         freeVarsToLiveVars bind_fvs `thenLne` \ bind_lv_info ->
653         let
654             env_ext_item = mk_binding bind_lv_info binder rhs
655         in
656         returnLne (StgNonRec (mkSRT bind_lv_info) binder rhs2, 
657                    bind_fvs, escs, bind_lv_info, [env_ext_item])
658
659
660     vars_bind body_fvs (Rec pairs)
661       = fixLne (\ ~(_, rec_rhs_fvs, _, bind_lv_info, _) ->
662            let
663                 rec_scope_fvs = unionFVInfo body_fvs rec_rhs_fvs
664                 binders = map fst pairs
665                 env_ext = [ mk_binding bind_lv_info b rhs 
666                           | (b,rhs) <- pairs ]
667            in
668            extendVarEnvLne env_ext (
669               mapAndUnzip3Lne (coreToStgRhs rec_scope_fvs) pairs 
670                                         `thenLne` \ (rhss2, fvss, escss) ->
671               let
672                         bind_fvs = unionFVInfos fvss
673                         escs     = unionVarSets escss
674               in
675               freeVarsToLiveVars (binders `minusFVBinders` bind_fvs)
676                                         `thenLne` \ bind_lv_info ->
677
678               returnLne (StgRec (mkSRT bind_lv_info) (binders `zip` rhss2), 
679                          bind_fvs, escs, bind_lv_info, env_ext)
680            )
681         )
682
683 is_join_var :: Id -> Bool
684 -- A hack (used only for compiler debuggging) to tell if
685 -- a variable started life as a join point ($j)
686 is_join_var j = occNameUserString (getOccName j) == "$j"
687 \end{code}
688
689 \begin{code}
690 coreToStgRhs :: FreeVarsInfo            -- Free var info for the scope of the binding
691              -> (Id,CoreExpr)
692              -> LneM (StgRhs, FreeVarsInfo, EscVarsSet)
693
694 coreToStgRhs scope_fv_info (bndr, rhs)
695   = coreToStgExpr rhs           `thenLne` \ (new_rhs, rhs_fvs, rhs_escs) ->
696     getEnvLne                   `thenLne` \ env ->    
697     returnLne (mkStgRhs env rhs_fvs bndr_info new_rhs,
698                rhs_fvs, rhs_escs)
699   where
700     bndr_info = lookupFVInfo scope_fv_info bndr
701
702 mkStgRhs :: IdEnv HowBound -> FreeVarsInfo -> StgBinderInfo -> StgExpr -> StgRhs
703
704 mkStgRhs env rhs_fvs binder_info (StgConApp con args)
705   = StgRhsCon noCCS con args
706
707 mkStgRhs env rhs_fvs binder_info (StgLam _ bndrs body)
708   = StgRhsClosure noCCS binder_info
709                   (getFVs rhs_fvs)               
710                   ReEntrant
711                   bndrs body
712         
713 mkStgRhs env rhs_fvs binder_info rhs
714   = StgRhsClosure noCCS binder_info
715                   (getFVs rhs_fvs)               
716                   upd_flag [] rhs
717   where
718    upd_flag = Updatable
719   {-
720     SDM: disabled.  Eval/Apply can't handle functions with arity zero very
721     well; and making these into simple non-updatable thunks breaks other
722     assumptions (namely that they will be entered only once).
723
724     upd_flag | isPAP env rhs  = ReEntrant
725              | otherwise      = Updatable
726   -}
727
728 {- ToDo:
729           upd = if isOnceDem dem
730                     then (if isNotTop toplev 
731                             then SingleEntry    -- HA!  Paydirt for "dem"
732                             else 
733 #ifdef DEBUG
734                      trace "WARNING: SE CAFs unsupported, forcing UPD instead" $
735 #endif
736                      Updatable)
737                 else Updatable
738         -- For now we forbid SingleEntry CAFs; they tickle the
739         -- ASSERT in rts/Storage.c line 215 at newCAF() re mut_link,
740         -- and I don't understand why.  There's only one SE_CAF (well,
741         -- only one that tickled a great gaping bug in an earlier attempt
742         -- at ClosureInfo.getEntryConvention) in the whole of nofib, 
743         -- specifically Main.lvl6 in spectral/cryptarithm2.
744         -- So no great loss.  KSW 2000-07.
745 -}
746 \end{code}
747
748 Detect thunks which will reduce immediately to PAPs, and make them
749 non-updatable.  This has several advantages:
750
751         - the non-updatable thunk behaves exactly like the PAP,
752
753         - the thunk is more efficient to enter, because it is
754           specialised to the task.
755
756         - we save one update frame, one stg_update_PAP, one update
757           and lots of PAP_enters.
758
759         - in the case where the thunk is top-level, we save building
760           a black hole and futhermore the thunk isn't considered to
761           be a CAF any more, so it doesn't appear in any SRTs.
762
763 We do it here, because the arity information is accurate, and we need
764 to do it before the SRT pass to save the SRT entries associated with
765 any top-level PAPs.
766
767 isPAP env (StgApp f args) = listLengthCmp args arity == LT -- idArity f > length args
768                           where
769                             arity = stgArity f (lookupBinding env f)
770 isPAP env _               = False
771
772
773 %************************************************************************
774 %*                                                                      *
775 \subsection[LNE-monad]{A little monad for this let-no-escaping pass}
776 %*                                                                      *
777 %************************************************************************
778
779 There's a lot of stuff to pass around, so we use this @LneM@ monad to
780 help.  All the stuff here is only passed *down*.
781
782 \begin{code}
783 type LneM a =  IdEnv HowBound
784             -> LiveInfo         -- Vars and CAFs live in continuation
785             -> a
786
787 type LiveInfo = (StgLiveVars,   -- Dynamic live variables; 
788                                 -- i.e. ones with a nested (non-top-level) binding
789                  CafSet)        -- Static live variables;
790                                 -- i.e. top-level variables that are CAFs or refer to them
791
792 type EscVarsSet = IdSet
793 type CafSet     = IdSet
794
795 data HowBound
796   = ImportBound         -- Used only as a response to lookupBinding; never
797                         -- exists in the range of the (IdEnv HowBound)
798
799   | LetBound            -- A let(rec) in this module
800         LetInfo         -- Whether top level or nested
801         Arity           -- Its arity (local Ids don't have arity info at this point)
802
803   | LambdaBound         -- Used for both lambda and case
804
805 data LetInfo
806   = TopLet              -- top level things
807   | NestedLet LiveInfo  -- For nested things, what is live if this
808                         -- thing is live?  Invariant: the binder
809                         -- itself is always a member of
810                         -- the dynamic set of its own LiveInfo
811
812 isLetBound (LetBound _ _) = True
813 isLetBound other          = False
814
815 topLevelBound ImportBound         = True
816 topLevelBound (LetBound TopLet _) = True
817 topLevelBound other               = False
818 \end{code}
819
820 For a let(rec)-bound variable, x, we record LiveInfo, the set of
821 variables that are live if x is live.  This LiveInfo comprises
822         (a) dynamic live variables (ones with a non-top-level binding)
823         (b) static live variabes (CAFs or things that refer to CAFs)
824
825 For "normal" variables (a) is just x alone.  If x is a let-no-escaped
826 variable then x is represented by a code pointer and a stack pointer
827 (well, one for each stack).  So all of the variables needed in the
828 execution of x are live if x is, and are therefore recorded in the
829 LetBound constructor; x itself *is* included.
830
831 The set of dynamic live variables is guaranteed ot have no further let-no-escaped
832 variables in it.
833
834 \begin{code}
835 emptyLiveInfo :: LiveInfo
836 emptyLiveInfo = (emptyVarSet,emptyVarSet)
837
838 unitLiveVar :: Id -> LiveInfo
839 unitLiveVar lv = (unitVarSet lv, emptyVarSet)
840
841 unitLiveCaf :: Id -> LiveInfo
842 unitLiveCaf caf = (emptyVarSet, unitVarSet caf)
843
844 addLiveVar :: LiveInfo -> Id -> LiveInfo
845 addLiveVar (lvs, cafs) id = (lvs `extendVarSet` id, cafs)
846
847 unionLiveInfo :: LiveInfo -> LiveInfo -> LiveInfo
848 unionLiveInfo (lv1,caf1) (lv2,caf2) = (lv1 `unionVarSet` lv2, caf1 `unionVarSet` caf2)
849
850 mkSRT :: LiveInfo -> SRT
851 mkSRT (_, cafs) = SRTEntries cafs
852
853 getLiveVars :: LiveInfo -> StgLiveVars
854 getLiveVars (lvs, _) = lvs
855 \end{code}
856
857
858 The std monad functions:
859 \begin{code}
860 initLne :: IdEnv HowBound -> LneM a -> a
861 initLne env m = m env emptyLiveInfo
862
863
864
865 {-# INLINE thenLne #-}
866 {-# INLINE returnLne #-}
867
868 returnLne :: a -> LneM a
869 returnLne e env lvs_cont = e
870
871 thenLne :: LneM a -> (a -> LneM b) -> LneM b
872 thenLne m k env lvs_cont 
873   = k (m env lvs_cont) env lvs_cont
874
875 mapLne  :: (a -> LneM b)   -> [a] -> LneM [b]
876 mapLne f [] = returnLne []
877 mapLne f (x:xs)
878   = f x         `thenLne` \ r  ->
879     mapLne f xs `thenLne` \ rs ->
880     returnLne (r:rs)
881
882 mapAndUnzipLne  :: (a -> LneM (b,c))   -> [a] -> LneM ([b],[c])
883
884 mapAndUnzipLne f [] = returnLne ([],[])
885 mapAndUnzipLne f (x:xs)
886   = f x                 `thenLne` \ (r1,  r2)  ->
887     mapAndUnzipLne f xs `thenLne` \ (rs1, rs2) ->
888     returnLne (r1:rs1, r2:rs2)
889
890 mapAndUnzip3Lne :: (a -> LneM (b,c,d)) -> [a] -> LneM ([b],[c],[d])
891
892 mapAndUnzip3Lne f []    = returnLne ([],[],[])
893 mapAndUnzip3Lne f (x:xs)
894   = f x                  `thenLne` \ (r1,  r2,  r3)  ->
895     mapAndUnzip3Lne f xs `thenLne` \ (rs1, rs2, rs3) ->
896     returnLne (r1:rs1, r2:rs2, r3:rs3)
897
898 fixLne :: (a -> LneM a) -> LneM a
899 fixLne expr env lvs_cont
900   = result
901   where
902     result = expr result env lvs_cont
903 \end{code}
904
905 Functions specific to this monad:
906
907 \begin{code}
908 getVarsLiveInCont :: LneM LiveInfo
909 getVarsLiveInCont env lvs_cont = lvs_cont
910
911 setVarsLiveInCont :: LiveInfo -> LneM a -> LneM a
912 setVarsLiveInCont new_lvs_cont expr env lvs_cont
913   = expr env new_lvs_cont
914
915 extendVarEnvLne :: [(Id, HowBound)] -> LneM a -> LneM a
916 extendVarEnvLne ids_w_howbound expr env lvs_cont
917   = expr (extendVarEnvList env ids_w_howbound) lvs_cont
918
919 lookupVarLne :: Id -> LneM HowBound
920 lookupVarLne v env lvs_cont = returnLne (lookupBinding env v) env lvs_cont
921
922 getEnvLne :: LneM (IdEnv HowBound)
923 getEnvLne env lvs_cont = returnLne env env lvs_cont
924
925 lookupBinding :: IdEnv HowBound -> Id -> HowBound
926 lookupBinding env v = case lookupVarEnv env v of
927                         Just xx -> xx
928                         Nothing -> ASSERT2( isGlobalId v, ppr v ) ImportBound
929
930
931 -- The result of lookupLiveVarsForSet, a set of live variables, is
932 -- only ever tacked onto a decorated expression. It is never used as
933 -- the basis of a control decision, which might give a black hole.
934
935 freeVarsToLiveVars :: FreeVarsInfo -> LneM LiveInfo
936 freeVarsToLiveVars fvs env live_in_cont
937   = returnLne live_info env live_in_cont
938   where
939     live_info    = foldr unionLiveInfo live_in_cont lvs_from_fvs
940     lvs_from_fvs = map do_one (allFreeIds fvs)
941
942     do_one (v, how_bound)
943       = case how_bound of
944           ImportBound                     -> unitLiveCaf v      -- Only CAF imports are 
945                                                                 -- recorded in fvs
946           LetBound TopLet _              
947                 | mayHaveCafRefs (idCafInfo v) -> unitLiveCaf v
948                 | otherwise                    -> emptyLiveInfo
949
950           LetBound (NestedLet lvs) _      -> lvs        -- lvs already contains v
951                                                         -- (see the invariant on NestedLet)
952
953           _lambda_or_case_binding         -> unitLiveVar v      -- Bound by lambda or case
954 \end{code}
955
956 %************************************************************************
957 %*                                                                      *
958 \subsection[Free-var info]{Free variable information}
959 %*                                                                      *
960 %************************************************************************
961
962 \begin{code}
963 type FreeVarsInfo = VarEnv (Var, HowBound, StgBinderInfo)
964         -- The Var is so we can gather up the free variables
965         -- as a set.
966         --
967         -- The HowBound info just saves repeated lookups;
968         -- we look up just once when we encounter the occurrence.
969         -- INVARIANT: Any ImportBound Ids are HaveCafRef Ids
970         --            Imported Ids without CAF refs are simply
971         --            not put in the FreeVarsInfo for an expression.
972         --            See singletonFVInfo and freeVarsToLiveVars
973         --
974         -- StgBinderInfo records how it occurs; notably, we
975         -- are interested in whether it only occurs in saturated 
976         -- applications, because then we don't need to build a
977         -- curried version.
978         -- If f is mapped to noBinderInfo, that means
979         -- that f *is* mentioned (else it wouldn't be in the
980         -- IdEnv at all), but perhaps in an unsaturated applications.
981         --
982         -- All case/lambda-bound things are also mapped to
983         -- noBinderInfo, since we aren't interested in their
984         -- occurence info.
985         --
986         -- For ILX we track free var info for type variables too;
987         -- hence VarEnv not IdEnv
988 \end{code}
989
990 \begin{code}
991 emptyFVInfo :: FreeVarsInfo
992 emptyFVInfo = emptyVarEnv
993
994 singletonFVInfo :: Id -> HowBound -> StgBinderInfo -> FreeVarsInfo
995 -- Don't record non-CAF imports at all, to keep free-var sets small
996 singletonFVInfo id ImportBound info
997    | mayHaveCafRefs (idCafInfo id) = unitVarEnv id (id, ImportBound, info)
998    | otherwise                     = emptyVarEnv
999 singletonFVInfo id how_bound info  = unitVarEnv id (id, how_bound, info)
1000
1001 tyvarFVInfo :: TyVarSet -> FreeVarsInfo
1002 tyvarFVInfo tvs = foldVarSet add emptyFVInfo tvs
1003         where
1004           add tv fvs = extendVarEnv fvs tv (tv, LambdaBound, noBinderInfo)
1005                 -- Type variables must be lambda-bound
1006
1007 unionFVInfo :: FreeVarsInfo -> FreeVarsInfo -> FreeVarsInfo
1008 unionFVInfo fv1 fv2 = plusVarEnv_C plusFVInfo fv1 fv2
1009
1010 unionFVInfos :: [FreeVarsInfo] -> FreeVarsInfo
1011 unionFVInfos fvs = foldr unionFVInfo emptyFVInfo fvs
1012
1013 minusFVBinders :: [Id] -> FreeVarsInfo -> FreeVarsInfo
1014 minusFVBinders vs fv = foldr minusFVBinder fv vs
1015
1016 minusFVBinder :: Id -> FreeVarsInfo -> FreeVarsInfo
1017 minusFVBinder v fv | isId v && opt_RuntimeTypes
1018                    = (fv `delVarEnv` v) `unionFVInfo` 
1019                      tyvarFVInfo (tyVarsOfType (idType v))
1020                    | otherwise = fv `delVarEnv` v
1021         -- When removing a binder, remember to add its type variables
1022         -- c.f. CoreFVs.delBinderFV
1023
1024 elementOfFVInfo :: Id -> FreeVarsInfo -> Bool
1025 elementOfFVInfo id fvs = maybeToBool (lookupVarEnv fvs id)
1026
1027 lookupFVInfo :: FreeVarsInfo -> Id -> StgBinderInfo
1028 -- Find how the given Id is used.
1029 -- Externally visible things may be used any old how
1030 lookupFVInfo fvs id 
1031   | isExternalName (idName id) = noBinderInfo
1032   | otherwise = case lookupVarEnv fvs id of
1033                         Nothing         -> noBinderInfo
1034                         Just (_,_,info) -> info
1035
1036 allFreeIds :: FreeVarsInfo -> [(Id,HowBound)]   -- Both top level and non-top-level Ids
1037 allFreeIds fvs = [(id,how_bound) | (id,how_bound,_) <- rngVarEnv fvs, isId id]
1038
1039 -- Non-top-level things only, both type variables and ids
1040 -- (type variables only if opt_RuntimeTypes)
1041 getFVs :: FreeVarsInfo -> [Var] 
1042 getFVs fvs = [id | (id, how_bound, _) <- rngVarEnv fvs, 
1043                     not (topLevelBound how_bound) ]
1044
1045 getFVSet :: FreeVarsInfo -> VarSet
1046 getFVSet fvs = mkVarSet (getFVs fvs)
1047
1048 plusFVInfo (id1,hb1,info1) (id2,hb2,info2)
1049   = ASSERT (id1 == id2 && hb1 `check_eq_how_bound` hb2)
1050     (id1, hb1, combineStgBinderInfo info1 info2)
1051
1052 #ifdef DEBUG
1053 -- The HowBound info for a variable in the FVInfo should be consistent
1054 check_eq_how_bound ImportBound        ImportBound        = True
1055 check_eq_how_bound LambdaBound        LambdaBound        = True
1056 check_eq_how_bound (LetBound li1 ar1) (LetBound li2 ar2) = ar1 == ar2 && check_eq_li li1 li2
1057 check_eq_how_bound hb1                hb2                = False
1058
1059 check_eq_li (NestedLet _) (NestedLet _) = True
1060 check_eq_li TopLet        TopLet        = True
1061 check_eq_li li1           li2           = False
1062 #endif
1063 \end{code}
1064
1065 Misc.
1066 \begin{code}
1067 filterStgBinders :: [Var] -> [Var]
1068 filterStgBinders bndrs
1069   | opt_RuntimeTypes = bndrs
1070   | otherwise        = filter isId bndrs
1071 \end{code}
1072
1073
1074 \begin{code}
1075         -- Ignore all notes except SCC
1076 myCollectBinders expr
1077   = go [] expr
1078   where
1079     go bs (Lam b e)          = go (b:bs) e
1080     go bs e@(Note (SCC _) _) = (reverse bs, e) 
1081     go bs (Note _ e)         = go bs e
1082     go bs e                  = (reverse bs, e)
1083
1084 myCollectArgs :: CoreExpr -> (Id, [CoreArg])
1085         -- We assume that we only have variables
1086         -- in the function position by now
1087 myCollectArgs expr
1088   = go expr []
1089   where
1090     go (Var v)          as = (v, as)
1091     go (App f a) as        = go f (a:as)
1092     go (Note (SCC _) e) as = pprPanic "CoreToStg.myCollectArgs" (ppr expr)
1093     go (Note n e)       as = go e as
1094     go _                as = pprPanic "CoreToStg.myCollectArgs" (ppr expr)
1095 \end{code}
1096
1097 \begin{code}
1098 stgArity :: Id -> HowBound -> Arity
1099 stgArity f (LetBound _ arity) = arity
1100 stgArity f ImportBound        = idArity f
1101 stgArity f LambdaBound        = 0
1102 \end{code}