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