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