[project @ 1996-12-19 09:10:02 by simonpj]
[ghc-hetmet.git] / ghc / compiler / stgSyn / CoreToStg.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 %************************************************************************
5 %*                                                                      *
6 \section[CoreToStg]{Converting core syntax to STG syntax}
7 %*                                                                      *
8 %************************************************************************
9
10 Convert a @CoreSyntax@ program to a @StgSyntax@ program.
11
12 \begin{code}
13 #include "HsVersions.h"
14
15 module CoreToStg ( topCoreBindsToStg ) where
16
17 IMP_Ubiq(){-uitous-}
18 IMPORT_1_3(Ratio(numerator,denominator))
19
20 import CoreSyn          -- input
21 import StgSyn           -- output
22
23 import Bag              ( emptyBag, unitBag, unionBags, unionManyBags, bagToList )
24 import CoreUtils        ( coreExprType )
25 import CostCentre       ( noCostCentre )
26 import Id               ( mkSysLocal, idType, isBottomingId, addIdArity,
27                           externallyVisibleId,
28                           nullIdEnv, addOneToIdEnv, lookupIdEnv, growIdEnvList,
29                           SYN_IE(IdEnv), GenId{-instance NamedThing-}
30                         )
31 import IdInfo           ( ArityInfo, exactArity )
32 import Literal          ( mkMachInt, Literal(..) )
33 import PrelVals         ( unpackCStringId, unpackCString2Id,
34                           integerZeroId, integerPlusOneId,
35                           integerPlusTwoId, integerMinusOneId
36                         )
37 import PrimOp           ( PrimOp(..) )
38 import SpecUtils        ( mkSpecialisedCon )
39 import SrcLoc           ( noSrcLoc )
40 import TyCon            ( TyCon{-instance Uniquable-} )
41 import Type             ( maybeAppDataTyCon, getAppDataTyConExpandingDicts )
42 import TysWiredIn       ( stringTy )
43 import Unique           ( integerTyConKey, ratioTyConKey, Unique{-instance Eq-} )
44 import UniqSupply       -- all of it, really
45 import Util             ( zipLazy, panic, assertPanic{-, pprTrace ToDo:rm-} )
46 --import Pretty--ToDo:rm
47 --import PprStyle--ToDo:rm
48 --import PprType  --ToDo:rm
49 --import Outputable--ToDo:rm
50 --import PprEnv--ToDo:rm
51
52 isLeakFreeType x y = False -- safe option; ToDo
53 \end{code}
54
55
56         ***************  OVERVIEW   *********************
57
58
59 The business of this pass is to convert Core to Stg.  On the way:
60
61 * We discard type lambdas and applications. In so doing we discard
62   "trivial" bindings such as
63         x = y t1 t2
64   where t1, t2 are types
65
66 * We pin correct arities on each let(rec)-bound binder, and propagate them
67   to their uses.  This is used
68         a) when emitting arity info into interface files
69         b) in the code generator, when deciding if a right-hand side
70                  is a saturated application so we can generate a VAP closure.
71   (b) is rather untidy, but the easiest compromise was to propagate arities here.
72
73 * We do *not* pin on the correct free/live var info; that's done later.
74   Instead we use bOGUS_LVS and _FVS as a placeholder.
75
76 [Quite a bit of stuff that used to be here has moved 
77  to tidyCorePgm (SimplCore.lhs) SLPJ Nov 96]
78
79
80 %************************************************************************
81 %*                                                                      *
82 \subsection[coreToStg-programs]{Converting a core program and core bindings}
83 %*                                                                      *
84 %************************************************************************
85
86 Because we're going to come across ``boring'' bindings like
87 \tr{let x = /\ tyvars -> y in ...}, we want to keep a small
88 environment, so we can just replace all occurrences of \tr{x}
89 with \tr{y}.
90
91 \begin{code}
92 type StgEnv = IdEnv StgArg
93 \end{code}
94
95 No free/live variable information is pinned on in this pass; it's added
96 later.  For this pass
97 we use @bOGUS_LVs@ and @bOGUS_FVs@ as placeholders.
98
99 \begin{code}
100 bOGUS_LVs :: StgLiveVars
101 bOGUS_LVs = panic "bOGUS_LVs" -- emptyUniqSet (used when pprTracing)
102
103 bOGUS_FVs :: [Id]
104 bOGUS_FVs = panic "bOGUS_FVs" -- [] (ditto)
105 \end{code}
106
107 \begin{code}
108 topCoreBindsToStg :: UniqSupply -- name supply
109                   -> [CoreBinding]      -- input
110                   -> [StgBinding]       -- output
111
112 topCoreBindsToStg us core_binds
113   = case (initUs us (coreBindsToStg nullIdEnv core_binds)) of
114       (_, stuff) -> stuff
115   where
116     coreBindsToStg :: StgEnv -> [CoreBinding] -> UniqSM [StgBinding]
117
118     coreBindsToStg env [] = returnUs []
119     coreBindsToStg env (b:bs)
120       = coreBindToStg  env b            `thenUs` \ (new_b, new_env) ->
121         coreBindsToStg new_env bs       `thenUs` \ new_bs ->
122         returnUs (new_b ++ new_bs)
123 \end{code}
124
125 %************************************************************************
126 %*                                                                      *
127 \subsection[coreToStg-binds]{Converting bindings}
128 %*                                                                      *
129 %************************************************************************
130
131 \begin{code}
132 coreBindToStg :: StgEnv
133               -> CoreBinding
134               -> UniqSM ([StgBinding],  -- Empty or singleton
135                          StgEnv)        -- Floats
136
137 coreBindToStg env (NonRec binder rhs)
138   = coreRhsToStg env rhs        `thenUs` \ stg_rhs ->
139     let
140         -- Binds to return if RHS is trivial
141         triv_binds | externallyVisibleId binder = [StgNonRec binder stg_rhs]    -- Retain it
142                    | otherwise                  = []                            -- Discard it
143     in
144     case stg_rhs of
145       StgRhsClosure cc bi fvs upd [] (StgApp atom [] lvs) ->
146                 -- Trivial RHS, so augment envt, and ditch the binding
147                 returnUs (triv_binds, new_env)
148            where
149                 new_env = addOneToIdEnv env binder atom
150
151       StgRhsCon cc con_id [] ->
152                 -- Trivial RHS, so augment envt, and ditch the binding
153                 returnUs (triv_binds, new_env)
154            where
155                 new_env = addOneToIdEnv env binder (StgVarArg con_id)
156
157       other ->  -- Non-trivial RHS, so don't augment envt
158                 returnUs ([StgNonRec binder_w_arity stg_rhs], new_env)
159            where
160                 binder_w_arity = binder `addIdArity` (rhsArity stg_rhs)
161                 new_env = addOneToIdEnv env binder (StgVarArg binder_w_arity)
162                 -- new_env propagates the arity
163
164 coreBindToStg env (Rec pairs)
165   = -- NB: *** WE DO NOT CHECK FOR TRIV_BINDS in REC BIND ****
166     -- (possibly ToDo)
167     let
168         (binders, rhss) = unzip pairs
169     in
170     mapUs (coreRhsToStg env) rhss `thenUs` \ stg_rhss ->
171     let 
172             binders_w_arities = [ b `addIdArity` rhsArity rhs 
173                                 | (b,rhs) <- binders `zip` stg_rhss]
174     in
175     returnUs ([StgRec (binders_w_arities `zip` stg_rhss)], env)
176
177 rhsArity (StgRhsClosure _ _ _ _ args _) = exactArity (length args)
178 rhsArity (StgRhsCon _ _ _)              = exactArity 0
179 \end{code}
180
181
182 %************************************************************************
183 %*                                                                      *
184 \subsection[coreToStg-rhss]{Converting right hand sides}
185 %*                                                                      *
186 %************************************************************************
187
188 \begin{code}
189 coreRhsToStg :: StgEnv -> CoreExpr -> UniqSM StgRhs
190
191 coreRhsToStg env core_rhs
192   = coreExprToStg env core_rhs  `thenUs` \ stg_expr ->
193
194     let stg_rhs = case stg_expr of
195                     StgLet (StgNonRec var1 rhs) (StgApp (StgVarArg var2) [] _)
196                         | var1 == var2 -> rhs
197                         -- This curious stuff is to unravel what a lambda turns into
198                         -- We have to do it this way, rather than spot a lambda in the
199                         -- incoming rhs.  Why?  Because trivial bindings might conceal
200                         -- what the rhs is actually like.
201
202                     StgCon con args _ -> StgRhsCon noCostCentre con args
203
204                     other -> StgRhsClosure noCostCentre -- No cost centre (ToDo?)
205                                            stgArgOcc    -- safe
206                                            bOGUS_FVs
207                                            Updatable    -- Be pessimistic
208                                            []
209                                            stg_expr
210     in
211     returnUs stg_rhs
212 \end{code}
213
214
215 %************************************************************************
216 %*                                                                      *
217 \subsection[coreToStg-atoms{Converting atoms}
218 %*                                                                      *
219 %************************************************************************
220
221 \begin{code}
222 coreArgsToStg :: StgEnv -> [CoreArg] -> ([Type], [StgArg])
223
224 coreArgsToStg env [] = ([], [])
225 coreArgsToStg env (a:as)
226   = case a of
227         TyArg    t -> (t:trest, vrest)
228         UsageArg u -> (trest,   vrest)
229         VarArg   v -> (trest,   stgLookup env v : vrest)
230         LitArg   l -> (trest,   StgLitArg l     : vrest)
231   where
232     (trest,vrest) = coreArgsToStg env as
233 \end{code}
234
235
236 %************************************************************************
237 %*                                                                      *
238 \subsection[coreToStg-exprs]{Converting core expressions}
239 %*                                                                      *
240 %************************************************************************
241
242 \begin{code}
243 coreExprToStg :: StgEnv -> CoreExpr -> UniqSM StgExpr
244
245 coreExprToStg env (Lit lit)
246   = returnUs (StgApp (StgLitArg lit) [] bOGUS_LVs)
247
248 coreExprToStg env (Var var)
249   = returnUs (StgApp (stgLookup env var) [] bOGUS_LVs)
250
251 coreExprToStg env (Con con args)
252   = let
253         (types, stg_atoms) = coreArgsToStg env args
254         spec_con = mkSpecialisedCon con types
255     in
256     returnUs (StgCon spec_con stg_atoms bOGUS_LVs)
257
258 coreExprToStg env (Prim op args)
259   = let
260         (types, stg_atoms) = coreArgsToStg env args
261     in
262     returnUs (StgPrim op stg_atoms bOGUS_LVs)
263 \end{code}
264
265 %************************************************************************
266 %*                                                                      *
267 \subsubsection[coreToStg-lambdas]{Lambda abstractions}
268 %*                                                                      *
269 %************************************************************************
270
271 \begin{code}
272 coreExprToStg env expr@(Lam _ _)
273   = let
274         (_,_, binders, body) = collectBinders expr
275     in
276     coreExprToStg env body              `thenUs` \ stg_body ->
277
278     if null binders then -- it was all type/usage binders; tossed
279         returnUs stg_body
280     else
281         newStgVar (coreExprType expr)   `thenUs` \ var ->
282         returnUs
283           (StgLet (StgNonRec (var `addIdArity` exactArity (length binders))
284                                   (StgRhsClosure noCostCentre
285                                   stgArgOcc
286                                   bOGUS_FVs
287                                   ReEntrant     -- binders is non-empty
288                                   binders
289                                   stg_body))
290            (StgApp (StgVarArg var) [] bOGUS_LVs))
291 \end{code}
292
293 %************************************************************************
294 %*                                                                      *
295 \subsubsection[coreToStg-applications]{Applications}
296 %*                                                                      *
297 %************************************************************************
298
299 \begin{code}
300 coreExprToStg env expr@(App _ _)
301   = let
302         (fun,args)    = collect_args expr []
303         (_, stg_args) = coreArgsToStg env args
304     in
305         -- Now deal with the function
306     case (fun, args) of
307       (Var fun_id, _) ->        -- A function Id, so do an StgApp; it's ok if
308                                 -- there are no arguments.
309                             returnUs (StgApp (stgLookup env fun_id) stg_args bOGUS_LVs)
310
311       (non_var_fun, []) ->      -- No value args, so recurse into the function
312                             coreExprToStg env non_var_fun
313
314       other ->  -- A non-variable applied to things; better let-bind it.
315                 newStgVar (coreExprType fun)    `thenUs` \ fun_id ->
316                 coreExprToStg env fun           `thenUs` \ (stg_fun) ->
317                 let
318                    fun_rhs = StgRhsClosure noCostCentre -- No cost centre (ToDo?)
319                                            stgArgOcc
320                                            bOGUS_FVs
321                                            SingleEntry  -- Only entered once
322                                            []
323                                            stg_fun
324                 in
325                 returnUs (StgLet (StgNonRec fun_id fun_rhs)
326                                  (StgApp (StgVarArg fun_id) stg_args bOGUS_LVs))
327   where
328         -- Collect arguments, discarding type/usage applications
329     collect_args (App e   (TyArg _))    args = collect_args e   args
330     collect_args (App e   (UsageArg _)) args = collect_args e   args
331     collect_args (App fun arg)          args = collect_args fun (arg:args)
332     collect_args fun                    args = (fun, args)
333 \end{code}
334
335 %************************************************************************
336 %*                                                                      *
337 \subsubsection[coreToStg-cases]{Case expressions}
338 %*                                                                      *
339 %************************************************************************
340
341 \begin{code}
342 coreExprToStg env (Case discrim alts)
343   = coreExprToStg env discrim           `thenUs` \ stg_discrim ->
344     alts_to_stg discrim alts            `thenUs` \ stg_alts ->
345     getUnique                           `thenUs` \ uniq ->
346     returnUs (
347         StgCase stg_discrim
348                 bOGUS_LVs
349                 bOGUS_LVs
350                 uniq
351                 stg_alts
352     )
353   where
354     discrim_ty              = coreExprType discrim
355     (_, discrim_ty_args, _) = getAppDataTyConExpandingDicts discrim_ty
356
357     alts_to_stg discrim (AlgAlts alts deflt)
358       = default_to_stg discrim deflt            `thenUs` \ stg_deflt ->
359         mapUs boxed_alt_to_stg alts             `thenUs` \ stg_alts  ->
360         returnUs (StgAlgAlts discrim_ty stg_alts stg_deflt)
361       where
362         boxed_alt_to_stg (con, bs, rhs)
363           = coreExprToStg env rhs    `thenUs` \ stg_rhs ->
364             returnUs (spec_con, bs, [ True | b <- bs ]{-bogus use mask-}, stg_rhs)
365           where
366             spec_con = mkSpecialisedCon con discrim_ty_args
367
368     alts_to_stg discrim (PrimAlts alts deflt)
369       = default_to_stg discrim deflt            `thenUs` \ stg_deflt ->
370         mapUs unboxed_alt_to_stg alts           `thenUs` \ stg_alts  ->
371         returnUs (StgPrimAlts discrim_ty stg_alts stg_deflt)
372       where
373         unboxed_alt_to_stg (lit, rhs)
374           = coreExprToStg env rhs    `thenUs` \ stg_rhs ->
375             returnUs (lit, stg_rhs)
376
377     default_to_stg discrim NoDefault
378       = returnUs StgNoDefault
379
380     default_to_stg discrim (BindDefault binder rhs)
381       = coreExprToStg env rhs    `thenUs` \ stg_rhs ->
382         returnUs (StgBindDefault binder True{-used? no it is lying-} stg_rhs)
383 \end{code}
384
385 %************************************************************************
386 %*                                                                      *
387 \subsubsection[coreToStg-let(rec)]{Let and letrec expressions}
388 %*                                                                      *
389 %************************************************************************
390
391 \begin{code}
392 coreExprToStg env (Let bind body)
393   = coreBindToStg env     bind   `thenUs` \ (stg_binds, new_env) ->
394     coreExprToStg new_env body   `thenUs` \ stg_body ->
395     returnUs (mkStgLets stg_binds stg_body)
396 \end{code}
397
398
399 %************************************************************************
400 %*                                                                      *
401 \subsubsection[coreToStg-scc]{SCC expressions}
402 %*                                                                      *
403 %************************************************************************
404
405 Covert core @scc@ expression directly to STG @scc@ expression.
406 \begin{code}
407 coreExprToStg env (SCC cc expr)
408   = coreExprToStg env expr   `thenUs` \ stg_expr ->
409     returnUs (StgSCC (coreExprType expr) cc stg_expr)
410 \end{code}
411
412 \begin{code}
413 coreExprToStg env (Coerce c ty expr) = coreExprToStg env expr
414 \end{code}
415
416
417 %************************************************************************
418 %*                                                                      *
419 \subsection[coreToStg-misc]{Miscellaneous helping functions}
420 %*                                                                      *
421 %************************************************************************
422
423 There's not anything interesting we can ASSERT about \tr{var} if it
424 isn't in the StgEnv. (WDP 94/06)
425
426 \begin{code}
427 stgLookup :: StgEnv -> Id -> StgArg
428 stgLookup env var = case (lookupIdEnv env var) of
429                       Nothing   -> StgVarArg var
430                       Just atom -> atom
431 \end{code}
432
433 Invent a fresh @Id@:
434 \begin{code}
435 newStgVar :: Type -> UniqSM Id
436 newStgVar ty
437  = getUnique                    `thenUs` \ uniq ->
438    returnUs (mkSysLocal SLIT("stg") uniq ty noSrcLoc)
439 \end{code}
440
441 \begin{code}
442 mkStgLets ::   [StgBinding]
443             -> StgExpr  -- body of let
444             -> StgExpr
445
446 mkStgLets binds body = foldr StgLet body binds
447 \end{code}