2 % (c) The University of Glasgow, 1994-2006
5 Core pass to saturate constructors and PrimOps
9 corePrepPgm, corePrepExpr
12 #include "HsVersions.h"
14 import PrelNames ( lazyIdKey, hasKey )
18 import CoreMonad ( endPass, CoreToDo(..) )
42 import Data.List ( mapAccumL )
46 -- ---------------------------------------------------------------------------
48 -- ---------------------------------------------------------------------------
50 The goal of this pass is to prepare for code generation.
52 1. Saturate constructor and primop applications.
54 2. Convert to A-normal form; that is, function arguments
57 * Use case for strict arguments:
58 f E ==> case E of x -> f x
61 * Use let for non-trivial lazy arguments
62 f E ==> let x = E in f x
63 (were f is lazy and x is non-trivial)
65 3. Similarly, convert any unboxed lets into cases.
66 [I'm experimenting with leaving 'ok-for-speculation'
67 rhss in let-form right up to this point.]
69 4. Ensure that *value* lambdas only occur as the RHS of a binding
70 (The code generator can't deal with anything else.)
71 Type lambdas are ok, however, because the code gen discards them.
73 5. [Not any more; nuked Jun 2002] Do the seq/par munging.
75 6. Clone all local Ids.
76 This means that all such Ids are unique, rather than the
77 weaker guarantee of no clashes which the simplifier provides.
78 And that is what the code generator needs.
80 We don't clone TyVars. The code gen doesn't need that,
81 and doing so would be tiresome because then we'd need
82 to substitute in types.
85 7. Give each dynamic CCall occurrence a fresh unique; this is
86 rather like the cloning step above.
88 8. Inject bindings for the "implicit" Ids:
89 * Constructor wrappers
91 We want curried definitions for all of these in case they
92 aren't inlined by some caller.
94 9. Replace (lazy e) by e. See Note [lazyId magic] in MkId.lhs
96 This is all done modulo type applications and abstractions, so that
97 when type erasure is done for conversion to STG, we don't end up with
98 any trivial or useless bindings.
103 Here is the syntax of the Core produced by CorePrep:
106 triv ::= lit | var | triv ty | /\a. triv | triv |> co
109 app ::= lit | var | app triv | app ty | app |> co
113 | let(rec) x = rhs in body -- Boxed only
114 | case body of pat -> body
118 Right hand sides (only place where lambdas can occur)
119 rhs ::= /\a.rhs | \x.rhs | body
121 We define a synonym for each of these non-terminals. Functions
122 with the corresponding name produce a result in that syntax.
125 type CpeTriv = CoreExpr -- Non-terminal 'triv'
126 type CpeApp = CoreExpr -- Non-terminal 'app'
127 type CpeBody = CoreExpr -- Non-terminal 'body'
128 type CpeRhs = CoreExpr -- Non-terminal 'rhs'
131 %************************************************************************
135 %************************************************************************
138 corePrepPgm :: DynFlags -> [CoreBind] -> [TyCon] -> IO [CoreBind]
139 corePrepPgm dflags binds data_tycons = do
140 showPass dflags "CorePrep"
141 us <- mkSplitUniqSupply 's'
143 let implicit_binds = mkDataConWorkers data_tycons
144 -- NB: we must feed mkImplicitBinds through corePrep too
145 -- so that they are suitably cloned and eta-expanded
147 binds_out = initUs_ us $ do
148 floats1 <- corePrepTopBinds binds
149 floats2 <- corePrepTopBinds implicit_binds
150 return (deFloatTop (floats1 `appendFloats` floats2))
152 endPass dflags CorePrep binds_out []
155 corePrepExpr :: DynFlags -> CoreExpr -> IO CoreExpr
156 corePrepExpr dflags expr = do
157 showPass dflags "CorePrep"
158 us <- mkSplitUniqSupply 's'
159 let new_expr = initUs_ us (cpeBodyNF emptyCorePrepEnv expr)
160 dumpIfSet_dyn dflags Opt_D_dump_prep "CorePrep" (ppr new_expr)
163 corePrepTopBinds :: [CoreBind] -> UniqSM Floats
164 -- Note [Floating out of top level bindings]
165 corePrepTopBinds binds
166 = go emptyCorePrepEnv binds
168 go _ [] = return emptyFloats
169 go env (bind : binds) = do (env', bind') <- cpeBind TopLevel env bind
170 binds' <- go env' binds
171 return (bind' `appendFloats` binds')
173 mkDataConWorkers :: [TyCon] -> [CoreBind]
174 -- See Note [Data constructor workers]
175 mkDataConWorkers data_tycons
176 = [ NonRec id (Var id) -- The ice is thin here, but it works
177 | tycon <- data_tycons, -- CorePrep will eta-expand it
178 data_con <- tyConDataCons tycon,
179 let id = dataConWorkId data_con ]
182 Note [Floating out of top level bindings]
183 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
184 NB: we do need to float out of top-level bindings
185 Consider x = length [True,False]
191 We return a *list* of bindings, because we may start with
193 where x is demanded, in which case we want to finish with
196 And then x will actually end up case-bound
198 Note [CafInfo and floating]
199 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
200 What happense when we try to float bindings to the top level. At this
201 point all the CafInfo is supposed to be correct, and we must make certain
202 that is true of the new top-level bindings. There are two cases
205 a) The top-level binding is marked asCafRefs. In that case we are
206 basically fine. The floated bindings had better all be lazy lets,
207 so they can float to top level, but they'll all have HasCafRefs
208 (the default) which is safe.
210 b) The top-level binding is marked NoCafRefs. This really happens
211 Example. CoreTidy produces
212 $fApplicativeSTM [NoCafRefs] = D:Alternative retry# ...blah...
213 Now CorePrep has to eta-expand to
214 $fApplicativeSTM = let sat = \xy. retry x y
215 in D:Alternative sat ...blah...
217 sat [NoCafRefs] = \xy. retry x y
218 $fApplicativeSTM [NoCafRefs] = D:Alternative sat ...blah...
220 So, gruesomely, we must set the NoCafRefs flag on the sat bindings,
221 *and* substutite the modified 'sat' into the old RHS.
223 It should be the case that 'sat' is itself [NoCafRefs] (a value, no
224 cafs) else the original top-level binding would not itself have been
225 marked [NoCafRefs]. The DEBUG check in CoreToStg for
226 consistentCafInfo will find this.
228 This is all very gruesome and horrible. It would be better to figure
229 out CafInfo later, after CorePrep. We'll do that in due course.
230 Meanwhile this horrible hack works.
233 Note [Data constructor workers]
234 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
235 Create any necessary "implicit" bindings for data con workers. We
236 create the rather strange (non-recursive!) binding
238 $wC = \x y -> $wC x y
240 i.e. a curried constructor that allocates. This means that we can
241 treat the worker for a constructor like any other function in the rest
242 of the compiler. The point here is that CoreToStg will generate a
243 StgConApp for the RHS, rather than a call to the worker (which would
244 give a loop). As Lennart says: the ice is thin here, but it works.
246 Hmm. Should we create bindings for dictionary constructors? They are
247 always fully applied, and the bindings are just there to support
248 partial applications. But it's easier to let them through.
251 %************************************************************************
255 %************************************************************************
258 cpeBind :: TopLevelFlag
259 -> CorePrepEnv -> CoreBind
260 -> UniqSM (CorePrepEnv, Floats)
261 cpeBind top_lvl env (NonRec bndr rhs)
262 = do { (_, bndr1) <- cloneBndr env bndr
263 ; let is_strict = isStrictDmd (idDemandInfo bndr)
264 is_unlifted = isUnLiftedType (idType bndr)
265 ; (floats, bndr2, rhs2) <- cpePair top_lvl NonRecursive
266 (is_strict || is_unlifted)
268 ; let new_float = mkFloat is_strict is_unlifted bndr2 rhs2
270 -- We want bndr'' in the envt, because it records
271 -- the evaluated-ness of the binder
272 ; return (extendCorePrepEnv env bndr bndr2,
273 addFloat floats new_float) }
275 cpeBind top_lvl env (Rec pairs)
276 = do { let (bndrs,rhss) = unzip pairs
277 ; (env', bndrs1) <- cloneBndrs env (map fst pairs)
278 ; stuff <- zipWithM (cpePair top_lvl Recursive False env') bndrs1 rhss
280 ; let (floats_s, bndrs2, rhss2) = unzip3 stuff
281 all_pairs = foldrOL add_float (bndrs1 `zip` rhss2)
282 (concatFloats floats_s)
283 ; return (extendCorePrepEnvList env (bndrs `zip` bndrs2),
284 unitFloat (FloatLet (Rec all_pairs))) }
286 -- Flatten all the floats, and the currrent
287 -- group into a single giant Rec
288 add_float (FloatLet (NonRec b r)) prs2 = (b,r) : prs2
289 add_float (FloatLet (Rec prs1)) prs2 = prs1 ++ prs2
290 add_float b _ = pprPanic "cpeBind" (ppr b)
293 cpePair :: TopLevelFlag -> RecFlag -> RhsDemand
294 -> CorePrepEnv -> Id -> CoreExpr
295 -> UniqSM (Floats, Id, CpeRhs)
296 -- Used for all bindings
297 cpePair top_lvl is_rec is_strict_or_unlifted env bndr rhs
298 = do { (floats1, rhs1) <- cpeRhsE env rhs
301 <- if manifestArity rhs1 <= arity
302 then return (floats1, cpeEtaExpand arity rhs1)
303 else WARN(True, text "CorePrep: silly extra arguments:" <+> ppr bndr)
304 -- Note [Silly extra arguments]
305 (do { v <- newVar (idType bndr)
306 ; let float = mkFloat False False v rhs1
307 ; return (addFloat floats1 float, cpeEtaExpand arity (Var v)) })
309 ; (floats3, rhs') <- float_from_rhs floats2 rhs2
311 -- Record if the binder is evaluated
312 ; let bndr' | exprIsHNF rhs' = bndr `setIdUnfolding` evaldUnfolding
315 ; return (floats3, bndr', rhs') }
317 arity = idArity bndr -- We must match this arity
319 ---------------------
320 float_from_rhs floats2 rhs2
321 | isEmptyFloats floats2 = return (emptyFloats, rhs2)
322 | isTopLevel top_lvl = float_top floats2 rhs2
323 | otherwise = float_nested floats2 rhs2
325 ---------------------
326 float_nested floats2 rhs2
327 | wantFloatNested is_rec is_strict_or_unlifted floats2 rhs2
328 = return (floats2, rhs2)
329 | otherwise = dont_float floats2 rhs2
331 ---------------------
332 float_top floats2 rhs2 -- Urhgh! See Note [CafInfo and floating]
333 | mayHaveCafRefs (idCafInfo bndr)
334 = if allLazyTop floats2
335 then return (floats2, rhs2)
336 else dont_float floats2 rhs2
339 = case canFloatFromNoCaf floats2 rhs2 of
340 Just (floats2', rhs2') -> return (floats2', rhs2')
341 Nothing -> pprPanic "cpePair" (ppr bndr $$ ppr rhs2 $$ ppr floats2)
343 ---------------------
344 dont_float floats2 rhs2
345 -- Non-empty floats, but do not want to float from rhs
346 -- So wrap the rhs in the floats
347 -- But: rhs1 might have lambdas, and we can't
348 -- put them inside a wrapBinds
349 = do { body2 <- rhsToBodyNF rhs2
350 ; return (emptyFloats, wrapBinds floats2 body2) }
352 {- Note [Silly extra arguments]
353 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
356 We *must* match the arity on the Id, so we have to generate
360 It's a bizarre case: why is the arity on the Id wrong? Reason
361 (in the days of __inline_me__):
362 f{arity=0} = __inline_me__ (let v = expensive in \xy. e)
363 When InlineMe notes go away this won't happen any more. But
364 it seems good for CorePrep to be robust.
367 -- ---------------------------------------------------------------------------
368 -- CpeRhs: produces a result satisfying CpeRhs
369 -- ---------------------------------------------------------------------------
371 cpeRhsE :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
375 -- e = let bs in e' (semantically, that is!)
378 -- f (g x) ===> ([v = g x], f v)
380 cpeRhsE _env expr@(Type _) = return (emptyFloats, expr)
381 cpeRhsE _env expr@(Lit _) = return (emptyFloats, expr)
382 cpeRhsE env expr@(Var {}) = cpeApp env expr
384 cpeRhsE env (Var f `App` _ `App` arg)
385 | f `hasKey` lazyIdKey -- Replace (lazy a) by a
386 = cpeRhsE env arg -- See Note [lazyId magic] in MkId
388 cpeRhsE env expr@(App {}) = cpeApp env expr
390 cpeRhsE env (Let bind expr)
391 = do { (env', new_binds) <- cpeBind NotTopLevel env bind
392 ; (floats, body) <- cpeRhsE env' expr
393 ; return (new_binds `appendFloats` floats, body) }
395 cpeRhsE env (Note note expr)
398 | otherwise -- Just SCCs actually
399 = do { body <- cpeBodyNF env expr
400 ; return (emptyFloats, Note note body) }
402 cpeRhsE env (Cast expr co)
403 = do { (floats, expr') <- cpeRhsE env expr
404 ; return (floats, Cast expr' co) }
406 cpeRhsE env expr@(Lam {})
407 = do { let (bndrs,body) = collectBinders expr
408 ; (env', bndrs') <- cloneBndrs env bndrs
409 ; body' <- cpeBodyNF env' body
410 ; return (emptyFloats, mkLams bndrs' body') }
412 cpeRhsE env (Case (Var id) bndr ty [(DEFAULT,[],expr)])
413 | Just (TickBox {}) <- isTickBoxOp_maybe id
414 = do { body <- cpeBodyNF env expr
415 ; return (emptyFloats, Case (Var id) bndr ty [(DEFAULT,[],body)]) }
417 cpeRhsE env (Case scrut bndr ty alts)
418 = do { (floats, scrut') <- cpeBody env scrut
419 ; let bndr1 = bndr `setIdUnfolding` evaldUnfolding
420 -- Record that the case binder is evaluated in the alternatives
421 ; (env', bndr2) <- cloneBndr env bndr1
422 ; alts' <- mapM (sat_alt env') alts
423 ; return (floats, Case scrut' bndr2 ty alts') }
425 sat_alt env (con, bs, rhs)
426 = do { (env2, bs') <- cloneBndrs env bs
427 ; rhs' <- cpeBodyNF env2 rhs
428 ; return (con, bs', rhs') }
430 -- ---------------------------------------------------------------------------
431 -- CpeBody: produces a result satisfying CpeBody
432 -- ---------------------------------------------------------------------------
434 cpeBodyNF :: CorePrepEnv -> CoreExpr -> UniqSM CpeBody
436 = do { (floats, body) <- cpeBody env expr
437 ; return (wrapBinds floats body) }
440 cpeBody :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeBody)
442 = do { (floats1, rhs) <- cpeRhsE env expr
443 ; (floats2, body) <- rhsToBody rhs
444 ; return (floats1 `appendFloats` floats2, body) }
447 rhsToBodyNF :: CpeRhs -> UniqSM CpeBody
448 rhsToBodyNF rhs = do { (floats,body) <- rhsToBody rhs
449 ; return (wrapBinds floats body) }
452 rhsToBody :: CpeRhs -> UniqSM (Floats, CpeBody)
453 -- Remove top level lambdas by let-binding
455 rhsToBody (Note n expr)
456 -- You can get things like
457 -- case e of { p -> coerce t (\s -> ...) }
458 = do { (floats, expr') <- rhsToBody expr
459 ; return (floats, Note n expr') }
461 rhsToBody (Cast e co)
462 = do { (floats, e') <- rhsToBody e
463 ; return (floats, Cast e' co) }
465 rhsToBody expr@(Lam {})
466 | Just no_lam_result <- tryEtaReduce bndrs body
467 = return (emptyFloats, no_lam_result)
468 | all isTyVar bndrs -- Type lambdas are ok
469 = return (emptyFloats, expr)
470 | otherwise -- Some value lambdas
471 = do { fn <- newVar (exprType expr)
472 ; let rhs = cpeEtaExpand (exprArity expr) expr
473 float = FloatLet (NonRec fn rhs)
474 ; return (unitFloat float, Var fn) }
476 (bndrs,body) = collectBinders expr
478 rhsToBody expr = return (emptyFloats, expr)
482 -- ---------------------------------------------------------------------------
483 -- CpeApp: produces a result satisfying CpeApp
484 -- ---------------------------------------------------------------------------
486 cpeApp :: CorePrepEnv -> CoreExpr -> UniqSM (Floats, CpeRhs)
487 -- May return a CpeRhs because of saturating primops
489 = do { (app, (head,depth), _, floats, ss) <- collect_args expr 0
490 ; MASSERT(null ss) -- make sure we used all the strictness info
492 -- Now deal with the function
494 Var fn_id -> do { sat_app <- maybeSaturate fn_id app depth
495 ; return (floats, sat_app) }
496 _other -> return (floats, app) }
499 -- Deconstruct and rebuild the application, floating any non-atomic
500 -- arguments to the outside. We collect the type of the expression,
501 -- the head of the application, and the number of actual value arguments,
502 -- all of which are used to possibly saturate this application if it
503 -- has a constructor or primop at the head.
507 -> Int -- Current app depth
508 -> UniqSM (CpeApp, -- The rebuilt expression
509 (CoreExpr,Int), -- The head of the application,
510 -- and no. of args it was applied to
511 Type, -- Type of the whole expr
512 Floats, -- Any floats we pulled out
513 [Demand]) -- Remaining argument demands
515 collect_args (App fun arg@(Type arg_ty)) depth
516 = do { (fun',hd,fun_ty,floats,ss) <- collect_args fun depth
517 ; return (App fun' arg, hd, applyTy fun_ty arg_ty, floats, ss) }
519 collect_args (App fun arg) depth
520 = do { (fun',hd,fun_ty,floats,ss) <- collect_args fun (depth+1)
522 (ss1, ss_rest) = case ss of
523 (ss1:ss_rest) -> (ss1, ss_rest)
525 (arg_ty, res_ty) = expectJust "cpeBody:collect_args" $
526 splitFunTy_maybe fun_ty
528 ; (fs, arg') <- cpeArg env (isStrictDmd ss1) arg arg_ty
529 ; return (App fun' arg', hd, res_ty, fs `appendFloats` floats, ss_rest) }
531 collect_args (Var v) depth
532 = do { v1 <- fiddleCCall v
533 ; let v2 = lookupCorePrepEnv env v1
534 ; return (Var v2, (Var v2, depth), idType v2, emptyFloats, stricts) }
536 stricts = case idStrictness v of
537 StrictSig (DmdType _ demands _)
538 | listLengthCmp demands depth /= GT -> demands
539 -- length demands <= depth
541 -- If depth < length demands, then we have too few args to
542 -- satisfy strictness info so we have to ignore all the
543 -- strictness info, e.g. + (error "urk")
544 -- Here, we can't evaluate the arg strictly, because this
545 -- partial application might be seq'd
547 collect_args (Cast fun co) depth
548 = do { let (_ty1,ty2) = coercionKind co
549 ; (fun', hd, _, floats, ss) <- collect_args fun depth
550 ; return (Cast fun' co, hd, ty2, floats, ss) }
552 collect_args (Note note fun) depth
553 | ignoreNote note -- Drop these notes altogether
554 = collect_args fun depth -- They aren't used by the code generator
556 -- N-variable fun, better let-bind it
557 collect_args fun depth
558 = do { (fun_floats, fun') <- cpeArg env True fun ty
559 -- The True says that it's sure to be evaluated,
560 -- so we'll end up case-binding it
561 ; return (fun', (fun', depth), ty, fun_floats, []) }
565 -- ---------------------------------------------------------------------------
566 -- CpeArg: produces a result satisfying CpeArg
567 -- ---------------------------------------------------------------------------
569 -- This is where we arrange that a non-trivial argument is let-bound
570 cpeArg :: CorePrepEnv -> RhsDemand -> CoreArg -> Type
571 -> UniqSM (Floats, CpeTriv)
572 cpeArg env is_strict arg arg_ty
573 | cpe_ExprIsTrivial arg -- Do not eta expand etc a trivial argument
574 = cpeBody env arg -- Must still do substitution though
576 = do { (floats1, arg1) <- cpeRhsE env arg -- arg1 can be a lambda
577 ; (floats2, arg2) <- if want_float floats1 arg1
578 then return (floats1, arg1)
579 else do { body1 <- rhsToBodyNF arg1
580 ; return (emptyFloats, wrapBinds floats1 body1) }
581 -- Else case: arg1 might have lambdas, and we can't
582 -- put them inside a wrapBinds
585 ; let arg3 = cpeEtaExpand (exprArity arg2) arg2
586 arg_float = mkFloat is_strict is_unlifted v arg3
587 ; return (addFloat floats2 arg_float, Var v) }
589 is_unlifted = isUnLiftedType arg_ty
590 want_float = wantFloatNested NonRecursive (is_strict || is_unlifted)
593 Note [Floating unlifted arguments]
594 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
595 Consider C (let v* = expensive in v)
597 where the "*" indicates "will be demanded". Usually v will have been
598 inlined by now, but let's suppose it hasn't (see Trac #2756). Then we
601 let v* = expensive in C v
603 because that has different strictness. Hence the use of 'allLazy'.
604 (NB: the let v* turns into a FloatCase, in mkLocalNonRec.)
607 ------------------------------------------------------------------------------
608 -- Building the saturated syntax
609 -- ---------------------------------------------------------------------------
611 maybeSaturate deals with saturating primops and constructors
612 The type is the type of the entire application
615 maybeSaturate :: Id -> CpeApp -> Int -> UniqSM CpeRhs
616 maybeSaturate fn expr n_args
617 | Just DataToTagOp <- isPrimOpId_maybe fn -- DataToTag must have an evaluated arg
618 -- A gruesome special case
619 = saturateDataToTag sat_expr
621 | hasNoBinding fn -- There's no binding
627 fn_arity = idArity fn
628 excess_arity = fn_arity - n_args
629 sat_expr = cpeEtaExpand excess_arity expr
632 saturateDataToTag :: CpeApp -> UniqSM CpeApp
633 -- Horrid: ensure that the arg of data2TagOp is evaluated
634 -- (data2tag x) --> (case x of y -> data2tag y)
635 -- (yuk yuk) take into account the lambdas we've now introduced
636 saturateDataToTag sat_expr
637 = do { let (eta_bndrs, eta_body) = collectBinders sat_expr
638 ; eta_body' <- eval_data2tag_arg eta_body
639 ; return (mkLams eta_bndrs eta_body') }
641 eval_data2tag_arg :: CpeApp -> UniqSM CpeBody
642 eval_data2tag_arg app@(fun `App` arg)
643 | exprIsHNF arg -- Includes nullary constructors
644 = return app -- The arg is evaluated
645 | otherwise -- Arg not evaluated, so evaluate it
646 = do { arg_id <- newVar (exprType arg)
647 ; let arg_id1 = setIdUnfolding arg_id evaldUnfolding
648 ; return (Case arg arg_id1 (exprType app)
649 [(DEFAULT, [], fun `App` Var arg_id1)]) }
651 eval_data2tag_arg (Note note app) -- Scc notes can appear
652 = do { app' <- eval_data2tag_arg app
653 ; return (Note note app') }
655 eval_data2tag_arg other -- Should not happen
656 = pprPanic "eval_data2tag" (ppr other)
662 %************************************************************************
664 Simple CoreSyn operations
666 %************************************************************************
669 -- We don't ignore SCCs, since they require some code generation
670 ignoreNote :: Note -> Bool
671 -- Tells which notes to drop altogether; they are ignored by code generation
672 -- Do not ignore SCCs!
673 -- It's important that we do drop InlineMe notes; for example
674 -- unzip = __inline_me__ (/\ab. foldr (..) (..))
675 -- Here unzip gets arity 1 so we'll eta-expand it. But we don't
677 -- unzip = /\ab \xs. (__inline_me__ ...) a b xs
678 ignoreNote (CoreNote _) = True
679 ignoreNote _other = False
682 cpe_ExprIsTrivial :: CoreExpr -> Bool
683 -- Version that doesn't consider an scc annotation to be trivial.
684 cpe_ExprIsTrivial (Var _) = True
685 cpe_ExprIsTrivial (Type _) = True
686 cpe_ExprIsTrivial (Lit _) = True
687 cpe_ExprIsTrivial (App e arg) = isTypeArg arg && cpe_ExprIsTrivial e
688 cpe_ExprIsTrivial (Note (SCC _) _) = False
689 cpe_ExprIsTrivial (Note _ e) = cpe_ExprIsTrivial e
690 cpe_ExprIsTrivial (Cast e _) = cpe_ExprIsTrivial e
691 cpe_ExprIsTrivial (Lam b body) | isTyVar b = cpe_ExprIsTrivial body
692 cpe_ExprIsTrivial _ = False
695 -- -----------------------------------------------------------------------------
697 -- -----------------------------------------------------------------------------
700 ~~~~~~~~~~~~~~~~~~~~~
701 Eta expand to match the arity claimed by the binder Remember,
702 CorePrep must not change arity
704 Eta expansion might not have happened already, because it is done by
705 the simplifier only when there at least one lambda already.
707 NB1:we could refrain when the RHS is trivial (which can happen
708 for exported things). This would reduce the amount of code
709 generated (a little) and make things a little words for
710 code compiled without -O. The case in point is data constructor
713 NB2: we have to be careful that the result of etaExpand doesn't
714 invalidate any of the assumptions that CorePrep is attempting
715 to establish. One possible cause is eta expanding inside of
716 an SCC note - we're now careful in etaExpand to make sure the
717 SCC is pushed inside any new lambdas that are generated.
719 Note [Eta expansion and the CorePrep invariants]
720 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
721 It turns out to be much much easier to do eta expansion
722 *after* the main CorePrep stuff. But that places constraints
723 on the eta expander: given a CpeRhs, it must return a CpeRhs.
725 For example here is what we do not want:
726 f = /\a -> g (h 3) -- h has arity 2
728 f = /\a -> let s = h 3 in g s
729 and now we do NOT want eta expansion to give
730 f = /\a -> \ y -> (let s = h 3 in g s) y
732 Instead CoreArity.etaExpand gives
733 f = /\a -> \y -> let s = h 3 in g s y
736 cpeEtaExpand :: Arity -> CpeRhs -> CpeRhs
737 cpeEtaExpand arity expr
739 | otherwise = etaExpand arity expr
742 -- -----------------------------------------------------------------------------
744 -- -----------------------------------------------------------------------------
746 Why try eta reduction? Hasn't the simplifier already done eta?
747 But the simplifier only eta reduces if that leaves something
748 trivial (like f, or f Int). But for deLam it would be enough to
749 get to a partial application:
750 case x of { p -> \xs. map f xs }
751 ==> case x of { p -> map f }
754 tryEtaReduce :: [CoreBndr] -> CoreExpr -> Maybe CoreExpr
755 tryEtaReduce bndrs expr@(App _ _)
756 | ok_to_eta_reduce f &&
758 and (zipWith ok bndrs last_args) &&
759 not (any (`elemVarSet` fvs_remaining) bndrs)
760 = Just remaining_expr
762 (f, args) = collectArgs expr
763 remaining_expr = mkApps f remaining_args
764 fvs_remaining = exprFreeVars remaining_expr
765 (remaining_args, last_args) = splitAt n_remaining args
766 n_remaining = length args - length bndrs
768 ok bndr (Var arg) = bndr == arg
771 -- we can't eta reduce something which must be saturated.
772 ok_to_eta_reduce (Var f) = not (hasNoBinding f)
773 ok_to_eta_reduce _ = False --safe. ToDo: generalise
775 tryEtaReduce bndrs (Let bind@(NonRec _ r) body)
776 | not (any (`elemVarSet` fvs) bndrs)
777 = case tryEtaReduce bndrs body of
778 Just e -> Just (Let bind e)
783 tryEtaReduce _ _ = Nothing
787 -- -----------------------------------------------------------------------------
789 -- -----------------------------------------------------------------------------
792 type RhsDemand = Bool -- True => used strictly; hence not top-level, non-recursive
795 %************************************************************************
799 %************************************************************************
803 = FloatLet CoreBind -- Rhs of bindings are CpeRhss
804 -- They are always of lifted type;
805 -- unlifted ones are done with FloatCase
809 Bool -- The bool indicates "ok-for-speculation"
811 data Floats = Floats OkToSpec (OrdList FloatingBind)
813 instance Outputable FloatingBind where
814 ppr (FloatLet b) = ppr b
815 ppr (FloatCase b r ok) = brackets (ppr ok) <+> ppr b <+> equals <+> ppr r
817 instance Outputable Floats where
818 ppr (Floats flag fs) = ptext (sLit "Floats") <> brackets (ppr flag) <+>
819 braces (vcat (map ppr (fromOL fs)))
821 instance Outputable OkToSpec where
822 ppr OkToSpec = ptext (sLit "OkToSpec")
823 ppr IfUnboxedOk = ptext (sLit "IfUnboxedOk")
824 ppr NotOkToSpec = ptext (sLit "NotOkToSpec")
826 -- Can we float these binds out of the rhs of a let? We cache this decision
827 -- to avoid having to recompute it in a non-linear way when there are
828 -- deeply nested lets.
830 = OkToSpec -- Lazy bindings of lifted type
831 | IfUnboxedOk -- A mixture of lazy lifted bindings and n
832 -- ok-to-speculate unlifted bindings
833 | NotOkToSpec -- Some not-ok-to-speculate unlifted bindings
835 mkFloat :: Bool -> Bool -> Id -> CpeRhs -> FloatingBind
836 mkFloat is_strict is_unlifted bndr rhs
837 | use_case = FloatCase bndr rhs (exprOkForSpeculation rhs)
838 | otherwise = FloatLet (NonRec bndr rhs)
840 use_case = is_unlifted || is_strict && not (exprIsHNF rhs)
841 -- Don't make a case for a value binding,
842 -- even if it's strict. Otherwise we get
843 -- case (\x -> e) of ...!
845 emptyFloats :: Floats
846 emptyFloats = Floats OkToSpec nilOL
848 isEmptyFloats :: Floats -> Bool
849 isEmptyFloats (Floats _ bs) = isNilOL bs
851 wrapBinds :: Floats -> CpeBody -> CpeBody
852 wrapBinds (Floats _ binds) body
853 = foldrOL mk_bind body binds
855 mk_bind (FloatCase bndr rhs _) body = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
856 mk_bind (FloatLet bind) body = Let bind body
858 addFloat :: Floats -> FloatingBind -> Floats
859 addFloat (Floats ok_to_spec floats) new_float
860 = Floats (combine ok_to_spec (check new_float)) (floats `snocOL` new_float)
862 check (FloatLet _) = OkToSpec
863 check (FloatCase _ _ ok_for_spec)
864 | ok_for_spec = IfUnboxedOk
865 | otherwise = NotOkToSpec
866 -- The ok-for-speculation flag says that it's safe to
867 -- float this Case out of a let, and thereby do it more eagerly
868 -- We need the top-level flag because it's never ok to float
869 -- an unboxed binding to the top level
871 unitFloat :: FloatingBind -> Floats
872 unitFloat = addFloat emptyFloats
874 appendFloats :: Floats -> Floats -> Floats
875 appendFloats (Floats spec1 floats1) (Floats spec2 floats2)
876 = Floats (combine spec1 spec2) (floats1 `appOL` floats2)
878 concatFloats :: [Floats] -> OrdList FloatingBind
879 concatFloats = foldr (\ (Floats _ bs1) bs2 -> appOL bs1 bs2) nilOL
881 combine :: OkToSpec -> OkToSpec -> OkToSpec
882 combine NotOkToSpec _ = NotOkToSpec
883 combine _ NotOkToSpec = NotOkToSpec
884 combine IfUnboxedOk _ = IfUnboxedOk
885 combine _ IfUnboxedOk = IfUnboxedOk
886 combine _ _ = OkToSpec
888 deFloatTop :: Floats -> [CoreBind]
889 -- For top level only; we don't expect any FloatCases
890 deFloatTop (Floats _ floats)
891 = foldrOL get [] floats
893 get (FloatLet b) bs = b:bs
894 get b _ = pprPanic "corePrepPgm" (ppr b)
896 -------------------------------------------
897 canFloatFromNoCaf :: Floats -> CpeRhs -> Maybe (Floats, CpeRhs)
898 -- Note [CafInfo and floating]
899 canFloatFromNoCaf (Floats ok_to_spec fs) rhs
900 | OkToSpec <- ok_to_spec
901 = Just (Floats OkToSpec (toOL fs'), subst_expr subst rhs)
905 (subst, fs') = mapAccumL set_nocaf emptySubst (fromOL fs)
907 subst_expr = substExpr (text "CorePrep")
909 set_nocaf _ (FloatCase {})
910 = panic "canFloatFromNoCaf"
912 set_nocaf subst (FloatLet (NonRec b r))
913 = (subst', FloatLet (NonRec b' (subst_expr subst r)))
915 (subst', b') = set_nocaf_bndr subst b
917 set_nocaf subst (FloatLet (Rec prs))
918 = (subst', FloatLet (Rec (bs' `zip` rs')))
921 (subst', bs') = mapAccumL set_nocaf_bndr subst bs
922 rs' = map (subst_expr subst') rs
924 set_nocaf_bndr subst bndr
925 = (extendIdSubst subst bndr (Var bndr'), bndr')
927 bndr' = bndr `setIdCafInfo` NoCafRefs
929 wantFloatNested :: RecFlag -> Bool -> Floats -> CpeRhs -> Bool
930 wantFloatNested is_rec strict_or_unlifted floats rhs
931 = isEmptyFloats floats
932 || strict_or_unlifted
933 || (allLazyNested is_rec floats && exprIsHNF rhs)
934 -- Why the test for allLazyNested?
935 -- v = f (x `divInt#` y)
936 -- we don't want to float the case, even if f has arity 2,
937 -- because floating the case would make it evaluated too early
939 allLazyTop :: Floats -> Bool
940 allLazyTop (Floats OkToSpec _) = True
943 allLazyNested :: RecFlag -> Floats -> Bool
944 allLazyNested _ (Floats OkToSpec _) = True
945 allLazyNested _ (Floats NotOkToSpec _) = False
946 allLazyNested is_rec (Floats IfUnboxedOk _) = isNonRec is_rec
950 %************************************************************************
954 %************************************************************************
957 -- ---------------------------------------------------------------------------
959 -- ---------------------------------------------------------------------------
961 data CorePrepEnv = CPE (IdEnv Id) -- Clone local Ids
963 emptyCorePrepEnv :: CorePrepEnv
964 emptyCorePrepEnv = CPE emptyVarEnv
966 extendCorePrepEnv :: CorePrepEnv -> Id -> Id -> CorePrepEnv
967 extendCorePrepEnv (CPE env) id id' = CPE (extendVarEnv env id id')
969 extendCorePrepEnvList :: CorePrepEnv -> [(Id,Id)] -> CorePrepEnv
970 extendCorePrepEnvList (CPE env) prs = CPE (extendVarEnvList env prs)
972 lookupCorePrepEnv :: CorePrepEnv -> Id -> Id
973 lookupCorePrepEnv (CPE env) id
974 = case lookupVarEnv env id of
978 ------------------------------------------------------------------------------
980 -- ---------------------------------------------------------------------------
982 cloneBndrs :: CorePrepEnv -> [Var] -> UniqSM (CorePrepEnv, [Var])
983 cloneBndrs env bs = mapAccumLM cloneBndr env bs
985 cloneBndr :: CorePrepEnv -> Var -> UniqSM (CorePrepEnv, Var)
988 = do bndr' <- setVarUnique bndr <$> getUniqueM
989 return (extendCorePrepEnv env bndr bndr', bndr')
991 | otherwise -- Top level things, which we don't want
992 -- to clone, have become GlobalIds by now
993 -- And we don't clone tyvars
997 ------------------------------------------------------------------------------
998 -- Cloning ccall Ids; each must have a unique name,
999 -- to give the code generator a handle to hang it on
1000 -- ---------------------------------------------------------------------------
1002 fiddleCCall :: Id -> UniqSM Id
1004 | isFCallId id = (id `setVarUnique`) <$> getUniqueM
1005 | otherwise = return id
1007 ------------------------------------------------------------------------------
1008 -- Generating new binders
1009 -- ---------------------------------------------------------------------------
1011 newVar :: Type -> UniqSM Id
1013 = seqType ty `seq` do
1015 return (mkSysLocal (fsLit "sat") uniq ty)