Deal correctly with infix type constructors in GADT decls
[ghc-hetmet.git] / compiler / coreSyn / CorePrep.lhs
1 %
2 % (c) The University of Glasgow, 1994-2000
3 %
4 \section{Core pass to saturate constructors and PrimOps}
5
6 \begin{code}
7 module CorePrep (
8       corePrepPgm, corePrepExpr
9   ) where
10
11 #include "HsVersions.h"
12
13 import CoreUtils( exprType, exprIsHNF, etaExpand, exprArity, exprOkForSpeculation )
14 import CoreFVs  ( exprFreeVars )
15 import CoreLint ( endPass )
16 import CoreSyn
17 import Type     ( Type, applyTy, splitFunTy_maybe, 
18                   isUnLiftedType, isUnboxedTupleType, seqType )
19 import TyCon    ( TyCon, tyConDataCons )
20 import NewDemand  ( Demand, isStrictDmd, lazyDmd, StrictSig(..), DmdType(..) )
21 import Var      ( Var, Id, setVarUnique )
22 import VarSet
23 import VarEnv
24 import Id       ( mkSysLocal, idType, idNewDemandInfo, idArity, setIdUnfolding, setIdType,
25                   isFCallId, isGlobalId, 
26                   isLocalId, hasNoBinding, idNewStrictness, 
27                   isPrimOpId_maybe
28                 )
29 import DataCon    ( isVanillaDataCon, dataConWorkId )
30 import PrimOp     ( PrimOp( DataToTagOp ) )
31 import BasicTypes ( TopLevelFlag(..), isTopLevel, isNotTopLevel,
32                     RecFlag(..), isNonRec
33                   )
34 import UniqSupply
35 import Maybes
36 import OrdList
37 import ErrUtils
38 import DynFlags
39 import Util       ( listLengthCmp )
40 import Outputable
41 \end{code}
42
43 -- ---------------------------------------------------------------------------
44 -- Overview
45 -- ---------------------------------------------------------------------------
46
47 The goal of this pass is to prepare for code generation.
48
49 1.  Saturate constructor and primop applications.
50
51 2.  Convert to A-normal form:
52
53     * Use case for strict arguments:
54         f E ==> case E of x -> f x
55         (where f is strict)
56
57     * Use let for non-trivial lazy arguments
58         f E ==> let x = E in f x
59         (were f is lazy and x is non-trivial)
60
61 3.  Similarly, convert any unboxed lets into cases.
62     [I'm experimenting with leaving 'ok-for-speculation' 
63      rhss in let-form right up to this point.]
64
65 4.  Ensure that lambdas only occur as the RHS of a binding
66     (The code generator can't deal with anything else.)
67
68 5.  [Not any more; nuked Jun 2002] Do the seq/par munging.
69
70 6.  Clone all local Ids.
71     This means that all such Ids are unique, rather than the 
72     weaker guarantee of no clashes which the simplifier provides.
73     And that is what the code generator needs.
74
75     We don't clone TyVars. The code gen doesn't need that, 
76     and doing so would be tiresome because then we'd need
77     to substitute in types.
78
79
80 7.  Give each dynamic CCall occurrence a fresh unique; this is
81     rather like the cloning step above.
82
83 8.  Inject bindings for the "implicit" Ids:
84         * Constructor wrappers
85         * Constructor workers
86         * Record selectors
87     We want curried definitions for all of these in case they
88     aren't inlined by some caller.
89         
90 This is all done modulo type applications and abstractions, so that
91 when type erasure is done for conversion to STG, we don't end up with
92 any trivial or useless bindings.
93
94   
95
96 -- -----------------------------------------------------------------------------
97 -- Top level stuff
98 -- -----------------------------------------------------------------------------
99
100 \begin{code}
101 corePrepPgm :: DynFlags -> [CoreBind] -> [TyCon] -> IO [CoreBind]
102 corePrepPgm dflags binds data_tycons
103   = do  showPass dflags "CorePrep"
104         us <- mkSplitUniqSupply 's'
105
106         let implicit_binds = mkDataConWorkers data_tycons
107                 -- NB: we must feed mkImplicitBinds through corePrep too
108                 -- so that they are suitably cloned and eta-expanded
109
110             binds_out = initUs_ us (
111                           corePrepTopBinds binds        `thenUs` \ floats1 ->
112                           corePrepTopBinds implicit_binds       `thenUs` \ floats2 ->
113                           returnUs (deFloatTop (floats1 `appendFloats` floats2))
114                         )
115             
116         endPass dflags "CorePrep" Opt_D_dump_prep binds_out
117         return binds_out
118
119 corePrepExpr :: DynFlags -> CoreExpr -> IO CoreExpr
120 corePrepExpr dflags expr
121   = do showPass dflags "CorePrep"
122        us <- mkSplitUniqSupply 's'
123        let new_expr = initUs_ us (corePrepAnExpr emptyCorePrepEnv expr)
124        dumpIfSet_dyn dflags Opt_D_dump_prep "CorePrep" 
125                      (ppr new_expr)
126        return new_expr
127 \end{code}
128
129 -- -----------------------------------------------------------------------------
130 -- Implicit bindings
131 -- -----------------------------------------------------------------------------
132
133 Create any necessary "implicit" bindings for data con workers.  We
134 create the rather strange (non-recursive!) binding
135
136         $wC = \x y -> $wC x y
137
138 i.e. a curried constructor that allocates.  This means that we can
139 treat the worker for a constructor like any other function in the rest
140 of the compiler.  The point here is that CoreToStg will generate a
141 StgConApp for the RHS, rather than a call to the worker (which would
142 give a loop).  As Lennart says: the ice is thin here, but it works.
143
144 Hmm.  Should we create bindings for dictionary constructors?  They are
145 always fully applied, and the bindings are just there to support
146 partial applications. But it's easier to let them through.
147
148 \begin{code}
149 mkDataConWorkers data_tycons
150   = [ NonRec id (Var id)        -- The ice is thin here, but it works
151     | tycon <- data_tycons,     -- CorePrep will eta-expand it
152       data_con <- tyConDataCons tycon,
153       let id = dataConWorkId data_con ]
154 \end{code}
155         
156
157 \begin{code}
158 -- ---------------------------------------------------------------------------
159 -- Dealing with bindings
160 -- ---------------------------------------------------------------------------
161
162 data FloatingBind = FloatLet CoreBind
163                   | FloatCase Id CoreExpr Bool
164                         -- The bool indicates "ok-for-speculation"
165
166 data Floats = Floats OkToSpec (OrdList FloatingBind)
167
168 -- Can we float these binds out of the rhs of a let?  We cache this decision
169 -- to avoid having to recompute it in a non-linear way when there are
170 -- deeply nested lets.
171 data OkToSpec
172    = NotOkToSpec        -- definitely not
173    | OkToSpec           -- yes
174    | IfUnboxedOk        -- only if floating an unboxed binding is ok
175
176 emptyFloats :: Floats
177 emptyFloats = Floats OkToSpec nilOL
178
179 addFloat :: Floats -> FloatingBind -> Floats
180 addFloat (Floats ok_to_spec floats) new_float
181   = Floats (combine ok_to_spec (check new_float)) (floats `snocOL` new_float)
182   where
183     check (FloatLet _)                = OkToSpec
184     check (FloatCase _ _ ok_for_spec) 
185         | ok_for_spec  =  IfUnboxedOk
186         | otherwise    =  NotOkToSpec
187         -- The ok-for-speculation flag says that it's safe to
188         -- float this Case out of a let, and thereby do it more eagerly
189         -- We need the top-level flag because it's never ok to float
190         -- an unboxed binding to the top level
191
192 unitFloat :: FloatingBind -> Floats
193 unitFloat = addFloat emptyFloats
194
195 appendFloats :: Floats -> Floats -> Floats
196 appendFloats (Floats spec1 floats1) (Floats spec2 floats2)
197   = Floats (combine spec1 spec2) (floats1 `appOL` floats2)
198
199 concatFloats :: [Floats] -> Floats
200 concatFloats = foldr appendFloats emptyFloats
201
202 combine NotOkToSpec _ = NotOkToSpec
203 combine _ NotOkToSpec = NotOkToSpec
204 combine IfUnboxedOk _ = IfUnboxedOk
205 combine _ IfUnboxedOk = IfUnboxedOk
206 combine _ _           = OkToSpec
207     
208 instance Outputable FloatingBind where
209   ppr (FloatLet bind)        = text "FloatLet" <+> ppr bind
210   ppr (FloatCase b rhs spec) = text "FloatCase" <+> ppr b <+> ppr spec <+> equals <+> ppr rhs
211
212 deFloatTop :: Floats -> [CoreBind]
213 -- For top level only; we don't expect any FloatCases
214 deFloatTop (Floats _ floats)
215   = foldrOL get [] floats
216   where
217     get (FloatLet b) bs = b:bs
218     get b            bs = pprPanic "corePrepPgm" (ppr b)
219
220 allLazy :: TopLevelFlag -> RecFlag -> Floats -> Bool
221 allLazy top_lvl is_rec (Floats ok_to_spec _)
222   = case ok_to_spec of
223         OkToSpec    -> True
224         NotOkToSpec -> False
225         IfUnboxedOk -> isNotTopLevel top_lvl && isNonRec is_rec
226
227 -- ---------------------------------------------------------------------------
228 --                      Bindings
229 -- ---------------------------------------------------------------------------
230
231 corePrepTopBinds :: [CoreBind] -> UniqSM Floats
232 corePrepTopBinds binds 
233   = go emptyCorePrepEnv binds
234   where
235     go env []             = returnUs emptyFloats
236     go env (bind : binds) = corePrepTopBind env bind    `thenUs` \ (env', bind') ->
237                             go env' binds               `thenUs` \ binds' ->
238                             returnUs (bind' `appendFloats` binds')
239
240 -- NB: we do need to float out of top-level bindings
241 -- Consider     x = length [True,False]
242 -- We want to get
243 --              s1 = False : []
244 --              s2 = True  : s1
245 --              x  = length s2
246
247 -- We return a *list* of bindings, because we may start with
248 --      x* = f (g y)
249 -- where x is demanded, in which case we want to finish with
250 --      a = g y
251 --      x* = f a
252 -- And then x will actually end up case-bound
253 --
254 -- What happens to the CafInfo on the floated bindings?  By
255 -- default, all the CafInfos will be set to MayHaveCafRefs,
256 -- which is safe.
257 --
258 -- This might be pessimistic, because eg. s1 & s2
259 -- might not refer to any CAFs and the GC will end up doing
260 -- more traversal than is necessary, but it's still better
261 -- than not floating the bindings at all, because then
262 -- the GC would have to traverse the structure in the heap
263 -- instead.  Given this, we decided not to try to get
264 -- the CafInfo on the floated bindings correct, because
265 -- it looks difficult.
266
267 --------------------------------
268 corePrepTopBind :: CorePrepEnv -> CoreBind -> UniqSM (CorePrepEnv, Floats)
269 corePrepTopBind env (NonRec bndr rhs) 
270   = cloneBndr env bndr                                  `thenUs` \ (env', bndr') ->
271     corePrepRhs TopLevel NonRecursive env (bndr, rhs)   `thenUs` \ (floats, rhs') -> 
272     returnUs (env', addFloat floats (FloatLet (NonRec bndr' rhs')))
273
274 corePrepTopBind env (Rec pairs) = corePrepRecPairs TopLevel env pairs
275
276 --------------------------------
277 corePrepBind ::  CorePrepEnv -> CoreBind -> UniqSM (CorePrepEnv, Floats)
278         -- This one is used for *local* bindings
279 corePrepBind env (NonRec bndr rhs)
280   = etaExpandRhs bndr rhs                               `thenUs` \ rhs1 ->
281     corePrepExprFloat env rhs1                          `thenUs` \ (floats, rhs2) ->
282     cloneBndr env bndr                                  `thenUs` \ (_, bndr') ->
283     mkLocalNonRec bndr' (bdrDem bndr) floats rhs2       `thenUs` \ (floats', bndr'') ->
284         -- We want bndr'' in the envt, because it records
285         -- the evaluated-ness of the binder
286     returnUs (extendCorePrepEnv env bndr bndr'', floats')
287
288 corePrepBind env (Rec pairs) = corePrepRecPairs NotTopLevel env pairs
289
290 --------------------------------
291 corePrepRecPairs :: TopLevelFlag -> CorePrepEnv
292                  -> [(Id,CoreExpr)]     -- Recursive bindings
293                  -> UniqSM (CorePrepEnv, Floats)
294 -- Used for all recursive bindings, top level and otherwise
295 corePrepRecPairs lvl env pairs
296   = cloneBndrs env (map fst pairs)                              `thenUs` \ (env', bndrs') ->
297     mapAndUnzipUs (corePrepRhs lvl Recursive env') pairs        `thenUs` \ (floats_s, rhss') ->
298     returnUs (env', unitFloat (FloatLet (Rec (flatten (concatFloats floats_s) bndrs' rhss'))))
299   where
300         -- Flatten all the floats, and the currrent
301         -- group into a single giant Rec
302     flatten (Floats _ floats) bndrs rhss = foldrOL get (bndrs `zip` rhss) floats
303
304     get (FloatLet (NonRec b r)) prs2 = (b,r) : prs2
305     get (FloatLet (Rec prs1))   prs2 = prs1 ++ prs2
306     get b                       prs2 = pprPanic "corePrepRecPairs" (ppr b)
307
308 --------------------------------
309 corePrepRhs :: TopLevelFlag -> RecFlag
310             -> CorePrepEnv -> (Id, CoreExpr)
311             -> UniqSM (Floats, CoreExpr)
312 -- Used for top-level bindings, and local recursive bindings
313 corePrepRhs top_lvl is_rec env (bndr, rhs)
314   = etaExpandRhs bndr rhs       `thenUs` \ rhs' ->
315     corePrepExprFloat env rhs'  `thenUs` \ floats_w_rhs ->
316     floatRhs top_lvl is_rec bndr floats_w_rhs
317
318
319 -- ---------------------------------------------------------------------------
320 -- Making arguments atomic (function args & constructor args)
321 -- ---------------------------------------------------------------------------
322
323 -- This is where we arrange that a non-trivial argument is let-bound
324 corePrepArg :: CorePrepEnv -> CoreArg -> RhsDemand
325            -> UniqSM (Floats, CoreArg)
326 corePrepArg env arg dem
327   = corePrepExprFloat env arg           `thenUs` \ (floats, arg') ->
328     if exprIsTrivial arg'
329     then returnUs (floats, arg')
330     else newVar (exprType arg')                 `thenUs` \ v ->
331          mkLocalNonRec v dem floats arg'        `thenUs` \ (floats', v') -> 
332          returnUs (floats', Var v')
333
334 -- version that doesn't consider an scc annotation to be trivial.
335 exprIsTrivial (Var v)                  = True
336 exprIsTrivial (Type _)                 = True
337 exprIsTrivial (Lit lit)                = True
338 exprIsTrivial (App e arg)              = isTypeArg arg && exprIsTrivial e
339 exprIsTrivial (Note (SCC _) e)         = False
340 exprIsTrivial (Note _ e)               = exprIsTrivial e
341 exprIsTrivial (Lam b body) | isTyVar b = exprIsTrivial body
342 exprIsTrivial other                    = False
343
344 -- ---------------------------------------------------------------------------
345 -- Dealing with expressions
346 -- ---------------------------------------------------------------------------
347
348 corePrepAnExpr :: CorePrepEnv -> CoreExpr -> UniqSM CoreExpr
349 corePrepAnExpr env expr
350   = corePrepExprFloat env expr          `thenUs` \ (floats, expr) ->
351     mkBinds floats expr
352
353
354 corePrepExprFloat :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CoreExpr)
355 -- If
356 --      e  ===>  (bs, e')
357 -- then 
358 --      e = let bs in e'        (semantically, that is!)
359 --
360 -- For example
361 --      f (g x)   ===>   ([v = g x], f v)
362
363 corePrepExprFloat env (Var v)
364   = fiddleCCall v                               `thenUs` \ v1 ->
365     let 
366         v2 = lookupCorePrepEnv env v1
367     in
368     maybeSaturate v2 (Var v2) 0 emptyFloats (idType v2)
369
370 corePrepExprFloat env expr@(Type _)
371   = returnUs (emptyFloats, expr)
372
373 corePrepExprFloat env expr@(Lit lit)
374   = returnUs (emptyFloats, expr)
375
376 corePrepExprFloat env (Let bind body)
377   = corePrepBind env bind               `thenUs` \ (env', new_binds) ->
378     corePrepExprFloat env' body         `thenUs` \ (floats, new_body) ->
379     returnUs (new_binds `appendFloats` floats, new_body)
380
381 corePrepExprFloat env (Note n@(SCC _) expr)
382   = corePrepAnExpr env expr             `thenUs` \ expr1 ->
383     deLamFloat expr1                    `thenUs` \ (floats, expr2) ->
384     returnUs (floats, Note n expr2)
385
386 corePrepExprFloat env (Note other_note expr)
387   = corePrepExprFloat env expr          `thenUs` \ (floats, expr') ->
388     returnUs (floats, Note other_note expr')
389
390 corePrepExprFloat env expr@(Lam _ _)
391   = cloneBndrs env bndrs                `thenUs` \ (env', bndrs') ->
392     corePrepAnExpr env' body            `thenUs` \ body' ->
393     returnUs (emptyFloats, mkLams bndrs' body')
394   where
395     (bndrs,body) = collectBinders expr
396
397 corePrepExprFloat env (Case scrut bndr ty alts)
398   = corePrepExprFloat env scrut         `thenUs` \ (floats1, scrut1) ->
399     deLamFloat scrut1                   `thenUs` \ (floats2, scrut2) ->
400     let
401         bndr1 = bndr `setIdUnfolding` evaldUnfolding
402         -- Record that the case binder is evaluated in the alternatives
403     in
404     cloneBndr env bndr1                 `thenUs` \ (env', bndr2) ->
405     mapUs (sat_alt env') alts           `thenUs` \ alts' ->
406     returnUs (floats1 `appendFloats` floats2 , Case scrut2 bndr2 ty alts')
407   where
408     sat_alt env (con, bs, rhs)
409           = let 
410                 env1 = setGadt env con
411             in
412             cloneBndrs env1 bs          `thenUs` \ (env2, bs') ->
413             corePrepAnExpr env2 rhs     `thenUs` \ rhs1 ->
414             deLam rhs1                  `thenUs` \ rhs2 ->
415             returnUs (con, bs', rhs2)
416
417 corePrepExprFloat env expr@(App _ _)
418   = collect_args expr 0  `thenUs` \ (app, (head,depth), ty, floats, ss) ->
419     ASSERT(null ss)     -- make sure we used all the strictness info
420
421         -- Now deal with the function
422     case head of
423       Var fn_id -> maybeSaturate fn_id app depth floats ty
424       _other    -> returnUs (floats, app)
425
426   where
427
428     -- Deconstruct and rebuild the application, floating any non-atomic
429     -- arguments to the outside.  We collect the type of the expression,
430     -- the head of the application, and the number of actual value arguments,
431     -- all of which are used to possibly saturate this application if it
432     -- has a constructor or primop at the head.
433
434     collect_args
435         :: CoreExpr
436         -> Int                            -- current app depth
437         -> UniqSM (CoreExpr,              -- the rebuilt expression
438                    (CoreExpr,Int),        -- the head of the application,
439                                           -- and no. of args it was applied to
440                    Type,                  -- type of the whole expr
441                    Floats,                -- any floats we pulled out
442                    [Demand])              -- remaining argument demands
443
444     collect_args (App fun arg@(Type arg_ty)) depth
445         = collect_args fun depth   `thenUs` \ (fun',hd,fun_ty,floats,ss) ->
446           returnUs (App fun' arg, hd, applyTy fun_ty arg_ty, floats, ss)
447
448     collect_args (App fun arg) depth
449         = collect_args fun (depth+1)   `thenUs` \ (fun',hd,fun_ty,floats,ss) ->
450           let
451               (ss1, ss_rest)   = case ss of
452                                    (ss1:ss_rest) -> (ss1,     ss_rest)
453                                    []            -> (lazyDmd, [])
454               (arg_ty, res_ty) = expectJust "corePrepExprFloat:collect_args" $
455                                  splitFunTy_maybe fun_ty
456           in
457           corePrepArg env arg (mkDemTy ss1 arg_ty)      `thenUs` \ (fs, arg') ->
458           returnUs (App fun' arg', hd, res_ty, fs `appendFloats` floats, ss_rest)
459
460     collect_args (Var v) depth
461         = fiddleCCall v `thenUs` \ v1 ->
462           let 
463                 v2 = lookupCorePrepEnv env v1
464           in
465           returnUs (Var v2, (Var v2, depth), idType v2, emptyFloats, stricts)
466         where
467           stricts = case idNewStrictness v of
468                         StrictSig (DmdType _ demands _)
469                             | listLengthCmp demands depth /= GT -> demands
470                                     -- length demands <= depth
471                             | otherwise                         -> []
472                 -- If depth < length demands, then we have too few args to 
473                 -- satisfy strictness  info so we have to  ignore all the 
474                 -- strictness info, e.g. + (error "urk")
475                 -- Here, we can't evaluate the arg strictly, because this 
476                 -- partial application might be seq'd
477
478
479     collect_args (Note (Coerce ty1 ty2) fun) depth
480         = collect_args fun depth  `thenUs` \ (fun', hd, fun_ty, floats, ss) ->
481           returnUs (Note (Coerce ty1 ty2) fun', hd, ty1, floats, ss)
482
483     collect_args (Note note fun) depth
484         | ignore_note note      -- Drop these notes altogether
485                                 -- They aren't used by the code generator
486         = collect_args fun depth   `thenUs` \ (fun', hd, fun_ty, floats, ss) ->
487           returnUs (fun', hd, fun_ty, floats, ss)
488
489         -- N-variable fun, better let-bind it
490         -- ToDo: perhaps we can case-bind rather than let-bind this closure,
491         -- since it is sure to be evaluated.
492     collect_args fun depth
493         = corePrepExprFloat env fun                     `thenUs` \ (fun_floats, fun') ->
494           newVar ty                                     `thenUs` \ fn_id ->
495           mkLocalNonRec fn_id onceDem fun_floats fun'   `thenUs` \ (floats, fn_id') ->
496           returnUs (Var fn_id', (Var fn_id', depth), ty, floats, [])
497         where
498           ty = exprType fun
499
500     ignore_note (CoreNote _) = True 
501     ignore_note InlineMe     = True
502     ignore_note _other       = False
503         -- We don't ignore SCCs, since they require some code generation
504
505 ------------------------------------------------------------------------------
506 -- Building the saturated syntax
507 -- ---------------------------------------------------------------------------
508
509 -- maybeSaturate deals with saturating primops and constructors
510 -- The type is the type of the entire application
511 maybeSaturate :: Id -> CoreExpr -> Int -> Floats -> Type -> UniqSM (Floats, CoreExpr)
512 maybeSaturate fn expr n_args floats ty
513   | Just DataToTagOp <- isPrimOpId_maybe fn     -- DataToTag must have an evaluated arg
514                                                 -- A gruesome special case
515   = saturate_it         `thenUs` \ sat_expr ->
516
517         -- OK, now ensure that the arg is evaluated.
518         -- But (sigh) take into account the lambdas we've now introduced
519     let 
520         (eta_bndrs, eta_body) = collectBinders sat_expr
521     in
522     eval_data2tag_arg eta_body  `thenUs` \ (eta_floats, eta_body') -> 
523     if null eta_bndrs then
524         returnUs (floats `appendFloats` eta_floats, eta_body')
525     else
526         mkBinds eta_floats eta_body'            `thenUs` \ eta_body'' ->
527         returnUs (floats, mkLams eta_bndrs eta_body'')
528
529   | hasNoBinding fn = saturate_it       `thenUs` \ sat_expr ->
530                       returnUs (floats, sat_expr)
531
532   | otherwise       = returnUs (floats, expr)
533
534   where
535     fn_arity     = idArity fn
536     excess_arity = fn_arity - n_args
537
538     saturate_it :: UniqSM CoreExpr
539     saturate_it | excess_arity == 0 = returnUs expr
540                 | otherwise         = getUniquesUs              `thenUs` \ us ->
541                                       returnUs (etaExpand excess_arity us expr ty)
542
543         -- Ensure that the argument of DataToTagOp is evaluated
544     eval_data2tag_arg :: CoreExpr -> UniqSM (Floats, CoreExpr)
545     eval_data2tag_arg app@(fun `App` arg)
546         | exprIsHNF arg         -- Includes nullary constructors
547         = returnUs (emptyFloats, app)   -- The arg is evaluated
548         | otherwise                     -- Arg not evaluated, so evaluate it
549         = newVar (exprType arg)         `thenUs` \ arg_id ->
550           let 
551              arg_id1 = setIdUnfolding arg_id evaldUnfolding
552           in
553           returnUs (unitFloat (FloatCase arg_id1 arg False ),
554                     fun `App` Var arg_id1)
555
556     eval_data2tag_arg (Note note app)   -- Scc notes can appear
557         = eval_data2tag_arg app         `thenUs` \ (floats, app') ->
558           returnUs (floats, Note note app')
559
560     eval_data2tag_arg other     -- Should not happen
561         = pprPanic "eval_data2tag" (ppr other)
562
563
564 -- ---------------------------------------------------------------------------
565 -- Precipitating the floating bindings
566 -- ---------------------------------------------------------------------------
567
568 floatRhs :: TopLevelFlag -> RecFlag
569          -> Id
570          -> (Floats, CoreExpr)  -- Rhs: let binds in body
571          -> UniqSM (Floats,     -- Floats out of this bind
572                     CoreExpr)   -- Final Rhs
573
574 floatRhs top_lvl is_rec bndr (floats, rhs)
575   | isTopLevel top_lvl || exprIsHNF rhs,        -- Float to expose value or 
576     allLazy top_lvl is_rec floats               -- at top level
577   =     -- Why the test for allLazy? 
578         --      v = f (x `divInt#` y)
579         -- we don't want to float the case, even if f has arity 2,
580         -- because floating the case would make it evaluated too early
581     returnUs (floats, rhs)
582     
583   | otherwise
584         -- Don't float; the RHS isn't a value
585   = mkBinds floats rhs          `thenUs` \ rhs' ->
586     returnUs (emptyFloats, rhs')
587
588 -- mkLocalNonRec is used only for *nested*, *non-recursive* bindings
589 mkLocalNonRec :: Id  -> RhsDemand       -- Lhs: id with demand
590               -> Floats -> CoreExpr     -- Rhs: let binds in body
591               -> UniqSM (Floats, Id)    -- The new Id may have an evaldUnfolding, 
592                                         -- to record that it's been evaluated
593
594 mkLocalNonRec bndr dem floats rhs
595   | isUnLiftedType (idType bndr)
596         -- If this is an unlifted binding, we always make a case for it.
597   = ASSERT( not (isUnboxedTupleType (idType bndr)) )
598     let
599         float = FloatCase bndr rhs (exprOkForSpeculation rhs)
600     in
601     returnUs (addFloat floats float, evald_bndr)
602
603   | isStrict dem 
604         -- It's a strict let so we definitely float all the bindings
605  = let          -- Don't make a case for a value binding,
606                 -- even if it's strict.  Otherwise we get
607                 --      case (\x -> e) of ...!
608         float | exprIsHNF rhs = FloatLet (NonRec bndr rhs)
609               | otherwise       = FloatCase bndr rhs (exprOkForSpeculation rhs)
610     in
611     returnUs (addFloat floats float, evald_bndr)
612
613   | otherwise
614   = floatRhs NotTopLevel NonRecursive bndr (floats, rhs)        `thenUs` \ (floats', rhs') ->
615     returnUs (addFloat floats' (FloatLet (NonRec bndr rhs')),
616               if exprIsHNF rhs' then evald_bndr else bndr)
617
618   where
619     evald_bndr = bndr `setIdUnfolding` evaldUnfolding
620         -- Record if the binder is evaluated
621
622
623 mkBinds :: Floats -> CoreExpr -> UniqSM CoreExpr
624 mkBinds (Floats _ binds) body 
625   | isNilOL binds = returnUs body
626   | otherwise     = deLam body          `thenUs` \ body' ->
627                         -- Lambdas are not allowed as the body of a 'let'
628                     returnUs (foldrOL mk_bind body' binds)
629   where
630     mk_bind (FloatCase bndr rhs _) body = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
631     mk_bind (FloatLet bind)        body = Let bind body
632
633 etaExpandRhs bndr rhs
634   =     -- Eta expand to match the arity claimed by the binder
635         -- Remember, after CorePrep we must not change arity
636         --
637         -- Eta expansion might not have happened already, 
638         -- because it is done by the simplifier only when 
639         -- there at least one lambda already.
640         -- 
641         -- NB1:we could refrain when the RHS is trivial (which can happen
642         --     for exported things).  This would reduce the amount of code
643         --     generated (a little) and make things a little words for
644         --     code compiled without -O.  The case in point is data constructor
645         --     wrappers.
646         --
647         -- NB2: we have to be careful that the result of etaExpand doesn't
648         --    invalidate any of the assumptions that CorePrep is attempting
649         --    to establish.  One possible cause is eta expanding inside of
650         --    an SCC note - we're now careful in etaExpand to make sure the
651         --    SCC is pushed inside any new lambdas that are generated.
652         --
653         -- NB3: It's important to do eta expansion, and *then* ANF-ising
654         --              f = /\a -> g (h 3)      -- h has arity 2
655         -- If we ANF first we get
656         --              f = /\a -> let s = h 3 in g s
657         -- and now eta expansion gives
658         --              f = /\a -> \ y -> (let s = h 3 in g s) y
659         -- which is horrible.
660         -- Eta expanding first gives
661         --              f = /\a -> \y -> let s = h 3 in g s y
662         --
663     getUniquesUs                `thenUs` \ us ->
664     returnUs (etaExpand arity us rhs (idType bndr))
665   where
666         -- For a GlobalId, take the Arity from the Id.
667         -- It was set in CoreTidy and must not change
668         -- For all others, just expand at will
669     arity | isGlobalId bndr = idArity bndr
670           | otherwise       = exprArity rhs
671
672 -- ---------------------------------------------------------------------------
673 -- Eliminate Lam as a non-rhs (STG doesn't have such a thing)
674 -- We arrange that they only show up as the RHS of a let(rec)
675 -- ---------------------------------------------------------------------------
676
677 deLam :: CoreExpr -> UniqSM CoreExpr
678 deLam expr = 
679   deLamFloat expr   `thenUs` \ (floats, expr) ->
680   mkBinds floats expr
681
682
683 deLamFloat :: CoreExpr -> UniqSM (Floats, CoreExpr)
684 -- Remove top level lambdas by let-bindinig
685
686 deLamFloat (Note n expr)
687   =     -- You can get things like
688         --      case e of { p -> coerce t (\s -> ...) }
689     deLamFloat expr     `thenUs` \ (floats, expr') ->
690     returnUs (floats, Note n expr')
691
692 deLamFloat expr 
693   | null bndrs = returnUs (emptyFloats, expr)
694   | otherwise 
695   = case tryEta bndrs body of
696       Just no_lam_result -> returnUs (emptyFloats, no_lam_result)
697       Nothing            -> newVar (exprType expr)      `thenUs` \ fn ->
698                             returnUs (unitFloat (FloatLet (NonRec fn expr)), 
699                                       Var fn)
700   where
701     (bndrs,body) = collectBinders expr
702
703 -- Why try eta reduction?  Hasn't the simplifier already done eta?
704 -- But the simplifier only eta reduces if that leaves something
705 -- trivial (like f, or f Int).  But for deLam it would be enough to
706 -- get to a partial application, like (map f).
707
708 tryEta bndrs expr@(App _ _)
709   | ok_to_eta_reduce f &&
710     n_remaining >= 0 &&
711     and (zipWith ok bndrs last_args) &&
712     not (any (`elemVarSet` fvs_remaining) bndrs)
713   = Just remaining_expr
714   where
715     (f, args) = collectArgs expr
716     remaining_expr = mkApps f remaining_args
717     fvs_remaining = exprFreeVars remaining_expr
718     (remaining_args, last_args) = splitAt n_remaining args
719     n_remaining = length args - length bndrs
720
721     ok bndr (Var arg) = bndr == arg
722     ok bndr other     = False
723
724           -- we can't eta reduce something which must be saturated.
725     ok_to_eta_reduce (Var f) = not (hasNoBinding f)
726     ok_to_eta_reduce _       = False --safe. ToDo: generalise
727
728 tryEta bndrs (Let bind@(NonRec b r) body)
729   | not (any (`elemVarSet` fvs) bndrs)
730   = case tryEta bndrs body of
731         Just e -> Just (Let bind e)
732         Nothing -> Nothing
733   where
734     fvs = exprFreeVars r
735
736 tryEta bndrs _ = Nothing
737 \end{code}
738
739
740 -- -----------------------------------------------------------------------------
741 -- Demands
742 -- -----------------------------------------------------------------------------
743
744 \begin{code}
745 data RhsDemand
746      = RhsDemand { isStrict :: Bool,  -- True => used at least once
747                    isOnceDem   :: Bool   -- True => used at most once
748                  }
749
750 mkDem :: Demand -> Bool -> RhsDemand
751 mkDem strict once = RhsDemand (isStrictDmd strict) once
752
753 mkDemTy :: Demand -> Type -> RhsDemand
754 mkDemTy strict ty = RhsDemand (isStrictDmd strict) 
755                               False {- For now -}
756
757 bdrDem :: Id -> RhsDemand
758 bdrDem id = mkDem (idNewDemandInfo id)
759                   False {- For now -}
760
761 -- safeDem :: RhsDemand
762 -- safeDem = RhsDemand False False  -- always safe to use this
763
764 onceDem :: RhsDemand
765 onceDem = RhsDemand False True   -- used at most once
766 \end{code}
767
768
769
770
771 %************************************************************************
772 %*                                                                      *
773 \subsection{Cloning}
774 %*                                                                      *
775 %************************************************************************
776
777 \begin{code}
778 -- ---------------------------------------------------------------------------
779 --                      The environment
780 -- ---------------------------------------------------------------------------
781
782 data CorePrepEnv = CPE (IdEnv Id)       -- Clone local Ids
783                        Bool             -- True <=> inside a GADT case; see Note [GADT]
784
785 -- Note [GADT]
786 --
787 -- Be careful with cloning inside GADTs.  For example, 
788 --      /\a. \f::a. \x::T a. case x of { T -> f True; ... }
789 -- The case on x may refine the type of f to be a function type.
790 -- Without this type refinement, exprType (f True) may simply fail,
791 -- which is bad.  
792 --
793 -- Solution: remember when we are inside a potentially-type-refining case,
794 --           and in that situation use the type from the old occurrence
795 --           when looking up occurrences
796
797 emptyCorePrepEnv :: CorePrepEnv
798 emptyCorePrepEnv = CPE emptyVarEnv False
799
800 extendCorePrepEnv :: CorePrepEnv -> Id -> Id -> CorePrepEnv
801 extendCorePrepEnv (CPE env gadt) id id' = CPE (extendVarEnv env id id') gadt
802
803 lookupCorePrepEnv :: CorePrepEnv -> Id -> Id
804 -- See Note [GADT] above
805 lookupCorePrepEnv (CPE env gadt) id
806   = case lookupVarEnv env id of
807         Nothing              -> id
808         Just id' | gadt      -> setIdType id' (idType id)
809                  | otherwise -> id'
810
811 setGadt :: CorePrepEnv -> AltCon -> CorePrepEnv
812 setGadt env@(CPE id_env _) (DataAlt data_con) | not (isVanillaDataCon data_con) = CPE id_env True
813 setGadt env                other                                                = env
814
815
816 ------------------------------------------------------------------------------
817 -- Cloning binders
818 -- ---------------------------------------------------------------------------
819
820 cloneBndrs :: CorePrepEnv -> [Var] -> UniqSM (CorePrepEnv, [Var])
821 cloneBndrs env bs = mapAccumLUs cloneBndr env bs
822
823 cloneBndr  :: CorePrepEnv -> Var -> UniqSM (CorePrepEnv, Var)
824 cloneBndr env bndr
825   | isLocalId bndr
826   = getUniqueUs   `thenUs` \ uniq ->
827     let
828         bndr' = setVarUnique bndr uniq
829     in
830     returnUs (extendCorePrepEnv env bndr bndr', bndr')
831
832   | otherwise   -- Top level things, which we don't want
833                 -- to clone, have become GlobalIds by now
834                 -- And we don't clone tyvars
835   = returnUs (env, bndr)
836   
837
838 ------------------------------------------------------------------------------
839 -- Cloning ccall Ids; each must have a unique name,
840 -- to give the code generator a handle to hang it on
841 -- ---------------------------------------------------------------------------
842
843 fiddleCCall :: Id -> UniqSM Id
844 fiddleCCall id 
845   | isFCallId id = getUniqueUs          `thenUs` \ uniq ->
846                    returnUs (id `setVarUnique` uniq)
847   | otherwise    = returnUs id
848
849 ------------------------------------------------------------------------------
850 -- Generating new binders
851 -- ---------------------------------------------------------------------------
852
853 newVar :: Type -> UniqSM Id
854 newVar ty
855  = seqType ty                   `seq`
856    getUniqueUs                  `thenUs` \ uniq ->
857    returnUs (mkSysLocal FSLIT("sat") uniq ty)
858 \end{code}