Fix a huge space leak in the mighty Simplifier
[ghc.git] / compiler / simplCore / Simplify.hs
1 {-
2 (c) The AQUA Project, Glasgow University, 1993-1998
3
4 \section[Simplify]{The main module of the simplifier}
5 -}
6
7 {-# LANGUAGE CPP #-}
8
9 module Simplify ( simplTopBinds, simplExpr, simplRule ) where
10
11 #include "HsVersions.h"
12
13 import DynFlags
14 import SimplMonad
15 import Type hiding ( substTy, extendTvSubst, substTyVar )
16 import SimplEnv
17 import SimplUtils
18 import FamInstEnv ( FamInstEnv )
19 import Literal ( litIsLifted ) --, mkMachInt ) -- temporalily commented out. See #8326
20 import Id
21 import MkId ( seqId, voidPrimId )
22 import MkCore ( mkImpossibleExpr, castBottomExpr )
23 import IdInfo
24 import Name ( Name, mkSystemVarName, isExternalName )
25 import Coercion hiding ( substCo, substTy, substCoVar, extendTvSubst )
26 import OptCoercion ( optCoercion )
27 import FamInstEnv ( topNormaliseType_maybe )
28 import DataCon ( DataCon, dataConWorkId, dataConRepStrictness
29 , isMarkedStrict ) --, dataConTyCon, dataConTag, fIRST_TAG )
30 --import TyCon ( isEnumerationTyCon ) -- temporalily commented out. See #8326
31 import CoreMonad ( Tick(..), SimplifierMode(..) )
32 import CoreSyn
33 import Demand ( StrictSig(..), dmdTypeDepth, isStrictDmd )
34 import PprCore ( pprCoreExpr )
35 import CoreUnfold
36 import CoreUtils
37 import CoreArity
38 --import PrimOp ( tagToEnumKey ) -- temporalily commented out. See #8326
39 import Rules ( mkSpecInfo, lookupRule, getRules )
40 import TysPrim ( voidPrimTy ) --, intPrimTy ) -- temporalily commented out. See #8326
41 import BasicTypes ( TopLevelFlag(..), isTopLevel, RecFlag(..) )
42 import MonadUtils ( foldlM, mapAccumLM, liftIO )
43 import Maybes ( orElse )
44 --import Unique ( hasKey ) -- temporalily commented out. See #8326
45 import Control.Monad
46 import Outputable
47 import FastString
48 import Pair
49 import Util
50 import ErrUtils
51
52 {-
53 The guts of the simplifier is in this module, but the driver loop for
54 the simplifier is in SimplCore.hs.
55
56
57 -----------------------------------------
58 *** IMPORTANT NOTE ***
59 -----------------------------------------
60 The simplifier used to guarantee that the output had no shadowing, but
61 it does not do so any more. (Actually, it never did!) The reason is
62 documented with simplifyArgs.
63
64
65 -----------------------------------------
66 *** IMPORTANT NOTE ***
67 -----------------------------------------
68 Many parts of the simplifier return a bunch of "floats" as well as an
69 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
70
71 All "floats" are let-binds, not case-binds, but some non-rec lets may
72 be unlifted (with RHS ok-for-speculation).
73
74
75
76 -----------------------------------------
77 ORGANISATION OF FUNCTIONS
78 -----------------------------------------
79 simplTopBinds
80 - simplify all top-level binders
81 - for NonRec, call simplRecOrTopPair
82 - for Rec, call simplRecBind
83
84
85 ------------------------------
86 simplExpr (applied lambda) ==> simplNonRecBind
87 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
88 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
89
90 ------------------------------
91 simplRecBind [binders already simplfied]
92 - use simplRecOrTopPair on each pair in turn
93
94 simplRecOrTopPair [binder already simplified]
95 Used for: recursive bindings (top level and nested)
96 top-level non-recursive bindings
97 Returns:
98 - check for PreInlineUnconditionally
99 - simplLazyBind
100
101 simplNonRecBind
102 Used for: non-top-level non-recursive bindings
103 beta reductions (which amount to the same thing)
104 Because it can deal with strict arts, it takes a
105 "thing-inside" and returns an expression
106
107 - check for PreInlineUnconditionally
108 - simplify binder, including its IdInfo
109 - if strict binding
110 simplStrictArg
111 mkAtomicArgs
112 completeNonRecX
113 else
114 simplLazyBind
115 addFloats
116
117 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
118 Used for: binding case-binder and constr args in a known-constructor case
119 - check for PreInLineUnconditionally
120 - simplify binder
121 - completeNonRecX
122
123 ------------------------------
124 simplLazyBind: [binder already simplified, RHS not]
125 Used for: recursive bindings (top level and nested)
126 top-level non-recursive bindings
127 non-top-level, but *lazy* non-recursive bindings
128 [must not be strict or unboxed]
129 Returns floats + an augmented environment, not an expression
130 - substituteIdInfo and add result to in-scope
131 [so that rules are available in rec rhs]
132 - simplify rhs
133 - mkAtomicArgs
134 - float if exposes constructor or PAP
135 - completeBind
136
137
138 completeNonRecX: [binder and rhs both simplified]
139 - if the the thing needs case binding (unlifted and not ok-for-spec)
140 build a Case
141 else
142 completeBind
143 addFloats
144
145 completeBind: [given a simplified RHS]
146 [used for both rec and non-rec bindings, top level and not]
147 - try PostInlineUnconditionally
148 - add unfolding [this is the only place we add an unfolding]
149 - add arity
150
151
152
153 Right hand sides and arguments
154 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
155 In many ways we want to treat
156 (a) the right hand side of a let(rec), and
157 (b) a function argument
158 in the same way. But not always! In particular, we would
159 like to leave these arguments exactly as they are, so they
160 will match a RULE more easily.
161
162 f (g x, h x)
163 g (+ x)
164
165 It's harder to make the rule match if we ANF-ise the constructor,
166 or eta-expand the PAP:
167
168 f (let { a = g x; b = h x } in (a,b))
169 g (\y. + x y)
170
171 On the other hand if we see the let-defns
172
173 p = (g x, h x)
174 q = + x
175
176 then we *do* want to ANF-ise and eta-expand, so that p and q
177 can be safely inlined.
178
179 Even floating lets out is a bit dubious. For let RHS's we float lets
180 out if that exposes a value, so that the value can be inlined more vigorously.
181 For example
182
183 r = let x = e in (x,x)
184
185 Here, if we float the let out we'll expose a nice constructor. We did experiments
186 that showed this to be a generally good thing. But it was a bad thing to float
187 lets out unconditionally, because that meant they got allocated more often.
188
189 For function arguments, there's less reason to expose a constructor (it won't
190 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
191 So for the moment we don't float lets out of function arguments either.
192
193
194 Eta expansion
195 ~~~~~~~~~~~~~~
196 For eta expansion, we want to catch things like
197
198 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
199
200 If the \x was on the RHS of a let, we'd eta expand to bring the two
201 lambdas together. And in general that's a good thing to do. Perhaps
202 we should eta expand wherever we find a (value) lambda? Then the eta
203 expansion at a let RHS can concentrate solely on the PAP case.
204
205
206 ************************************************************************
207 * *
208 \subsection{Bindings}
209 * *
210 ************************************************************************
211 -}
212
213 simplTopBinds :: SimplEnv -> [InBind] -> SimplM SimplEnv
214
215 simplTopBinds env0 binds0
216 = do { -- Put all the top-level binders into scope at the start
217 -- so that if a transformation rule has unexpectedly brought
218 -- anything into scope, then we don't get a complaint about that.
219 -- It's rather as if the top-level binders were imported.
220 -- See note [Glomming] in OccurAnal.
221 ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
222 ; env2 <- simpl_binds env1 binds0
223 ; freeTick SimplifierDone
224 ; return env2 }
225 where
226 -- We need to track the zapped top-level binders, because
227 -- they should have their fragile IdInfo zapped (notably occurrence info)
228 -- That's why we run down binds and bndrs' simultaneously.
229 --
230 simpl_binds :: SimplEnv -> [InBind] -> SimplM SimplEnv
231 simpl_binds env [] = return env
232 simpl_binds env (bind:binds) = do { env' <- simpl_bind env bind
233 ; simpl_binds env' binds }
234
235 simpl_bind env (Rec pairs) = simplRecBind env TopLevel pairs
236 simpl_bind env (NonRec b r) = do { (env', b') <- addBndrRules env b (lookupRecBndr env b)
237 ; simplRecOrTopPair env' TopLevel NonRecursive b b' r }
238
239 {-
240 ************************************************************************
241 * *
242 \subsection{Lazy bindings}
243 * *
244 ************************************************************************
245
246 simplRecBind is used for
247 * recursive bindings only
248 -}
249
250 simplRecBind :: SimplEnv -> TopLevelFlag
251 -> [(InId, InExpr)]
252 -> SimplM SimplEnv
253 simplRecBind env0 top_lvl pairs0
254 = do { (env_with_info, triples) <- mapAccumLM add_rules env0 pairs0
255 ; env1 <- go (zapFloats env_with_info) triples
256 ; return (env0 `addRecFloats` env1) }
257 -- addFloats adds the floats from env1,
258 -- _and_ updates env0 with the in-scope set from env1
259 where
260 add_rules :: SimplEnv -> (InBndr,InExpr) -> SimplM (SimplEnv, (InBndr, OutBndr, InExpr))
261 -- Add the (substituted) rules to the binder
262 add_rules env (bndr, rhs)
263 = do { (env', bndr') <- addBndrRules env bndr (lookupRecBndr env bndr)
264 ; return (env', (bndr, bndr', rhs)) }
265
266 go env [] = return env
267
268 go env ((old_bndr, new_bndr, rhs) : pairs)
269 = do { env' <- simplRecOrTopPair env top_lvl Recursive old_bndr new_bndr rhs
270 ; go env' pairs }
271
272 {-
273 simplOrTopPair is used for
274 * recursive bindings (whether top level or not)
275 * top-level non-recursive bindings
276
277 It assumes the binder has already been simplified, but not its IdInfo.
278 -}
279
280 simplRecOrTopPair :: SimplEnv
281 -> TopLevelFlag -> RecFlag
282 -> InId -> OutBndr -> InExpr -- Binder and rhs
283 -> SimplM SimplEnv -- Returns an env that includes the binding
284
285 simplRecOrTopPair env top_lvl is_rec old_bndr new_bndr rhs
286 = do { dflags <- getDynFlags
287 ; trace_bind dflags $
288 if preInlineUnconditionally dflags env top_lvl old_bndr rhs
289 -- Check for unconditional inline
290 then do tick (PreInlineUnconditionally old_bndr)
291 return (extendIdSubst env old_bndr (mkContEx env rhs))
292 else simplLazyBind env top_lvl is_rec old_bndr new_bndr rhs env }
293 where
294 trace_bind dflags thing_inside
295 | not (dopt Opt_D_verbose_core2core dflags)
296 = thing_inside
297 | otherwise
298 = pprTrace "SimplBind" (ppr old_bndr) thing_inside
299 -- trace_bind emits a trace for each top-level binding, which
300 -- helps to locate the tracing for inlining and rule firing
301
302 {-
303 simplLazyBind is used for
304 * [simplRecOrTopPair] recursive bindings (whether top level or not)
305 * [simplRecOrTopPair] top-level non-recursive bindings
306 * [simplNonRecE] non-top-level *lazy* non-recursive bindings
307
308 Nota bene:
309 1. It assumes that the binder is *already* simplified,
310 and is in scope, and its IdInfo too, except unfolding
311
312 2. It assumes that the binder type is lifted.
313
314 3. It does not check for pre-inline-unconditionally;
315 that should have been done already.
316 -}
317
318 simplLazyBind :: SimplEnv
319 -> TopLevelFlag -> RecFlag
320 -> InId -> OutId -- Binder, both pre-and post simpl
321 -- The OutId has IdInfo, except arity, unfolding
322 -> InExpr -> SimplEnv -- The RHS and its environment
323 -> SimplM SimplEnv
324 -- Precondition: rhs obeys the let/app invariant
325 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
326 = -- pprTrace "simplLazyBind" ((ppr bndr <+> ppr bndr1) $$ ppr rhs $$ ppr (seIdSubst rhs_se)) $
327 do { let rhs_env = rhs_se `setInScope` env
328 (tvs, body) = case collectTyBinders rhs of
329 (tvs, body) | not_lam body -> (tvs,body)
330 | otherwise -> ([], rhs)
331 not_lam (Lam _ _) = False
332 not_lam (Tick t e) | not (tickishFloatable t)
333 = not_lam e -- eta-reduction could float
334 not_lam _ = True
335 -- Do not do the "abstract tyyvar" thing if there's
336 -- a lambda inside, because it defeats eta-reduction
337 -- f = /\a. \x. g a x
338 -- should eta-reduce.
339
340
341 ; (body_env, tvs') <- simplBinders rhs_env tvs
342 -- See Note [Floating and type abstraction] in SimplUtils
343
344 -- Simplify the RHS
345 ; let rhs_cont = mkRhsStop (substTy body_env (exprType body))
346 ; (body_env1, body1) <- simplExprF body_env body rhs_cont
347 -- ANF-ise a constructor or PAP rhs
348 ; (body_env2, body2) <- prepareRhs top_lvl body_env1 bndr1 body1
349
350 ; (env', rhs')
351 <- if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
352 then -- No floating, revert to body1
353 do { rhs' <- mkLam tvs' (wrapFloats body_env1 body1) rhs_cont
354 ; return (env, rhs') }
355
356 else if null tvs then -- Simple floating
357 do { tick LetFloatFromLet
358 ; return (addFloats env body_env2, body2) }
359
360 else -- Do type-abstraction first
361 do { tick LetFloatFromLet
362 ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
363 ; rhs' <- mkLam tvs' body3 rhs_cont
364 ; env' <- foldlM (addPolyBind top_lvl) env poly_binds
365 ; return (env', rhs') }
366
367 ; completeBind env' top_lvl bndr bndr1 rhs' }
368
369 {-
370 A specialised variant of simplNonRec used when the RHS is already simplified,
371 notably in knownCon. It uses case-binding where necessary.
372 -}
373
374 simplNonRecX :: SimplEnv
375 -> InId -- Old binder
376 -> OutExpr -- Simplified RHS
377 -> SimplM SimplEnv
378 -- Precondition: rhs satisfies the let/app invariant
379 simplNonRecX env bndr new_rhs
380 | isDeadBinder bndr -- Not uncommon; e.g. case (a,b) of c { (p,q) -> p }
381 = return env -- Here c is dead, and we avoid creating
382 -- the binding c = (a,b)
383
384 | Coercion co <- new_rhs
385 = return (extendCvSubst env bndr co)
386
387 | otherwise
388 = do { (env', bndr') <- simplBinder env bndr
389 ; completeNonRecX NotTopLevel env' (isStrictId bndr) bndr bndr' new_rhs }
390 -- simplNonRecX is only used for NotTopLevel things
391
392 completeNonRecX :: TopLevelFlag -> SimplEnv
393 -> Bool
394 -> InId -- Old binder
395 -> OutId -- New binder
396 -> OutExpr -- Simplified RHS
397 -> SimplM SimplEnv
398 -- Precondition: rhs satisfies the let/app invariant
399 -- See Note [CoreSyn let/app invariant] in CoreSyn
400
401 completeNonRecX top_lvl env is_strict old_bndr new_bndr new_rhs
402 = do { (env1, rhs1) <- prepareRhs top_lvl (zapFloats env) new_bndr new_rhs
403 ; (env2, rhs2) <-
404 if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
405 then do { tick LetFloatFromLet
406 ; return (addFloats env env1, rhs1) } -- Add the floats to the main env
407 else return (env, wrapFloats env1 rhs1) -- Wrap the floats around the RHS
408 ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
409
410 {-
411 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
412 Doing so risks exponential behaviour, because new_rhs has been simplified once already
413 In the cases described by the folowing commment, postInlineUnconditionally will
414 catch many of the relevant cases.
415 -- This happens; for example, the case_bndr during case of
416 -- known constructor: case (a,b) of x { (p,q) -> ... }
417 -- Here x isn't mentioned in the RHS, so we don't want to
418 -- create the (dead) let-binding let x = (a,b) in ...
419 --
420 -- Similarly, single occurrences can be inlined vigourously
421 -- e.g. case (f x, g y) of (a,b) -> ....
422 -- If a,b occur once we can avoid constructing the let binding for them.
423
424 Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
425 -- Consider case I# (quotInt# x y) of
426 -- I# v -> let w = J# v in ...
427 -- If we gaily inline (quotInt# x y) for v, we end up building an
428 -- extra thunk:
429 -- let w = J# (quotInt# x y) in ...
430 -- because quotInt# can fail.
431
432 | preInlineUnconditionally env NotTopLevel bndr new_rhs
433 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
434 -}
435
436 ----------------------------------
437 prepareRhs takes a putative RHS, checks whether it's a PAP or
438 constructor application and, if so, converts it to ANF, so that the
439 resulting thing can be inlined more easily. Thus
440 x = (f a, g b)
441 becomes
442 t1 = f a
443 t2 = g b
444 x = (t1,t2)
445
446 We also want to deal well cases like this
447 v = (f e1 `cast` co) e2
448 Here we want to make e1,e2 trivial and get
449 x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
450 That's what the 'go' loop in prepareRhs does
451 -}
452
453 prepareRhs :: TopLevelFlag -> SimplEnv -> OutId -> OutExpr -> SimplM (SimplEnv, OutExpr)
454 -- Adds new floats to the env iff that allows us to return a good RHS
455 prepareRhs top_lvl env id (Cast rhs co) -- Note [Float coercions]
456 | Pair ty1 _ty2 <- coercionKind co -- Do *not* do this if rhs has an unlifted type
457 , not (isUnLiftedType ty1) -- see Note [Float coercions (unlifted)]
458 = do { (env', rhs') <- makeTrivialWithInfo top_lvl env sanitised_info rhs
459 ; return (env', Cast rhs' co) }
460 where
461 sanitised_info = vanillaIdInfo `setStrictnessInfo` strictnessInfo info
462 `setDemandInfo` demandInfo info
463 info = idInfo id
464
465 prepareRhs top_lvl env0 _ rhs0
466 = do { (_is_exp, env1, rhs1) <- go 0 env0 rhs0
467 ; return (env1, rhs1) }
468 where
469 go n_val_args env (Cast rhs co)
470 = do { (is_exp, env', rhs') <- go n_val_args env rhs
471 ; return (is_exp, env', Cast rhs' co) }
472 go n_val_args env (App fun (Type ty))
473 = do { (is_exp, env', rhs') <- go n_val_args env fun
474 ; return (is_exp, env', App rhs' (Type ty)) }
475 go n_val_args env (App fun arg)
476 = do { (is_exp, env', fun') <- go (n_val_args+1) env fun
477 ; case is_exp of
478 True -> do { (env'', arg') <- makeTrivial top_lvl env' arg
479 ; return (True, env'', App fun' arg') }
480 False -> return (False, env, App fun arg) }
481 go n_val_args env (Var fun)
482 = return (is_exp, env, Var fun)
483 where
484 is_exp = isExpandableApp fun n_val_args -- The fun a constructor or PAP
485 -- See Note [CONLIKE pragma] in BasicTypes
486 -- The definition of is_exp should match that in
487 -- OccurAnal.occAnalApp
488
489 go n_val_args env (Tick t rhs)
490 -- We want to be able to float bindings past this
491 -- tick. Non-scoping ticks don't care.
492 | tickishScoped t == NoScope
493 = do { (is_exp, env', rhs') <- go n_val_args env rhs
494 ; return (is_exp, env', Tick t rhs') }
495 -- On the other hand, for scoping ticks we need to be able to
496 -- copy them on the floats, which in turn is only allowed if
497 -- we can obtain non-counting ticks.
498 | not (tickishCounts t) || tickishCanSplit t
499 = do { (is_exp, env', rhs') <- go n_val_args (zapFloats env) rhs
500 ; let tickIt (id, expr) = (id, mkTick (mkNoCount t) expr)
501 floats' = seFloats $ env `addFloats` mapFloats env' tickIt
502 ; return (is_exp, env' { seFloats = floats' }, Tick t rhs') }
503
504 go _ env other
505 = return (False, env, other)
506
507 {-
508 Note [Float coercions]
509 ~~~~~~~~~~~~~~~~~~~~~~
510 When we find the binding
511 x = e `cast` co
512 we'd like to transform it to
513 x' = e
514 x = x `cast` co -- A trivial binding
515 There's a chance that e will be a constructor application or function, or something
516 like that, so moving the coercion to the usage site may well cancel the coercions
517 and lead to further optimisation. Example:
518
519 data family T a :: *
520 data instance T Int = T Int
521
522 foo :: Int -> Int -> Int
523 foo m n = ...
524 where
525 x = T m
526 go 0 = 0
527 go n = case x of { T m -> go (n-m) }
528 -- This case should optimise
529
530 Note [Preserve strictness when floating coercions]
531 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
532 In the Note [Float coercions] transformation, keep the strictness info.
533 Eg
534 f = e `cast` co -- f has strictness SSL
535 When we transform to
536 f' = e -- f' also has strictness SSL
537 f = f' `cast` co -- f still has strictness SSL
538
539 Its not wrong to drop it on the floor, but better to keep it.
540
541 Note [Float coercions (unlifted)]
542 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
543 BUT don't do [Float coercions] if 'e' has an unlifted type.
544 This *can* happen:
545
546 foo :: Int = (error (# Int,Int #) "urk")
547 `cast` CoUnsafe (# Int,Int #) Int
548
549 If do the makeTrivial thing to the error call, we'll get
550 foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
551 But 'v' isn't in scope!
552
553 These strange casts can happen as a result of case-of-case
554 bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
555 (# p,q #) -> p+q
556 -}
557
558 makeTrivialArg :: SimplEnv -> ArgSpec -> SimplM (SimplEnv, ArgSpec)
559 makeTrivialArg env (ValArg e) = do { (env', e') <- makeTrivial NotTopLevel env e
560 ; return (env', ValArg e') }
561 makeTrivialArg env arg = return (env, arg) -- CastBy, TyArg
562
563 makeTrivial :: TopLevelFlag -> SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
564 -- Binds the expression to a variable, if it's not trivial, returning the variable
565 makeTrivial top_lvl env expr = makeTrivialWithInfo top_lvl env vanillaIdInfo expr
566
567 makeTrivialWithInfo :: TopLevelFlag -> SimplEnv -> IdInfo
568 -> OutExpr -> SimplM (SimplEnv, OutExpr)
569 -- Propagate strictness and demand info to the new binder
570 -- Note [Preserve strictness when floating coercions]
571 -- Returned SimplEnv has same substitution as incoming one
572 makeTrivialWithInfo top_lvl env info expr
573 | exprIsTrivial expr -- Already trivial
574 || not (bindingOk top_lvl expr expr_ty) -- Cannot trivialise
575 -- See Note [Cannot trivialise]
576 = return (env, expr)
577 | otherwise -- See Note [Take care] below
578 = do { uniq <- getUniqueM
579 ; let name = mkSystemVarName uniq (fsLit "a")
580 var = mkLocalIdWithInfo name expr_ty info
581 ; env' <- completeNonRecX top_lvl env False var var expr
582 ; expr' <- simplVar env' var
583 ; return (env', expr') }
584 -- The simplVar is needed becase we're constructing a new binding
585 -- a = rhs
586 -- And if rhs is of form (rhs1 |> co), then we might get
587 -- a1 = rhs1
588 -- a = a1 |> co
589 -- and now a's RHS is trivial and can be substituted out, and that
590 -- is what completeNonRecX will do
591 -- To put it another way, it's as if we'd simplified
592 -- let var = e in var
593 where
594 expr_ty = exprType expr
595
596 bindingOk :: TopLevelFlag -> CoreExpr -> Type -> Bool
597 -- True iff we can have a binding of this expression at this level
598 -- Precondition: the type is the type of the expression
599 bindingOk top_lvl _ expr_ty
600 | isTopLevel top_lvl = not (isUnLiftedType expr_ty)
601 | otherwise = True
602
603 {-
604 Note [Cannot trivialise]
605 ~~~~~~~~~~~~~~~~~~~~~~~~
606 Consider tih
607 f :: Int -> Addr#
608
609 foo :: Bar
610 foo = Bar (f 3)
611
612 Then we can't ANF-ise foo, even though we'd like to, because
613 we can't make a top-level binding for the Addr# (f 3). And if
614 so we don't want to turn it into
615 foo = let x = f 3 in Bar x
616 because we'll just end up inlining x back, and that makes the
617 simplifier loop. Better not to ANF-ise it at all.
618
619 A case in point is literal strings (a MachStr is not regarded as
620 trivial):
621
622 foo = Ptr "blob"#
623
624 We don't want to ANF-ise this.
625
626 ************************************************************************
627 * *
628 \subsection{Completing a lazy binding}
629 * *
630 ************************************************************************
631
632 completeBind
633 * deals only with Ids, not TyVars
634 * takes an already-simplified binder and RHS
635 * is used for both recursive and non-recursive bindings
636 * is used for both top-level and non-top-level bindings
637
638 It does the following:
639 - tries discarding a dead binding
640 - tries PostInlineUnconditionally
641 - add unfolding [this is the only place we add an unfolding]
642 - add arity
643
644 It does *not* attempt to do let-to-case. Why? Because it is used for
645 - top-level bindings (when let-to-case is impossible)
646 - many situations where the "rhs" is known to be a WHNF
647 (so let-to-case is inappropriate).
648
649 Nor does it do the atomic-argument thing
650 -}
651
652 completeBind :: SimplEnv
653 -> TopLevelFlag -- Flag stuck into unfolding
654 -> InId -- Old binder
655 -> OutId -> OutExpr -- New binder and RHS
656 -> SimplM SimplEnv
657 -- completeBind may choose to do its work
658 -- * by extending the substitution (e.g. let x = y in ...)
659 -- * or by adding to the floats in the envt
660 --
661 -- Precondition: rhs obeys the let/app invariant
662 completeBind env top_lvl old_bndr new_bndr new_rhs
663 | isCoVar old_bndr
664 = case new_rhs of
665 Coercion co -> return (extendCvSubst env old_bndr co)
666 _ -> return (addNonRec env new_bndr new_rhs)
667
668 | otherwise
669 = ASSERT( isId new_bndr )
670 do { let old_info = idInfo old_bndr
671 old_unf = unfoldingInfo old_info
672 occ_info = occInfo old_info
673
674 -- Do eta-expansion on the RHS of the binding
675 -- See Note [Eta-expanding at let bindings] in SimplUtils
676 ; (new_arity, final_rhs) <- tryEtaExpandRhs env new_bndr new_rhs
677
678 -- Simplify the unfolding
679 ; new_unfolding <- simplLetUnfolding env top_lvl old_bndr final_rhs old_unf
680
681 ; dflags <- getDynFlags
682 ; if postInlineUnconditionally dflags env top_lvl new_bndr occ_info
683 final_rhs new_unfolding
684
685 -- Inline and discard the binding
686 then do { tick (PostInlineUnconditionally old_bndr)
687 ; return (extendIdSubst env old_bndr (DoneEx final_rhs)) }
688 -- Use the substitution to make quite, quite sure that the
689 -- substitution will happen, since we are going to discard the binding
690 else
691 do { let info1 = idInfo new_bndr `setArityInfo` new_arity
692
693 -- Unfolding info: Note [Setting the new unfolding]
694 info2 = info1 `setUnfoldingInfo` new_unfolding
695
696 -- Demand info: Note [Setting the demand info]
697 --
698 -- We also have to nuke demand info if for some reason
699 -- eta-expansion *reduces* the arity of the binding to less
700 -- than that of the strictness sig. This can happen: see Note [Arity decrease].
701 info3 | isEvaldUnfolding new_unfolding
702 || (case strictnessInfo info2 of
703 StrictSig dmd_ty -> new_arity < dmdTypeDepth dmd_ty)
704 = zapDemandInfo info2 `orElse` info2
705 | otherwise
706 = info2
707
708 final_id = new_bndr `setIdInfo` info3
709
710 ; -- pprTrace "Binding" (ppr final_id <+> ppr new_unfolding) $
711 return (addNonRec env final_id final_rhs) } }
712 -- The addNonRec adds it to the in-scope set too
713
714 ------------------------------
715 addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplM SimplEnv
716 -- Add a new binding to the environment, complete with its unfolding
717 -- but *do not* do postInlineUnconditionally, because we have already
718 -- processed some of the scope of the binding
719 -- We still want the unfolding though. Consider
720 -- let
721 -- x = /\a. let y = ... in Just y
722 -- in body
723 -- Then we float the y-binding out (via abstractFloats and addPolyBind)
724 -- but 'x' may well then be inlined in 'body' in which case we'd like the
725 -- opportunity to inline 'y' too.
726 --
727 -- INVARIANT: the arity is correct on the incoming binders
728
729 addPolyBind top_lvl env (NonRec poly_id rhs)
730 = do { unfolding <- simplLetUnfolding env top_lvl poly_id rhs noUnfolding
731 -- Assumes that poly_id did not have an INLINE prag
732 -- which is perhaps wrong. ToDo: think about this
733 ; let final_id = setIdInfo poly_id $
734 idInfo poly_id `setUnfoldingInfo` unfolding
735
736 ; return (addNonRec env final_id rhs) }
737
738 addPolyBind _ env bind@(Rec _)
739 = return (extendFloats env bind)
740 -- Hack: letrecs are more awkward, so we extend "by steam"
741 -- without adding unfoldings etc. At worst this leads to
742 -- more simplifier iterations
743
744 {- Note [Arity decrease]
745 ~~~~~~~~~~~~~~~~~~~~~~~~
746 Generally speaking the arity of a binding should not decrease. But it *can*
747 legitimately happen because of RULES. Eg
748 f = g Int
749 where g has arity 2, will have arity 2. But if there's a rewrite rule
750 g Int --> h
751 where h has arity 1, then f's arity will decrease. Here's a real-life example,
752 which is in the output of Specialise:
753
754 Rec {
755 $dm {Arity 2} = \d.\x. op d
756 {-# RULES forall d. $dm Int d = $s$dm #-}
757
758 dInt = MkD .... opInt ...
759 opInt {Arity 1} = $dm dInt
760
761 $s$dm {Arity 0} = \x. op dInt }
762
763 Here opInt has arity 1; but when we apply the rule its arity drops to 0.
764 That's why Specialise goes to a little trouble to pin the right arity
765 on specialised functions too.
766
767 Note [Setting the demand info]
768 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
769 If the unfolding is a value, the demand info may
770 go pear-shaped, so we nuke it. Example:
771 let x = (a,b) in
772 case x of (p,q) -> h p q x
773 Here x is certainly demanded. But after we've nuked
774 the case, we'll get just
775 let x = (a,b) in h a b x
776 and now x is not demanded (I'm assuming h is lazy)
777 This really happens. Similarly
778 let f = \x -> e in ...f..f...
779 After inlining f at some of its call sites the original binding may
780 (for example) be no longer strictly demanded.
781 The solution here is a bit ad hoc...
782
783
784 ************************************************************************
785 * *
786 \subsection[Simplify-simplExpr]{The main function: simplExpr}
787 * *
788 ************************************************************************
789
790 The reason for this OutExprStuff stuff is that we want to float *after*
791 simplifying a RHS, not before. If we do so naively we get quadratic
792 behaviour as things float out.
793
794 To see why it's important to do it after, consider this (real) example:
795
796 let t = f x
797 in fst t
798 ==>
799 let t = let a = e1
800 b = e2
801 in (a,b)
802 in fst t
803 ==>
804 let a = e1
805 b = e2
806 t = (a,b)
807 in
808 a -- Can't inline a this round, cos it appears twice
809 ==>
810 e1
811
812 Each of the ==> steps is a round of simplification. We'd save a
813 whole round if we float first. This can cascade. Consider
814
815 let f = g d
816 in \x -> ...f...
817 ==>
818 let f = let d1 = ..d.. in \y -> e
819 in \x -> ...f...
820 ==>
821 let d1 = ..d..
822 in \x -> ...(\y ->e)...
823
824 Only in this second round can the \y be applied, and it
825 might do the same again.
826 -}
827
828 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
829 simplExpr env expr = simplExprC env expr (mkBoringStop expr_out_ty)
830 where
831 expr_out_ty :: OutType
832 expr_out_ty = substTy env (exprType expr)
833
834 simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
835 -- Simplify an expression, given a continuation
836 simplExprC env expr cont
837 = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
838 do { (env', expr') <- simplExprF (zapFloats env) expr cont
839 ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
840 -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
841 -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
842 return (wrapFloats env' expr') }
843
844 --------------------------------------------------
845 simplExprF :: SimplEnv -> InExpr -> SimplCont
846 -> SimplM (SimplEnv, OutExpr)
847
848 simplExprF env e cont
849 = {- pprTrace "simplExprF" (vcat
850 [ ppr e
851 , text "cont =" <+> ppr cont
852 , text "inscope =" <+> ppr (seInScope env)
853 , text "tvsubst =" <+> ppr (seTvSubst env)
854 , text "idsubst =" <+> ppr (seIdSubst env)
855 , text "cvsubst =" <+> ppr (seCvSubst env)
856 {- , ppr (seFloats env) -}
857 ]) $ -}
858 simplExprF1 env e cont
859
860 simplExprF1 :: SimplEnv -> InExpr -> SimplCont
861 -> SimplM (SimplEnv, OutExpr)
862 simplExprF1 env (Var v) cont = simplIdF env v cont
863 simplExprF1 env (Lit lit) cont = rebuild env (Lit lit) cont
864 simplExprF1 env (Tick t expr) cont = simplTick env t expr cont
865 simplExprF1 env (Cast body co) cont = simplCast env body co cont
866 simplExprF1 env (Coercion co) cont = simplCoercionF env co cont
867 simplExprF1 env (Type ty) cont = ASSERT( contIsRhsOrArg cont )
868 rebuild env (Type (substTy env ty)) cont
869
870 simplExprF1 env (App fun arg) cont
871 = simplExprF env fun $
872 case arg of
873 Type ty -> ApplyToTy { sc_arg_ty = substTy env ty
874 , sc_hole_ty = substTy env (exprType fun)
875 , sc_cont = cont }
876 _ -> ApplyToVal { sc_arg = arg, sc_env = env
877 , sc_dup = NoDup, sc_cont = cont }
878
879 simplExprF1 env expr@(Lam {}) cont
880 = simplLam env zapped_bndrs body cont
881 -- The main issue here is under-saturated lambdas
882 -- (\x1. \x2. e) arg1
883 -- Here x1 might have "occurs-once" occ-info, because occ-info
884 -- is computed assuming that a group of lambdas is applied
885 -- all at once. If there are too few args, we must zap the
886 -- occ-info, UNLESS the remaining binders are one-shot
887 where
888 (bndrs, body) = collectBinders expr
889 zapped_bndrs | need_to_zap = map zap bndrs
890 | otherwise = bndrs
891
892 need_to_zap = any zappable_bndr (drop n_args bndrs)
893 n_args = countArgs cont
894 -- NB: countArgs counts all the args (incl type args)
895 -- and likewise drop counts all binders (incl type lambdas)
896
897 zappable_bndr b = isId b && not (isOneShotBndr b)
898 zap b | isTyVar b = b
899 | otherwise = zapLamIdInfo b
900
901 simplExprF1 env (Case scrut bndr _ alts) cont
902 = simplExprF env scrut (Select NoDup bndr alts env cont)
903
904 simplExprF1 env (Let (Rec pairs) body) cont
905 = do { env' <- simplRecBndrs env (map fst pairs)
906 -- NB: bndrs' don't have unfoldings or rules
907 -- We add them as we go down
908
909 ; env'' <- simplRecBind env' NotTopLevel pairs
910 ; simplExprF env'' body cont }
911
912 simplExprF1 env (Let (NonRec bndr rhs) body) cont
913 = simplNonRecE env bndr (rhs, env) ([], body) cont
914
915 ---------------------------------
916 simplType :: SimplEnv -> InType -> SimplM OutType
917 -- Kept monadic just so we can do the seqType
918 simplType env ty
919 = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
920 seqType new_ty `seq` return new_ty
921 where
922 new_ty = substTy env ty
923
924 ---------------------------------
925 simplCoercionF :: SimplEnv -> InCoercion -> SimplCont
926 -> SimplM (SimplEnv, OutExpr)
927 simplCoercionF env co cont
928 = do { co' <- simplCoercion env co
929 ; rebuild env (Coercion co') cont }
930
931 simplCoercion :: SimplEnv -> InCoercion -> SimplM OutCoercion
932 simplCoercion env co
933 = let opt_co = optCoercion (getCvSubst env) co
934 in seqCo opt_co `seq` return opt_co
935
936 -----------------------------------
937 -- | Push a TickIt context outwards past applications and cases, as
938 -- long as this is a non-scoping tick, to let case and application
939 -- optimisations apply.
940
941 simplTick :: SimplEnv -> Tickish Id -> InExpr -> SimplCont
942 -> SimplM (SimplEnv, OutExpr)
943 simplTick env tickish expr cont
944 -- A scoped tick turns into a continuation, so that we can spot
945 -- (scc t (\x . e)) in simplLam and eliminate the scc. If we didn't do
946 -- it this way, then it would take two passes of the simplifier to
947 -- reduce ((scc t (\x . e)) e').
948 -- NB, don't do this with counting ticks, because if the expr is
949 -- bottom, then rebuildCall will discard the continuation.
950
951 -- XXX: we cannot do this, because the simplifier assumes that
952 -- the context can be pushed into a case with a single branch. e.g.
953 -- scc<f> case expensive of p -> e
954 -- becomes
955 -- case expensive of p -> scc<f> e
956 --
957 -- So I'm disabling this for now. It just means we will do more
958 -- simplifier iterations that necessary in some cases.
959
960 -- | tickishScoped tickish && not (tickishCounts tickish)
961 -- = simplExprF env expr (TickIt tickish cont)
962
963 -- For unscoped or soft-scoped ticks, we are allowed to float in new
964 -- cost, so we simply push the continuation inside the tick. This
965 -- has the effect of moving the tick to the outside of a case or
966 -- application context, allowing the normal case and application
967 -- optimisations to fire.
968 | tickish `tickishScopesLike` SoftScope
969 = do { (env', expr') <- simplExprF env expr cont
970 ; return (env', mkTick tickish expr')
971 }
972
973 -- Push tick inside if the context looks like this will allow us to
974 -- do a case-of-case - see Note [case-of-scc-of-case]
975 | Select {} <- cont, Just expr' <- push_tick_inside
976 = simplExprF env expr' cont
977
978 -- We don't want to move the tick, but we might still want to allow
979 -- floats to pass through with appropriate wrapping (or not, see
980 -- wrap_floats below)
981 --- | not (tickishCounts tickish) || tickishCanSplit tickish
982 -- = wrap_floats
983
984 | otherwise
985 = no_floating_past_tick
986
987 where
988
989 -- Try to push tick inside a case, see Note [case-of-scc-of-case].
990 push_tick_inside =
991 case expr0 of
992 Case scrut bndr ty alts
993 -> Just $ Case (tickScrut scrut) bndr ty (map tickAlt alts)
994 _other -> Nothing
995 where (ticks, expr0) = stripTicksTop movable (Tick tickish expr)
996 movable t = not (tickishCounts t) ||
997 t `tickishScopesLike` NoScope ||
998 tickishCanSplit t
999 tickScrut e = foldr mkTick e ticks
1000 -- Alternatives get annotated with all ticks that scope in some way,
1001 -- but we don't want to count entries.
1002 tickAlt (c,bs,e) = (c,bs, foldr mkTick e ts_scope)
1003 ts_scope = map mkNoCount $
1004 filter (not . (`tickishScopesLike` NoScope)) ticks
1005
1006 no_floating_past_tick =
1007 do { let (inc,outc) = splitCont cont
1008 ; (env', expr') <- simplExprF (zapFloats env) expr inc
1009 ; let tickish' = simplTickish env tickish
1010 ; (env'', expr'') <- rebuild (zapFloats env')
1011 (wrapFloats env' expr')
1012 (TickIt tickish' outc)
1013 ; return (addFloats env env'', expr'')
1014 }
1015
1016 -- Alternative version that wraps outgoing floats with the tick. This
1017 -- results in ticks being duplicated, as we don't make any attempt to
1018 -- eliminate the tick if we re-inline the binding (because the tick
1019 -- semantics allows unrestricted inlining of HNFs), so I'm not doing
1020 -- this any more. FloatOut will catch any real opportunities for
1021 -- floating.
1022 --
1023 -- wrap_floats =
1024 -- do { let (inc,outc) = splitCont cont
1025 -- ; (env', expr') <- simplExprF (zapFloats env) expr inc
1026 -- ; let tickish' = simplTickish env tickish
1027 -- ; let wrap_float (b,rhs) = (zapIdStrictness (setIdArity b 0),
1028 -- mkTick (mkNoCount tickish') rhs)
1029 -- -- when wrapping a float with mkTick, we better zap the Id's
1030 -- -- strictness info and arity, because it might be wrong now.
1031 -- ; let env'' = addFloats env (mapFloats env' wrap_float)
1032 -- ; rebuild env'' expr' (TickIt tickish' outc)
1033 -- }
1034
1035
1036 simplTickish env tickish
1037 | Breakpoint n ids <- tickish
1038 = Breakpoint n (map (getDoneId . substId env) ids)
1039 | otherwise = tickish
1040
1041 -- Push type application and coercion inside a tick
1042 splitCont :: SimplCont -> (SimplCont, SimplCont)
1043 splitCont cont@(ApplyToTy { sc_cont = tail }) = (cont { sc_cont = inc }, outc)
1044 where (inc,outc) = splitCont tail
1045 splitCont (CastIt co c) = (CastIt co inc, outc)
1046 where (inc,outc) = splitCont c
1047 splitCont other = (mkBoringStop (contHoleType other), other)
1048
1049 getDoneId (DoneId id) = id
1050 getDoneId (DoneEx e) = getIdFromTrivialExpr e -- Note [substTickish] in CoreSubst
1051 getDoneId other = pprPanic "getDoneId" (ppr other)
1052
1053 -- Note [case-of-scc-of-case]
1054 -- It's pretty important to be able to transform case-of-case when
1055 -- there's an SCC in the way. For example, the following comes up
1056 -- in nofib/real/compress/Encode.hs:
1057 --
1058 -- case scctick<code_string.r1>
1059 -- case $wcode_string_r13s wild_XC w1_s137 w2_s138 l_aje
1060 -- of _ { (# ww1_s13f, ww2_s13g, ww3_s13h #) ->
1061 -- (ww1_s13f, ww2_s13g, ww3_s13h)
1062 -- }
1063 -- of _ { (ww_s12Y, ww1_s12Z, ww2_s130) ->
1064 -- tick<code_string.f1>
1065 -- (ww_s12Y,
1066 -- ww1_s12Z,
1067 -- PTTrees.PT
1068 -- @ GHC.Types.Char @ GHC.Types.Int wild2_Xj ww2_s130 r_ajf)
1069 -- }
1070 --
1071 -- We really want this case-of-case to fire, because then the 3-tuple
1072 -- will go away (indeed, the CPR optimisation is relying on this
1073 -- happening). But the scctick is in the way - we need to push it
1074 -- inside to expose the case-of-case. So we perform this
1075 -- transformation on the inner case:
1076 --
1077 -- scctick c (case e of { p1 -> e1; ...; pn -> en })
1078 -- ==>
1079 -- case (scctick c e) of { p1 -> scc c e1; ...; pn -> scc c en }
1080 --
1081 -- So we've moved a constant amount of work out of the scc to expose
1082 -- the case. We only do this when the continuation is interesting: in
1083 -- for now, it has to be another Case (maybe generalise this later).
1084
1085 {-
1086 ************************************************************************
1087 * *
1088 \subsection{The main rebuilder}
1089 * *
1090 ************************************************************************
1091 -}
1092
1093 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
1094 -- At this point the substitution in the SimplEnv should be irrelevant
1095 -- only the in-scope set and floats should matter
1096 rebuild env expr cont
1097 = case cont of
1098 Stop {} -> return (env, expr)
1099 TickIt t cont -> rebuild env (mkTick t expr) cont
1100 CastIt co cont -> rebuild env (mkCast expr co) cont
1101 -- NB: mkCast implements the (Coercion co |> g) optimisation
1102
1103 Select _ bndr alts se cont -> rebuildCase (se `setFloats` env) expr bndr alts cont
1104 StrictArg info _ cont -> rebuildCall env (info `addValArgTo` expr) cont
1105
1106 StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
1107 -- expr satisfies let/app since it started life
1108 -- in a call to simplNonRecE
1109 ; simplLam env' bs body cont }
1110
1111 ApplyToTy { sc_arg_ty = ty, sc_cont = cont}
1112 -> rebuild env (App expr (Type ty)) cont
1113 ApplyToVal { sc_arg = arg, sc_env = se, sc_dup = dup_flag, sc_cont = cont}
1114 -- See Note [Avoid redundant simplification]
1115 | isSimplified dup_flag -> rebuild env (App expr arg) cont
1116 | otherwise -> do { arg' <- simplExpr (se `setInScope` env) arg
1117 ; rebuild env (App expr arg') cont }
1118
1119
1120 {-
1121 ************************************************************************
1122 * *
1123 \subsection{Lambdas}
1124 * *
1125 ************************************************************************
1126 -}
1127
1128 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
1129 -> SimplM (SimplEnv, OutExpr)
1130 simplCast env body co0 cont0
1131 = do { co1 <- simplCoercion env co0
1132 ; cont1 <- addCoerce co1 cont0
1133 ; simplExprF env body cont1 }
1134 where
1135 addCoerce co cont = add_coerce co (coercionKind co) cont
1136
1137 add_coerce _co (Pair s1 k1) cont -- co :: ty~ty
1138 | s1 `eqType` k1 = return cont -- is a no-op
1139
1140 add_coerce co1 (Pair s1 _k2) (CastIt co2 cont)
1141 | (Pair _l1 t1) <- coercionKind co2
1142 -- e |> (g1 :: S1~L) |> (g2 :: L~T1)
1143 -- ==>
1144 -- e, if S1=T1
1145 -- e |> (g1 . g2 :: S1~T1) otherwise
1146 --
1147 -- For example, in the initial form of a worker
1148 -- we may find (coerce T (coerce S (\x.e))) y
1149 -- and we'd like it to simplify to e[y/x] in one round
1150 -- of simplification
1151 , s1 `eqType` t1 = return cont -- The coerces cancel out
1152 | otherwise = return (CastIt (mkTransCo co1 co2) cont)
1153
1154 add_coerce co (Pair s1s2 _t1t2) cont@(ApplyToTy { sc_arg_ty = arg_ty, sc_cont = tail })
1155 -- (f |> g) ty ---> (f ty) |> (g @ ty)
1156 -- This implements the PushT rule from the paper
1157 | Just (tyvar,_) <- splitForAllTy_maybe s1s2
1158 = ASSERT( isTyVar tyvar )
1159 do { cont' <- addCoerce new_cast tail
1160 ; return (cont { sc_cont = cont' }) }
1161 where
1162 new_cast = mkInstCo co arg_ty
1163
1164 add_coerce co (Pair s1s2 t1t2) (ApplyToVal { sc_arg = arg, sc_env = arg_se
1165 , sc_dup = dup, sc_cont = cont })
1166 | isFunTy s1s2 -- This implements the Push rule from the paper
1167 , isFunTy t1t2 -- Check t1t2 to ensure 'arg' is a value arg
1168 -- (e |> (g :: s1s2 ~ t1->t2)) f
1169 -- ===>
1170 -- (e (f |> (arg g :: t1~s1))
1171 -- |> (res g :: s2->t2)
1172 --
1173 -- t1t2 must be a function type, t1->t2, because it's applied
1174 -- to something but s1s2 might conceivably not be
1175 --
1176 -- When we build the ApplyTo we can't mix the out-types
1177 -- with the InExpr in the argument, so we simply substitute
1178 -- to make it all consistent. It's a bit messy.
1179 -- But it isn't a common case.
1180 --
1181 -- Example of use: Trac #995
1182 = do { (dup', arg_se', arg') <- simplArg env dup arg_se arg
1183 ; cont' <- addCoerce co2 cont
1184 ; return (ApplyToVal { sc_arg = mkCast arg' (mkSymCo co1)
1185 , sc_env = arg_se'
1186 , sc_dup = dup'
1187 , sc_cont = cont' }) }
1188 where
1189 -- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and
1190 -- t2 ~ s2 with left and right on the curried form:
1191 -- (->) t1 t2 ~ (->) s1 s2
1192 [co1, co2] = decomposeCo 2 co
1193
1194 add_coerce co _ cont = return (CastIt co cont)
1195
1196 simplArg :: SimplEnv -> DupFlag -> StaticEnv -> CoreExpr
1197 -> SimplM (DupFlag, StaticEnv, OutExpr)
1198 simplArg env dup_flag arg_env arg
1199 | isSimplified dup_flag
1200 = return (dup_flag, arg_env, arg)
1201 | otherwise
1202 = do { arg' <- simplExpr (arg_env `setInScope` env) arg
1203 ; return (Simplified, zapSubstEnv arg_env, arg') }
1204
1205 {-
1206 ************************************************************************
1207 * *
1208 \subsection{Lambdas}
1209 * *
1210 ************************************************************************
1211
1212 Note [Zap unfolding when beta-reducing]
1213 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1214 Lambda-bound variables can have stable unfoldings, such as
1215 $j = \x. \b{Unf=Just x}. e
1216 See Note [Case binders and join points] below; the unfolding for lets
1217 us optimise e better. However when we beta-reduce it we want to
1218 revert to using the actual value, otherwise we can end up in the
1219 stupid situation of
1220 let x = blah in
1221 let b{Unf=Just x} = y
1222 in ...b...
1223 Here it'd be far better to drop the unfolding and use the actual RHS.
1224 -}
1225
1226 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
1227 -> SimplM (SimplEnv, OutExpr)
1228
1229 simplLam env [] body cont = simplExprF env body cont
1230
1231 -- Beta reduction
1232
1233 simplLam env (bndr:bndrs) body (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
1234 = do { tick (BetaReduction bndr)
1235 ; simplLam (extendTvSubst env bndr arg_ty) bndrs body cont }
1236
1237 simplLam env (bndr:bndrs) body (ApplyToVal { sc_arg = arg, sc_env = arg_se
1238 , sc_cont = cont })
1239 = do { tick (BetaReduction bndr)
1240 ; simplNonRecE env (zap_unfolding bndr) (arg, arg_se) (bndrs, body) cont }
1241 where
1242 zap_unfolding bndr -- See Note [Zap unfolding when beta-reducing]
1243 | isId bndr, isStableUnfolding (realIdUnfolding bndr)
1244 = setIdUnfolding bndr NoUnfolding
1245 | otherwise = bndr
1246
1247 -- discard a non-counting tick on a lambda. This may change the
1248 -- cost attribution slightly (moving the allocation of the
1249 -- lambda elsewhere), but we don't care: optimisation changes
1250 -- cost attribution all the time.
1251 simplLam env bndrs body (TickIt tickish cont)
1252 | not (tickishCounts tickish)
1253 = simplLam env bndrs body cont
1254
1255 -- Not enough args, so there are real lambdas left to put in the result
1256 simplLam env bndrs body cont
1257 = do { (env', bndrs') <- simplLamBndrs env bndrs
1258 ; body' <- simplExpr env' body
1259 ; new_lam <- mkLam bndrs' body' cont
1260 ; rebuild env' new_lam cont }
1261
1262 simplLamBndrs :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr])
1263 simplLamBndrs env bndrs = mapAccumLM simplLamBndr env bndrs
1264
1265 -------------
1266 simplLamBndr :: SimplEnv -> Var -> SimplM (SimplEnv, Var)
1267 -- Used for lambda binders. These sometimes have unfoldings added by
1268 -- the worker/wrapper pass that must be preserved, because they can't
1269 -- be reconstructed from context. For example:
1270 -- f x = case x of (a,b) -> fw a b x
1271 -- fw a b x{=(a,b)} = ...
1272 -- The "{=(a,b)}" is an unfolding we can't reconstruct otherwise.
1273 simplLamBndr env bndr
1274 | isId bndr && hasSomeUnfolding old_unf -- Special case
1275 = do { (env1, bndr1) <- simplBinder env bndr
1276 ; unf' <- simplUnfolding env1 NotTopLevel bndr old_unf
1277 ; let bndr2 = bndr1 `setIdUnfolding` unf'
1278 ; return (modifyInScope env1 bndr2, bndr2) }
1279
1280 | otherwise
1281 = simplBinder env bndr -- Normal case
1282 where
1283 old_unf = idUnfolding bndr
1284
1285 ------------------
1286 simplNonRecE :: SimplEnv
1287 -> InBndr -- The binder
1288 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
1289 -> ([InBndr], InExpr) -- Body of the let/lambda
1290 -- \xs.e
1291 -> SimplCont
1292 -> SimplM (SimplEnv, OutExpr)
1293
1294 -- simplNonRecE is used for
1295 -- * non-top-level non-recursive lets in expressions
1296 -- * beta reduction
1297 --
1298 -- It deals with strict bindings, via the StrictBind continuation,
1299 -- which may abort the whole process
1300 --
1301 -- Precondition: rhs satisfies the let/app invariant
1302 -- Note [CoreSyn let/app invariant] in CoreSyn
1303 --
1304 -- The "body" of the binding comes as a pair of ([InId],InExpr)
1305 -- representing a lambda; so we recurse back to simplLam
1306 -- Why? Because of the binder-occ-info-zapping done before
1307 -- the call to simplLam in simplExprF (Lam ...)
1308
1309 -- First deal with type applications and type lets
1310 -- (/\a. e) (Type ty) and (let a = Type ty in e)
1311 simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont
1312 = ASSERT( isTyVar bndr )
1313 do { ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg
1314 ; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }
1315
1316 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
1317 = do dflags <- getDynFlags
1318 case () of
1319 _ | preInlineUnconditionally dflags env NotTopLevel bndr rhs
1320 -> do { tick (PreInlineUnconditionally bndr)
1321 ; -- pprTrace "preInlineUncond" (ppr bndr <+> ppr rhs) $
1322 simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
1323
1324 | isStrictId bndr -- Includes coercions
1325 -> simplExprF (rhs_se `setFloats` env) rhs
1326 (StrictBind bndr bndrs body env cont)
1327
1328 | otherwise
1329 -> ASSERT( not (isTyVar bndr) )
1330 do { (env1, bndr1) <- simplNonRecBndr env bndr
1331 ; (env2, bndr2) <- addBndrRules env1 bndr bndr1
1332 ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
1333 ; simplLam env3 bndrs body cont }
1334
1335 {-
1336 ************************************************************************
1337 * *
1338 Variables
1339 * *
1340 ************************************************************************
1341 -}
1342
1343 simplVar :: SimplEnv -> InVar -> SimplM OutExpr
1344 -- Look up an InVar in the environment
1345 simplVar env var
1346 | isTyVar var = return (Type (substTyVar env var))
1347 | isCoVar var = return (Coercion (substCoVar env var))
1348 | otherwise
1349 = case substId env var of
1350 DoneId var1 -> return (Var var1)
1351 DoneEx e -> return e
1352 ContEx tvs cvs ids e -> simplExpr (setSubstEnv env tvs cvs ids) e
1353
1354 simplIdF :: SimplEnv -> InId -> SimplCont -> SimplM (SimplEnv, OutExpr)
1355 simplIdF env var cont
1356 = case substId env var of
1357 DoneEx e -> simplExprF (zapSubstEnv env) e cont
1358 ContEx tvs cvs ids e -> simplExprF (setSubstEnv env tvs cvs ids) e cont
1359 DoneId var1 -> completeCall env var1 cont
1360 -- Note [zapSubstEnv]
1361 -- The template is already simplified, so don't re-substitute.
1362 -- This is VITAL. Consider
1363 -- let x = e in
1364 -- let y = \z -> ...x... in
1365 -- \ x -> ...y...
1366 -- We'll clone the inner \x, adding x->x' in the id_subst
1367 -- Then when we inline y, we must *not* replace x by x' in
1368 -- the inlined copy!!
1369
1370 ---------------------------------------------------------
1371 -- Dealing with a call site
1372
1373 completeCall :: SimplEnv -> OutId -> SimplCont -> SimplM (SimplEnv, OutExpr)
1374 completeCall env var cont
1375 = do { ------------- Try inlining ----------------
1376 dflags <- getDynFlags
1377 ; let (lone_variable, arg_infos, call_cont) = contArgs cont
1378 n_val_args = length arg_infos
1379 interesting_cont = interestingCallContext call_cont
1380 unfolding = activeUnfolding env var
1381 maybe_inline = callSiteInline dflags var unfolding
1382 lone_variable arg_infos interesting_cont
1383 ; case maybe_inline of {
1384 Just expr -- There is an inlining!
1385 -> do { checkedTick (UnfoldingDone var)
1386 ; dump_inline dflags expr cont
1387 ; simplExprF (zapSubstEnv env) expr cont }
1388
1389 ; Nothing -> do -- No inlining!
1390
1391 { rule_base <- getSimplRules
1392 ; let info = mkArgInfo var (getRules rule_base var) n_val_args call_cont
1393 ; rebuildCall env info cont
1394 }}}
1395 where
1396 dump_inline dflags unfolding cont
1397 | not (dopt Opt_D_dump_inlinings dflags) = return ()
1398 | not (dopt Opt_D_verbose_core2core dflags)
1399 = when (isExternalName (idName var)) $
1400 liftIO $ printOutputForUser dflags alwaysQualify $
1401 sep [text "Inlining done:", nest 4 (ppr var)]
1402 | otherwise
1403 = liftIO $ printOutputForUser dflags alwaysQualify $
1404 sep [text "Inlining done: " <> ppr var,
1405 nest 4 (vcat [text "Inlined fn: " <+> nest 2 (ppr unfolding),
1406 text "Cont: " <+> ppr cont])]
1407
1408 rebuildCall :: SimplEnv
1409 -> ArgInfo
1410 -> SimplCont
1411 -> SimplM (SimplEnv, OutExpr)
1412 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_strs = [] }) cont
1413 -- When we run out of strictness args, it means
1414 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1415 -- Then we want to discard the entire strict continuation. E.g.
1416 -- * case (error "hello") of { ... }
1417 -- * (error "Hello") arg
1418 -- * f (error "Hello") where f is strict
1419 -- etc
1420 -- Then, especially in the first of these cases, we'd like to discard
1421 -- the continuation, leaving just the bottoming expression. But the
1422 -- type might not be right, so we may have to add a coerce.
1423 | not (contIsTrivial cont) -- Only do this if there is a non-trivial
1424 = return (env, castBottomExpr res cont_ty) -- contination to discard, else we do it
1425 where -- again and again!
1426 res = argInfoExpr fun rev_args
1427 cont_ty = contResultType cont
1428
1429 rebuildCall env info (CastIt co cont)
1430 = rebuildCall env (addCastTo info co) cont
1431
1432 rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
1433 = rebuildCall env (info `addTyArgTo` arg_ty) cont
1434
1435 rebuildCall env info@(ArgInfo { ai_encl = encl_rules, ai_type = fun_ty
1436 , ai_strs = str:strs, ai_discs = disc:discs })
1437 (ApplyToVal { sc_arg = arg, sc_env = arg_se
1438 , sc_dup = dup_flag, sc_cont = cont })
1439 | isSimplified dup_flag -- See Note [Avoid redundant simplification]
1440 = rebuildCall env (addValArgTo info' arg) cont
1441
1442 | str -- Strict argument
1443 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1444 simplExprF (arg_se `setFloats` env) arg
1445 (StrictArg info' cci cont)
1446 -- Note [Shadowing]
1447
1448 | otherwise -- Lazy argument
1449 -- DO NOT float anything outside, hence simplExprC
1450 -- There is no benefit (unlike in a let-binding), and we'd
1451 -- have to be very careful about bogus strictness through
1452 -- floating a demanded let.
1453 = do { arg' <- simplExprC (arg_se `setInScope` env) arg
1454 (mkLazyArgStop (funArgTy fun_ty) cci)
1455 ; rebuildCall env (addValArgTo info' arg') cont }
1456 where
1457 info' = info { ai_strs = strs, ai_discs = discs }
1458 cci | encl_rules = RuleArgCtxt
1459 | disc > 0 = DiscArgCtxt -- Be keener here
1460 | otherwise = BoringCtxt -- Nothing interesting
1461
1462 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_rules = rules }) cont
1463 | null rules
1464 = rebuild env (argInfoExpr fun rev_args) cont -- No rules, common case
1465
1466 | otherwise
1467 = do { -- We've accumulated a simplified call in <fun,rev_args>
1468 -- so try rewrite rules; see Note [RULEs apply to simplified arguments]
1469 -- See also Note [Rules for recursive functions]
1470 ; let env' = zapSubstEnv env -- See Note [zapSubstEnv];
1471 -- and NB that 'rev_args' are all fully simplified
1472 ; mb_rule <- tryRules env' rules fun (reverse rev_args) cont
1473 ; case mb_rule of {
1474 Just (rule_rhs, cont') -> simplExprF env' rule_rhs cont'
1475
1476 -- Rules don't match
1477 ; Nothing -> rebuild env (argInfoExpr fun rev_args) cont -- No rules
1478 } }
1479
1480 {-
1481 Note [RULES apply to simplified arguments]
1482 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1483 It's very desirable to try RULES once the arguments have been simplified, because
1484 doing so ensures that rule cascades work in one pass. Consider
1485 {-# RULES g (h x) = k x
1486 f (k x) = x #-}
1487 ...f (g (h x))...
1488 Then we want to rewrite (g (h x)) to (k x) and only then try f's rules. If
1489 we match f's rules against the un-simplified RHS, it won't match. This
1490 makes a particularly big difference when superclass selectors are involved:
1491 op ($p1 ($p2 (df d)))
1492 We want all this to unravel in one sweeep.
1493
1494 Note [Avoid redundant simplification]
1495 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1496 Because RULES apply to simplified arguments, there's a danger of repeatedly
1497 simplifying already-simplified arguments. An important example is that of
1498 (>>=) d e1 e2
1499 Here e1, e2 are simplified before the rule is applied, but don't really
1500 participate in the rule firing. So we mark them as Simplified to avoid
1501 re-simplifying them.
1502
1503 Note [Shadowing]
1504 ~~~~~~~~~~~~~~~~
1505 This part of the simplifier may break the no-shadowing invariant
1506 Consider
1507 f (...(\a -> e)...) (case y of (a,b) -> e')
1508 where f is strict in its second arg
1509 If we simplify the innermost one first we get (...(\a -> e)...)
1510 Simplifying the second arg makes us float the case out, so we end up with
1511 case y of (a,b) -> f (...(\a -> e)...) e'
1512 So the output does not have the no-shadowing invariant. However, there is
1513 no danger of getting name-capture, because when the first arg was simplified
1514 we used an in-scope set that at least mentioned all the variables free in its
1515 static environment, and that is enough.
1516
1517 We can't just do innermost first, or we'd end up with a dual problem:
1518 case x of (a,b) -> f e (...(\a -> e')...)
1519
1520 I spent hours trying to recover the no-shadowing invariant, but I just could
1521 not think of an elegant way to do it. The simplifier is already knee-deep in
1522 continuations. We have to keep the right in-scope set around; AND we have
1523 to get the effect that finding (error "foo") in a strict arg position will
1524 discard the entire application and replace it with (error "foo"). Getting
1525 all this at once is TOO HARD!
1526
1527
1528 ************************************************************************
1529 * *
1530 Rewrite rules
1531 * *
1532 ************************************************************************
1533 -}
1534
1535 tryRules :: SimplEnv -> [CoreRule]
1536 -> Id -> [ArgSpec] -> SimplCont
1537 -> SimplM (Maybe (CoreExpr, SimplCont))
1538 -- The SimplEnv already has zapSubstEnv applied to it
1539
1540 tryRules env rules fn args call_cont
1541 | null rules
1542 = return Nothing
1543 {- Disabled until we fix #8326
1544 | fn `hasKey` tagToEnumKey -- See Note [Optimising tagToEnum#]
1545 , [_type_arg, val_arg] <- args
1546 , Select dup bndr ((_,[],rhs1) : rest_alts) se cont <- call_cont
1547 , isDeadBinder bndr
1548 = do { dflags <- getDynFlags
1549 ; let enum_to_tag :: CoreAlt -> CoreAlt
1550 -- Takes K -> e into tagK# -> e
1551 -- where tagK# is the tag of constructor K
1552 enum_to_tag (DataAlt con, [], rhs)
1553 = ASSERT( isEnumerationTyCon (dataConTyCon con) )
1554 (LitAlt tag, [], rhs)
1555 where
1556 tag = mkMachInt dflags (toInteger (dataConTag con - fIRST_TAG))
1557 enum_to_tag alt = pprPanic "tryRules: tagToEnum" (ppr alt)
1558
1559 new_alts = (DEFAULT, [], rhs1) : map enum_to_tag rest_alts
1560 new_bndr = setIdType bndr intPrimTy
1561 -- The binder is dead, but should have the right type
1562 ; return (Just (val_arg, Select dup new_bndr new_alts se cont)) }
1563 -}
1564 | otherwise
1565 = do { dflags <- getDynFlags
1566 ; case lookupRule dflags (getUnfoldingInRuleMatch env) (activeRule env)
1567 fn (argInfoAppArgs args) rules of {
1568 Nothing -> return Nothing ; -- No rule matches
1569 Just (rule, rule_rhs) ->
1570 do { checkedTick (RuleFired (ru_name rule))
1571 ; let cont' = pushSimplifiedArgs env
1572 (drop (ruleArity rule) args)
1573 call_cont
1574 -- (ruleArity rule) says how many args the rule consumed
1575 ; dump dflags rule rule_rhs
1576 ; return (Just (rule_rhs, cont')) }}}
1577 where
1578 dump dflags rule rule_rhs
1579 | dopt Opt_D_dump_rule_rewrites dflags
1580 = log_rule dflags Opt_D_dump_rule_rewrites "Rule fired" $ vcat
1581 [ text "Rule:" <+> ftext (ru_name rule)
1582 , text "Before:" <+> hang (ppr fn) 2 (sep (map ppr args))
1583 , text "After: " <+> pprCoreExpr rule_rhs
1584 , text "Cont: " <+> ppr call_cont ]
1585
1586 | dopt Opt_D_dump_rule_firings dflags
1587 = log_rule dflags Opt_D_dump_rule_firings "Rule fired:" $
1588 ftext (ru_name rule)
1589
1590 | otherwise
1591 = return ()
1592
1593 log_rule dflags flag hdr details
1594 = liftIO . dumpSDoc dflags alwaysQualify flag "" $
1595 sep [text hdr, nest 4 details]
1596
1597 {-
1598 Note [Optimising tagToEnum#]
1599 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1600 If we have an enumeration data type:
1601
1602 data Foo = A | B | C
1603
1604 Then we want to transform
1605
1606 case tagToEnum# x of ==> case x of
1607 A -> e1 DEFAULT -> e1
1608 B -> e2 1# -> e2
1609 C -> e3 2# -> e3
1610
1611 thereby getting rid of the tagToEnum# altogether. If there was a DEFAULT
1612 alternative we retain it (remember it comes first). If not the case must
1613 be exhaustive, and we reflect that in the transformed version by adding
1614 a DEFAULT. Otherwise Lint complains that the new case is not exhaustive.
1615 See #8317.
1616
1617 Note [Rules for recursive functions]
1618 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1619 You might think that we shouldn't apply rules for a loop breaker:
1620 doing so might give rise to an infinite loop, because a RULE is
1621 rather like an extra equation for the function:
1622 RULE: f (g x) y = x+y
1623 Eqn: f a y = a-y
1624
1625 But it's too drastic to disable rules for loop breakers.
1626 Even the foldr/build rule would be disabled, because foldr
1627 is recursive, and hence a loop breaker:
1628 foldr k z (build g) = g k z
1629 So it's up to the programmer: rules can cause divergence
1630
1631
1632 ************************************************************************
1633 * *
1634 Rebuilding a case expression
1635 * *
1636 ************************************************************************
1637
1638 Note [Case elimination]
1639 ~~~~~~~~~~~~~~~~~~~~~~~
1640 The case-elimination transformation discards redundant case expressions.
1641 Start with a simple situation:
1642
1643 case x# of ===> let y# = x# in e
1644 y# -> e
1645
1646 (when x#, y# are of primitive type, of course). We can't (in general)
1647 do this for algebraic cases, because we might turn bottom into
1648 non-bottom!
1649
1650 The code in SimplUtils.prepareAlts has the effect of generalise this
1651 idea to look for a case where we're scrutinising a variable, and we
1652 know that only the default case can match. For example:
1653
1654 case x of
1655 0# -> ...
1656 DEFAULT -> ...(case x of
1657 0# -> ...
1658 DEFAULT -> ...) ...
1659
1660 Here the inner case is first trimmed to have only one alternative, the
1661 DEFAULT, after which it's an instance of the previous case. This
1662 really only shows up in eliminating error-checking code.
1663
1664 Note that SimplUtils.mkCase combines identical RHSs. So
1665
1666 case e of ===> case e of DEFAULT -> r
1667 True -> r
1668 False -> r
1669
1670 Now again the case may be elminated by the CaseElim transformation.
1671 This includes things like (==# a# b#)::Bool so that we simplify
1672 case ==# a# b# of { True -> x; False -> x }
1673 to just
1674 x
1675 This particular example shows up in default methods for
1676 comparison operations (e.g. in (>=) for Int.Int32)
1677
1678 Note [Case elimination: lifted case]
1679 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1680 If a case over a lifted type has a single alternative, and is being used
1681 as a strict 'let' (all isDeadBinder bndrs), we may want to do this
1682 transformation:
1683
1684 case e of r ===> let r = e in ...r...
1685 _ -> ...r...
1686
1687 (a) 'e' is already evaluated (it may so if e is a variable)
1688 Specifically we check (exprIsHNF e). In this case
1689 we can just allocate the WHNF directly with a let.
1690 or
1691 (b) 'x' is not used at all and e is ok-for-speculation
1692 The ok-for-spec bit checks that we don't lose any
1693 exceptions or divergence.
1694
1695 NB: it'd be *sound* to switch from case to let if the
1696 scrutinee was not yet WHNF but was guaranteed to
1697 converge; but sticking with case means we won't build a
1698 thunk
1699
1700 or
1701 (c) 'x' is used strictly in the body, and 'e' is a variable
1702 Then we can just substitute 'e' for 'x' in the body.
1703 See Note [Eliminating redundant seqs]
1704
1705 For (b), the "not used at all" test is important. Consider
1706 case (case a ># b of { True -> (p,q); False -> (q,p) }) of
1707 r -> blah
1708 The scrutinee is ok-for-speculation (it looks inside cases), but we do
1709 not want to transform to
1710 let r = case a ># b of { True -> (p,q); False -> (q,p) }
1711 in blah
1712 because that builds an unnecessary thunk.
1713
1714 Note [Eliminating redundant seqs]
1715 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1716 If we have this:
1717 case x of r { _ -> ..r.. }
1718 where 'r' is used strictly in (..r..), the case is effectively a 'seq'
1719 on 'x', but since 'r' is used strictly anyway, we can safely transform to
1720 (...x...)
1721
1722 Note that this can change the error behaviour. For example, we might
1723 transform
1724 case x of { _ -> error "bad" }
1725 --> error "bad"
1726 which is might be puzzling if 'x' currently lambda-bound, but later gets
1727 let-bound to (error "good").
1728
1729 Nevertheless, the paper "A semantics for imprecise exceptions" allows
1730 this transformation. If you want to fix the evaluation order, use
1731 'pseq'. See Trac #8900 for an example where the loss of this
1732 transformation bit us in practice.
1733
1734 See also Note [Empty case alternatives] in CoreSyn.
1735
1736 Just for reference, the original code (added Jan 13) looked like this:
1737 || case_bndr_evald_next rhs
1738
1739 case_bndr_evald_next :: CoreExpr -> Bool
1740 -- See Note [Case binder next]
1741 case_bndr_evald_next (Var v) = v == case_bndr
1742 case_bndr_evald_next (Cast e _) = case_bndr_evald_next e
1743 case_bndr_evald_next (App e _) = case_bndr_evald_next e
1744 case_bndr_evald_next (Case e _ _ _) = case_bndr_evald_next e
1745 case_bndr_evald_next _ = False
1746
1747 (This came up when fixing Trac #7542. See also Note [Eta reduction of
1748 an eval'd function] in CoreUtils.)
1749
1750
1751 Note [Case elimination: unlifted case]
1752 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1753 Consider
1754 case a +# b of r -> ...r...
1755 Then we do case-elimination (to make a let) followed by inlining,
1756 to get
1757 .....(a +# b)....
1758 If we have
1759 case indexArray# a i of r -> ...r...
1760 we might like to do the same, and inline the (indexArray# a i).
1761 But indexArray# is not okForSpeculation, so we don't build a let
1762 in rebuildCase (lest it get floated *out*), so the inlining doesn't
1763 happen either.
1764
1765 This really isn't a big deal I think. The let can be
1766
1767
1768 Further notes about case elimination
1769 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1770 Consider: test :: Integer -> IO ()
1771 test = print
1772
1773 Turns out that this compiles to:
1774 Print.test
1775 = \ eta :: Integer
1776 eta1 :: Void# ->
1777 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1778 case hPutStr stdout
1779 (PrelNum.jtos eta ($w[] @ Char))
1780 eta1
1781 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
1782
1783 Notice the strange '<' which has no effect at all. This is a funny one.
1784 It started like this:
1785
1786 f x y = if x < 0 then jtos x
1787 else if y==0 then "" else jtos x
1788
1789 At a particular call site we have (f v 1). So we inline to get
1790
1791 if v < 0 then jtos x
1792 else if 1==0 then "" else jtos x
1793
1794 Now simplify the 1==0 conditional:
1795
1796 if v<0 then jtos v else jtos v
1797
1798 Now common-up the two branches of the case:
1799
1800 case (v<0) of DEFAULT -> jtos v
1801
1802 Why don't we drop the case? Because it's strict in v. It's technically
1803 wrong to drop even unnecessary evaluations, and in practice they
1804 may be a result of 'seq' so we *definitely* don't want to drop those.
1805 I don't really know how to improve this situation.
1806 -}
1807
1808 ---------------------------------------------------------
1809 -- Eliminate the case if possible
1810
1811 rebuildCase, reallyRebuildCase
1812 :: SimplEnv
1813 -> OutExpr -- Scrutinee
1814 -> InId -- Case binder
1815 -> [InAlt] -- Alternatives (inceasing order)
1816 -> SimplCont
1817 -> SimplM (SimplEnv, OutExpr)
1818
1819 --------------------------------------------------
1820 -- 1. Eliminate the case if there's a known constructor
1821 --------------------------------------------------
1822
1823 rebuildCase env scrut case_bndr alts cont
1824 | Lit lit <- scrut -- No need for same treatment as constructors
1825 -- because literals are inlined more vigorously
1826 , not (litIsLifted lit)
1827 = do { tick (KnownBranch case_bndr)
1828 ; case findAlt (LitAlt lit) alts of
1829 Nothing -> missingAlt env case_bndr alts cont
1830 Just (_, bs, rhs) -> simple_rhs bs rhs }
1831
1832 | Just (con, ty_args, other_args) <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut
1833 -- Works when the scrutinee is a variable with a known unfolding
1834 -- as well as when it's an explicit constructor application
1835 = do { tick (KnownBranch case_bndr)
1836 ; case findAlt (DataAlt con) alts of
1837 Nothing -> missingAlt env case_bndr alts cont
1838 Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
1839 Just (_, bs, rhs) -> knownCon env scrut con ty_args other_args
1840 case_bndr bs rhs cont
1841 }
1842 where
1843 simple_rhs bs rhs = ASSERT( null bs )
1844 do { env' <- simplNonRecX env case_bndr scrut
1845 -- scrut is a constructor application,
1846 -- hence satisfies let/app invariant
1847 ; simplExprF env' rhs cont }
1848
1849
1850 --------------------------------------------------
1851 -- 2. Eliminate the case if scrutinee is evaluated
1852 --------------------------------------------------
1853
1854 rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
1855 -- See if we can get rid of the case altogether
1856 -- See Note [Case elimination]
1857 -- mkCase made sure that if all the alternatives are equal,
1858 -- then there is now only one (DEFAULT) rhs
1859
1860 -- 2a. Dropping the case altogether, if
1861 -- a) it binds nothing (so it's really just a 'seq')
1862 -- b) evaluating the scrutinee has no side effects
1863 | is_plain_seq
1864 , exprOkForSideEffects scrut
1865 -- The entire case is dead, so we can drop it
1866 -- if the scrutinee converges without having imperative
1867 -- side effects or raising a Haskell exception
1868 -- See Note [PrimOp can_fail and has_side_effects] in PrimOp
1869 = simplExprF env rhs cont
1870
1871 -- 2b. Turn the case into a let, if
1872 -- a) it binds only the case-binder
1873 -- b) unlifted case: the scrutinee is ok-for-speculation
1874 -- lifted case: the scrutinee is in HNF (or will later be demanded)
1875 | all_dead_bndrs
1876 , if is_unlifted
1877 then exprOkForSpeculation scrut -- See Note [Case elimination: unlifted case]
1878 else exprIsHNF scrut -- See Note [Case elimination: lifted case]
1879 || scrut_is_demanded_var scrut
1880 = do { tick (CaseElim case_bndr)
1881 ; env' <- simplNonRecX env case_bndr scrut
1882 ; simplExprF env' rhs cont }
1883
1884 -- 2c. Try the seq rules if
1885 -- a) it binds only the case binder
1886 -- b) a rule for seq applies
1887 -- See Note [User-defined RULES for seq] in MkId
1888 | is_plain_seq
1889 = do { let scrut_ty = exprType scrut
1890 rhs_ty = substTy env (exprType rhs)
1891 out_args = [ TyArg { as_arg_ty = scrut_ty
1892 , as_hole_ty = seq_id_ty }
1893 , TyArg { as_arg_ty = rhs_ty
1894 , as_hole_ty = applyTy seq_id_ty scrut_ty }
1895 , ValArg scrut]
1896 rule_cont = ApplyToVal { sc_dup = NoDup, sc_arg = rhs
1897 , sc_env = env, sc_cont = cont }
1898 env' = zapSubstEnv env
1899 -- Lazily evaluated, so we don't do most of this
1900
1901 ; rule_base <- getSimplRules
1902 ; mb_rule <- tryRules env' (getRules rule_base seqId) seqId out_args rule_cont
1903 ; case mb_rule of
1904 Just (rule_rhs, cont') -> simplExprF env' rule_rhs cont'
1905 Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
1906 where
1907 is_unlifted = isUnLiftedType (idType case_bndr)
1908 all_dead_bndrs = all isDeadBinder bndrs -- bndrs are [InId]
1909 is_plain_seq = all_dead_bndrs && isDeadBinder case_bndr -- Evaluation *only* for effect
1910 seq_id_ty = idType seqId
1911
1912 scrut_is_demanded_var :: CoreExpr -> Bool
1913 -- See Note [Eliminating redundant seqs]
1914 scrut_is_demanded_var (Cast s _) = scrut_is_demanded_var s
1915 scrut_is_demanded_var (Var _) = isStrictDmd (idDemandInfo case_bndr)
1916 scrut_is_demanded_var _ = False
1917
1918
1919 rebuildCase env scrut case_bndr alts cont
1920 = reallyRebuildCase env scrut case_bndr alts cont
1921
1922 --------------------------------------------------
1923 -- 3. Catch-all case
1924 --------------------------------------------------
1925
1926 reallyRebuildCase env scrut case_bndr alts cont
1927 = do { -- Prepare the continuation;
1928 -- The new subst_env is in place
1929 (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
1930
1931 -- Simplify the alternatives
1932 ; (scrut', case_bndr', alts') <- simplAlts env' scrut case_bndr alts dup_cont
1933
1934 ; dflags <- getDynFlags
1935 ; let alts_ty' = contResultType dup_cont
1936 ; case_expr <- mkCase dflags scrut' case_bndr' alts_ty' alts'
1937
1938 -- Notice that rebuild gets the in-scope set from env', not alt_env
1939 -- (which in any case is only build in simplAlts)
1940 -- The case binder *not* scope over the whole returned case-expression
1941 ; rebuild env' case_expr nodup_cont }
1942
1943 {-
1944 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1945 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1946 way, there's a chance that v will now only be used once, and hence
1947 inlined.
1948
1949 Historical note: we use to do the "case binder swap" in the Simplifier
1950 so there were additional complications if the scrutinee was a variable.
1951 Now the binder-swap stuff is done in the occurrence analyer; see
1952 OccurAnal Note [Binder swap].
1953
1954 Note [knownCon occ info]
1955 ~~~~~~~~~~~~~~~~~~~~~~~~
1956 If the case binder is not dead, then neither are the pattern bound
1957 variables:
1958 case <any> of x { (a,b) ->
1959 case x of { (p,q) -> p } }
1960 Here (a,b) both look dead, but come alive after the inner case is eliminated.
1961 The point is that we bring into the envt a binding
1962 let x = (a,b)
1963 after the outer case, and that makes (a,b) alive. At least we do unless
1964 the case binder is guaranteed dead.
1965
1966 Note [Case alternative occ info]
1967 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1968 When we are simply reconstructing a case (the common case), we always
1969 zap the occurrence info on the binders in the alternatives. Even
1970 if the case binder is dead, the scrutinee is usually a variable, and *that*
1971 can bring the case-alternative binders back to life.
1972 See Note [Add unfolding for scrutinee]
1973
1974 Note [Improving seq]
1975 ~~~~~~~~~~~~~~~~~~~
1976 Consider
1977 type family F :: * -> *
1978 type instance F Int = Int
1979
1980 ... case e of x { DEFAULT -> rhs } ...
1981
1982 where x::F Int. Then we'd like to rewrite (F Int) to Int, getting
1983
1984 case e `cast` co of x'::Int
1985 I# x# -> let x = x' `cast` sym co
1986 in rhs
1987
1988 so that 'rhs' can take advantage of the form of x'.
1989
1990 Notice that Note [Case of cast] (in OccurAnal) may then apply to the result.
1991
1992 Nota Bene: We only do the [Improving seq] transformation if the
1993 case binder 'x' is actually used in the rhs; that is, if the case
1994 is *not* a *pure* seq.
1995 a) There is no point in adding the cast to a pure seq.
1996 b) There is a good reason not to: doing so would interfere
1997 with seq rules (Note [Built-in RULES for seq] in MkId).
1998 In particular, this [Improving seq] thing *adds* a cast
1999 while [Built-in RULES for seq] *removes* one, so they
2000 just flip-flop.
2001
2002 You might worry about
2003 case v of x { __DEFAULT ->
2004 ... case (v `cast` co) of y { I# -> ... }}
2005 This is a pure seq (since x is unused), so [Improving seq] won't happen.
2006 But it's ok: the simplifier will replace 'v' by 'x' in the rhs to get
2007 case v of x { __DEFAULT ->
2008 ... case (x `cast` co) of y { I# -> ... }}
2009 Now the outer case is not a pure seq, so [Improving seq] will happen,
2010 and then the inner case will disappear.
2011
2012 The need for [Improving seq] showed up in Roman's experiments. Example:
2013 foo :: F Int -> Int -> Int
2014 foo t n = t `seq` bar n
2015 where
2016 bar 0 = 0
2017 bar n = bar (n - case t of TI i -> i)
2018 Here we'd like to avoid repeated evaluating t inside the loop, by
2019 taking advantage of the `seq`.
2020
2021 At one point I did transformation in LiberateCase, but it's more
2022 robust here. (Otherwise, there's a danger that we'll simply drop the
2023 'seq' altogether, before LiberateCase gets to see it.)
2024 -}
2025
2026 simplAlts :: SimplEnv
2027 -> OutExpr
2028 -> InId -- Case binder
2029 -> [InAlt] -- Non-empty
2030 -> SimplCont
2031 -> SimplM (OutExpr, OutId, [OutAlt]) -- Includes the continuation
2032 -- Like simplExpr, this just returns the simplified alternatives;
2033 -- it does not return an environment
2034 -- The returned alternatives can be empty, none are possible
2035
2036 simplAlts env scrut case_bndr alts cont'
2037 = do { let env0 = zapFloats env
2038
2039 ; (env1, case_bndr1) <- simplBinder env0 case_bndr
2040
2041 ; fam_envs <- getFamEnvs
2042 ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env1 scrut
2043 case_bndr case_bndr1 alts
2044
2045 ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut' case_bndr' alts
2046 -- NB: it's possible that the returned in_alts is empty: this is handled
2047 -- by the caller (rebuildCase) in the missingAlt function
2048
2049 ; alts' <- mapM (simplAlt alt_env' (Just scrut') imposs_deflt_cons case_bndr' cont') in_alts
2050 ; -- pprTrace "simplAlts" (ppr case_bndr $$ ppr alts_ty $$ ppr alts_ty' $$ ppr alts $$ ppr cont') $
2051 return (scrut', case_bndr', alts') }
2052
2053
2054 ------------------------------------
2055 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
2056 -> OutExpr -> InId -> OutId -> [InAlt]
2057 -> SimplM (SimplEnv, OutExpr, OutId)
2058 -- Note [Improving seq]
2059 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
2060 | not (isDeadBinder case_bndr) -- Not a pure seq! See Note [Improving seq]
2061 , Just (co, ty2) <- topNormaliseType_maybe fam_envs (idType case_bndr1)
2062 = do { case_bndr2 <- newId (fsLit "nt") ty2
2063 ; let rhs = DoneEx (Var case_bndr2 `Cast` mkSymCo co)
2064 env2 = extendIdSubst env case_bndr rhs
2065 ; return (env2, scrut `Cast` co, case_bndr2) }
2066
2067 improveSeq _ env scrut _ case_bndr1 _
2068 = return (env, scrut, case_bndr1)
2069
2070
2071 ------------------------------------
2072 simplAlt :: SimplEnv
2073 -> Maybe OutExpr -- The scrutinee
2074 -> [AltCon] -- These constructors can't be present when
2075 -- matching the DEFAULT alternative
2076 -> OutId -- The case binder
2077 -> SimplCont
2078 -> InAlt
2079 -> SimplM OutAlt
2080
2081 simplAlt env _ imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
2082 = ASSERT( null bndrs )
2083 do { let env' = addBinderUnfolding env case_bndr'
2084 (mkOtherCon imposs_deflt_cons)
2085 -- Record the constructors that the case-binder *can't* be.
2086 ; rhs' <- simplExprC env' rhs cont'
2087 ; return (DEFAULT, [], rhs') }
2088
2089 simplAlt env scrut' _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
2090 = ASSERT( null bndrs )
2091 do { env' <- addAltUnfoldings env scrut' case_bndr' (Lit lit)
2092 ; rhs' <- simplExprC env' rhs cont'
2093 ; return (LitAlt lit, [], rhs') }
2094
2095 simplAlt env scrut' _ case_bndr' cont' (DataAlt con, vs, rhs)
2096 = do { -- Deal with the pattern-bound variables
2097 -- Mark the ones that are in ! positions in the
2098 -- data constructor as certainly-evaluated.
2099 -- NB: simplLamBinders preserves this eval info
2100 ; let vs_with_evals = add_evals (dataConRepStrictness con)
2101 ; (env', vs') <- simplLamBndrs env vs_with_evals
2102
2103 -- Bind the case-binder to (con args)
2104 ; let inst_tys' = tyConAppArgs (idType case_bndr')
2105 con_app :: OutExpr
2106 con_app = mkConApp2 con inst_tys' vs'
2107
2108 ; env'' <- addAltUnfoldings env' scrut' case_bndr' con_app
2109 ; rhs' <- simplExprC env'' rhs cont'
2110 ; return (DataAlt con, vs', rhs') }
2111 where
2112 -- add_evals records the evaluated-ness of the bound variables of
2113 -- a case pattern. This is *important*. Consider
2114 -- data T = T !Int !Int
2115 --
2116 -- case x of { T a b -> T (a+1) b }
2117 --
2118 -- We really must record that b is already evaluated so that we don't
2119 -- go and re-evaluate it when constructing the result.
2120 -- See Note [Data-con worker strictness] in MkId.hs
2121 add_evals the_strs
2122 = go vs the_strs
2123 where
2124 go [] [] = []
2125 go (v:vs') strs | isTyVar v = v : go vs' strs
2126 go (v:vs') (str:strs)
2127 | isMarkedStrict str = evald_v : go vs' strs
2128 | otherwise = zapped_v : go vs' strs
2129 where
2130 zapped_v = zapIdOccInfo v -- See Note [Case alternative occ info]
2131 evald_v = zapped_v `setIdUnfolding` evaldUnfolding
2132 go _ _ = pprPanic "cat_evals" (ppr con $$ ppr vs $$ ppr the_strs)
2133
2134
2135 addAltUnfoldings :: SimplEnv -> Maybe OutExpr -> OutId -> OutExpr -> SimplM SimplEnv
2136 addAltUnfoldings env scrut case_bndr con_app
2137 = do { dflags <- getDynFlags
2138 ; let con_app_unf = mkSimpleUnfolding dflags con_app
2139 env1 = addBinderUnfolding env case_bndr con_app_unf
2140
2141 -- See Note [Add unfolding for scrutinee]
2142 env2 = case scrut of
2143 Just (Var v) -> addBinderUnfolding env1 v con_app_unf
2144 Just (Cast (Var v) co) -> addBinderUnfolding env1 v $
2145 mkSimpleUnfolding dflags (Cast con_app (mkSymCo co))
2146 _ -> env1
2147
2148 ; traceSmpl "addAltUnf" (vcat [ppr case_bndr <+> ppr scrut, ppr con_app])
2149 ; return env2 }
2150
2151 addBinderUnfolding :: SimplEnv -> Id -> Unfolding -> SimplEnv
2152 addBinderUnfolding env bndr unf
2153 | debugIsOn, Just tmpl <- maybeUnfoldingTemplate unf
2154 = WARN( not (eqType (idType bndr) (exprType tmpl)),
2155 ppr bndr $$ ppr (idType bndr) $$ ppr tmpl $$ ppr (exprType tmpl) )
2156 modifyInScope env (bndr `setIdUnfolding` unf)
2157
2158 | otherwise
2159 = modifyInScope env (bndr `setIdUnfolding` unf)
2160
2161 zapBndrOccInfo :: Bool -> Id -> Id
2162 -- Consider case e of b { (a,b) -> ... }
2163 -- Then if we bind b to (a,b) in "...", and b is not dead,
2164 -- then we must zap the deadness info on a,b
2165 zapBndrOccInfo keep_occ_info pat_id
2166 | keep_occ_info = pat_id
2167 | otherwise = zapIdOccInfo pat_id
2168
2169 {-
2170 Note [Add unfolding for scrutinee]
2171 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2172 In general it's unlikely that a variable scrutinee will appear
2173 in the case alternatives case x of { ...x unlikely to appear... }
2174 because the binder-swap in OccAnal has got rid of all such occcurrences
2175 See Note [Binder swap] in OccAnal.
2176
2177 BUT it is still VERY IMPORTANT to add a suitable unfolding for a
2178 variable scrutinee, in simplAlt. Here's why
2179 case x of y
2180 (a,b) -> case b of c
2181 I# v -> ...(f y)...
2182 There is no occurrence of 'b' in the (...(f y)...). But y gets
2183 the unfolding (a,b), and *that* mentions b. If f has a RULE
2184 RULE f (p, I# q) = ...
2185 we want that rule to match, so we must extend the in-scope env with a
2186 suitable unfolding for 'y'. It's *essential* for rule matching; but
2187 it's also good for case-elimintation -- suppose that 'f' was inlined
2188 and did multi-level case analysis, then we'd solve it in one
2189 simplifier sweep instead of two.
2190
2191 Exactly the same issue arises in SpecConstr;
2192 see Note [Add scrutinee to ValueEnv too] in SpecConstr
2193
2194 HOWEVER, given
2195 case x of y { Just a -> r1; Nothing -> r2 }
2196 we do not want to add the unfolding x -> y to 'x', which might seem cool,
2197 since 'y' itself has different unfoldings in r1 and r2. Reason: if we
2198 did that, we'd have to zap y's deadness info and that is a very useful
2199 piece of information.
2200
2201 So instead we add the unfolding x -> Just a, and x -> Nothing in the
2202 respective RHSs.
2203
2204
2205 ************************************************************************
2206 * *
2207 \subsection{Known constructor}
2208 * *
2209 ************************************************************************
2210
2211 We are a bit careful with occurrence info. Here's an example
2212
2213 (\x* -> case x of (a*, b) -> f a) (h v, e)
2214
2215 where the * means "occurs once". This effectively becomes
2216 case (h v, e) of (a*, b) -> f a)
2217 and then
2218 let a* = h v; b = e in f a
2219 and then
2220 f (h v)
2221
2222 All this should happen in one sweep.
2223 -}
2224
2225 knownCon :: SimplEnv
2226 -> OutExpr -- The scrutinee
2227 -> DataCon -> [OutType] -> [OutExpr] -- The scrutinee (in pieces)
2228 -> InId -> [InBndr] -> InExpr -- The alternative
2229 -> SimplCont
2230 -> SimplM (SimplEnv, OutExpr)
2231
2232 knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
2233 = do { env' <- bind_args env bs dc_args
2234 ; env'' <- bind_case_bndr env'
2235 ; simplExprF env'' rhs cont }
2236 where
2237 zap_occ = zapBndrOccInfo (isDeadBinder bndr) -- bndr is an InId
2238
2239 -- Ugh!
2240 bind_args env' [] _ = return env'
2241
2242 bind_args env' (b:bs') (Type ty : args)
2243 = ASSERT( isTyVar b )
2244 bind_args (extendTvSubst env' b ty) bs' args
2245
2246 bind_args env' (b:bs') (arg : args)
2247 = ASSERT( isId b )
2248 do { let b' = zap_occ b
2249 -- Note that the binder might be "dead", because it doesn't
2250 -- occur in the RHS; and simplNonRecX may therefore discard
2251 -- it via postInlineUnconditionally.
2252 -- Nevertheless we must keep it if the case-binder is alive,
2253 -- because it may be used in the con_app. See Note [knownCon occ info]
2254 ; env'' <- simplNonRecX env' b' arg -- arg satisfies let/app invariant
2255 ; bind_args env'' bs' args }
2256
2257 bind_args _ _ _ =
2258 pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
2259 text "scrut:" <+> ppr scrut
2260
2261 -- It's useful to bind bndr to scrut, rather than to a fresh
2262 -- binding x = Con arg1 .. argn
2263 -- because very often the scrut is a variable, so we avoid
2264 -- creating, and then subsequently eliminating, a let-binding
2265 -- BUT, if scrut is a not a variable, we must be careful
2266 -- about duplicating the arg redexes; in that case, make
2267 -- a new con-app from the args
2268 bind_case_bndr env
2269 | isDeadBinder bndr = return env
2270 | exprIsTrivial scrut = return (extendIdSubst env bndr (DoneEx scrut))
2271 | otherwise = do { dc_args <- mapM (simplVar env) bs
2272 -- dc_ty_args are aready OutTypes,
2273 -- but bs are InBndrs
2274 ; let con_app = Var (dataConWorkId dc)
2275 `mkTyApps` dc_ty_args
2276 `mkApps` dc_args
2277 ; simplNonRecX env bndr con_app }
2278
2279 -------------------
2280 missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
2281 -- This isn't strictly an error, although it is unusual.
2282 -- It's possible that the simplifer might "see" that
2283 -- an inner case has no accessible alternatives before
2284 -- it "sees" that the entire branch of an outer case is
2285 -- inaccessible. So we simply put an error case here instead.
2286 missingAlt env case_bndr _ cont
2287 = WARN( True, ptext (sLit "missingAlt") <+> ppr case_bndr )
2288 return (env, mkImpossibleExpr (contResultType cont))
2289
2290 {-
2291 ************************************************************************
2292 * *
2293 \subsection{Duplicating continuations}
2294 * *
2295 ************************************************************************
2296 -}
2297
2298 prepareCaseCont :: SimplEnv
2299 -> [InAlt] -> SimplCont
2300 -> SimplM (SimplEnv,
2301 SimplCont, -- Dupable part
2302 SimplCont) -- Non-dupable part
2303 -- We are considering
2304 -- K[case _ of { p1 -> r1; ...; pn -> rn }]
2305 -- where K is some enclosing continuation for the case
2306 -- Goal: split K into two pieces Kdup,Knodup so that
2307 -- a) Kdup can be duplicated
2308 -- b) Knodup[Kdup[e]] = K[e]
2309 -- The idea is that we'll transform thus:
2310 -- Knodup[ (case _ of { p1 -> Kdup[r1]; ...; pn -> Kdup[rn] }
2311 --
2312 -- We may also return some extra bindings in SimplEnv (that scope over
2313 -- the entire continuation)
2314 --
2315 -- When case-of-case is off, just make the entire continuation non-dupable
2316
2317 prepareCaseCont env alts cont
2318 | not (sm_case_case (getMode env)) = return (env, mkBoringStop (contHoleType cont), cont)
2319 | not (many_alts alts) = return (env, cont, mkBoringStop (contResultType cont))
2320 | otherwise = mkDupableCont env cont
2321 where
2322 many_alts :: [InAlt] -> Bool -- True iff strictly > 1 non-bottom alternative
2323 many_alts [] = False -- See Note [Bottom alternatives]
2324 many_alts [_] = False
2325 many_alts (alt:alts)
2326 | is_bot_alt alt = many_alts alts
2327 | otherwise = not (all is_bot_alt alts)
2328
2329 is_bot_alt (_,_,rhs) = exprIsBottom rhs
2330
2331 {-
2332 Note [Bottom alternatives]
2333 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2334 When we have
2335 case (case x of { A -> error .. ; B -> e; C -> error ..)
2336 of alts
2337 then we can just duplicate those alts because the A and C cases
2338 will disappear immediately. This is more direct than creating
2339 join points and inlining them away; and in some cases we would
2340 not even create the join points (see Note [Single-alternative case])
2341 and we would keep the case-of-case which is silly. See Trac #4930.
2342 -}
2343
2344 mkDupableCont :: SimplEnv -> SimplCont
2345 -> SimplM (SimplEnv, SimplCont, SimplCont)
2346
2347 mkDupableCont env cont
2348 | contIsDupable cont
2349 = return (env, cont, mkBoringStop (contResultType cont))
2350
2351 mkDupableCont _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
2352
2353 mkDupableCont env (CastIt ty cont)
2354 = do { (env', dup, nodup) <- mkDupableCont env cont
2355 ; return (env', CastIt ty dup, nodup) }
2356
2357 -- Duplicating ticks for now, not sure if this is good or not
2358 mkDupableCont env cont@(TickIt{})
2359 = return (env, mkBoringStop (contHoleType cont), cont)
2360
2361 mkDupableCont env cont@(StrictBind {})
2362 = return (env, mkBoringStop (contHoleType cont), cont)
2363 -- See Note [Duplicating StrictBind]
2364
2365 mkDupableCont env (StrictArg info cci cont)
2366 -- See Note [Duplicating StrictArg]
2367 = do { (env', dup, nodup) <- mkDupableCont env cont
2368 ; (env'', args') <- mapAccumLM makeTrivialArg env' (ai_args info)
2369 ; return (env'', StrictArg (info { ai_args = args' }) cci dup, nodup) }
2370
2371 mkDupableCont env cont@(ApplyToTy { sc_cont = tail })
2372 = do { (env', dup_cont, nodup_cont) <- mkDupableCont env tail
2373 ; return (env', cont { sc_cont = dup_cont }, nodup_cont ) }
2374
2375 mkDupableCont env (ApplyToVal { sc_arg = arg, sc_dup = dup, sc_env = se, sc_cont = cont })
2376 = -- e.g. [...hole...] (...arg...)
2377 -- ==>
2378 -- let a = ...arg...
2379 -- in [...hole...] a
2380 do { (env', dup_cont, nodup_cont) <- mkDupableCont env cont
2381 ; (_, se', arg') <- simplArg env' dup se arg
2382 ; (env'', arg'') <- makeTrivial NotTopLevel env' arg'
2383 ; let app_cont = ApplyToVal { sc_arg = arg'', sc_env = se'
2384 , sc_dup = OkToDup, sc_cont = dup_cont }
2385 ; return (env'', app_cont, nodup_cont) }
2386
2387 mkDupableCont env cont@(Select _ case_bndr [(_, bs, _rhs)] _ _)
2388 -- See Note [Single-alternative case]
2389 -- | not (exprIsDupable rhs && contIsDupable case_cont)
2390 -- | not (isDeadBinder case_bndr)
2391 | all isDeadBinder bs -- InIds
2392 && not (isUnLiftedType (idType case_bndr))
2393 -- Note [Single-alternative-unlifted]
2394 = return (env, mkBoringStop (contHoleType cont), cont)
2395
2396 mkDupableCont env (Select _ case_bndr alts se cont)
2397 = -- e.g. (case [...hole...] of { pi -> ei })
2398 -- ===>
2399 -- let ji = \xij -> ei
2400 -- in case [...hole...] of { pi -> ji xij }
2401 do { tick (CaseOfCase case_bndr)
2402 ; (env', dup_cont, nodup_cont) <- prepareCaseCont env alts cont
2403 -- NB: We call prepareCaseCont here. If there is only one
2404 -- alternative, then dup_cont may be big, but that's ok
2405 -- because we push it into the single alternative, and then
2406 -- use mkDupableAlt to turn that simplified alternative into
2407 -- a join point if it's too big to duplicate.
2408 -- And this is important: see Note [Fusing case continuations]
2409
2410 ; let alt_env = se `setInScope` env'
2411
2412 ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
2413 ; alts' <- mapM (simplAlt alt_env' Nothing [] case_bndr' dup_cont) alts
2414 -- Safe to say that there are no handled-cons for the DEFAULT case
2415 -- NB: simplBinder does not zap deadness occ-info, so
2416 -- a dead case_bndr' will still advertise its deadness
2417 -- This is really important because in
2418 -- case e of b { (# p,q #) -> ... }
2419 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
2420 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
2421 -- In the new alts we build, we have the new case binder, so it must retain
2422 -- its deadness.
2423 -- NB: we don't use alt_env further; it has the substEnv for
2424 -- the alternatives, and we don't want that
2425
2426 ; (env'', alts'') <- mkDupableAlts env' case_bndr' alts'
2427 ; return (env'', -- Note [Duplicated env]
2428 Select OkToDup case_bndr' alts'' (zapSubstEnv env'')
2429 (mkBoringStop (contHoleType nodup_cont)),
2430 nodup_cont) }
2431
2432
2433 mkDupableAlts :: SimplEnv -> OutId -> [InAlt]
2434 -> SimplM (SimplEnv, [InAlt])
2435 -- Absorbs the continuation into the new alternatives
2436
2437 mkDupableAlts env case_bndr' the_alts
2438 = go env the_alts
2439 where
2440 go env0 [] = return (env0, [])
2441 go env0 (alt:alts)
2442 = do { (env1, alt') <- mkDupableAlt env0 case_bndr' alt
2443 ; (env2, alts') <- go env1 alts
2444 ; return (env2, alt' : alts' ) }
2445
2446 mkDupableAlt :: SimplEnv -> OutId -> (AltCon, [CoreBndr], CoreExpr)
2447 -> SimplM (SimplEnv, (AltCon, [CoreBndr], CoreExpr))
2448 mkDupableAlt env case_bndr (con, bndrs', rhs') = do
2449 dflags <- getDynFlags
2450 if exprIsDupable dflags rhs' -- Note [Small alternative rhs]
2451 then return (env, (con, bndrs', rhs'))
2452 else
2453 do { let rhs_ty' = exprType rhs'
2454 scrut_ty = idType case_bndr
2455 case_bndr_w_unf
2456 = case con of
2457 DEFAULT -> case_bndr
2458 DataAlt dc -> setIdUnfolding case_bndr unf
2459 where
2460 -- See Note [Case binders and join points]
2461 unf = mkInlineUnfolding Nothing rhs
2462 rhs = mkConApp2 dc (tyConAppArgs scrut_ty) bndrs'
2463
2464 LitAlt {} -> WARN( True, ptext (sLit "mkDupableAlt")
2465 <+> ppr case_bndr <+> ppr con )
2466 case_bndr
2467 -- The case binder is alive but trivial, so why has
2468 -- it not been substituted away?
2469
2470 used_bndrs' | isDeadBinder case_bndr = filter abstract_over bndrs'
2471 | otherwise = bndrs' ++ [case_bndr_w_unf]
2472
2473 abstract_over bndr
2474 | isTyVar bndr = True -- Abstract over all type variables just in case
2475 | otherwise = not (isDeadBinder bndr)
2476 -- The deadness info on the new Ids is preserved by simplBinders
2477
2478 ; (final_bndrs', final_args) -- Note [Join point abstraction]
2479 <- if (any isId used_bndrs')
2480 then return (used_bndrs', varsToCoreExprs used_bndrs')
2481 else do { rw_id <- newId (fsLit "w") voidPrimTy
2482 ; return ([setOneShotLambda rw_id], [Var voidPrimId]) }
2483
2484 ; join_bndr <- newId (fsLit "$j") (mkPiTypes final_bndrs' rhs_ty')
2485 -- Note [Funky mkPiTypes]
2486
2487 ; let -- We make the lambdas into one-shot-lambdas. The
2488 -- join point is sure to be applied at most once, and doing so
2489 -- prevents the body of the join point being floated out by
2490 -- the full laziness pass
2491 really_final_bndrs = map one_shot final_bndrs'
2492 one_shot v | isId v = setOneShotLambda v
2493 | otherwise = v
2494 join_rhs = mkLams really_final_bndrs rhs'
2495 join_arity = exprArity join_rhs
2496 join_call = mkApps (Var join_bndr) final_args
2497
2498 ; env' <- addPolyBind NotTopLevel env (NonRec (join_bndr `setIdArity` join_arity) join_rhs)
2499 ; return (env', (con, bndrs', join_call)) }
2500 -- See Note [Duplicated env]
2501
2502 {-
2503 Note [Fusing case continuations]
2504 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2505 It's important to fuse two successive case continuations when the
2506 first has one alternative. That's why we call prepareCaseCont here.
2507 Consider this, which arises from thunk splitting (see Note [Thunk
2508 splitting] in WorkWrap):
2509
2510 let
2511 x* = case (case v of {pn -> rn}) of
2512 I# a -> I# a
2513 in body
2514
2515 The simplifier will find
2516 (Var v) with continuation
2517 Select (pn -> rn) (
2518 Select [I# a -> I# a] (
2519 StrictBind body Stop
2520
2521 So we'll call mkDupableCont on
2522 Select [I# a -> I# a] (StrictBind body Stop)
2523 There is just one alternative in the first Select, so we want to
2524 simplify the rhs (I# a) with continuation (StricgtBind body Stop)
2525 Supposing that body is big, we end up with
2526 let $j a = <let x = I# a in body>
2527 in case v of { pn -> case rn of
2528 I# a -> $j a }
2529 This is just what we want because the rn produces a box that
2530 the case rn cancels with.
2531
2532 See Trac #4957 a fuller example.
2533
2534 Note [Case binders and join points]
2535 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2536 Consider this
2537 case (case .. ) of c {
2538 I# c# -> ....c....
2539
2540 If we make a join point with c but not c# we get
2541 $j = \c -> ....c....
2542
2543 But if later inlining scrutines the c, thus
2544
2545 $j = \c -> ... case c of { I# y -> ... } ...
2546
2547 we won't see that 'c' has already been scrutinised. This actually
2548 happens in the 'tabulate' function in wave4main, and makes a significant
2549 difference to allocation.
2550
2551 An alternative plan is this:
2552
2553 $j = \c# -> let c = I# c# in ...c....
2554
2555 but that is bad if 'c' is *not* later scrutinised.
2556
2557 So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
2558 (a stable unfolding) that it's really I# c#, thus
2559
2560 $j = \c# -> \c[=I# c#] -> ...c....
2561
2562 Absence analysis may later discard 'c'.
2563
2564 NB: take great care when doing strictness analysis;
2565 see Note [Lamba-bound unfoldings] in DmdAnal.
2566
2567 Also note that we can still end up passing stuff that isn't used. Before
2568 strictness analysis we have
2569 let $j x y c{=(x,y)} = (h c, ...)
2570 in ...
2571 After strictness analysis we see that h is strict, we end up with
2572 let $j x y c{=(x,y)} = ($wh x y, ...)
2573 and c is unused.
2574
2575 Note [Duplicated env]
2576 ~~~~~~~~~~~~~~~~~~~~~
2577 Some of the alternatives are simplified, but have not been turned into a join point
2578 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
2579 bind the join point, because it might to do PostInlineUnconditionally, and
2580 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
2581 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
2582 at worst delays the join-point inlining.
2583
2584 Note [Small alternative rhs]
2585 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2586 It is worth checking for a small RHS because otherwise we
2587 get extra let bindings that may cause an extra iteration of the simplifier to
2588 inline back in place. Quite often the rhs is just a variable or constructor.
2589 The Ord instance of Maybe in PrelMaybe.hs, for example, took several extra
2590 iterations because the version with the let bindings looked big, and so wasn't
2591 inlined, but after the join points had been inlined it looked smaller, and so
2592 was inlined.
2593
2594 NB: we have to check the size of rhs', not rhs.
2595 Duplicating a small InAlt might invalidate occurrence information
2596 However, if it *is* dupable, we return the *un* simplified alternative,
2597 because otherwise we'd need to pair it up with an empty subst-env....
2598 but we only have one env shared between all the alts.
2599 (Remember we must zap the subst-env before re-simplifying something).
2600 Rather than do this we simply agree to re-simplify the original (small) thing later.
2601
2602 Note [Funky mkPiTypes]
2603 ~~~~~~~~~~~~~~~~~~~~~~
2604 Notice the funky mkPiTypes. If the contructor has existentials
2605 it's possible that the join point will be abstracted over
2606 type variables as well as term variables.
2607 Example: Suppose we have
2608 data T = forall t. C [t]
2609 Then faced with
2610 case (case e of ...) of
2611 C t xs::[t] -> rhs
2612 We get the join point
2613 let j :: forall t. [t] -> ...
2614 j = /\t \xs::[t] -> rhs
2615 in
2616 case (case e of ...) of
2617 C t xs::[t] -> j t xs
2618
2619 Note [Join point abstraction]
2620 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2621 Join points always have at least one value argument,
2622 for several reasons
2623
2624 * If we try to lift a primitive-typed something out
2625 for let-binding-purposes, we will *caseify* it (!),
2626 with potentially-disastrous strictness results. So
2627 instead we turn it into a function: \v -> e
2628 where v::Void#. The value passed to this function is void,
2629 which generates (almost) no code.
2630
2631 * CPR. We used to say "&& isUnLiftedType rhs_ty'" here, but now
2632 we make the join point into a function whenever used_bndrs'
2633 is empty. This makes the join-point more CPR friendly.
2634 Consider: let j = if .. then I# 3 else I# 4
2635 in case .. of { A -> j; B -> j; C -> ... }
2636
2637 Now CPR doesn't w/w j because it's a thunk, so
2638 that means that the enclosing function can't w/w either,
2639 which is a lose. Here's the example that happened in practice:
2640 kgmod :: Int -> Int -> Int
2641 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
2642 then 78
2643 else 5
2644
2645 * Let-no-escape. We want a join point to turn into a let-no-escape
2646 so that it is implemented as a jump, and one of the conditions
2647 for LNE is that it's not updatable. In CoreToStg, see
2648 Note [What is a non-escaping let]
2649
2650 * Floating. Since a join point will be entered once, no sharing is
2651 gained by floating out, but something might be lost by doing
2652 so because it might be allocated.
2653
2654 I have seen a case alternative like this:
2655 True -> \v -> ...
2656 It's a bit silly to add the realWorld dummy arg in this case, making
2657 $j = \s v -> ...
2658 True -> $j s
2659 (the \v alone is enough to make CPR happy) but I think it's rare
2660
2661 There's a slight infelicity here: we pass the overall
2662 case_bndr to all the join points if it's used in *any* RHS,
2663 because we don't know its usage in each RHS separately
2664
2665
2666 Note [Duplicating StrictArg]
2667 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2668 The original plan had (where E is a big argument)
2669 e.g. f E [..hole..]
2670 ==> let $j = \a -> f E a
2671 in $j [..hole..]
2672
2673 But this is terrible! Here's an example:
2674 && E (case x of { T -> F; F -> T })
2675 Now, && is strict so we end up simplifying the case with
2676
2677 an ArgOf continuation. If we let-bind it, we get
2678 let $j = \v -> && E v
2679 in simplExpr (case x of { T -> F; F -> T })
2680 (ArgOf (\r -> $j r)
2681 And after simplifying more we get
2682 let $j = \v -> && E v
2683 in case x of { T -> $j F; F -> $j T }
2684 Which is a Very Bad Thing
2685
2686 What we do now is this
2687 f E [..hole..]
2688 ==> let a = E
2689 in f a [..hole..]
2690 Now if the thing in the hole is a case expression (which is when
2691 we'll call mkDupableCont), we'll push the function call into the
2692 branches, which is what we want. Now RULES for f may fire, and
2693 call-pattern specialisation. Here's an example from Trac #3116
2694 go (n+1) (case l of
2695 1 -> bs'
2696 _ -> Chunk p fpc (o+1) (l-1) bs')
2697 If we can push the call for 'go' inside the case, we get
2698 call-pattern specialisation for 'go', which is *crucial* for
2699 this program.
2700
2701 Here is the (&&) example:
2702 && E (case x of { T -> F; F -> T })
2703 ==> let a = E in
2704 case x of { T -> && a F; F -> && a T }
2705 Much better!
2706
2707 Notice that
2708 * Arguments to f *after* the strict one are handled by
2709 the ApplyToVal case of mkDupableCont. Eg
2710 f [..hole..] E
2711
2712 * We can only do the let-binding of E because the function
2713 part of a StrictArg continuation is an explicit syntax
2714 tree. In earlier versions we represented it as a function
2715 (CoreExpr -> CoreEpxr) which we couldn't take apart.
2716
2717 Do *not* duplicate StrictBind and StritArg continuations. We gain
2718 nothing by propagating them into the expressions, and we do lose a
2719 lot.
2720
2721 The desire not to duplicate is the entire reason that
2722 mkDupableCont returns a pair of continuations.
2723
2724 Note [Duplicating StrictBind]
2725 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2726 Unlike StrictArg, there doesn't seem anything to gain from
2727 duplicating a StrictBind continuation, so we don't.
2728
2729
2730 Note [Single-alternative cases]
2731 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2732 This case is just like the ArgOf case. Here's an example:
2733 data T a = MkT !a
2734 ...(MkT (abs x))...
2735 Then we get
2736 case (case x of I# x' ->
2737 case x' <# 0# of
2738 True -> I# (negate# x')
2739 False -> I# x') of y {
2740 DEFAULT -> MkT y
2741 Because the (case x) has only one alternative, we'll transform to
2742 case x of I# x' ->
2743 case (case x' <# 0# of
2744 True -> I# (negate# x')
2745 False -> I# x') of y {
2746 DEFAULT -> MkT y
2747 But now we do *NOT* want to make a join point etc, giving
2748 case x of I# x' ->
2749 let $j = \y -> MkT y
2750 in case x' <# 0# of
2751 True -> $j (I# (negate# x'))
2752 False -> $j (I# x')
2753 In this case the $j will inline again, but suppose there was a big
2754 strict computation enclosing the orginal call to MkT. Then, it won't
2755 "see" the MkT any more, because it's big and won't get duplicated.
2756 And, what is worse, nothing was gained by the case-of-case transform.
2757
2758 So, in circumstances like these, we don't want to build join points
2759 and push the outer case into the branches of the inner one. Instead,
2760 don't duplicate the continuation.
2761
2762 When should we use this strategy? We should not use it on *every*
2763 single-alternative case:
2764 e.g. case (case ....) of (a,b) -> (# a,b #)
2765 Here we must push the outer case into the inner one!
2766 Other choices:
2767
2768 * Match [(DEFAULT,_,_)], but in the common case of Int,
2769 the alternative-filling-in code turned the outer case into
2770 case (...) of y { I# _ -> MkT y }
2771
2772 * Match on single alternative plus (not (isDeadBinder case_bndr))
2773 Rationale: pushing the case inwards won't eliminate the construction.
2774 But there's a risk of
2775 case (...) of y { (a,b) -> let z=(a,b) in ... }
2776 Now y looks dead, but it'll come alive again. Still, this
2777 seems like the best option at the moment.
2778
2779 * Match on single alternative plus (all (isDeadBinder bndrs))
2780 Rationale: this is essentially seq.
2781
2782 * Match when the rhs is *not* duplicable, and hence would lead to a
2783 join point. This catches the disaster-case above. We can test
2784 the *un-simplified* rhs, which is fine. It might get bigger or
2785 smaller after simplification; if it gets smaller, this case might
2786 fire next time round. NB also that we must test contIsDupable
2787 case_cont *too, because case_cont might be big!
2788
2789 HOWEVER: I found that this version doesn't work well, because
2790 we can get let x = case (...) of { small } in ...case x...
2791 When x is inlined into its full context, we find that it was a bad
2792 idea to have pushed the outer case inside the (...) case.
2793
2794 Note [Single-alternative-unlifted]
2795 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2796 Here's another single-alternative where we really want to do case-of-case:
2797
2798 data Mk1 = Mk1 Int# | Mk2 Int#
2799
2800 M1.f =
2801 \r [x_s74 y_s6X]
2802 case
2803 case y_s6X of tpl_s7m {
2804 M1.Mk1 ipv_s70 -> ipv_s70;
2805 M1.Mk2 ipv_s72 -> ipv_s72;
2806 }
2807 of
2808 wild_s7c
2809 { __DEFAULT ->
2810 case
2811 case x_s74 of tpl_s7n {
2812 M1.Mk1 ipv_s77 -> ipv_s77;
2813 M1.Mk2 ipv_s79 -> ipv_s79;
2814 }
2815 of
2816 wild1_s7b
2817 { __DEFAULT -> ==# [wild1_s7b wild_s7c];
2818 };
2819 };
2820
2821 So the outer case is doing *nothing at all*, other than serving as a
2822 join-point. In this case we really want to do case-of-case and decide
2823 whether to use a real join point or just duplicate the continuation:
2824
2825 let $j s7c = case x of
2826 Mk1 ipv77 -> (==) s7c ipv77
2827 Mk1 ipv79 -> (==) s7c ipv79
2828 in
2829 case y of
2830 Mk1 ipv70 -> $j ipv70
2831 Mk2 ipv72 -> $j ipv72
2832
2833 Hence: check whether the case binder's type is unlifted, because then
2834 the outer case is *not* a seq.
2835
2836 ************************************************************************
2837 * *
2838 Unfoldings
2839 * *
2840 ************************************************************************
2841 -}
2842
2843 simplLetUnfolding :: SimplEnv-> TopLevelFlag
2844 -> InId
2845 -> OutExpr
2846 -> Unfolding -> SimplM Unfolding
2847 simplLetUnfolding env top_lvl id new_rhs unf
2848 | isStableUnfolding unf
2849 = simplUnfolding env top_lvl id unf
2850 | otherwise
2851 = bottoming `seq` -- See Note [Force bottoming field]
2852 do { dflags <- getDynFlags
2853 ; return (mkUnfolding dflags InlineRhs (isTopLevel top_lvl) bottoming new_rhs) }
2854 -- We make an unfolding *even for loop-breakers*.
2855 -- Reason: (a) It might be useful to know that they are WHNF
2856 -- (b) In TidyPgm we currently assume that, if we want to
2857 -- expose the unfolding then indeed we *have* an unfolding
2858 -- to expose. (We could instead use the RHS, but currently
2859 -- we don't.) The simple thing is always to have one.
2860 where
2861 bottoming = isBottomingId id
2862
2863 simplUnfolding :: SimplEnv-> TopLevelFlag -> InId -> Unfolding -> SimplM Unfolding
2864 -- Note [Setting the new unfolding]
2865 simplUnfolding env top_lvl id unf
2866 = case unf of
2867 NoUnfolding -> return unf
2868 OtherCon {} -> return unf
2869
2870 DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = args }
2871 -> do { (env', bndrs') <- simplBinders rule_env bndrs
2872 ; args' <- mapM (simplExpr env') args
2873 ; return (mkDFunUnfolding bndrs' con args') }
2874
2875 CoreUnfolding { uf_tmpl = expr, uf_src = src, uf_guidance = guide }
2876 | isStableSource src
2877 -> do { expr' <- simplExpr rule_env expr
2878 ; case guide of
2879 UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok } -- Happens for INLINE things
2880 -> let guide' = UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok
2881 , ug_boring_ok = inlineBoringOk expr' }
2882 -- Refresh the boring-ok flag, in case expr'
2883 -- has got small. This happens, notably in the inlinings
2884 -- for dfuns for single-method classes; see
2885 -- Note [Single-method classes] in TcInstDcls.
2886 -- A test case is Trac #4138
2887 in return (mkCoreUnfolding src is_top_lvl expr' guide')
2888 -- See Note [Top-level flag on inline rules] in CoreUnfold
2889
2890 _other -- Happens for INLINABLE things
2891 -> bottoming `seq` -- See Note [Force bottoming field]
2892 do { dflags <- getDynFlags
2893 ; return (mkUnfolding dflags src is_top_lvl bottoming expr') } }
2894 -- If the guidance is UnfIfGoodArgs, this is an INLINABLE
2895 -- unfolding, and we need to make sure the guidance is kept up
2896 -- to date with respect to any changes in the unfolding.
2897
2898 | otherwise -> return noUnfolding -- Discard unstable unfoldings
2899 where
2900 bottoming = isBottomingId id
2901 is_top_lvl = isTopLevel top_lvl
2902 act = idInlineActivation id
2903 rule_env = updMode (updModeForStableUnfoldings act) env
2904 -- See Note [Simplifying inside stable unfoldings] in SimplUtils
2905
2906 {-
2907 Note [Force bottoming field]
2908 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2909 We need to force bottoming, or the new unfolding holds
2910 on to the old unfolding (which is part of the id).
2911
2912 Note [Setting the new unfolding]
2913 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2914 * If there's an INLINE pragma, we simplify the RHS gently. Maybe we
2915 should do nothing at all, but simplifying gently might get rid of
2916 more crap.
2917
2918 * If not, we make an unfolding from the new RHS. But *only* for
2919 non-loop-breakers. Making loop breakers not have an unfolding at all
2920 means that we can avoid tests in exprIsConApp, for example. This is
2921 important: if exprIsConApp says 'yes' for a recursive thing, then we
2922 can get into an infinite loop
2923
2924 If there's an stable unfolding on a loop breaker (which happens for
2925 INLINEABLE), we hang on to the inlining. It's pretty dodgy, but the
2926 user did say 'INLINE'. May need to revisit this choice.
2927
2928 ************************************************************************
2929 * *
2930 Rules
2931 * *
2932 ************************************************************************
2933
2934 Note [Rules in a letrec]
2935 ~~~~~~~~~~~~~~~~~~~~~~~~
2936 After creating fresh binders for the binders of a letrec, we
2937 substitute the RULES and add them back onto the binders; this is done
2938 *before* processing any of the RHSs. This is important. Manuel found
2939 cases where he really, really wanted a RULE for a recursive function
2940 to apply in that function's own right-hand side.
2941
2942 See Note [Loop breaking and RULES] in OccAnal.
2943 -}
2944
2945 addBndrRules :: SimplEnv -> InBndr -> OutBndr -> SimplM (SimplEnv, OutBndr)
2946 -- Rules are added back into the bin
2947 addBndrRules env in_id out_id
2948 | null old_rules
2949 = return (env, out_id)
2950 | otherwise
2951 = do { new_rules <- mapM (simplRule env (Just (idName out_id))) old_rules
2952 ; let final_id = out_id `setIdSpecialisation` mkSpecInfo new_rules
2953 ; return (modifyInScope env final_id, final_id) }
2954 where
2955 old_rules = specInfoRules (idSpecialisation in_id)
2956
2957 simplRule :: SimplEnv -> Maybe Name -> CoreRule -> SimplM CoreRule
2958 simplRule _ _ rule@(BuiltinRule {}) = return rule
2959 simplRule env mb_new_nm rule@(Rule { ru_bndrs = bndrs, ru_args = args
2960 , ru_fn = fn_name, ru_rhs = rhs
2961 , ru_act = act })
2962 = do { (env, bndrs') <- simplBinders env bndrs
2963 ; let rule_env = updMode (updModeForStableUnfoldings act) env
2964 ; args' <- mapM (simplExpr rule_env) args
2965 ; rhs' <- simplExpr rule_env rhs
2966 ; return (rule { ru_bndrs = bndrs'
2967 , ru_fn = mb_new_nm `orElse` fn_name
2968 , ru_args = args'
2969 , ru_rhs = rhs' }) }