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