Tag ForeignCalls with the package they correspond to
[ghc-hetmet.git] / 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        ( rhsIsStatic, exprType, findDefault )
16 import CoreArity        ( manifestArity )
17 import StgSyn
18
19 import Type
20 import TyCon
21 import Id
22 import Var              ( Var )
23 import IdInfo
24 import DataCon
25 import CostCentre       ( noCCS )
26 import VarSet
27 import VarEnv
28 import Maybes           ( maybeToBool )
29 import Name             ( getOccName, isExternalName, nameOccName )
30 import OccName          ( occNameString, occNameFS )
31 import BasicTypes       ( Arity )
32 import Module
33 import Outputable
34 import MonadUtils
35 import FastString
36 import Util
37 import ForeignCall
38 import PrimOp           ( PrimCall(..) )
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 :: PackageId -> [CoreBind] -> IO [StgBinding]
143 coreToStg this_pkg pgm
144   = return pgm'
145   where (_, _, pgm') = coreTopBindsToStg this_pkg 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     :: PackageId
154     -> IdEnv HowBound           -- environment for the bindings
155     -> [CoreBind]
156     -> (IdEnv HowBound, FreeVarsInfo, [StgBinding])
157
158 coreTopBindsToStg _        env [] = (env, emptyFVInfo, [])
159 coreTopBindsToStg this_pkg env (b:bs)
160   = (env2, fvs2, b':bs')
161   where
162         -- Notice the mutually-recursive "knot" here:
163         --   env accumulates down the list of binds, 
164         --   fvs accumulates upwards
165         (env1, fvs2, b' ) = coreTopBindToStg this_pkg env fvs1 b
166         (env2, fvs1, bs') = coreTopBindsToStg this_pkg env1 bs
167
168 coreTopBindToStg
169         :: PackageId
170         -> IdEnv HowBound
171         -> FreeVarsInfo         -- Info about the body
172         -> CoreBind
173         -> (IdEnv HowBound, FreeVarsInfo, StgBinding)
174
175 coreTopBindToStg this_pkg env body_fvs (NonRec id rhs)
176   = let 
177         env'      = extendVarEnv env id how_bound
178         how_bound = LetBound TopLet $! manifestArity rhs
179
180         (stg_rhs, fvs') = 
181             initLne env $ do
182               (stg_rhs, fvs') <- coreToTopStgRhs this_pkg body_fvs (id,rhs)
183               return (stg_rhs, fvs')
184         
185         bind = StgNonRec id stg_rhs
186     in
187     ASSERT2(consistentCafInfo id bind, ppr id $$ ppr rhs $$ ppr bind )
188     (env', fvs' `unionFVInfo` body_fvs, bind)
189
190 coreTopBindToStg this_pkg env body_fvs (Rec pairs)
191   = ASSERT( not (null pairs) )
192     let 
193         binders = map fst 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')
200           = initLne env' $ do
201                (stg_rhss, fvss') <- mapAndUnzipM (coreToTopStgRhs this_pkg body_fvs) pairs
202                let fvs' = unionFVInfos fvss'
203                return (stg_rhss, fvs')
204
205         bind = StgRec (zip binders stg_rhss)
206     in
207     ASSERT2(consistentCafInfo (head binders) bind, ppr binders)
208     (env', fvs' `unionFVInfo` body_fvs, bind)
209
210
211 -- Assertion helper: this checks that the CafInfo on the Id matches
212 -- what CoreToStg has figured out about the binding's SRT.  The
213 -- CafInfo will be exact in all cases except when CorePrep has
214 -- floated out a binding, in which case it will be approximate.
215 consistentCafInfo :: Id -> GenStgBinding Var Id -> Bool
216 consistentCafInfo id bind
217   | occNameFS (nameOccName (idName id)) == fsLit "sat"
218   = safe
219   | otherwise
220   = WARN (not exact, ppr id) safe
221   where
222         safe  = id_marked_caffy || not binding_is_caffy
223         exact = id_marked_caffy == binding_is_caffy
224         id_marked_caffy  = mayHaveCafRefs (idCafInfo id)
225         binding_is_caffy = stgBindHasCafRefs bind
226 \end{code}
227
228 \begin{code}
229 coreToTopStgRhs
230         :: PackageId
231         -> FreeVarsInfo         -- Free var info for the scope of the binding
232         -> (Id,CoreExpr)
233         -> LneM (StgRhs, FreeVarsInfo)
234
235 coreToTopStgRhs this_pkg scope_fv_info (bndr, rhs)
236   = do { (new_rhs, rhs_fvs, _) <- coreToStgExpr rhs
237        ; lv_info <- freeVarsToLiveVars rhs_fvs
238
239        ; let stg_rhs   = mkTopStgRhs is_static rhs_fvs (mkSRT lv_info) bndr_info new_rhs
240              stg_arity = stgRhsArity stg_rhs
241        ; return (ASSERT2( arity_ok stg_arity, mk_arity_msg stg_arity) stg_rhs, 
242                  rhs_fvs) }
243   where
244     bndr_info = lookupFVInfo scope_fv_info bndr
245     is_static = rhsIsStatic this_pkg rhs
246
247         -- It's vital that the arity on a top-level Id matches
248         -- the arity of the generated STG binding, else an importing 
249         -- module will use the wrong calling convention
250         --      (Trac #2844 was an example where this happened)
251         -- NB1: we can't move the assertion further out without
252         --      blocking the "knot" tied in coreTopBindsToStg
253         -- NB2: the arity check is only needed for Ids with External
254         --      Names, because they are externally visible.  The CorePrep
255         --      pass introduces "sat" things with Local Names and does
256         --      not bother to set their Arity info, so don't fail for those
257     arity_ok stg_arity
258        | isExternalName (idName bndr) = id_arity == stg_arity
259        | otherwise                    = True
260     id_arity  = idArity bndr
261     mk_arity_msg stg_arity
262         = vcat [ppr bndr, 
263                 ptext (sLit "Id arity:") <+> ppr id_arity,
264                 ptext (sLit "STG arity:") <+> ppr stg_arity]
265
266 mkTopStgRhs :: Bool -> FreeVarsInfo
267             -> SRT -> StgBinderInfo -> StgExpr
268             -> StgRhs
269
270 mkTopStgRhs is_static rhs_fvs srt binder_info (StgLam _ bndrs body)
271   = ASSERT( is_static )
272     StgRhsClosure noCCS binder_info
273                   (getFVs rhs_fvs)               
274                   ReEntrant
275                   srt
276                   bndrs body
277
278 mkTopStgRhs is_static _ _ _ (StgConApp con args)
279   | is_static    -- StgConApps can be updatable (see isCrossDllConApp)
280   = StgRhsCon noCCS con args
281
282 mkTopStgRhs is_static rhs_fvs srt binder_info rhs
283   = ASSERT2( not is_static, ppr rhs )
284     StgRhsClosure noCCS binder_info
285                   (getFVs rhs_fvs)               
286                   Updatable
287                   srt
288                   [] rhs
289 \end{code}
290
291
292 -- ---------------------------------------------------------------------------
293 -- Expressions
294 -- ---------------------------------------------------------------------------
295
296 \begin{code}
297 coreToStgExpr
298         :: CoreExpr
299         -> LneM (StgExpr,       -- Decorated STG expr
300                  FreeVarsInfo,  -- Its free vars (NB free, not live)
301                  EscVarsSet)    -- Its escapees, a subset of its free vars;
302                                 -- also a subset of the domain of the envt
303                                 -- because we are only interested in the escapees
304                                 -- for vars which might be turned into
305                                 -- let-no-escaped ones.
306 \end{code}
307
308 The second and third components can be derived in a simple bottom up pass, not
309 dependent on any decisions about which variables will be let-no-escaped or
310 not.  The first component, that is, the decorated expression, may then depend
311 on these components, but it in turn is not scrutinised as the basis for any
312 decisions.  Hence no black holes.
313
314 \begin{code}
315 coreToStgExpr (Lit l) = return (StgLit l, emptyFVInfo, emptyVarSet)
316 coreToStgExpr (Var v) = coreToStgApp Nothing v []
317
318 coreToStgExpr expr@(App _ _)
319   = coreToStgApp Nothing f args
320   where
321     (f, args) = myCollectArgs expr
322
323 coreToStgExpr expr@(Lam _ _)
324   = let
325         (args, body) = myCollectBinders expr 
326         args'        = filterStgBinders args
327     in
328     extendVarEnvLne [ (a, LambdaBound) | a <- args' ] $ do
329     (body, body_fvs, body_escs) <- coreToStgExpr body
330     let
331         fvs             = args' `minusFVBinders` body_fvs
332         escs            = body_escs `delVarSetList` args'
333         result_expr | null args' = body
334                     | otherwise  = StgLam (exprType expr) args' body
335
336     return (result_expr, fvs, escs)
337
338 coreToStgExpr (Note (SCC cc) expr) = do
339     (expr2, fvs, escs) <- coreToStgExpr expr
340     return (StgSCC cc expr2, fvs, escs)
341
342 coreToStgExpr (Case (Var id) _bndr _ty [(DEFAULT,[],expr)])
343   | Just (TickBox m n) <- isTickBoxOp_maybe id = do
344     (expr2, fvs, escs) <- coreToStgExpr expr
345     return (StgTick m n expr2, fvs, escs)
346
347 coreToStgExpr (Note _ expr)
348   = coreToStgExpr expr
349
350 coreToStgExpr (Cast expr _)
351   = coreToStgExpr expr
352
353 -- Cases require a little more real work.
354
355 coreToStgExpr (Case scrut bndr _ alts) = do
356     (alts2, alts_fvs, alts_escs)
357        <- extendVarEnvLne [(bndr, LambdaBound)] $ do
358             (alts2, fvs_s, escs_s) <- mapAndUnzip3M vars_alt alts
359             return ( alts2,
360                      unionFVInfos fvs_s,
361                      unionVarSets escs_s )
362     let
363         -- Determine whether the default binder is dead or not
364         -- This helps the code generator to avoid generating an assignment
365         -- for the case binder (is extremely rare cases) ToDo: remove.
366         bndr' | bndr `elementOfFVInfo` alts_fvs = bndr
367               | otherwise                       = bndr `setIdOccInfo` IAmDead
368
369         -- Don't consider the default binder as being 'live in alts',
370         -- since this is from the point of view of the case expr, where
371         -- the default binder is not free.
372         alts_fvs_wo_bndr  = bndr `minusFVBinder` alts_fvs
373         alts_escs_wo_bndr = alts_escs `delVarSet` bndr
374
375     alts_lv_info <- freeVarsToLiveVars alts_fvs_wo_bndr
376
377         -- We tell the scrutinee that everything 
378         -- live in the alts is live in it, too.
379     (scrut2, scrut_fvs, _scrut_escs, scrut_lv_info)
380        <- setVarsLiveInCont alts_lv_info $ do
381             (scrut2, scrut_fvs, scrut_escs) <- coreToStgExpr scrut
382             scrut_lv_info <- freeVarsToLiveVars scrut_fvs
383             return (scrut2, scrut_fvs, scrut_escs, scrut_lv_info)
384
385     return (
386       StgCase scrut2 (getLiveVars scrut_lv_info)
387                      (getLiveVars alts_lv_info)
388                      bndr'
389                      (mkSRT alts_lv_info)
390                      (mkStgAltType bndr alts)
391                      alts2,
392       scrut_fvs `unionFVInfo` alts_fvs_wo_bndr,
393       alts_escs_wo_bndr `unionVarSet` getFVSet scrut_fvs
394                 -- You might think we should have scrut_escs, not 
395                 -- (getFVSet scrut_fvs), but actually we can't call, and 
396                 -- then return from, a let-no-escape thing.
397       )
398   where
399     vars_alt (con, binders, rhs)
400       = let     -- Remove type variables
401             binders' = filterStgBinders binders
402         in      
403         extendVarEnvLne [(b, LambdaBound) | b <- binders'] $ do
404         (rhs2, rhs_fvs, rhs_escs) <- coreToStgExpr rhs
405         let
406                 -- Records whether each param is used in the RHS
407             good_use_mask = [ b `elementOfFVInfo` rhs_fvs | b <- binders' ]
408
409         return ( (con, binders', good_use_mask, rhs2),
410                  binders' `minusFVBinders` rhs_fvs,
411                  rhs_escs `delVarSetList` binders' )
412                 -- ToDo: remove the delVarSet;
413                 -- since escs won't include any of these binders
414 \end{code}
415
416 Lets not only take quite a bit of work, but this is where we convert
417 then to let-no-escapes, if we wish.
418
419 (Meanwhile, we don't expect to see let-no-escapes...)
420 \begin{code}
421 coreToStgExpr (Let bind body) = do
422     (new_let, fvs, escs, _)
423        <- mfix (\ ~(_, _, _, no_binder_escapes) ->
424              coreToStgLet no_binder_escapes bind body
425           )
426
427     return (new_let, fvs, escs)
428
429 coreToStgExpr e = pprPanic "coreToStgExpr" (ppr e)
430 \end{code}
431
432 \begin{code}
433 mkStgAltType :: Id -> [CoreAlt] -> AltType
434 mkStgAltType bndr alts
435   = case splitTyConApp_maybe (repType (idType bndr)) of
436         Just (tc,_) | isUnboxedTupleTyCon tc -> UbxTupAlt tc
437                     | isUnLiftedTyCon tc     -> PrimAlt tc
438                     | isHiBootTyCon tc       -> look_for_better_tycon
439                     | isAlgTyCon tc          -> AlgAlt tc
440                     | otherwise              -> ASSERT2( _is_poly_alt_tycon tc, ppr tc )
441                                                 PolyAlt
442         Nothing                              -> PolyAlt
443
444   where
445    _is_poly_alt_tycon tc
446         =  isFunTyCon tc
447         || isPrimTyCon tc   -- "Any" is lifted but primitive
448         || isOpenTyCon tc   -- Type family; e.g. arising from strict
449                             -- function application where argument has a
450                             -- type-family type
451
452    -- Sometimes, the TyCon is a HiBootTyCon which may not have any 
453    -- constructors inside it.  Then we can get a better TyCon by 
454    -- grabbing the one from a constructor alternative
455    -- if one exists.
456    look_for_better_tycon
457         | ((DataAlt con, _, _) : _) <- data_alts = 
458                 AlgAlt (dataConTyCon con)
459         | otherwise =
460                 ASSERT(null data_alts)
461                 PolyAlt
462         where
463                 (data_alts, _deflt) = findDefault alts
464 \end{code}
465
466
467 -- ---------------------------------------------------------------------------
468 -- Applications
469 -- ---------------------------------------------------------------------------
470
471 \begin{code}
472 coreToStgApp
473          :: Maybe UpdateFlag            -- Just upd <=> this application is
474                                         -- the rhs of a thunk binding
475                                         --      x = [...] \upd [] -> the_app
476                                         -- with specified update flag
477         -> Id                           -- Function
478         -> [CoreArg]                    -- Arguments
479         -> LneM (StgExpr, FreeVarsInfo, EscVarsSet)
480
481
482 coreToStgApp _ f args = do
483     (args', args_fvs) <- coreToStgArgs args
484     how_bound <- lookupVarLne f
485
486     let
487         n_val_args       = valArgCount args
488         not_letrec_bound = not (isLetBound how_bound)
489         fun_fvs = singletonFVInfo f how_bound fun_occ
490             -- e.g. (f :: a -> int) (x :: a) 
491             -- Here the free variables are "f", "x" AND the type variable "a"
492             -- coreToStgArgs will deal with the arguments recursively
493
494         -- Mostly, the arity info of a function is in the fn's IdInfo
495         -- But new bindings introduced by CoreSat may not have no
496         -- arity info; it would do us no good anyway.  For example:
497         --      let f = \ab -> e in f
498         -- No point in having correct arity info for f!
499         -- Hence the hasArity stuff below.
500         -- NB: f_arity is only consulted for LetBound things
501         f_arity   = stgArity f how_bound
502         saturated = f_arity <= n_val_args
503
504         fun_occ 
505          | not_letrec_bound         = noBinderInfo      -- Uninteresting variable
506          | f_arity > 0 && saturated = stgSatOcc -- Saturated or over-saturated function call
507          | otherwise                = stgUnsatOcc       -- Unsaturated function or thunk
508
509         fun_escs
510          | not_letrec_bound      = emptyVarSet  -- Only letrec-bound escapees are interesting
511          | f_arity == n_val_args = emptyVarSet  -- A function *or thunk* with an exactly
512                                                 -- saturated call doesn't escape
513                                                 -- (let-no-escape applies to 'thunks' too)
514
515          | otherwise         = unitVarSet f     -- Inexact application; it does escape
516
517         -- At the moment of the call:
518
519         --  either the function is *not* let-no-escaped, in which case
520         --         nothing is live except live_in_cont
521         --      or the function *is* let-no-escaped in which case the
522         --         variables it uses are live, but still the function
523         --         itself is not.  PS.  In this case, the function's
524         --         live vars should already include those of the
525         --         continuation, but it does no harm to just union the
526         --         two regardless.
527
528         res_ty = exprType (mkApps (Var f) args)
529         app = case idDetails f of
530                 DataConWorkId dc | saturated -> StgConApp dc args'
531
532                 -- Some primitive operator that might be implemented as a library call.
533                 PrimOpId op      -> ASSERT( saturated )
534                                     StgOpApp (StgPrimOp op) args' res_ty
535
536                 -- A call to some primitive Cmm function.
537                 FCallId (CCall (CCallSpec (PackageTarget lbl (Just pkgId)) PrimCallConv _))
538                                  -> ASSERT( saturated )
539                                     StgOpApp (StgPrimCallOp (PrimCall lbl pkgId)) args' res_ty
540
541                 -- A regular foreign call.
542                 FCallId call     -> ASSERT( saturated )
543                                     StgOpApp (StgFCallOp call (idUnique f)) args' res_ty
544
545                 TickBoxOpId {}   -> pprPanic "coreToStg TickBox" $ ppr (f,args')
546                 _other           -> StgApp f args'
547
548     return (
549         app,
550         fun_fvs  `unionFVInfo` args_fvs,
551         fun_escs `unionVarSet` (getFVSet args_fvs)
552                                 -- All the free vars of the args are disqualified
553                                 -- from being let-no-escaped.
554      )
555
556
557
558 -- ---------------------------------------------------------------------------
559 -- Argument lists
560 -- This is the guy that turns applications into A-normal form
561 -- ---------------------------------------------------------------------------
562
563 coreToStgArgs :: [CoreArg] -> LneM ([StgArg], FreeVarsInfo)
564 coreToStgArgs []
565   = return ([], emptyFVInfo)
566
567 coreToStgArgs (Type _ : args) = do     -- Type argument
568     (args', fvs) <- coreToStgArgs args
569     return (args', fvs)
570
571 coreToStgArgs (arg : args) = do         -- Non-type argument
572     (stg_args, args_fvs) <- coreToStgArgs args
573     (arg', arg_fvs, _escs) <- coreToStgExpr arg
574     let
575         fvs = args_fvs `unionFVInfo` arg_fvs
576         stg_arg = case arg' of
577                        StgApp v []      -> StgVarArg v
578                        StgConApp con [] -> StgVarArg (dataConWorkId con)
579                        StgLit lit       -> StgLitArg lit
580                        _                -> pprPanic "coreToStgArgs" (ppr arg)
581
582         -- WARNING: what if we have an argument like (v `cast` co)
583         --          where 'co' changes the representation type?
584         --          (This really only happens if co is unsafe.)
585         -- Then all the getArgAmode stuff in CgBindery will set the
586         -- cg_rep of the CgIdInfo based on the type of v, rather
587         -- than the type of 'co'.
588         -- This matters particularly when the function is a primop
589         -- or foreign call.
590         -- Wanted: a better solution than this hacky warning
591     let
592         arg_ty = exprType arg
593         stg_arg_ty = stgArgType stg_arg
594         bad_args = (isUnLiftedType arg_ty && not (isUnLiftedType stg_arg_ty)) 
595                 || (typePrimRep arg_ty /= typePrimRep stg_arg_ty)
596         -- In GHCi we coerce an argument of type BCO# (unlifted) to HValue (lifted), 
597         -- and pass it to a function expecting an HValue (arg_ty).  This is ok because
598         -- we can treat an unlifted value as lifted.  But the other way round 
599         -- we complain.
600         -- We also want to check if a pointer is cast to a non-ptr etc
601
602     WARN( bad_args, ptext (sLit "Dangerous-looking argument. Probable cause: bad unsafeCoerce#") $$ ppr arg )
603      return (stg_arg : stg_args, fvs)
604
605
606 -- ---------------------------------------------------------------------------
607 -- The magic for lets:
608 -- ---------------------------------------------------------------------------
609
610 coreToStgLet
611          :: Bool        -- True <=> yes, we are let-no-escaping this let
612          -> CoreBind    -- bindings
613          -> CoreExpr    -- body
614          -> LneM (StgExpr,      -- new let
615                   FreeVarsInfo, -- variables free in the whole let
616                   EscVarsSet,   -- variables that escape from the whole let
617                   Bool)         -- True <=> none of the binders in the bindings
618                                 -- is among the escaping vars
619
620 coreToStgLet let_no_escape bind body = do
621     (bind2, bind_fvs, bind_escs, bind_lvs,
622      body2, body_fvs, body_escs, body_lvs)
623        <- mfix $ \ ~(_, _, _, _, _, rec_body_fvs, _, _) -> do
624
625           -- Do the bindings, setting live_in_cont to empty if
626           -- we ain't in a let-no-escape world
627           live_in_cont <- getVarsLiveInCont
628           ( bind2, bind_fvs, bind_escs, bind_lv_info, env_ext)
629                 <- setVarsLiveInCont (if let_no_escape 
630                                           then live_in_cont 
631                                           else emptyLiveInfo)
632                                      (vars_bind rec_body_fvs bind)
633
634           -- Do the body
635           extendVarEnvLne env_ext $ do
636              (body2, body_fvs, body_escs) <- coreToStgExpr body
637              body_lv_info <- freeVarsToLiveVars body_fvs
638
639              return (bind2, bind_fvs, bind_escs, getLiveVars bind_lv_info,
640                      body2, body_fvs, body_escs, getLiveVars body_lv_info)
641
642
643         -- Compute the new let-expression
644     let
645         new_let | let_no_escape = StgLetNoEscape live_in_whole_let bind_lvs bind2 body2
646                 | otherwise     = StgLet bind2 body2
647
648         free_in_whole_let
649           = binders `minusFVBinders` (bind_fvs `unionFVInfo` body_fvs)
650
651         live_in_whole_let
652           = bind_lvs `unionVarSet` (body_lvs `delVarSetList` binders)
653
654         real_bind_escs = if let_no_escape then
655                             bind_escs
656                          else
657                             getFVSet bind_fvs
658                             -- Everything escapes which is free in the bindings
659
660         let_escs = (real_bind_escs `unionVarSet` body_escs) `delVarSetList` binders
661
662         all_escs = bind_escs `unionVarSet` body_escs    -- Still includes binders of
663                                                         -- this let(rec)
664
665         no_binder_escapes = isEmptyVarSet (set_of_binders `intersectVarSet` all_escs)
666
667         -- Debugging code as requested by Andrew Kennedy
668         checked_no_binder_escapes
669                 | debugIsOn && not no_binder_escapes && any is_join_var binders
670                 = pprTrace "Interesting!  A join var that isn't let-no-escaped" (ppr binders)
671                   False
672                 | otherwise = no_binder_escapes
673                             
674                 -- Mustn't depend on the passed-in let_no_escape flag, since
675                 -- no_binder_escapes is used by the caller to derive the flag!
676     return (
677         new_let,
678         free_in_whole_let,
679         let_escs,
680         checked_no_binder_escapes
681       )
682   where
683     set_of_binders = mkVarSet binders
684     binders        = bindersOf bind
685
686     mk_binding bind_lv_info binder rhs
687         = (binder, LetBound (NestedLet live_vars) (manifestArity rhs))
688         where
689            live_vars | let_no_escape = addLiveVar bind_lv_info binder
690                      | otherwise     = unitLiveVar binder
691                 -- c.f. the invariant on NestedLet
692
693     vars_bind :: FreeVarsInfo           -- Free var info for body of binding
694               -> CoreBind
695               -> LneM (StgBinding,
696                        FreeVarsInfo, 
697                        EscVarsSet,        -- free vars; escapee vars
698                        LiveInfo,          -- Vars and CAFs live in binding
699                        [(Id, HowBound)])  -- extension to environment
700                                          
701
702     vars_bind body_fvs (NonRec binder rhs) = do
703         (rhs2, bind_fvs, bind_lv_info, escs) <- coreToStgRhs body_fvs [] (binder,rhs)
704         let
705             env_ext_item = mk_binding bind_lv_info binder rhs
706
707         return (StgNonRec binder rhs2,
708                 bind_fvs, escs, bind_lv_info, [env_ext_item])
709
710
711     vars_bind body_fvs (Rec pairs)
712       = mfix $ \ ~(_, rec_rhs_fvs, _, bind_lv_info, _) ->
713            let
714                 rec_scope_fvs = unionFVInfo body_fvs rec_rhs_fvs
715                 binders = map fst pairs
716                 env_ext = [ mk_binding bind_lv_info b rhs 
717                           | (b,rhs) <- pairs ]
718            in
719            extendVarEnvLne env_ext $ do
720               (rhss2, fvss, lv_infos, escss)
721                      <- mapAndUnzip4M (coreToStgRhs rec_scope_fvs binders) pairs 
722               let
723                         bind_fvs = unionFVInfos fvss
724                         bind_lv_info = foldr unionLiveInfo emptyLiveInfo lv_infos
725                         escs     = unionVarSets escss
726               
727               return (StgRec (binders `zip` rhss2),
728                       bind_fvs, escs, bind_lv_info, env_ext)
729
730
731 is_join_var :: Id -> Bool
732 -- A hack (used only for compiler debuggging) to tell if
733 -- a variable started life as a join point ($j)
734 is_join_var j = occNameString (getOccName j) == "$j"
735 \end{code}
736
737 \begin{code}
738 coreToStgRhs :: FreeVarsInfo            -- Free var info for the scope of the binding
739              -> [Id]
740              -> (Id,CoreExpr)
741              -> LneM (StgRhs, FreeVarsInfo, LiveInfo, EscVarsSet)
742
743 coreToStgRhs scope_fv_info binders (bndr, rhs) = do
744     (new_rhs, rhs_fvs, rhs_escs) <- coreToStgExpr rhs
745     lv_info <- freeVarsToLiveVars (binders `minusFVBinders` rhs_fvs)
746     return (mkStgRhs rhs_fvs (mkSRT lv_info) bndr_info new_rhs,
747             rhs_fvs, lv_info, rhs_escs)
748   where
749     bndr_info = lookupFVInfo scope_fv_info bndr
750
751 mkStgRhs :: FreeVarsInfo -> SRT -> StgBinderInfo -> StgExpr -> StgRhs
752
753 mkStgRhs _ _ _ (StgConApp con args) = StgRhsCon noCCS con args
754
755 mkStgRhs rhs_fvs srt binder_info (StgLam _ bndrs body)
756   = StgRhsClosure noCCS binder_info
757                   (getFVs rhs_fvs)               
758                   ReEntrant
759                   srt bndrs body
760         
761 mkStgRhs rhs_fvs srt binder_info rhs
762   = StgRhsClosure noCCS binder_info
763                   (getFVs rhs_fvs)               
764                   upd_flag srt [] rhs
765   where
766    upd_flag = Updatable
767   {-
768     SDM: disabled.  Eval/Apply can't handle functions with arity zero very
769     well; and making these into simple non-updatable thunks breaks other
770     assumptions (namely that they will be entered only once).
771
772     upd_flag | isPAP env rhs  = ReEntrant
773              | otherwise      = Updatable
774   -}
775
776 {- ToDo:
777           upd = if isOnceDem dem
778                     then (if isNotTop toplev 
779                             then SingleEntry    -- HA!  Paydirt for "dem"
780                             else 
781 #ifdef DEBUG
782                      trace "WARNING: SE CAFs unsupported, forcing UPD instead" $
783 #endif
784                      Updatable)
785                 else Updatable
786         -- For now we forbid SingleEntry CAFs; they tickle the
787         -- ASSERT in rts/Storage.c line 215 at newCAF() re mut_link,
788         -- and I don't understand why.  There's only one SE_CAF (well,
789         -- only one that tickled a great gaping bug in an earlier attempt
790         -- at ClosureInfo.getEntryConvention) in the whole of nofib, 
791         -- specifically Main.lvl6 in spectral/cryptarithm2.
792         -- So no great loss.  KSW 2000-07.
793 -}
794 \end{code}
795
796 Detect thunks which will reduce immediately to PAPs, and make them
797 non-updatable.  This has several advantages:
798
799         - the non-updatable thunk behaves exactly like the PAP,
800
801         - the thunk is more efficient to enter, because it is
802           specialised to the task.
803
804         - we save one update frame, one stg_update_PAP, one update
805           and lots of PAP_enters.
806
807         - in the case where the thunk is top-level, we save building
808           a black hole and futhermore the thunk isn't considered to
809           be a CAF any more, so it doesn't appear in any SRTs.
810
811 We do it here, because the arity information is accurate, and we need
812 to do it before the SRT pass to save the SRT entries associated with
813 any top-level PAPs.
814
815 isPAP env (StgApp f args) = listLengthCmp args arity == LT -- idArity f > length args
816                           where
817                             arity = stgArity f (lookupBinding env f)
818 isPAP env _               = False
819
820
821 %************************************************************************
822 %*                                                                      *
823 \subsection[LNE-monad]{A little monad for this let-no-escaping pass}
824 %*                                                                      *
825 %************************************************************************
826
827 There's a lot of stuff to pass around, so we use this @LneM@ monad to
828 help.  All the stuff here is only passed *down*.
829
830 \begin{code}
831 newtype LneM a = LneM
832     { unLneM :: IdEnv HowBound
833              -> LiveInfo                -- Vars and CAFs live in continuation
834              -> a
835     }
836
837 type LiveInfo = (StgLiveVars,   -- Dynamic live variables; 
838                                 -- i.e. ones with a nested (non-top-level) binding
839                  CafSet)        -- Static live variables;
840                                 -- i.e. top-level variables that are CAFs or refer to them
841
842 type EscVarsSet = IdSet
843 type CafSet     = IdSet
844
845 data HowBound
846   = ImportBound         -- Used only as a response to lookupBinding; never
847                         -- exists in the range of the (IdEnv HowBound)
848
849   | LetBound            -- A let(rec) in this module
850         LetInfo         -- Whether top level or nested
851         Arity           -- Its arity (local Ids don't have arity info at this point)
852
853   | LambdaBound         -- Used for both lambda and case
854
855 data LetInfo
856   = TopLet              -- top level things
857   | NestedLet LiveInfo  -- For nested things, what is live if this
858                         -- thing is live?  Invariant: the binder
859                         -- itself is always a member of
860                         -- the dynamic set of its own LiveInfo
861
862 isLetBound :: HowBound -> Bool
863 isLetBound (LetBound _ _) = True
864 isLetBound _              = False
865
866 topLevelBound :: HowBound -> Bool
867 topLevelBound ImportBound         = True
868 topLevelBound (LetBound TopLet _) = True
869 topLevelBound _                   = False
870 \end{code}
871
872 For a let(rec)-bound variable, x, we record LiveInfo, the set of
873 variables that are live if x is live.  This LiveInfo comprises
874         (a) dynamic live variables (ones with a non-top-level binding)
875         (b) static live variabes (CAFs or things that refer to CAFs)
876
877 For "normal" variables (a) is just x alone.  If x is a let-no-escaped
878 variable then x is represented by a code pointer and a stack pointer
879 (well, one for each stack).  So all of the variables needed in the
880 execution of x are live if x is, and are therefore recorded in the
881 LetBound constructor; x itself *is* included.
882
883 The set of dynamic live variables is guaranteed ot have no further let-no-escaped
884 variables in it.
885
886 \begin{code}
887 emptyLiveInfo :: LiveInfo
888 emptyLiveInfo = (emptyVarSet,emptyVarSet)
889
890 unitLiveVar :: Id -> LiveInfo
891 unitLiveVar lv = (unitVarSet lv, emptyVarSet)
892
893 unitLiveCaf :: Id -> LiveInfo
894 unitLiveCaf caf = (emptyVarSet, unitVarSet caf)
895
896 addLiveVar :: LiveInfo -> Id -> LiveInfo
897 addLiveVar (lvs, cafs) id = (lvs `extendVarSet` id, cafs)
898
899 unionLiveInfo :: LiveInfo -> LiveInfo -> LiveInfo
900 unionLiveInfo (lv1,caf1) (lv2,caf2) = (lv1 `unionVarSet` lv2, caf1 `unionVarSet` caf2)
901
902 mkSRT :: LiveInfo -> SRT
903 mkSRT (_, cafs) = SRTEntries cafs
904
905 getLiveVars :: LiveInfo -> StgLiveVars
906 getLiveVars (lvs, _) = lvs
907 \end{code}
908
909
910 The std monad functions:
911 \begin{code}
912 initLne :: IdEnv HowBound -> LneM a -> a
913 initLne env m = unLneM m env emptyLiveInfo
914
915
916
917 {-# INLINE thenLne #-}
918 {-# INLINE returnLne #-}
919
920 returnLne :: a -> LneM a
921 returnLne e = LneM $ \_ _ -> e
922
923 thenLne :: LneM a -> (a -> LneM b) -> LneM b
924 thenLne m k = LneM $ \env lvs_cont
925   -> unLneM (k (unLneM m env lvs_cont)) env lvs_cont
926
927 instance Monad LneM where
928     return = returnLne
929     (>>=)  = thenLne
930
931 instance MonadFix LneM where
932     mfix expr = LneM $ \env lvs_cont ->
933                        let result = unLneM (expr result) env lvs_cont
934                        in  result
935 \end{code}
936
937 Functions specific to this monad:
938
939 \begin{code}
940 getVarsLiveInCont :: LneM LiveInfo
941 getVarsLiveInCont = LneM $ \_env lvs_cont -> lvs_cont
942
943 setVarsLiveInCont :: LiveInfo -> LneM a -> LneM a
944 setVarsLiveInCont new_lvs_cont expr
945    =    LneM $   \env _lvs_cont
946    -> unLneM expr env new_lvs_cont
947
948 extendVarEnvLne :: [(Id, HowBound)] -> LneM a -> LneM a
949 extendVarEnvLne ids_w_howbound expr
950    =    LneM $   \env lvs_cont
951    -> unLneM expr (extendVarEnvList env ids_w_howbound) lvs_cont
952
953 lookupVarLne :: Id -> LneM HowBound
954 lookupVarLne v = LneM $ \env _lvs_cont -> lookupBinding env v
955
956 lookupBinding :: IdEnv HowBound -> Id -> HowBound
957 lookupBinding env v = case lookupVarEnv env v of
958                         Just xx -> xx
959                         Nothing -> ASSERT2( isGlobalId v, ppr v ) ImportBound
960
961
962 -- The result of lookupLiveVarsForSet, a set of live variables, is
963 -- only ever tacked onto a decorated expression. It is never used as
964 -- the basis of a control decision, which might give a black hole.
965
966 freeVarsToLiveVars :: FreeVarsInfo -> LneM LiveInfo
967 freeVarsToLiveVars fvs = LneM freeVarsToLiveVars'
968  where
969   freeVarsToLiveVars' _env live_in_cont = live_info
970    where
971     live_info    = foldr unionLiveInfo live_in_cont lvs_from_fvs
972     lvs_from_fvs = map do_one (allFreeIds fvs)
973
974     do_one (v, how_bound)
975       = case how_bound of
976           ImportBound                     -> unitLiveCaf v      -- Only CAF imports are 
977                                                                 -- recorded in fvs
978           LetBound TopLet _              
979                 | mayHaveCafRefs (idCafInfo v) -> unitLiveCaf v
980                 | otherwise                    -> emptyLiveInfo
981
982           LetBound (NestedLet lvs) _      -> lvs        -- lvs already contains v
983                                                         -- (see the invariant on NestedLet)
984
985           _lambda_or_case_binding         -> unitLiveVar v      -- Bound by lambda or case
986 \end{code}
987
988 %************************************************************************
989 %*                                                                      *
990 \subsection[Free-var info]{Free variable information}
991 %*                                                                      *
992 %************************************************************************
993
994 \begin{code}
995 type FreeVarsInfo = VarEnv (Var, HowBound, StgBinderInfo)
996         -- The Var is so we can gather up the free variables
997         -- as a set.
998         --
999         -- The HowBound info just saves repeated lookups;
1000         -- we look up just once when we encounter the occurrence.
1001         -- INVARIANT: Any ImportBound Ids are HaveCafRef Ids
1002         --            Imported Ids without CAF refs are simply
1003         --            not put in the FreeVarsInfo for an expression.
1004         --            See singletonFVInfo and freeVarsToLiveVars
1005         --
1006         -- StgBinderInfo records how it occurs; notably, we
1007         -- are interested in whether it only occurs in saturated 
1008         -- applications, because then we don't need to build a
1009         -- curried version.
1010         -- If f is mapped to noBinderInfo, that means
1011         -- that f *is* mentioned (else it wouldn't be in the
1012         -- IdEnv at all), but perhaps in an unsaturated applications.
1013         --
1014         -- All case/lambda-bound things are also mapped to
1015         -- noBinderInfo, since we aren't interested in their
1016         -- occurence info.
1017         --
1018         -- For ILX we track free var info for type variables too;
1019         -- hence VarEnv not IdEnv
1020 \end{code}
1021
1022 \begin{code}
1023 emptyFVInfo :: FreeVarsInfo
1024 emptyFVInfo = emptyVarEnv
1025
1026 singletonFVInfo :: Id -> HowBound -> StgBinderInfo -> FreeVarsInfo
1027 -- Don't record non-CAF imports at all, to keep free-var sets small
1028 singletonFVInfo id ImportBound info
1029    | mayHaveCafRefs (idCafInfo id) = unitVarEnv id (id, ImportBound, info)
1030    | otherwise                     = emptyVarEnv
1031 singletonFVInfo id how_bound info  = unitVarEnv id (id, how_bound, info)
1032
1033 unionFVInfo :: FreeVarsInfo -> FreeVarsInfo -> FreeVarsInfo
1034 unionFVInfo fv1 fv2 = plusVarEnv_C plusFVInfo fv1 fv2
1035
1036 unionFVInfos :: [FreeVarsInfo] -> FreeVarsInfo
1037 unionFVInfos fvs = foldr unionFVInfo emptyFVInfo fvs
1038
1039 minusFVBinders :: [Id] -> FreeVarsInfo -> FreeVarsInfo
1040 minusFVBinders vs fv = foldr minusFVBinder fv vs
1041
1042 minusFVBinder :: Id -> FreeVarsInfo -> FreeVarsInfo
1043 minusFVBinder v fv = fv `delVarEnv` v
1044         -- When removing a binder, remember to add its type variables
1045         -- c.f. CoreFVs.delBinderFV
1046
1047 elementOfFVInfo :: Id -> FreeVarsInfo -> Bool
1048 elementOfFVInfo id fvs = maybeToBool (lookupVarEnv fvs id)
1049
1050 lookupFVInfo :: FreeVarsInfo -> Id -> StgBinderInfo
1051 -- Find how the given Id is used.
1052 -- Externally visible things may be used any old how
1053 lookupFVInfo fvs id 
1054   | isExternalName (idName id) = noBinderInfo
1055   | otherwise = case lookupVarEnv fvs id of
1056                         Nothing         -> noBinderInfo
1057                         Just (_,_,info) -> info
1058
1059 allFreeIds :: FreeVarsInfo -> [(Id,HowBound)]   -- Both top level and non-top-level Ids
1060 allFreeIds fvs = ASSERT( all (isId . fst) ids ) ids
1061       where
1062         ids = [(id,how_bound) | (id,how_bound,_) <- varEnvElts fvs]
1063
1064 -- Non-top-level things only, both type variables and ids
1065 getFVs :: FreeVarsInfo -> [Var] 
1066 getFVs fvs = [id | (id, how_bound, _) <- varEnvElts fvs, 
1067                     not (topLevelBound how_bound) ]
1068
1069 getFVSet :: FreeVarsInfo -> VarSet
1070 getFVSet fvs = mkVarSet (getFVs fvs)
1071
1072 plusFVInfo :: (Var, HowBound, StgBinderInfo)
1073            -> (Var, HowBound, StgBinderInfo)
1074            -> (Var, HowBound, StgBinderInfo)
1075 plusFVInfo (id1,hb1,info1) (id2,hb2,info2)
1076   = ASSERT (id1 == id2 && hb1 `check_eq_how_bound` hb2)
1077     (id1, hb1, combineStgBinderInfo info1 info2)
1078
1079 -- The HowBound info for a variable in the FVInfo should be consistent
1080 check_eq_how_bound :: HowBound -> HowBound -> Bool
1081 check_eq_how_bound ImportBound        ImportBound        = True
1082 check_eq_how_bound LambdaBound        LambdaBound        = True
1083 check_eq_how_bound (LetBound li1 ar1) (LetBound li2 ar2) = ar1 == ar2 && check_eq_li li1 li2
1084 check_eq_how_bound _                  _                  = False
1085
1086 check_eq_li :: LetInfo -> LetInfo -> Bool
1087 check_eq_li (NestedLet _) (NestedLet _) = True
1088 check_eq_li TopLet        TopLet        = True
1089 check_eq_li _             _             = False
1090 \end{code}
1091
1092 Misc.
1093 \begin{code}
1094 filterStgBinders :: [Var] -> [Var]
1095 filterStgBinders bndrs = filter isId bndrs
1096 \end{code}
1097
1098
1099 \begin{code}
1100         -- Ignore all notes except SCC
1101 myCollectBinders :: Expr Var -> ([Var], Expr Var)
1102 myCollectBinders expr
1103   = go [] expr
1104   where
1105     go bs (Lam b e)          = go (b:bs) e
1106     go bs e@(Note (SCC _) _) = (reverse bs, e) 
1107     go bs (Cast e _)         = go bs e
1108     go bs (Note _ e)         = go bs e
1109     go bs e                  = (reverse bs, e)
1110
1111 myCollectArgs :: CoreExpr -> (Id, [CoreArg])
1112         -- We assume that we only have variables
1113         -- in the function position by now
1114 myCollectArgs expr
1115   = go expr []
1116   where
1117     go (Var v)          as = (v, as)
1118     go (App f a) as        = go f (a:as)
1119     go (Note (SCC _) _) _  = pprPanic "CoreToStg.myCollectArgs" (ppr expr)
1120     go (Cast e _)       as = go e as
1121     go (Note _ e)       as = go e as
1122     go (Lam b e)        as
1123        | isTyVar b         = go e as    -- Note [Collect args]
1124     go _                _  = pprPanic "CoreToStg.myCollectArgs" (ppr expr)
1125 \end{code}
1126
1127 Note [Collect args]
1128 ~~~~~~~~~~~~~~~~~~~
1129 This big-lambda case occurred following a rather obscure eta expansion.
1130 It all seems a bit yukky to me.
1131      
1132 \begin{code}
1133 stgArity :: Id -> HowBound -> Arity
1134 stgArity _ (LetBound _ arity) = arity
1135 stgArity f ImportBound        = idArity f
1136 stgArity _ LambdaBound        = 0
1137 \end{code}