[project @ 2001-09-14 15:44:13 by simonpj]
[ghc-hetmet.git] / ghc / compiler / simplCore / Simplify.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[Simplify]{The main module of the simplifier}
5
6 \begin{code}
7 module Simplify ( simplTopBinds, simplExpr ) where
8
9 #include "HsVersions.h"
10
11 import CmdLineOpts      ( switchIsOn, opt_SimplDoEtaReduction,
12                           opt_SimplNoPreInlining, 
13                           dopt, DynFlag(Opt_D_dump_inlinings),
14                           SimplifierSwitch(..)
15                         )
16 import SimplMonad
17 import SimplUtils       ( mkCase, tryRhsTyLam, tryEtaExpansion,
18                           simplBinder, simplBinders, simplRecIds, simplLetId, simplLamBinder,
19                           SimplCont(..), DupFlag(..), mkStop, mkRhsStop,
20                           contResultType, discardInline, countArgs, contIsDupable,
21                           getContArgs, interestingCallContext, interestingArg, isStrictType
22                         )
23 import Var              ( mkSysTyVar, tyVarKind, mustHaveLocalBinding )
24 import VarEnv
25 import Literal          ( Literal )
26 import Id               ( Id, idType, idInfo, isDataConId, hasNoBinding,
27                           idUnfolding, setIdUnfolding, isExportedId, isDeadBinder,
28                           idNewDemandInfo, setIdInfo,
29                           idOccInfo, setIdOccInfo, 
30                           zapLamIdInfo, setOneShotLambda, 
31                         )
32 import IdInfo           ( OccInfo(..), isDeadOcc, isLoopBreaker,
33                           setArityInfo, 
34                           setUnfoldingInfo, 
35                           occInfo
36                         )
37 import NewDemand        ( isStrictDmd )
38 import DataCon          ( dataConNumInstArgs, dataConRepStrictness,
39                           dataConSig, dataConArgTys
40                         )
41 import CoreSyn
42 import PprCore          ( pprParendExpr, pprCoreExpr )
43 import CoreUnfold       ( mkOtherCon, mkUnfolding, otherCons,
44                           callSiteInline
45                         )
46 import CoreUtils        ( cheapEqExpr, exprIsDupable, exprIsTrivial, 
47                           exprIsConApp_maybe, mkPiType, findAlt, findDefault,
48                           exprType, coreAltsType, exprIsValue, 
49                           exprOkForSpeculation, exprArity, 
50                           mkCoerce, mkSCC, mkInlineMe, mkAltExpr
51                         )
52 import Rules            ( lookupRule )
53 import BasicTypes       ( isMarkedStrict )
54 import CostCentre       ( currentCCS )
55 import Type             ( mkTyVarTys, isUnLiftedType, seqType,
56                           mkFunTy, splitTyConApp_maybe, tyConAppArgs,
57                           funResultTy, splitFunTy_maybe, splitFunTy, eqType
58                         )
59 import Subst            ( mkSubst, substTy, substEnv, substExpr,
60                           isInScope, lookupIdSubst, simplIdInfo
61                         )
62 import TyCon            ( isDataTyCon, tyConDataConsIfAvailable )
63 import TysPrim          ( realWorldStatePrimTy )
64 import PrelInfo         ( realWorldPrimId )
65 import OrdList
66 import Maybes           ( maybeToBool )
67 import Outputable
68 \end{code}
69
70
71 The guts of the simplifier is in this module, but the driver
72 loop for the simplifier is in SimplCore.lhs.
73
74
75 -----------------------------------------
76         *** IMPORTANT NOTE ***
77 -----------------------------------------
78 The simplifier used to guarantee that the output had no shadowing, but
79 it does not do so any more.   (Actually, it never did!)  The reason is
80 documented with simplifyArgs.
81
82
83
84
85 %************************************************************************
86 %*                                                                      *
87 \subsection{Bindings}
88 %*                                                                      *
89 %************************************************************************
90
91 \begin{code}
92 simplTopBinds :: [InBind] -> SimplM [OutBind]
93
94 simplTopBinds binds
95   =     -- Put all the top-level binders into scope at the start
96         -- so that if a transformation rule has unexpectedly brought
97         -- anything into scope, then we don't get a complaint about that.
98         -- It's rather as if the top-level binders were imported.
99     simplRecIds (bindersOfBinds binds)  $ \ bndrs' -> 
100     simpl_binds binds bndrs'            `thenSmpl` \ (binds', _) ->
101     freeTick SimplifierDone             `thenSmpl_`
102     returnSmpl (fromOL binds')
103   where
104
105         -- We need to track the zapped top-level binders, because
106         -- they should have their fragile IdInfo zapped (notably occurrence info)
107     simpl_binds []                        bs     = ASSERT( null bs ) returnSmpl (nilOL, panic "simplTopBinds corner")
108     simpl_binds (NonRec bndr rhs : binds) (b:bs) = simplLazyBind True bndr  b rhs       (simpl_binds binds bs)
109     simpl_binds (Rec pairs       : binds) bs     = simplRecBind  True pairs (take n bs) (simpl_binds binds (drop n bs))
110                                                  where 
111                                                    n = length pairs
112
113 simplRecBind :: Bool -> [(InId, InExpr)] -> [OutId]
114              -> SimplM (OutStuff a) -> SimplM (OutStuff a)
115 simplRecBind top_lvl pairs bndrs' thing_inside
116   = go pairs bndrs'             `thenSmpl` \ (binds', (_, (binds'', res))) ->
117     returnSmpl (unitOL (Rec (flattenBinds (fromOL binds'))) `appOL` binds'', res)
118   where
119     go [] _ = thing_inside      `thenSmpl` \ stuff ->
120               returnOutStuff stuff
121         
122     go ((bndr, rhs) : pairs) (bndr' : bndrs')
123         = simplLazyBind top_lvl bndr bndr' rhs (go pairs bndrs')
124                 -- Don't float unboxed bindings out,
125                 -- because we can't "rec" them
126 \end{code}
127
128
129 %************************************************************************
130 %*                                                                      *
131 \subsection[Simplify-simplExpr]{The main function: simplExpr}
132 %*                                                                      *
133 %************************************************************************
134
135 The reason for this OutExprStuff stuff is that we want to float *after*
136 simplifying a RHS, not before.  If we do so naively we get quadratic
137 behaviour as things float out.
138
139 To see why it's important to do it after, consider this (real) example:
140
141         let t = f x
142         in fst t
143 ==>
144         let t = let a = e1
145                     b = e2
146                 in (a,b)
147         in fst t
148 ==>
149         let a = e1
150             b = e2
151             t = (a,b)
152         in
153         a       -- Can't inline a this round, cos it appears twice
154 ==>
155         e1
156
157 Each of the ==> steps is a round of simplification.  We'd save a
158 whole round if we float first.  This can cascade.  Consider
159
160         let f = g d
161         in \x -> ...f...
162 ==>
163         let f = let d1 = ..d.. in \y -> e
164         in \x -> ...f...
165 ==>
166         let d1 = ..d..
167         in \x -> ...(\y ->e)...
168
169 Only in this second round can the \y be applied, and it 
170 might do the same again.
171
172
173 \begin{code}
174 simplExpr :: CoreExpr -> SimplM CoreExpr
175 simplExpr expr = getSubst       `thenSmpl` \ subst ->
176                  simplExprC expr (mkStop (substTy subst (exprType expr)))
177         -- The type in the Stop continuation is usually not used
178         -- It's only needed when discarding continuations after finding
179         -- a function that returns bottom.
180         -- Hence the lazy substitution
181
182 simplExprC :: CoreExpr -> SimplCont -> SimplM CoreExpr
183         -- Simplify an expression, given a continuation
184
185 simplExprC expr cont = simplExprF expr cont     `thenSmpl` \ (floats, (_, body)) ->
186                        returnSmpl (wrapFloats floats body)
187
188 simplExprF :: InExpr -> SimplCont -> SimplM OutExprStuff
189         -- Simplify an expression, returning floated binds
190
191 simplExprF (Var v)          cont = simplVar v cont
192 simplExprF (Lit lit)        cont = simplLit lit cont
193 simplExprF expr@(Lam _ _)   cont = simplLam expr cont
194 simplExprF (Note note expr) cont = simplNote note expr cont
195
196 simplExprF (App fun arg) cont
197   = getSubstEnv         `thenSmpl` \ se ->
198     simplExprF fun (ApplyTo NoDup arg se cont)
199
200 simplExprF (Type ty) cont
201   = ASSERT( case cont of { Stop _ _ -> True; ArgOf _ _ _ -> True; other -> False } )
202     simplType ty        `thenSmpl` \ ty' ->
203     rebuild (Type ty') cont
204
205 simplExprF (Case scrut bndr alts) cont
206   = getSubstEnv                 `thenSmpl` \ subst_env ->
207     getSwitchChecker            `thenSmpl` \ chkr ->
208     if not (switchIsOn chkr NoCaseOfCase) then
209         -- Simplify the scrutinee with a Select continuation
210         simplExprF scrut (Select NoDup bndr alts subst_env cont)
211
212     else
213         -- If case-of-case is off, simply simplify the case expression
214         -- in a vanilla Stop context, and rebuild the result around it
215         simplExprC scrut (Select NoDup bndr alts subst_env 
216                                  (mkStop (contResultType cont)))        `thenSmpl` \ case_expr' ->
217         rebuild case_expr' cont
218
219 simplExprF (Let (Rec pairs) body) cont
220   = simplRecIds (map fst pairs)                 $ \ bndrs' -> 
221         -- NB: bndrs' don't have unfoldings or spec-envs
222         -- We add them as we go down, using simplPrags
223
224     simplRecBind False pairs bndrs' (simplExprF body cont)
225
226 -- A non-recursive let is dealt with by simplNonRecBind
227 simplExprF (Let (NonRec bndr rhs) body) cont
228   = getSubstEnv                 `thenSmpl` \ se ->
229     simplNonRecBind bndr rhs se (contResultType cont)   $
230     simplExprF body cont
231
232
233 ---------------------------------
234 simplType :: InType -> SimplM OutType
235 simplType ty
236   = getSubst    `thenSmpl` \ subst ->
237     let
238         new_ty = substTy subst ty
239     in
240     seqType new_ty `seq`  
241     returnSmpl new_ty
242
243 ---------------------------------
244 simplLit :: Literal -> SimplCont -> SimplM OutExprStuff
245
246 simplLit lit (Select _ bndr alts se cont)
247   = knownCon (Lit lit) (LitAlt lit) [] bndr alts se cont
248
249 simplLit lit cont = rebuild (Lit lit) cont
250 \end{code}
251
252
253 %************************************************************************
254 %*                                                                      *
255 \subsection{Lambdas}
256 %*                                                                      *
257 %************************************************************************
258
259 \begin{code}
260 simplLam fun cont
261   = go fun cont
262   where
263     zap_it  = mkLamBndrZapper fun cont
264     cont_ty = contResultType cont
265
266         -- Type-beta reduction
267     go (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
268       = ASSERT( isTyVar bndr )
269         tick (BetaReduction bndr)       `thenSmpl_`
270         simplTyArg ty_arg arg_se        `thenSmpl` \ ty_arg' ->
271         extendSubst bndr (DoneTy ty_arg')
272         (go body body_cont)
273
274         -- Ordinary beta reduction
275     go (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
276       = tick (BetaReduction bndr)                       `thenSmpl_`
277         simplNonRecBind zapped_bndr arg arg_se cont_ty
278         (go body body_cont)
279       where
280         zapped_bndr = zap_it bndr
281
282         -- Not enough args
283     go lam@(Lam _ _) cont = completeLam [] lam cont
284
285         -- Exactly enough args
286     go expr cont = simplExprF expr cont
287
288 -- completeLam deals with the case where a lambda doesn't have an ApplyTo
289 -- continuation, so there are real lambdas left to put in the result
290
291 -- We try for eta reduction here, but *only* if we get all the 
292 -- way to an exprIsTrivial expression.    
293 -- We don't want to remove extra lambdas unless we are going 
294 -- to avoid allocating this thing altogether
295
296 completeLam rev_bndrs (Lam bndr body) cont
297   = simplLamBinder bndr                 $ \ bndr' ->
298     completeLam (bndr':rev_bndrs) body cont
299
300 completeLam rev_bndrs body cont
301   = simplExpr body                      `thenSmpl` \ body' ->
302     case try_eta body' of
303         Just etad_lam -> tick (EtaReduction (head rev_bndrs))   `thenSmpl_`
304                          rebuild etad_lam cont
305
306         Nothing       -> rebuild (foldl (flip Lam) body' rev_bndrs) cont
307   where
308         -- We don't use CoreUtils.etaReduce, because we can be more
309         -- efficient here:
310         --  (a) we already have the binders,
311         --  (b) we can do the triviality test before computing the free vars
312         --      [in fact I take the simple path and look for just a variable]
313         --  (c) we don't want to eta-reduce a data con worker or primop
314         --      because we only have to eta-expand them later when we saturate
315     try_eta body | not opt_SimplDoEtaReduction = Nothing
316                  | otherwise                   = go rev_bndrs body
317
318     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
319     go []       body          | ok_body body = Just body        -- Success!
320     go _        _                            = Nothing          -- Failure!
321
322     ok_body (Var v) = not (v `elem` rev_bndrs) && not (hasNoBinding v)
323     ok_body other   = False
324     ok_arg b arg    = varToCoreExpr b `cheapEqExpr` arg
325
326 mkLamBndrZapper :: CoreExpr     -- Function
327                 -> SimplCont    -- The context
328                 -> Id -> Id     -- Use this to zap the binders
329 mkLamBndrZapper fun cont
330   | n_args >= n_params fun = \b -> b            -- Enough args
331   | otherwise              = \b -> zapLamIdInfo b
332   where
333         -- NB: we count all the args incl type args
334         -- so we must count all the binders (incl type lambdas)
335     n_args = countArgs cont
336
337     n_params (Note _ e) = n_params e
338     n_params (Lam b e)  = 1 + n_params e
339     n_params other      = 0::Int
340 \end{code}
341
342
343 %************************************************************************
344 %*                                                                      *
345 \subsection{Notes}
346 %*                                                                      *
347 %************************************************************************
348
349 \begin{code}
350 simplNote (Coerce to from) body cont
351   = getInScope                  `thenSmpl` \ in_scope ->
352     let
353         addCoerce s1 k1 (CoerceIt t1 cont)
354                 --      coerce T1 S1 (coerce S1 K1 e)
355                 -- ==>
356                 --      e,                      if T1=K1
357                 --      coerce T1 K1 e,         otherwise
358                 --
359                 -- For example, in the initial form of a worker
360                 -- we may find  (coerce T (coerce S (\x.e))) y
361                 -- and we'd like it to simplify to e[y/x] in one round 
362                 -- of simplification
363           | t1 `eqType` k1  = cont              -- The coerces cancel out
364           | otherwise       = CoerceIt t1 cont  -- They don't cancel, but 
365                                                 -- the inner one is redundant
366
367         addCoerce t1t2 s1s2 (ApplyTo dup arg arg_se cont)
368           | Just (s1, s2) <- splitFunTy_maybe s1s2
369                 --      (coerce (T1->T2) (S1->S2) F) E
370                 -- ===> 
371                 --      coerce T2 S2 (F (coerce S1 T1 E))
372                 --
373                 -- t1t2 must be a function type, T1->T2
374                 -- but s1s2 might conceivably not be
375                 --
376                 -- When we build the ApplyTo we can't mix the out-types
377                 -- with the InExpr in the argument, so we simply substitute
378                 -- to make it all consistent.  This isn't a common case.
379           = let 
380                 (t1,t2) = splitFunTy t1t2
381                 new_arg = mkCoerce s1 t1 (substExpr (mkSubst in_scope arg_se) arg)
382             in
383             ApplyTo dup new_arg emptySubstEnv (addCoerce t2 s2 cont)
384                         
385         addCoerce to' _ cont = CoerceIt to' cont
386     in
387     simplType to                `thenSmpl` \ to' ->
388     simplType from              `thenSmpl` \ from' ->
389     simplExprF body (addCoerce to' from' cont)
390
391                 
392 -- Hack: we only distinguish subsumed cost centre stacks for the purposes of
393 -- inlining.  All other CCCSs are mapped to currentCCS.
394 simplNote (SCC cc) e cont
395   = setEnclosingCC currentCCS $
396     simplExpr e         `thenSmpl` \ e ->
397     rebuild (mkSCC cc e) cont
398
399 simplNote InlineCall e cont
400   = simplExprF e (InlinePlease cont)
401
402 --       Comments about the InlineMe case 
403 --       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
404 -- Don't inline in the RHS of something that has an
405 -- inline pragma.  But be careful that the InScopeEnv that
406 -- we return does still have inlinings on!
407 -- 
408 -- It really is important to switch off inlinings.  This function
409 -- may be inlinined in other modules, so we don't want to remove
410 -- (by inlining) calls to functions that have specialisations, or
411 -- that may have transformation rules in an importing scope.
412 -- E.g.         {-# INLINE f #-}
413 --              f x = ...g...
414 -- and suppose that g is strict *and* has specialisations.
415 -- If we inline g's wrapper, we deny f the chance of getting
416 -- the specialised version of g when f is inlined at some call site
417 -- (perhaps in some other module).
418
419 -- It's also important not to inline a worker back into a wrapper.
420 -- A wrapper looks like
421 --      wraper = inline_me (\x -> ...worker... )
422 -- Normally, the inline_me prevents the worker getting inlined into
423 -- the wrapper (initially, the worker's only call site!).  But,
424 -- if the wrapper is sure to be called, the strictness analyser will
425 -- mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
426 -- continuation.  That's why the keep_inline predicate returns True for
427 -- ArgOf continuations.  It shouldn't do any harm not to dissolve the
428 -- inline-me note under these circumstances
429
430 simplNote InlineMe e cont
431   | keep_inline cont            -- Totally boring continuation
432   =                             -- Don't inline inside an INLINE expression
433     noInlineBlackList                   `thenSmpl` \ bl ->
434     setBlackList bl (simplExpr e)       `thenSmpl` \ e' ->
435     rebuild (mkInlineMe e') cont
436
437   | otherwise   -- Dissolve the InlineMe note if there's
438                 -- an interesting context of any kind to combine with
439                 -- (even a type application -- anything except Stop)
440   = simplExprF e cont
441   where
442     keep_inline (Stop _ _)    = True            -- See notes above
443     keep_inline (ArgOf _ _ _) = True            -- about this predicate
444     keep_inline other         = False
445 \end{code}
446
447
448 %************************************************************************
449 %*                                                                      *
450 \subsection{Binding}
451 %*                                                                      *
452 %************************************************************************
453
454 @simplNonRecBind@ is used for non-recursive lets in expressions, 
455 as well as true beta reduction.
456
457 Very similar to @simplLazyBind@, but not quite the same.
458
459 \begin{code}
460 simplNonRecBind :: InId                 -- Binder
461           -> InExpr -> SubstEnv         -- Arg, with its subst-env
462           -> OutType                    -- Type of thing computed by the context
463           -> SimplM OutExprStuff        -- The body
464           -> SimplM OutExprStuff
465 #ifdef DEBUG
466 simplNonRecBind bndr rhs rhs_se cont_ty thing_inside
467   | isTyVar bndr
468   = pprPanic "simplNonRecBind" (ppr bndr <+> ppr rhs)
469 #endif
470
471 simplNonRecBind bndr rhs rhs_se cont_ty thing_inside
472   | preInlineUnconditionally False {- not black listed -} bndr
473   = tick (PreInlineUnconditionally bndr)                `thenSmpl_`
474     extendSubst bndr (ContEx rhs_se rhs) thing_inside
475
476   | otherwise
477   =     -- Simplify the binder.
478         -- Don't use simplBinder because that doesn't keep 
479         -- fragile occurrence in the substitution
480     simplLetId bndr                                     $ \ bndr' ->
481     getSubst                                            `thenSmpl` \ bndr_subst ->
482     let
483         -- Substitute its IdInfo (which simplLetId does not)
484         -- The appropriate substitution env is the one right here,
485         -- not rhs_se.  Often they are the same, when all this 
486         -- has arisen from an application (\x. E) RHS, perhaps they aren't
487         bndr''    = simplIdInfo bndr_subst (idInfo bndr) bndr'
488         bndr_ty'  = idType bndr'
489         is_strict = isStrictDmd (idNewDemandInfo bndr) || isStrictType bndr_ty'
490     in
491     modifyInScope bndr'' bndr''                         $
492
493         -- Simplify the argument
494     simplValArg bndr_ty' is_strict rhs rhs_se cont_ty   $ \ rhs' ->
495
496         -- Now complete the binding and simplify the body
497     if needsCaseBinding bndr_ty' rhs' then
498         addCaseBind bndr'' rhs' thing_inside
499     else
500         completeBinding bndr bndr'' False False rhs' thing_inside
501 \end{code}
502
503
504 \begin{code}
505 simplTyArg :: InType -> SubstEnv -> SimplM OutType
506 simplTyArg ty_arg se
507   = getInScope          `thenSmpl` \ in_scope ->
508     let
509         ty_arg' = substTy (mkSubst in_scope se) ty_arg
510     in
511     seqType ty_arg'     `seq`
512     returnSmpl ty_arg'
513
514 simplValArg :: OutType          -- rhs_ty: Type of arg; used only occasionally
515             -> Bool             -- True <=> evaluate eagerly
516             -> InExpr -> SubstEnv
517             -> OutType          -- cont_ty: Type of thing computed by the context
518             -> (OutExpr -> SimplM OutExprStuff) 
519                                 -- Takes an expression of type rhs_ty, 
520                                 -- returns an expression of type cont_ty
521             -> SimplM OutExprStuff      -- An expression of type cont_ty
522
523 simplValArg arg_ty is_strict arg arg_se cont_ty thing_inside
524   | is_strict
525   = getEnv                              `thenSmpl` \ env ->
526     setSubstEnv arg_se                          $
527     simplExprF arg (ArgOf NoDup cont_ty         $ \ rhs' ->
528     setAllExceptInScope env                     $
529     thing_inside rhs')
530
531   | otherwise
532   = simplRhs False {- Not top level -} 
533              True {- OK to float unboxed -}
534              arg_ty arg arg_se 
535              thing_inside
536 \end{code}
537
538
539 completeBinding
540         - deals only with Ids, not TyVars
541         - take an already-simplified RHS
542
543 It does *not* attempt to do let-to-case.  Why?  Because they are used for
544
545         - top-level bindings
546                 (when let-to-case is impossible) 
547
548         - many situations where the "rhs" is known to be a WHNF
549                 (so let-to-case is inappropriate).
550
551 \begin{code}
552 completeBinding :: InId                 -- Binder
553                 -> OutId                -- New binder
554                 -> Bool                 -- True <=> top level
555                 -> Bool                 -- True <=> black-listed; don't inline
556                 -> OutExpr              -- Simplified RHS
557                 -> SimplM (OutStuff a)  -- Thing inside
558                 -> SimplM (OutStuff a)
559
560 completeBinding old_bndr new_bndr top_lvl black_listed new_rhs thing_inside
561   |  isDeadOcc occ_info         -- This happens; for example, the case_bndr during case of
562                                 -- known constructor:  case (a,b) of x { (p,q) -> ... }
563                                 -- Here x isn't mentioned in the RHS, so we don't want to
564                                 -- create the (dead) let-binding  let x = (a,b) in ...
565   =  thing_inside
566
567   | trivial_rhs && not must_keep_binding
568         -- We're looking at a binding with a trivial RHS, so
569         -- perhaps we can discard it altogether!
570         --
571         -- NB: a loop breaker has must_keep_binding = True
572         -- and non-loop-breakers only have *forward* references
573         -- Hence, it's safe to discard the binding
574         --      
575         -- NOTE: This isn't our last opportunity to inline.
576         -- We're at the binding site right now, and
577         -- we'll get another opportunity when we get to the ocurrence(s)
578
579         -- Note that we do this unconditional inlining only for trival RHSs.
580         -- Don't inline even WHNFs inside lambdas; doing so may
581         -- simply increase allocation when the function is called
582         -- This isn't the last chance; see NOTE above.
583         --
584         -- NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here
585         -- Why?  Because we don't even want to inline them into the
586         -- RHS of constructor arguments. See NOTE above
587         --
588         -- NB: Even NOINLINEis ignored here: if the rhs is trivial
589         -- it's best to inline it anyway.  We often get a=E; b=a
590         -- from desugaring, with both a and b marked NOINLINE.
591   =             -- Drop the binding
592     extendSubst old_bndr (DoneEx new_rhs)       $
593                 -- Use the substitution to make quite, quite sure that the substitution
594                 -- will happen, since we are going to discard the binding
595     tick (PostInlineUnconditionally old_bndr)   `thenSmpl_`
596     thing_inside
597
598   | Note coercion@(Coerce _ inner_ty) inner_rhs <- new_rhs,
599     not trivial_rhs && not (isUnLiftedType inner_ty)
600         -- x = coerce t e  ==>  c = e; x = inline_me (coerce t c)
601         -- Now x can get inlined, which moves the coercion
602         -- to the usage site.  This is a bit like worker/wrapper stuff,
603         -- but it's useful to do it very promptly, so that
604         --      x = coerce T (I# 3)
605         -- get's w/wd to
606         --      c = I# 3
607         --      x = coerce T c
608         -- This in turn means that
609         --      case (coerce Int x) of ...
610         -- will inline x.  
611         -- Also the full-blown w/w thing isn't set up for non-functions
612         --
613         -- The (not (isUnLiftedType inner_ty)) avoids the nasty case of
614         --      x::Int = coerce Int Int# (foo y)
615         -- ==>
616         --      v::Int# = foo y
617         --      x::Int  = coerce Int Int# v
618         -- which would be bogus because then v will be evaluated strictly.
619         -- How can this arise?  Via 
620         --      x::Int = case (foo y) of { ... }
621         -- followed by case elimination.
622         --
623         -- The inline_me note is so that the simplifier doesn't 
624         -- just substitute c back inside x's rhs!  (Typically, x will
625         -- get substituted away, but not if it's exported.)
626   = newId SLIT("c") inner_ty                                    $ \ c_id ->
627     completeBinding c_id c_id top_lvl False inner_rhs           $
628     completeBinding old_bndr new_bndr top_lvl black_listed
629                     (Note InlineMe (Note coercion (Var c_id)))  $
630     thing_inside
631
632   |  otherwise
633   = let
634                 -- We make new IdInfo for the new binder by starting from the old binder, 
635                 -- doing appropriate substitutions.
636                 -- Then we add arity and unfolding info to get the new binder
637         new_bndr_info = idInfo new_bndr `setArityInfo` arity
638
639                 -- Add the unfolding *only* for non-loop-breakers
640                 -- Making loop breakers not have an unfolding at all 
641                 -- means that we can avoid tests in exprIsConApp, for example.
642                 -- This is important: if exprIsConApp says 'yes' for a recursive
643                 -- thing, then we can get into an infinite loop
644         info_w_unf | loop_breaker = new_bndr_info
645                    | otherwise    = new_bndr_info `setUnfoldingInfo` mkUnfolding top_lvl new_rhs
646
647         final_id = new_bndr `setIdInfo` info_w_unf
648     in
649                 -- These seqs forces the Id, and hence its IdInfo,
650                 -- and hence any inner substitutions
651     final_id                            `seq`
652     addLetBind (NonRec final_id new_rhs)        $
653     modifyInScope new_bndr final_id thing_inside
654
655   where
656     old_info          = idInfo old_bndr
657     occ_info          = occInfo old_info
658     loop_breaker      = isLoopBreaker occ_info
659     trivial_rhs       = exprIsTrivial new_rhs
660     must_keep_binding = black_listed || loop_breaker || isExportedId old_bndr
661     arity             = exprArity new_rhs
662 \end{code}    
663
664
665
666 %************************************************************************
667 %*                                                                      *
668 \subsection{simplLazyBind}
669 %*                                                                      *
670 %************************************************************************
671
672 simplLazyBind basically just simplifies the RHS of a let(rec).
673 It does two important optimisations though:
674
675         * It floats let(rec)s out of the RHS, even if they
676           are hidden by big lambdas
677
678         * It does eta expansion
679
680 \begin{code}
681 simplLazyBind :: Bool                   -- True <=> top level
682               -> InId -> OutId
683               -> InExpr                 -- The RHS
684               -> SimplM (OutStuff a)    -- The body of the binding
685               -> SimplM (OutStuff a)
686 -- When called, the subst env is correct for the entire let-binding
687 -- and hence right for the RHS.
688 -- Also the binder has already been simplified, and hence is in scope
689
690 simplLazyBind top_lvl bndr bndr' rhs thing_inside
691   = getBlackList                `thenSmpl` \ black_list_fn ->
692     let
693         black_listed = black_list_fn bndr
694     in
695
696     if preInlineUnconditionally black_listed bndr then
697         -- Inline unconditionally
698         tick (PreInlineUnconditionally bndr)    `thenSmpl_`
699         getSubstEnv                             `thenSmpl` \ rhs_se ->
700         (extendSubst bndr (ContEx rhs_se rhs) thing_inside)
701     else
702
703         -- Simplify the RHS
704     getSubst                                    `thenSmpl` \ rhs_subst ->
705     let
706         -- Substitute IdInfo on binder, in the light of earlier
707         -- substitutions in this very letrec, and extend the in-scope
708         -- env so that it can see the new thing
709         bndr'' = simplIdInfo rhs_subst (idInfo bndr) bndr'
710     in
711     modifyInScope bndr'' bndr''                         $
712
713     simplRhs top_lvl False {- Not ok to float unboxed (conservative) -}
714              (idType bndr')
715              rhs (substEnv rhs_subst)                   $ \ rhs' ->
716
717         -- Now compete the binding and simplify the body
718     completeBinding bndr bndr'' top_lvl black_listed rhs' thing_inside
719 \end{code}
720
721
722
723 \begin{code}
724 simplRhs :: Bool                -- True <=> Top level
725          -> Bool                -- True <=> OK to float unboxed (speculative) bindings
726                                 --          False for (a) recursive and (b) top-level bindings
727          -> OutType             -- Type of RHS; used only occasionally
728          -> InExpr -> SubstEnv
729          -> (OutExpr -> SimplM (OutStuff a))
730          -> SimplM (OutStuff a)
731 simplRhs top_lvl float_ubx rhs_ty rhs rhs_se thing_inside
732   =     -- Simplify it
733     setSubstEnv rhs_se (simplExprF rhs (mkRhsStop rhs_ty))      `thenSmpl` \ (floats1, (rhs_in_scope, rhs1)) ->
734     let
735         (floats2, rhs2) = splitFloats float_ubx floats1 rhs1
736     in
737         --                      Transform the RHS
738         -- It's important that we do eta expansion on function *arguments* (which are
739         -- simplified with simplRhs), as well as let-bound right-hand sides.  
740         -- Otherwise we find that things like
741         --      f (\x -> case x of I# x' -> coerce T (\ y -> ...))
742         -- get right through to the code generator as two separate lambdas, 
743         -- which is a Bad Thing
744     tryRhsTyLam rhs2            `thenSmpl` \ (floats3, rhs3) ->
745     tryEtaExpansion rhs3 rhs_ty `thenSmpl` \ (floats4, rhs4) ->
746
747         -- Float lets if (a) we're at the top level
748         -- or            (b) the resulting RHS is one we'd like to expose
749         --
750         -- NB: the test used to say "exprIsCheap", but that caused a strictness bug.
751         --         x = let y* = E in case (scc y) of { T -> F; F -> T}
752         -- The case expression is 'cheap', but it's wrong to transform to
753         --         y* = E; x = case (scc y) of {...}
754         -- Either we must be careful not to float demanded non-values, or
755         -- we must use exprIsValue for the test, which ensures that the
756         -- thing is non-strict.  I think.  The WARN below tests for this
757     if (top_lvl || exprIsValue rhs4) then
758
759                 -- There's a subtlety here.  There may be a binding (x* = e) in the
760                 -- floats, where the '*' means 'will be demanded'.  So is it safe
761                 -- to float it out?  Answer no, but it won't matter because
762                 -- we only float if arg' is a WHNF,
763                 -- and so there can't be any 'will be demanded' bindings in the floats.
764                 -- Hence the assert
765         WARN( any demanded_float (fromOL floats2), 
766               ppr (filter demanded_float (fromOL floats2)) )
767
768         (if (isNilOL floats2 && null floats3 && null floats4) then
769                 returnSmpl ()
770          else
771                 tick LetFloatFromLet)                   `thenSmpl_`
772
773         addFloats floats2 rhs_in_scope  $
774         addAuxiliaryBinds floats3       $
775         addAuxiliaryBinds floats4       $
776         thing_inside rhs4
777     else        
778                 -- Don't do the float
779         thing_inside (wrapFloats floats1 rhs1)
780
781 demanded_float (NonRec b r) = isStrictDmd (idNewDemandInfo b) && not (isUnLiftedType (idType b))
782                 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
783 demanded_float (Rec _)      = False
784
785 -- If float_ubx is true we float all the bindings, otherwise
786 -- we just float until we come across an unlifted one.
787 -- Remember that the unlifted bindings in the floats are all for
788 -- guaranteed-terminating non-exception-raising unlifted things,
789 -- which we are happy to do speculatively.  However, we may still
790 -- not be able to float them out, because the context
791 -- is either a Rec group, or the top level, neither of which
792 -- can tolerate them.
793 splitFloats float_ubx floats rhs
794   | float_ubx = (floats, rhs)           -- Float them all
795   | otherwise = go (fromOL floats)
796   where
797     go []                   = (nilOL, rhs)
798     go (f:fs) | must_stay f = (nilOL, mkLets (f:fs) rhs)
799               | otherwise   = case go fs of
800                                    (out, rhs') -> (f `consOL` out, rhs')
801
802     must_stay (Rec prs)    = False      -- No unlifted bindings in here
803     must_stay (NonRec b r) = isUnLiftedType (idType b)
804 \end{code}
805
806
807
808 %************************************************************************
809 %*                                                                      *
810 \subsection{Variables}
811 %*                                                                      *
812 %************************************************************************
813
814 \begin{code}
815 simplVar var cont
816   = getSubst            `thenSmpl` \ subst ->
817     case lookupIdSubst subst var of
818         DoneEx e        -> zapSubstEnv (simplExprF e cont)
819         ContEx env1 e   -> setSubstEnv env1 (simplExprF e cont)
820         DoneId var1 occ -> WARN( not (isInScope var1 subst) && mustHaveLocalBinding var1,
821                                  text "simplVar:" <+> ppr var )
822                            zapSubstEnv (completeCall var1 occ cont)
823                 -- The template is already simplified, so don't re-substitute.
824                 -- This is VITAL.  Consider
825                 --      let x = e in
826                 --      let y = \z -> ...x... in
827                 --      \ x -> ...y...
828                 -- We'll clone the inner \x, adding x->x' in the id_subst
829                 -- Then when we inline y, we must *not* replace x by x' in
830                 -- the inlined copy!!
831
832 ---------------------------------------------------------
833 --      Dealing with a call
834
835 completeCall var occ_info cont
836   = getBlackList                `thenSmpl` \ black_list_fn ->
837     getInScope                  `thenSmpl` \ in_scope ->
838     getContArgs var cont        `thenSmpl` \ (args, call_cont, inline_call) ->
839     getDOptsSmpl                `thenSmpl` \ dflags ->
840     let
841         black_listed       = black_list_fn var
842         arg_infos          = [ interestingArg in_scope arg subst 
843                              | (arg, subst, _) <- args, isValArg arg]
844
845         interesting_cont = interestingCallContext (not (null args)) 
846                                                   (not (null arg_infos))
847                                                   call_cont
848
849         inline_cont | inline_call = discardInline cont
850                     | otherwise   = cont
851
852         maybe_inline = callSiteInline dflags black_listed inline_call occ_info
853                                       var arg_infos interesting_cont
854     in
855         -- First, look for an inlining
856     case maybe_inline of {
857         Just unfolding          -- There is an inlining!
858           ->  tick (UnfoldingDone var)          `thenSmpl_`
859               simplExprF unfolding inline_cont
860
861         ;
862         Nothing ->              -- No inlining!
863
864
865     simplifyArgs (isDataConId var) args (contResultType call_cont)  $ \ args' ->
866
867         -- Next, look for rules or specialisations that match
868         --
869         -- It's important to simplify the args first, because the rule-matcher
870         -- doesn't do substitution as it goes.  We don't want to use subst_args
871         -- (defined in the 'where') because that throws away useful occurrence info,
872         -- and perhaps-very-important specialisations.
873         --
874         -- Some functions have specialisations *and* are strict; in this case,
875         -- we don't want to inline the wrapper of the non-specialised thing; better
876         -- to call the specialised thing instead.
877         -- But the black-listing mechanism means that inlining of the wrapper
878         -- won't occur for things that have specialisations till a later phase, so
879         -- it's ok to try for inlining first.
880         --
881         -- You might think that we shouldn't apply rules for a loop breaker: 
882         -- doing so might give rise to an infinite loop, because a RULE is
883         -- rather like an extra equation for the function:
884         --      RULE:           f (g x) y = x+y
885         --      Eqn:            f a     y = a-y
886         --
887         -- But it's too drastic to disable rules for loop breakers.  
888         -- Even the foldr/build rule would be disabled, because foldr 
889         -- is recursive, and hence a loop breaker:
890         --      foldr k z (build g) = g k z
891         -- So it's up to the programmer: rules can cause divergence
892
893     getSwitchChecker    `thenSmpl` \ chkr ->
894     let
895         maybe_rule | switchIsOn chkr DontApplyRules = Nothing
896                    | otherwise                      = lookupRule in_scope var args' 
897     in
898     case maybe_rule of {
899         Just (rule_name, rule_rhs) -> 
900                 tick (RuleFired rule_name)                      `thenSmpl_`
901 #ifdef DEBUG
902                 (if dopt Opt_D_dump_inlinings dflags then
903                    pprTrace "Rule fired" (vcat [
904                         text "Rule:" <+> ptext rule_name,
905                         text "Before:" <+> ppr var <+> sep (map pprParendExpr args'),
906                         text "After: " <+> pprCoreExpr rule_rhs])
907                  else
908                         id)             $
909 #endif
910                 simplExprF rule_rhs call_cont ;
911         
912         Nothing ->              -- No rules
913
914         -- Done
915     rebuild (mkApps (Var var) args') call_cont
916     }}
917
918
919 ---------------------------------------------------------
920 --      Simplifying the arguments of a call
921
922 simplifyArgs :: Bool                            -- It's a data constructor
923              -> [(InExpr, SubstEnv, Bool)]      -- Details of the arguments
924              -> OutType                         -- Type of the continuation
925              -> ([OutExpr] -> SimplM OutExprStuff)
926              -> SimplM OutExprStuff
927
928 -- Simplify the arguments to a call.
929 -- This part of the simplifier may break the no-shadowing invariant
930 -- Consider
931 --      f (...(\a -> e)...) (case y of (a,b) -> e')
932 -- where f is strict in its second arg
933 -- If we simplify the innermost one first we get (...(\a -> e)...)
934 -- Simplifying the second arg makes us float the case out, so we end up with
935 --      case y of (a,b) -> f (...(\a -> e)...) e'
936 -- So the output does not have the no-shadowing invariant.  However, there is
937 -- no danger of getting name-capture, because when the first arg was simplified
938 -- we used an in-scope set that at least mentioned all the variables free in its
939 -- static environment, and that is enough.
940 --
941 -- We can't just do innermost first, or we'd end up with a dual problem:
942 --      case x of (a,b) -> f e (...(\a -> e')...)
943 --
944 -- I spent hours trying to recover the no-shadowing invariant, but I just could
945 -- not think of an elegant way to do it.  The simplifier is already knee-deep in
946 -- continuations.  We have to keep the right in-scope set around; AND we have
947 -- to get the effect that finding (error "foo") in a strict arg position will
948 -- discard the entire application and replace it with (error "foo").  Getting
949 -- all this at once is TOO HARD!
950
951 simplifyArgs is_data_con args cont_ty thing_inside
952   | not is_data_con
953   = go args thing_inside
954
955   | otherwise   -- It's a data constructor, so we want 
956                 -- to switch off inlining in the arguments
957                 -- If we don't do this, consider:
958                 --      let x = +# p q in C {x}
959                 -- Even though x get's an occurrence of 'many', its RHS looks cheap,
960                 -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
961   = getBlackList                                `thenSmpl` \ old_bl ->
962     noInlineBlackList                           `thenSmpl` \ ni_bl ->
963     setBlackList ni_bl                          $
964     go args                                     $ \ args' ->
965     setBlackList old_bl                         $
966     thing_inside args'
967
968   where
969     go []         thing_inside = thing_inside []
970     go (arg:args) thing_inside = simplifyArg is_data_con arg cont_ty    $ \ arg' ->
971                                  go args                                $ \ args' ->
972                                  thing_inside (arg':args')
973
974 simplifyArg is_data_con (Type ty_arg, se, _) cont_ty thing_inside
975   = simplTyArg ty_arg se        `thenSmpl` \ new_ty_arg ->
976     thing_inside (Type new_ty_arg)
977
978 simplifyArg is_data_con (val_arg, se, is_strict) cont_ty thing_inside
979   = getInScope          `thenSmpl` \ in_scope ->
980     let
981         arg_ty = substTy (mkSubst in_scope se) (exprType val_arg)
982     in
983     if not is_data_con then
984         -- An ordinary function
985         simplValArg arg_ty is_strict val_arg se cont_ty thing_inside
986     else
987         -- A data constructor
988         -- simplifyArgs has already switched off inlining, so 
989         -- all we have to do here is to let-bind any non-trivial argument
990
991         -- It's not always the case that new_arg will be trivial
992         -- Consider             f x
993         -- where, in one pass, f gets substituted by a constructor,
994         -- but x gets substituted by an expression (assume this is the
995         -- unique occurrence of x).  It doesn't really matter -- it'll get
996         -- fixed up next pass.  And it happens for dictionary construction,
997         -- which mentions the wrapper constructor to start with.
998         simplValArg arg_ty is_strict val_arg se cont_ty         $ \ arg' ->
999         
1000         if exprIsTrivial arg' then
1001              thing_inside arg'
1002         else
1003         newId SLIT("a") (exprType arg')         $ \ arg_id ->
1004         addNonRecBind arg_id arg'               $
1005         thing_inside (Var arg_id)
1006 \end{code}                 
1007
1008
1009 %************************************************************************
1010 %*                                                                      *
1011 \subsection{Decisions about inlining}
1012 %*                                                                      *
1013 %************************************************************************
1014
1015 NB: At one time I tried not pre/post-inlining top-level things,
1016 even if they occur exactly once.  Reason: 
1017         (a) some might appear as a function argument, so we simply
1018                 replace static allocation with dynamic allocation:
1019                    l = <...>
1020                    x = f l
1021         becomes
1022                    x = f <...>
1023
1024         (b) some top level things might be black listed
1025
1026 HOWEVER, I found that some useful foldr/build fusion was lost (most
1027 notably in spectral/hartel/parstof) because the foldr didn't see the build.
1028
1029 Doing the dynamic allocation isn't a big deal, in fact, but losing the
1030 fusion can be.
1031
1032 \begin{code}
1033 preInlineUnconditionally :: Bool {- Black listed -} -> InId -> Bool
1034         -- Examines a bndr to see if it is used just once in a 
1035         -- completely safe way, so that it is safe to discard the binding
1036         -- inline its RHS at the (unique) usage site, REGARDLESS of how
1037         -- big the RHS might be.  If this is the case we don't simplify
1038         -- the RHS first, but just inline it un-simplified.
1039         --
1040         -- This is much better than first simplifying a perhaps-huge RHS
1041         -- and then inlining and re-simplifying it.
1042         --
1043         -- NB: we don't even look at the RHS to see if it's trivial
1044         -- We might have
1045         --                      x = y
1046         -- where x is used many times, but this is the unique occurrence
1047         -- of y.  We should NOT inline x at all its uses, because then
1048         -- we'd do the same for y -- aargh!  So we must base this
1049         -- pre-rhs-simplification decision solely on x's occurrences, not
1050         -- on its rhs.
1051         -- 
1052         -- Evne RHSs labelled InlineMe aren't caught here, because
1053         -- there might be no benefit from inlining at the call site.
1054
1055 preInlineUnconditionally black_listed bndr
1056   | black_listed || opt_SimplNoPreInlining = False
1057   | otherwise = case idOccInfo bndr of
1058                   OneOcc in_lam once -> not in_lam && once
1059                         -- Not inside a lambda, one occurrence ==> safe!
1060                   other              -> False
1061 \end{code}
1062
1063
1064
1065 %************************************************************************
1066 %*                                                                      *
1067 \subsection{The main rebuilder}
1068 %*                                                                      *
1069 %************************************************************************
1070
1071 \begin{code}
1072 -------------------------------------------------------------------
1073 -- Finish rebuilding
1074 rebuild_done expr = returnOutStuff expr
1075
1076 ---------------------------------------------------------
1077 rebuild :: OutExpr -> SimplCont -> SimplM OutExprStuff
1078
1079 --      Stop continuation
1080 rebuild expr (Stop _ _) = rebuild_done expr
1081
1082 --      ArgOf continuation
1083 rebuild expr (ArgOf _ _ cont_fn) = cont_fn expr
1084
1085 --      ApplyTo continuation
1086 rebuild expr cont@(ApplyTo _ arg se cont')
1087   = setSubstEnv se (simplExpr arg)      `thenSmpl` \ arg' ->
1088     rebuild (App expr arg') cont'
1089
1090 --      Coerce continuation
1091 rebuild expr (CoerceIt to_ty cont)
1092   = rebuild (mkCoerce to_ty (exprType expr) expr) cont
1093
1094 --      Inline continuation
1095 rebuild expr (InlinePlease cont)
1096   = rebuild (Note InlineCall expr) cont
1097
1098 rebuild scrut (Select _ bndr alts se cont)
1099   = rebuild_case scrut bndr alts se cont
1100 \end{code}
1101
1102 Case elimination [see the code above]
1103 ~~~~~~~~~~~~~~~~
1104 Start with a simple situation:
1105
1106         case x# of      ===>   e[x#/y#]
1107           y# -> e
1108
1109 (when x#, y# are of primitive type, of course).  We can't (in general)
1110 do this for algebraic cases, because we might turn bottom into
1111 non-bottom!
1112
1113 Actually, we generalise this idea to look for a case where we're
1114 scrutinising a variable, and we know that only the default case can
1115 match.  For example:
1116 \begin{verbatim}
1117         case x of
1118           0#    -> ...
1119           other -> ...(case x of
1120                          0#    -> ...
1121                          other -> ...) ...
1122 \end{code}
1123 Here the inner case can be eliminated.  This really only shows up in
1124 eliminating error-checking code.
1125
1126 We also make sure that we deal with this very common case:
1127
1128         case e of 
1129           x -> ...x...
1130
1131 Here we are using the case as a strict let; if x is used only once
1132 then we want to inline it.  We have to be careful that this doesn't 
1133 make the program terminate when it would have diverged before, so we
1134 check that 
1135         - x is used strictly, or
1136         - e is already evaluated (it may so if e is a variable)
1137
1138 Lastly, we generalise the transformation to handle this:
1139
1140         case e of       ===> r
1141            True  -> r
1142            False -> r
1143
1144 We only do this for very cheaply compared r's (constructors, literals
1145 and variables).  If pedantic bottoms is on, we only do it when the
1146 scrutinee is a PrimOp which can't fail.
1147
1148 We do it *here*, looking at un-simplified alternatives, because we
1149 have to check that r doesn't mention the variables bound by the
1150 pattern in each alternative, so the binder-info is rather useful.
1151
1152 So the case-elimination algorithm is:
1153
1154         1. Eliminate alternatives which can't match
1155
1156         2. Check whether all the remaining alternatives
1157                 (a) do not mention in their rhs any of the variables bound in their pattern
1158            and  (b) have equal rhss
1159
1160         3. Check we can safely ditch the case:
1161                    * PedanticBottoms is off,
1162                 or * the scrutinee is an already-evaluated variable
1163                 or * the scrutinee is a primop which is ok for speculation
1164                         -- ie we want to preserve divide-by-zero errors, and
1165                         -- calls to error itself!
1166
1167                 or * [Prim cases] the scrutinee is a primitive variable
1168
1169                 or * [Alg cases] the scrutinee is a variable and
1170                      either * the rhs is the same variable
1171                         (eg case x of C a b -> x  ===>   x)
1172                      or     * there is only one alternative, the default alternative,
1173                                 and the binder is used strictly in its scope.
1174                                 [NB this is helped by the "use default binder where
1175                                  possible" transformation; see below.]
1176
1177
1178 If so, then we can replace the case with one of the rhss.
1179
1180
1181 Blob of helper functions for the "case-of-something-else" situation.
1182
1183 \begin{code}
1184 ---------------------------------------------------------
1185 --      Eliminate the case if possible
1186
1187 rebuild_case scrut bndr alts se cont
1188   | maybeToBool maybe_con_app
1189   = knownCon scrut (DataAlt con) args bndr alts se cont
1190
1191   | canEliminateCase scrut bndr alts
1192   = tick (CaseElim bndr)                        `thenSmpl_` (
1193     setSubstEnv se                              $                       
1194     simplBinder bndr                            $ \ bndr' ->
1195         -- Remember to bind the case binder!
1196     completeBinding bndr bndr' False False scrut        $
1197     simplExprF (head (rhssOfAlts alts)) cont)
1198
1199   | otherwise
1200   = complete_case scrut bndr alts se cont
1201
1202   where
1203     maybe_con_app    = exprIsConApp_maybe scrut
1204     Just (con, args) = maybe_con_app
1205
1206         -- See if we can get rid of the case altogether
1207         -- See the extensive notes on case-elimination above
1208 canEliminateCase scrut bndr alts
1209   =     -- Check that the RHSs are all the same, and
1210         -- don't use the binders in the alternatives
1211         -- This test succeeds rapidly in the common case of
1212         -- a single DEFAULT alternative
1213     all (cheapEqExpr rhs1) other_rhss && all binders_unused alts
1214
1215         -- Check that the scrutinee can be let-bound instead of case-bound
1216     && (   exprOkForSpeculation scrut
1217                 -- OK not to evaluate it
1218                 -- This includes things like (==# a# b#)::Bool
1219                 -- so that we simplify 
1220                 --      case ==# a# b# of { True -> x; False -> x }
1221                 -- to just
1222                 --      x
1223                 -- This particular example shows up in default methods for
1224                 -- comparision operations (e.g. in (>=) for Int.Int32)
1225         || exprIsValue scrut                    -- It's already evaluated
1226         || var_demanded_later scrut             -- It'll be demanded later
1227
1228 --      || not opt_SimplPedanticBottoms)        -- Or we don't care!
1229 --      We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1230 --      but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1231 --      its argument:  case x of { y -> dataToTag# y }
1232 --      Here we must *not* discard the case, because dataToTag# just fetches the tag from
1233 --      the info pointer.  So we'll be pedantic all the time, and see if that gives any
1234 --      other problems
1235        )
1236
1237   where
1238     (rhs1:other_rhss)            = rhssOfAlts alts
1239     binders_unused (_, bndrs, _) = all isDeadBinder bndrs
1240
1241     var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo bndr)     -- It's going to be evaluated later
1242     var_demanded_later other   = False
1243
1244
1245 ---------------------------------------------------------
1246 --      Case of something else
1247
1248 complete_case scrut case_bndr alts se cont
1249   =     -- Prepare case alternatives
1250     prepareCaseAlts case_bndr (splitTyConApp_maybe (idType case_bndr))
1251                     impossible_cons alts                `thenSmpl` \ better_alts ->
1252     
1253         -- Set the new subst-env in place (before dealing with the case binder)
1254     setSubstEnv se                              $
1255
1256         -- Deal with the case binder, and prepare the continuation;
1257         -- The new subst_env is in place
1258     prepareCaseCont better_alts cont            $ \ cont' ->
1259         
1260
1261         -- Deal with variable scrutinee
1262     (   
1263         getSwitchChecker                                `thenSmpl` \ chkr ->
1264         simplCaseBinder (switchIsOn chkr NoCaseOfCase)
1265                         scrut case_bndr                 $ \ case_bndr' zap_occ_info ->
1266
1267         -- Deal with the case alternatives
1268         simplAlts zap_occ_info impossible_cons
1269                   case_bndr' better_alts cont'  `thenSmpl` \ alts' ->
1270
1271         mkCase scrut case_bndr' alts'
1272     )                                           `thenSmpl` \ case_expr ->
1273
1274         -- Notice that the simplBinder, prepareCaseCont, etc, do *not* scope
1275         -- over the rebuild_done; rebuild_done returns the in-scope set, and
1276         -- that should not include these chaps!
1277     rebuild_done case_expr      
1278   where
1279     impossible_cons = case scrut of
1280                             Var v -> otherCons (idUnfolding v)
1281                             other -> []
1282
1283
1284 knownCon :: OutExpr -> AltCon -> [OutExpr]
1285          -> InId -> [InAlt] -> SubstEnv -> SimplCont
1286          -> SimplM OutExprStuff
1287
1288 knownCon expr con args bndr alts se cont
1289   =     -- Arguments should be atomic;
1290         -- yell if not
1291     WARN( not (all exprIsTrivial args), 
1292           text "knownCon" <+> ppr expr )
1293     tick (KnownBranch bndr)     `thenSmpl_`
1294     setSubstEnv se              (
1295     simplBinder bndr            $ \ bndr' ->
1296     completeBinding bndr bndr' False False expr $
1297         -- Don't use completeBeta here.  The expr might be
1298         -- an unboxed literal, like 3, or a variable
1299         -- whose unfolding is an unboxed literal... and
1300         -- completeBeta will just construct another case
1301                                         -- expression!
1302     case findAlt con alts of
1303         (DEFAULT, bs, rhs)     -> ASSERT( null bs )
1304                                   simplExprF rhs cont
1305
1306         (LitAlt lit, bs, rhs) ->  ASSERT( null bs )
1307                                   simplExprF rhs cont
1308
1309         (DataAlt dc, bs, rhs)  -> ASSERT( length bs == length real_args )
1310                                   extendSubstList bs (map mk real_args) $
1311                                   simplExprF rhs cont
1312                                where
1313                                   real_args    = drop (dataConNumInstArgs dc) args
1314                                   mk (Type ty) = DoneTy ty
1315                                   mk other     = DoneEx other
1316     )
1317 \end{code}
1318
1319 \begin{code}
1320 prepareCaseCont :: [InAlt] -> SimplCont
1321                 -> (SimplCont -> SimplM (OutStuff a))
1322                 -> SimplM (OutStuff a)
1323         -- Polymorphic recursion here!
1324
1325 prepareCaseCont [alt] cont thing_inside = thing_inside cont
1326 prepareCaseCont alts  cont thing_inside = simplType (coreAltsType alts)         `thenSmpl` \ alts_ty ->
1327                                           mkDupableCont alts_ty cont thing_inside
1328         -- At one time I passed in the un-simplified type, and simplified
1329         -- it only if we needed to construct a join binder, but that    
1330         -- didn't work because we have to decompse function types
1331         -- (using funResultTy) in mkDupableCont.
1332 \end{code}
1333
1334 simplCaseBinder checks whether the scrutinee is a variable, v.  If so,
1335 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1336 way, there's a chance that v will now only be used once, and hence
1337 inlined.
1338
1339 There is a time we *don't* want to do that, namely when
1340 -fno-case-of-case is on.  This happens in the first simplifier pass,
1341 and enhances full laziness.  Here's the bad case:
1342         f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1343 If we eliminate the inner case, we trap it inside the I# v -> arm,
1344 which might prevent some full laziness happening.  I've seen this
1345 in action in spectral/cichelli/Prog.hs:
1346          [(m,n) | m <- [1..max], n <- [1..max]]
1347 Hence the no_case_of_case argument
1348
1349
1350 If we do this, then we have to nuke any occurrence info (eg IAmDead)
1351 in the case binder, because the case-binder now effectively occurs
1352 whenever v does.  AND we have to do the same for the pattern-bound
1353 variables!  Example:
1354
1355         (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1356
1357 Here, b and p are dead.  But when we move the argment inside the first
1358 case RHS, and eliminate the second case, we get
1359
1360         case x or { (a,b) -> a b }
1361
1362 Urk! b is alive!  Reason: the scrutinee was a variable, and case elimination
1363 happened.  Hence the zap_occ_info function returned by simplCaseBinder
1364
1365 \begin{code}
1366 simplCaseBinder no_case_of_case (Var v) case_bndr thing_inside
1367   | not no_case_of_case
1368   = simplBinder (zap case_bndr)                                 $ \ case_bndr' ->
1369     modifyInScope v case_bndr'                                  $
1370         -- We could extend the substitution instead, but it would be
1371         -- a hack because then the substitution wouldn't be idempotent
1372         -- any more (v is an OutId).  And this just just as well.
1373     thing_inside case_bndr' zap
1374   where
1375     zap b = b `setIdOccInfo` NoOccInfo
1376             
1377 simplCaseBinder add_eval_info other_scrut case_bndr thing_inside
1378   = simplBinder case_bndr               $ \ case_bndr' ->
1379     thing_inside case_bndr' (\ bndr -> bndr)    -- NoOp on bndr
1380 \end{code}
1381
1382 prepareCaseAlts does two things:
1383
1384 1.  Remove impossible alternatives
1385
1386 2.  If the DEFAULT alternative can match only one possible constructor,
1387     then make that constructor explicit.
1388     e.g.
1389         case e of x { DEFAULT -> rhs }
1390      ===>
1391         case e of x { (a,b) -> rhs }
1392     where the type is a single constructor type.  This gives better code
1393     when rhs also scrutinises x or e.
1394
1395 \begin{code}
1396 prepareCaseAlts bndr (Just (tycon, inst_tys)) scrut_cons alts
1397   | isDataTyCon tycon
1398   = case (findDefault filtered_alts, missing_cons) of
1399
1400         ((alts_no_deflt, Just rhs), [data_con])         -- Just one missing constructor!
1401                 -> tick (FillInCaseDefault bndr)        `thenSmpl_`
1402                    let
1403                         (_,_,ex_tyvars,_,_,_) = dataConSig data_con
1404                    in
1405                    getUniquesSmpl                       `thenSmpl` \ tv_uniqs ->
1406                    let
1407                         ex_tyvars' = zipWith mk tv_uniqs ex_tyvars
1408                         mk uniq tv = mkSysTyVar uniq (tyVarKind tv)
1409                         arg_tys    = dataConArgTys data_con
1410                                                    (inst_tys ++ mkTyVarTys ex_tyvars')
1411                    in
1412                    newIds SLIT("a") arg_tys             $ \ bndrs ->
1413                    returnSmpl ((DataAlt data_con, ex_tyvars' ++ bndrs, rhs) : alts_no_deflt)
1414
1415         other -> returnSmpl filtered_alts
1416   where
1417         -- Filter out alternatives that can't possibly match
1418     filtered_alts = case scrut_cons of
1419                         []    -> alts
1420                         other -> [alt | alt@(con,_,_) <- alts, not (con `elem` scrut_cons)]
1421
1422     missing_cons = [data_con | data_con <- tyConDataConsIfAvailable tycon, 
1423                                not (data_con `elem` handled_data_cons)]
1424     handled_data_cons = [data_con | DataAlt data_con         <- scrut_cons] ++
1425                         [data_con | (DataAlt data_con, _, _) <- filtered_alts]
1426
1427 -- The default case
1428 prepareCaseAlts _ _ scrut_cons alts
1429   = returnSmpl alts                     -- Functions
1430
1431
1432 ----------------------
1433 simplAlts zap_occ_info scrut_cons case_bndr' alts cont'
1434   = mapSmpl simpl_alt alts
1435   where
1436     inst_tys' = tyConAppArgs (idType case_bndr')
1437
1438         -- handled_cons is all the constructors that are dealt
1439         -- with, either by being impossible, or by there being an alternative
1440     (con_alts,_) = findDefault alts
1441     handled_cons = scrut_cons ++ [con | (con,_,_) <- con_alts]
1442
1443     simpl_alt (DEFAULT, _, rhs)
1444         =       -- In the default case we record the constructors that the
1445                 -- case-binder *can't* be.
1446                 -- We take advantage of any OtherCon info in the case scrutinee
1447           modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkOtherCon handled_cons)        $ 
1448           simplExprC rhs cont'                                                  `thenSmpl` \ rhs' ->
1449           returnSmpl (DEFAULT, [], rhs')
1450
1451     simpl_alt (con, vs, rhs)
1452         =       -- Deal with the pattern-bound variables
1453                 -- Mark the ones that are in ! positions in the data constructor
1454                 -- as certainly-evaluated.
1455                 -- NB: it happens that simplBinders does *not* erase the OtherCon
1456                 --     form of unfolding, so it's ok to add this info before 
1457                 --     doing simplBinders
1458           simplBinders (add_evals con vs)                                       $ \ vs' ->
1459
1460                 -- Bind the case-binder to (con args)
1461           let
1462                 unfolding = mkUnfolding False (mkAltExpr con vs' inst_tys')
1463           in
1464           modifyInScope case_bndr' (case_bndr' `setIdUnfolding` unfolding)      $
1465           simplExprC rhs cont'          `thenSmpl` \ rhs' ->
1466           returnSmpl (con, vs', rhs')
1467
1468
1469         -- add_evals records the evaluated-ness of the bound variables of
1470         -- a case pattern.  This is *important*.  Consider
1471         --      data T = T !Int !Int
1472         --
1473         --      case x of { T a b -> T (a+1) b }
1474         --
1475         -- We really must record that b is already evaluated so that we don't
1476         -- go and re-evaluate it when constructing the result.
1477
1478     add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
1479     add_evals other_con    vs = vs
1480
1481     cat_evals [] [] = []
1482     cat_evals (v:vs) (str:strs)
1483         | isTyVar v          = v        : cat_evals vs (str:strs)
1484         | isMarkedStrict str = evald_v  : cat_evals vs strs
1485         | otherwise          = zapped_v : cat_evals vs strs
1486         where
1487           zapped_v = zap_occ_info v
1488           evald_v  = zapped_v `setIdUnfolding` mkOtherCon []
1489 \end{code}
1490
1491
1492 %************************************************************************
1493 %*                                                                      *
1494 \subsection{Duplicating continuations}
1495 %*                                                                      *
1496 %************************************************************************
1497
1498 \begin{code}
1499 mkDupableCont :: OutType                -- Type of the thing to be given to the continuation
1500               -> SimplCont 
1501               -> (SimplCont -> SimplM (OutStuff a))
1502               -> SimplM (OutStuff a)
1503 mkDupableCont ty cont thing_inside 
1504   | contIsDupable cont
1505   = thing_inside cont
1506
1507 mkDupableCont _ (CoerceIt ty cont) thing_inside
1508   = mkDupableCont ty cont               $ \ cont' ->
1509     thing_inside (CoerceIt ty cont')
1510
1511 mkDupableCont ty (InlinePlease cont) thing_inside
1512   = mkDupableCont ty cont               $ \ cont' ->
1513     thing_inside (InlinePlease cont')
1514
1515 mkDupableCont join_arg_ty (ArgOf _ cont_ty cont_fn) thing_inside
1516   =     -- Build the RHS of the join point
1517     newId SLIT("a") join_arg_ty                         ( \ arg_id ->
1518         cont_fn (Var arg_id)                            `thenSmpl` \ (floats, (_, rhs)) ->
1519         returnSmpl (Lam (setOneShotLambda arg_id) (wrapFloats floats rhs))
1520     )                                                   `thenSmpl` \ join_rhs ->
1521    
1522         -- Build the join Id and continuation
1523         -- We give it a "$j" name just so that for later amusement
1524         -- we can identify any join points that don't end up as let-no-escapes
1525         -- [NOTE: the type used to be exprType join_rhs, but this seems more elegant.]
1526     newId SLIT("$j") (mkFunTy join_arg_ty cont_ty)      $ \ join_id ->
1527     let
1528         new_cont = ArgOf OkToDup cont_ty
1529                          (\arg' -> rebuild_done (App (Var join_id) arg'))
1530     in
1531
1532     tick (CaseOfCase join_id)                                           `thenSmpl_`
1533         -- Want to tick here so that we go round again,
1534         -- and maybe copy or inline the code;
1535         -- not strictly CaseOf Case
1536     addLetBind (NonRec join_id join_rhs)        $
1537     thing_inside new_cont
1538
1539 mkDupableCont ty (ApplyTo _ arg se cont) thing_inside
1540   = mkDupableCont (funResultTy ty) cont                 $ \ cont' ->
1541     setSubstEnv se (simplExpr arg)                      `thenSmpl` \ arg' ->
1542     if exprIsDupable arg' then
1543         thing_inside (ApplyTo OkToDup arg' emptySubstEnv cont')
1544     else
1545     newId SLIT("a") (exprType arg')                     $ \ bndr ->
1546
1547     tick (CaseOfCase bndr)                              `thenSmpl_`
1548         -- Want to tick here so that we go round again,
1549         -- and maybe copy or inline the code;
1550         -- not strictly CaseOf Case
1551
1552      addLetBind (NonRec bndr arg')              $
1553         -- But what if the arg should be case-bound?  We can't use
1554         -- addNonRecBind here because its type is too specific.
1555         -- This has been this way for a long time, so I'll leave it,
1556         -- but I can't convince myself that it's right.
1557
1558      thing_inside (ApplyTo OkToDup (Var bndr) emptySubstEnv cont')
1559
1560
1561 mkDupableCont ty (Select _ case_bndr alts se cont) thing_inside
1562   = tick (CaseOfCase case_bndr)                                         `thenSmpl_`
1563     setSubstEnv se (
1564         simplBinder case_bndr                                           $ \ case_bndr' ->
1565         prepareCaseCont alts cont                                       $ \ cont' ->
1566         mkDupableAlts case_bndr case_bndr' cont' alts                   $ \ alts' ->
1567         returnOutStuff alts'
1568     )                                   `thenSmpl` \ (alt_binds, (in_scope, alts')) ->
1569
1570     addFloats alt_binds in_scope                $
1571
1572         -- NB that the new alternatives, alts', are still InAlts, using the original
1573         -- binders.  That means we can keep the case_bndr intact. This is important
1574         -- because another case-of-case might strike, and so we want to keep the
1575         -- info that the case_bndr is dead (if it is, which is often the case).
1576         -- This is VITAL when the type of case_bndr is an unboxed pair (often the
1577         -- case in I/O rich code.  We aren't allowed a lambda bound
1578         -- arg of unboxed tuple type, and indeed such a case_bndr is always dead
1579     thing_inside (Select OkToDup case_bndr alts' se (mkStop (contResultType cont)))
1580
1581 mkDupableAlts :: InId -> OutId -> SimplCont -> [InAlt] 
1582              -> ([InAlt] -> SimplM (OutStuff a))
1583              -> SimplM (OutStuff a)
1584 mkDupableAlts case_bndr case_bndr' cont [] thing_inside
1585   = thing_inside []
1586 mkDupableAlts case_bndr case_bndr' cont (alt:alts) thing_inside
1587   = mkDupableAlt  case_bndr case_bndr' cont alt         $ \ alt' -> 
1588     mkDupableAlts case_bndr case_bndr' cont alts        $ \ alts' ->
1589     thing_inside (alt' : alts')
1590
1591 mkDupableAlt case_bndr case_bndr' cont alt@(con, bndrs, rhs) thing_inside
1592   = simplBinders bndrs                                  $ \ bndrs' ->
1593     simplExprC rhs cont                                 `thenSmpl` \ rhs' ->
1594
1595     if (case cont of { Stop _ _ -> exprIsDupable rhs'; other -> False}) then
1596         -- It is worth checking for a small RHS because otherwise we
1597         -- get extra let bindings that may cause an extra iteration of the simplifier to
1598         -- inline back in place.  Quite often the rhs is just a variable or constructor.
1599         -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1600         -- iterations because the version with the let bindings looked big, and so wasn't
1601         -- inlined, but after the join points had been inlined it looked smaller, and so
1602         -- was inlined.
1603         --
1604         -- But since the continuation is absorbed into the rhs, we only do this
1605         -- for a Stop continuation.
1606         --
1607         -- NB: we have to check the size of rhs', not rhs. 
1608         -- Duplicating a small InAlt might invalidate occurrence information
1609         -- However, if it *is* dupable, we return the *un* simplified alternative,
1610         -- because otherwise we'd need to pair it up with an empty subst-env.
1611         -- (Remember we must zap the subst-env before re-simplifying something).
1612         -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1613         thing_inside alt
1614
1615     else
1616     let
1617         rhs_ty' = exprType rhs'
1618         (used_bndrs, used_bndrs')
1619            = unzip [pr | pr@(bndr,bndr') <- zip (case_bndr  : bndrs)
1620                                                 (case_bndr' : bndrs'),
1621                          not (isDeadBinder bndr)]
1622                 -- The new binders have lost their occurrence info,
1623                 -- so we have to extract it from the old ones
1624     in
1625     ( if null used_bndrs' 
1626         -- If we try to lift a primitive-typed something out
1627         -- for let-binding-purposes, we will *caseify* it (!),
1628         -- with potentially-disastrous strictness results.  So
1629         -- instead we turn it into a function: \v -> e
1630         -- where v::State# RealWorld#.  The value passed to this function
1631         -- is realworld#, which generates (almost) no code.
1632
1633         -- There's a slight infelicity here: we pass the overall 
1634         -- case_bndr to all the join points if it's used in *any* RHS,
1635         -- because we don't know its usage in each RHS separately
1636
1637         -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1638         -- we make the join point into a function whenever used_bndrs'
1639         -- is empty.  This makes the join-point more CPR friendly. 
1640         -- Consider:    let j = if .. then I# 3 else I# 4
1641         --              in case .. of { A -> j; B -> j; C -> ... }
1642         --
1643         -- Now CPR doesn't w/w j because it's a thunk, so
1644         -- that means that the enclosing function can't w/w either,
1645         -- which is a lose.  Here's the example that happened in practice:
1646         --      kgmod :: Int -> Int -> Int
1647         --      kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1648         --                  then 78
1649         --                  else 5
1650         --
1651         -- I have seen a case alternative like this:
1652         --      True -> \v -> ...
1653         -- It's a bit silly to add the realWorld dummy arg in this case, making
1654         --      $j = \s v -> ...
1655         --         True -> $j s
1656         -- (the \v alone is enough to make CPR happy) but I think it's rare
1657
1658         then newId SLIT("w") realWorldStatePrimTy  $ \ rw_id ->
1659              returnSmpl ([rw_id], [Var realWorldPrimId])
1660         else 
1661              returnSmpl (used_bndrs', map varToCoreExpr used_bndrs)
1662     )
1663         `thenSmpl` \ (final_bndrs', final_args) ->
1664
1665         -- See comment about "$j" name above
1666     newId SLIT("$j") (foldr mkPiType rhs_ty' final_bndrs')      $ \ join_bndr ->
1667         -- Notice the funky mkPiType.  If the contructor has existentials
1668         -- it's possible that the join point will be abstracted over
1669         -- type varaibles as well as term variables.
1670         --  Example:  Suppose we have
1671         --      data T = forall t.  C [t]
1672         --  Then faced with
1673         --      case (case e of ...) of
1674         --          C t xs::[t] -> rhs
1675         --  We get the join point
1676         --      let j :: forall t. [t] -> ...
1677         --          j = /\t \xs::[t] -> rhs
1678         --      in
1679         --      case (case e of ...) of
1680         --          C t xs::[t] -> j t xs
1681
1682     let 
1683         -- We make the lambdas into one-shot-lambdas.  The
1684         -- join point is sure to be applied at most once, and doing so
1685         -- prevents the body of the join point being floated out by
1686         -- the full laziness pass
1687         really_final_bndrs = map one_shot final_bndrs'
1688         one_shot v | isId v    = setOneShotLambda v
1689                    | otherwise = v
1690     in
1691     addLetBind (NonRec join_bndr (mkLams really_final_bndrs rhs'))      $
1692     thing_inside (con, bndrs, mkApps (Var join_bndr) final_args)
1693 \end{code}