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