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