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