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