2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %************************************************************************
6 \section[CoreToStg]{Converting core syntax to STG syntax}
8 %************************************************************************
10 Convert a @CoreSyntax@ program to a @StgSyntax@ program.
13 module CoreToStg ( topCoreBindsToStg ) where
15 #include "HsVersions.h"
17 import CoreSyn -- input
18 import StgSyn -- output
20 import CoreUtils ( coreExprType )
21 import SimplUtils ( findDefault )
22 import CostCentre ( noCCS )
23 import Id ( Id, mkSysLocal, idType,
24 externallyVisibleId, setIdUnique, idName, getIdDemandInfo
26 import Var ( modifyIdInfo )
27 import IdInfo ( setDemandInfo )
28 import DataCon ( DataCon, dataConName, dataConId )
29 import Name ( Name, nameModule, isLocallyDefinedName )
30 import Module ( isDynamicModule )
31 import Const ( Con(..), Literal, isLitLitLit )
33 import Const ( Con(..), isWHNFCon, Literal(..) )
34 import PrimOp ( PrimOp(..) )
35 import Type ( isUnLiftedType, isUnboxedTupleType, Type )
36 import TysPrim ( intPrimTy )
38 import Unique ( Unique, Uniquable(..) )
39 import UniqSupply -- all of it, really
44 *************** OVERVIEW *********************
47 The business of this pass is to convert Core to Stg. On the way:
49 * We discard type lambdas and applications. In so doing we discard
50 "trivial" bindings such as
52 where t1, t2 are types
54 * We don't pin on correct arities any more, because they can be mucked up
55 by the lambda lifter. In particular, the lambda lifter can take a local
56 letrec-bound variable and make it a lambda argument, which shouldn't have
57 an arity. So SetStgVarInfo sets arities now.
59 * We do *not* pin on the correct free/live var info; that's done later.
60 Instead we use bOGUS_LVS and _FVS as a placeholder.
62 [Quite a bit of stuff that used to be here has moved
63 to tidyCorePgm (SimplCore.lhs) SLPJ Nov 96]
66 %************************************************************************
68 \subsection[coreToStg-programs]{Converting a core program and core bindings}
70 %************************************************************************
72 March 98: We keep a small environment to give all locally bound
73 Names new unique ids, since the code generator assumes that binders
74 are unique across a module. (Simplifier doesn't maintain this
75 invariant any longer.)
78 type StgEnv = IdEnv Id
85 No free/live variable information is pinned on in this pass; it's added
87 we use @bOGUS_LVs@ and @bOGUS_FVs@ as placeholders.
90 bOGUS_LVs :: StgLiveVars
91 bOGUS_LVs = panic "bOGUS_LVs" -- emptyUniqSet (used when pprTracing)
94 bOGUS_FVs = panic "bOGUS_FVs" -- [] (ditto)
98 topCoreBindsToStg :: UniqSupply -- name supply
99 -> [CoreBind] -- input
100 -> [StgBinding] -- output
102 topCoreBindsToStg us core_binds
103 = initUs us (coreBindsToStg emptyVarEnv core_binds)
105 coreBindsToStg :: StgEnv -> [CoreBind] -> UniqSM [StgBinding]
107 coreBindsToStg env [] = returnUs []
108 coreBindsToStg env (b:bs)
109 = coreBindToStg env b `thenUs` \ (new_b, new_env) ->
110 coreBindsToStg new_env bs `thenUs` \ new_bs ->
111 returnUs (new_b ++ new_bs)
114 %************************************************************************
116 \subsection[coreToStg-binds]{Converting bindings}
118 %************************************************************************
121 coreBindToStg :: StgEnv
123 -> UniqSM ([StgBinding], -- Empty or singleton
126 coreBindToStg env (NonRec binder rhs)
127 = coreRhsToStg env rhs `thenUs` \ stg_rhs ->
128 newLocalId env binder `thenUs` \ (new_env, new_binder) ->
129 returnUs ([StgNonRec new_binder stg_rhs], new_env)
131 coreBindToStg env (Rec pairs)
132 = newLocalIds env binders `thenUs` \ (env', binders') ->
133 mapUs (coreRhsToStg env') rhss `thenUs` \ stg_rhss ->
134 returnUs ([StgRec (binders' `zip` stg_rhss)], env')
136 (binders, rhss) = unzip pairs
140 %************************************************************************
142 \subsection[coreToStg-rhss]{Converting right hand sides}
144 %************************************************************************
147 coreRhsToStg :: StgEnv -> CoreExpr -> UniqSM StgRhs
149 coreRhsToStg env core_rhs
150 = coreExprToStg env core_rhs `thenUs` \ stg_expr ->
151 returnUs (exprToRhs stg_expr)
153 exprToRhs (StgLet (StgNonRec var1 rhs) (StgApp var2 []))
156 -- This curious stuff is to unravel what a lambda turns into
157 -- We have to do it this way, rather than spot a lambda in the
158 -- incoming rhs. Why? Because trivial bindings might conceal
159 -- what the rhs is actually like.
162 We reject the following candidates for 'static constructor'dom:
164 - any dcon that takes a lit-lit as an arg.
165 - [Win32 DLLs only]: any dcon that is (or takes as arg)
166 that's living in a DLL.
168 These constraints are necessary to ensure that the code
169 generated in the end for the static constructors, which
170 live in the data segment, remain valid - i.e., it has to
171 be constant. For obvious reasons, that's hard to guarantee
172 with lit-lits. The second case of a constructor referring
173 to static closures hiding out in some DLL is an artifact
174 of the way Win32 DLLs handle global DLL variables. A (data)
175 symbol exported from a DLL has to be accessed through a
176 level of indirection at the site of use, so whereas
178 extern StgClosure y_closure;
179 extern StgClosure z_closure;
180 x = { ..., &y_closure, &z_closure };
182 is legal when the symbols are in scope at link-time, it is
183 not when y_closure is in a DLL. So, any potential static
184 closures that refers to stuff that's residing in a DLL
185 will be put in an (updateable) thunk instead.
187 An alternative strategy is to support the generation of
188 constructors (ala C++ static class constructors) which will
189 then be run at load time to fix up static closures.
191 exprToRhs (StgCon (DataCon con) args _)
193 all (not.is_lit_lit) args = StgRhsCon noCCS con args
195 is_dynamic = isDynCon con || any (isDynArg) args
197 is_lit_lit (StgVarArg _) = False
198 is_lit_lit (StgConArg x) =
200 Literal l -> isLitLitLit l
204 = StgRhsClosure noCCS -- No cost centre (ToDo?)
206 noSRT -- figure out later
209 Updatable -- Be pessimistic
213 isDynCon :: DataCon -> Bool
214 isDynCon con = isDynName (dataConName con)
216 isDynArg :: StgArg -> Bool
217 isDynArg (StgVarArg v) = isDynName (idName v)
218 isDynArg (StgConArg con) =
220 DataCon dc -> isDynCon dc
221 Literal l -> isLitLitLit l
224 isDynName :: Name -> Bool
226 not (isLocallyDefinedName nm) &&
227 isDynamicModule (nameModule nm)
233 %************************************************************************
235 \subsection[coreToStg-atoms{Converting atoms}
237 %************************************************************************
240 coreArgsToStg :: StgEnv -> [CoreArg] -> UniqSM ([StgFloatBind], [StgArg])
245 coreArgsToStg env (Type ty : as) -- Discard type arguments
246 = coreArgsToStg env as
248 coreArgsToStg env (a:as)
249 = coreArgToStg env a `thenUs` \ (bs1, a') ->
250 coreArgsToStg env as `thenUs` \ (bs2, as') ->
251 returnUs (bs1 ++ bs2, a' : as')
253 -- This is where we arrange that a non-trivial argument is let-bound
255 coreArgToStg :: StgEnv -> CoreArg -> UniqSM ([StgFloatBind], StgArg)
258 = coreExprToStgFloat env arg `thenUs` \ (binds, arg') ->
259 case (binds, arg') of
260 ([], StgCon con [] _) | isWHNFCon con -> returnUs ([], StgConArg con)
261 ([], StgApp v []) -> returnUs ([], StgVarArg v)
263 -- A non-trivial argument: we must let (or case-bind)
264 -- We don't do the case part here... we leave that to mkStgBinds
266 -- Further complication: if we're converting this binding into
267 -- a case, then try to avoid generating any case-of-case
268 -- expressions by pulling out the floats.
270 newStgVar ty `thenUs` \ v ->
272 then returnUs (binds ++ [CaseBind v arg'], StgVarArg v)
273 else returnUs ([LetBind v (mkStgBinds binds arg')], StgVarArg v)
275 ty = coreExprType arg
280 %************************************************************************
282 \subsection[coreToStg-exprs]{Converting core expressions}
284 %************************************************************************
287 coreExprToStg :: StgEnv -> CoreExpr -> UniqSM StgExpr
289 coreExprToStg env (Var var)
290 = returnUs (StgApp (stgLookup env var) [])
294 %************************************************************************
296 \subsubsection[coreToStg-lambdas]{Lambda abstractions}
298 %************************************************************************
301 coreExprToStg env expr@(Lam _ _)
303 (binders, body) = collectBinders expr
304 id_binders = filter isId binders
306 newLocalIds env id_binders `thenUs` \ (env', binders') ->
307 coreExprToStg env' body `thenUs` \ stg_body ->
309 if null id_binders then -- it was all type/usage binders; tossed
314 -- if the body reduced to a lambda too...
315 (StgLet (StgNonRec var (StgRhsClosure cc bi srt fvs uf args body))
318 returnUs (StgLet (StgNonRec var
330 -- We must let-bind the lambda
331 newStgVar (coreExprType expr) `thenUs` \ var ->
333 (StgLet (StgNonRec var (StgRhsClosure noCCS
337 ReEntrant -- binders is non-empty
343 %************************************************************************
345 \subsubsection[coreToStg-let(rec)]{Let and letrec expressions}
347 %************************************************************************
350 coreExprToStg env (Let bind body)
351 = coreBindToStg env bind `thenUs` \ (stg_binds, new_env) ->
352 coreExprToStg new_env body `thenUs` \ stg_body ->
353 returnUs (foldr StgLet stg_body stg_binds)
357 %************************************************************************
359 \subsubsection[coreToStg-scc]{SCC expressions}
361 %************************************************************************
363 Covert core @scc@ expression directly to STG @scc@ expression.
365 coreExprToStg env (Note (SCC cc) expr)
366 = coreExprToStg env expr `thenUs` \ stg_expr ->
367 returnUs (StgSCC cc stg_expr)
371 coreExprToStg env (Note other_note expr) = coreExprToStg env expr
374 The rest are handled by coreExprStgFloat.
377 coreExprToStg env expr
378 = coreExprToStgFloat env expr `thenUs` \ (binds,stg_expr) ->
379 returnUs (mkStgBinds binds stg_expr)
382 %************************************************************************
384 \subsubsection[coreToStg-applications]{Applications}
386 %************************************************************************
389 coreExprToStgFloat env expr@(App _ _)
391 (fun,args) = collect_args expr []
393 coreArgsToStg env args `thenUs` \ (binds, stg_args) ->
395 -- Now deal with the function
396 case (fun, stg_args) of
397 (Var fun_id, _) -> -- A function Id, so do an StgApp; it's ok if
398 -- there are no arguments.
400 StgApp (stgLookup env fun_id) stg_args)
402 (non_var_fun, []) -> -- No value args, so recurse into the function
404 coreExprToStg env non_var_fun `thenUs` \e ->
407 other -> -- A non-variable applied to things; better let-bind it.
408 newStgVar (coreExprType fun) `thenUs` \ fun_id ->
409 coreExprToStg env fun `thenUs` \ (stg_fun) ->
411 fun_rhs = StgRhsClosure noCCS -- No cost centre (ToDo?)
415 SingleEntry -- Only entered once
420 StgLet (StgNonRec fun_id fun_rhs) $
421 StgApp fun_id stg_args)
424 collect_args (App fun arg) args = collect_args fun (arg:args)
425 collect_args (Note (Coerce _ _) expr) args = collect_args expr args
426 collect_args (Note InlineCall expr) args = collect_args expr args
427 collect_args fun args = (fun, args)
430 %************************************************************************
432 \subsubsection[coreToStg-con]{Constructors}
434 %************************************************************************
437 coreExprToStgFloat env expr@(Con (PrimOp (CCallOp (Right _) a b c)) args)
438 = getUniqueUs `thenUs` \ u ->
439 coreArgsToStg env args `thenUs` \ (binds, stg_atoms) ->
440 let con' = PrimOp (CCallOp (Right u) a b c) in
441 returnUs (binds, StgCon con' stg_atoms (coreExprType expr))
443 coreExprToStgFloat env expr@(Con con args)
444 = coreArgsToStg env args `thenUs` \ (binds, stg_atoms) ->
445 returnUs (binds, StgCon con stg_atoms (coreExprType expr))
448 %************************************************************************
450 \subsubsection[coreToStg-cases]{Case expressions}
452 %************************************************************************
455 coreExprToStgFloat env expr@(Case scrut bndr alts)
456 = coreExprToStgFloat env scrut `thenUs` \ (binds, scrut') ->
457 newEvaldLocalId env bndr `thenUs` \ (env', bndr') ->
458 alts_to_stg env' (findDefault alts) `thenUs` \ alts' ->
459 returnUs (binds, mkStgCase scrut' bndr' alts')
461 scrut_ty = idType bndr
462 prim_case = isUnLiftedType scrut_ty && not (isUnboxedTupleType scrut_ty)
464 alts_to_stg env (alts, deflt)
466 = default_to_stg env deflt `thenUs` \ deflt' ->
467 mapUs (prim_alt_to_stg env) alts `thenUs` \ alts' ->
468 returnUs (StgPrimAlts scrut_ty alts' deflt')
471 = default_to_stg env deflt `thenUs` \ deflt' ->
472 mapUs (alg_alt_to_stg env) alts `thenUs` \ alts' ->
473 returnUs (StgAlgAlts scrut_ty alts' deflt')
475 alg_alt_to_stg env (DataCon con, bs, rhs)
476 = coreExprToStg env rhs `thenUs` \ stg_rhs ->
477 returnUs (con, filter isId bs, [ True | b <- bs ]{-bogus use mask-}, stg_rhs)
478 -- NB the filter isId. Some of the binders may be
479 -- existential type variables, which STG doesn't care about
481 prim_alt_to_stg env (Literal lit, args, rhs)
482 = ASSERT( null args )
483 coreExprToStg env rhs `thenUs` \ stg_rhs ->
484 returnUs (lit, stg_rhs)
486 default_to_stg env Nothing
487 = returnUs StgNoDefault
489 default_to_stg env (Just rhs)
490 = coreExprToStg env rhs `thenUs` \ stg_rhs ->
491 returnUs (StgBindDefault stg_rhs)
492 -- The binder is used for prim cases and not otherwise
493 -- (hack for old code gen)
497 coreExprToStgFloat env expr
498 = coreExprToStg env expr `thenUs` \stg_expr ->
499 returnUs ([], stg_expr)
502 %************************************************************************
504 \subsection[coreToStg-misc]{Miscellaneous helping functions}
506 %************************************************************************
508 There's not anything interesting we can ASSERT about \tr{var} if it
509 isn't in the StgEnv. (WDP 94/06)
512 stgLookup :: StgEnv -> Id -> Id
513 stgLookup env var = case (lookupVarEnv env var) of
520 newStgVar :: Type -> UniqSM Id
522 = getUniqueUs `thenUs` \ uniq ->
523 returnUs (mkSysLocal SLIT("stg") uniq ty)
528 | externallyVisibleId id
532 = -- Local binder, give it a new unique Id.
533 getUniqueUs `thenUs` \ uniq ->
535 id' = setIdUnique id uniq
536 new_env = extendVarEnv env id id'
538 returnUs (new_env, id')
540 -- we overload the demandInfo field of an Id to indicate whether the Id is definitely
541 -- evaluated or not (i.e. whether it is a case binder). This can be used to eliminate
542 -- some redundant cases (c.f. dataToTag# above).
544 newEvaldLocalId env id
545 = getUniqueUs `thenUs` \ uniq ->
547 id' = setIdUnique id uniq `modifyIdInfo` setDemandInfo wwStrict
548 new_env = extendVarEnv env id id'
550 returnUs (new_env, id')
552 newLocalIds :: StgEnv -> [Id] -> UniqSM (StgEnv, [Id])
555 newLocalIds env (b:bs)
556 = newLocalId env b `thenUs` \ (env', b') ->
557 newLocalIds env' bs `thenUs` \ (env'', bs') ->
558 returnUs (env'', b':bs')
563 mkStgBinds :: [StgFloatBind] -> StgExpr -> StgExpr
564 mkStgBinds binds body = foldr mkStgBind body binds
566 mkStgBind (CaseBind bndr rhs) body
567 | isUnLiftedType bndr_ty
568 = mkStgCase rhs bndr (StgPrimAlts bndr_ty [] (StgBindDefault body))
570 = mkStgCase rhs bndr (StgAlgAlts bndr_ty [] (StgBindDefault body))
572 bndr_ty = idType bndr
574 mkStgBind (LetBind bndr rhs) body
575 | isUnboxedTupleType bndr_ty
576 = panic "mkStgBinds: unboxed tuple"
577 | isUnLiftedType bndr_ty
578 = mkStgCase rhs bndr (StgPrimAlts bndr_ty [] (StgBindDefault body))
581 = StgLet (StgNonRec bndr (exprToRhs rhs)) body
583 bndr_ty = idType bndr
585 mkStgCase (StgLet bind expr) bndr alts
586 = StgLet bind (mkStgCase expr bndr alts)
587 mkStgCase scrut bndr alts
588 = StgCase scrut bOGUS_LVs bOGUS_LVs bndr noSRT alts