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