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