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