Add the notion of "constructor-like" Ids for rule-matching
[ghc-hetmet.git] / compiler / simplCore / SimplUtils.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[SimplUtils]{The simplifier utilities}
5
6 \begin{code}
7 module SimplUtils (
8         -- Rebuilding
9         mkLam, mkCase, prepareAlts, bindCaseBndr,
10
11         -- Inlining,
12         preInlineUnconditionally, postInlineUnconditionally, 
13         activeInline, activeRule, inlineMode,
14
15         -- The continuation type
16         SimplCont(..), DupFlag(..), ArgInfo(..),
17         contIsDupable, contResultType, contIsTrivial, contArgs, dropArgs, 
18         countValArgs, countArgs, splitInlineCont,
19         mkBoringStop, mkLazyArgStop, contIsRhsOrArg,
20         interestingCallContext, interestingArgContext,
21
22         interestingArg, mkArgInfo,
23         
24         abstractFloats
25     ) where
26
27 #include "HsVersions.h"
28
29 import SimplEnv
30 import DynFlags
31 import StaticFlags
32 import CoreSyn
33 import qualified CoreSubst
34 import PprCore
35 import CoreFVs
36 import CoreUtils
37 import CoreArity        ( etaExpand, exprEtaExpandArity )
38 import CoreUnfold
39 import Name
40 import Id
41 import Var      ( isCoVar )
42 import NewDemand
43 import SimplMonad
44 import Type     hiding( substTy )
45 import Coercion ( coercionKind )
46 import TyCon
47 import Unify    ( dataConCannotMatch )
48 import VarSet
49 import BasicTypes
50 import Util
51 import MonadUtils
52 import Outputable
53 import FastString
54
55 import List( nub )
56 \end{code}
57
58
59 %************************************************************************
60 %*                                                                      *
61                 The SimplCont type
62 %*                                                                      *
63 %************************************************************************
64
65 A SimplCont allows the simplifier to traverse the expression in a 
66 zipper-like fashion.  The SimplCont represents the rest of the expression,
67 "above" the point of interest.
68
69 You can also think of a SimplCont as an "evaluation context", using
70 that term in the way it is used for operational semantics. This is the
71 way I usually think of it, For example you'll often see a syntax for
72 evaluation context looking like
73         C ::= []  |  C e   |  case C of alts  |  C `cast` co
74 That's the kind of thing we are doing here, and I use that syntax in
75 the comments.
76
77
78 Key points:
79   * A SimplCont describes a *strict* context (just like 
80     evaluation contexts do).  E.g. Just [] is not a SimplCont
81
82   * A SimplCont describes a context that *does not* bind
83     any variables.  E.g. \x. [] is not a SimplCont
84
85 \begin{code}
86 data SimplCont  
87   = Stop                -- An empty context, or hole, []     
88         CallCtxt        -- True <=> There is something interesting about
89                         --          the context, and hence the inliner
90                         --          should be a bit keener (see interestingCallContext)
91                         -- Specifically:
92                         --     This is an argument of a function that has RULES
93                         --     Inlining the call might allow the rule to fire
94
95   | CoerceIt            -- C `cast` co
96         OutCoercion             -- The coercion simplified
97         SimplCont
98
99   | ApplyTo             -- C arg
100         DupFlag 
101         InExpr SimplEnv         -- The argument and its static env
102         SimplCont
103
104   | Select              -- case C of alts
105         DupFlag 
106         InId [InAlt] SimplEnv   -- The case binder, alts, and subst-env
107         SimplCont
108
109   -- The two strict forms have no DupFlag, because we never duplicate them
110   | StrictBind          -- (\x* \xs. e) C
111         InId [InBndr]           -- let x* = [] in e     
112         InExpr SimplEnv         --      is a special case 
113         SimplCont       
114
115   | StrictArg           -- e C
116         OutExpr                 -- e 
117         CallCtxt                -- Whether *this* argument position is interesting
118         ArgInfo                 -- Whether the function at the head of e has rules, etc
119         SimplCont               --     plus strictness flags for *further* args
120
121 data ArgInfo 
122   = ArgInfo {
123         ai_rules :: Bool,       -- Function has rules (recursively)
124                                 --      => be keener to inline in all args
125         ai_strs :: [Bool],      -- Strictness of arguments
126                                 --   Usually infinite, but if it is finite it guarantees
127                                 --   that the function diverges after being given
128                                 --   that number of args
129         ai_discs :: [Int]       -- Discounts for arguments; non-zero => be keener to inline
130                                 --   Always infinite
131     }
132
133 instance Outputable SimplCont where
134   ppr (Stop interesting)             = ptext (sLit "Stop") <> brackets (ppr interesting)
135   ppr (ApplyTo dup arg _ cont)       = ((ptext (sLit "ApplyTo") <+> ppr dup <+> pprParendExpr arg)
136                                           {-  $$ nest 2 (pprSimplEnv se) -}) $$ ppr cont
137   ppr (StrictBind b _ _ _ cont)      = (ptext (sLit "StrictBind") <+> ppr b) $$ ppr cont
138   ppr (StrictArg f _ _ cont)         = (ptext (sLit "StrictArg") <+> ppr f) $$ ppr cont
139   ppr (Select dup bndr alts _ cont)  = (ptext (sLit "Select") <+> ppr dup <+> ppr bndr) $$ 
140                                        (nest 4 (ppr alts)) $$ ppr cont 
141   ppr (CoerceIt co cont)             = (ptext (sLit "CoerceIt") <+> ppr co) $$ ppr cont
142
143 data DupFlag = OkToDup | NoDup
144
145 instance Outputable DupFlag where
146   ppr OkToDup = ptext (sLit "ok")
147   ppr NoDup   = ptext (sLit "nodup")
148
149
150
151 -------------------
152 mkBoringStop :: SimplCont
153 mkBoringStop = Stop BoringCtxt
154
155 mkLazyArgStop :: CallCtxt -> SimplCont
156 mkLazyArgStop cci = Stop cci
157
158 -------------------
159 contIsRhsOrArg :: SimplCont -> Bool
160 contIsRhsOrArg (Stop {})       = True
161 contIsRhsOrArg (StrictBind {}) = True
162 contIsRhsOrArg (StrictArg {})  = True
163 contIsRhsOrArg _               = False
164
165 -------------------
166 contIsDupable :: SimplCont -> Bool
167 contIsDupable (Stop {})                  = True
168 contIsDupable (ApplyTo  OkToDup _ _ _)   = True
169 contIsDupable (Select   OkToDup _ _ _ _) = True
170 contIsDupable (CoerceIt _ cont)          = contIsDupable cont
171 contIsDupable _                          = False
172
173 -------------------
174 contIsTrivial :: SimplCont -> Bool
175 contIsTrivial (Stop {})                   = True
176 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
177 contIsTrivial (CoerceIt _ cont)           = contIsTrivial cont
178 contIsTrivial _                           = False
179
180 -------------------
181 contResultType :: SimplEnv -> OutType -> SimplCont -> OutType
182 contResultType env ty cont
183   = go cont ty
184   where
185     subst_ty se ty = substTy (se `setInScope` env) ty
186
187     go (Stop {})                      ty = ty
188     go (CoerceIt co cont)             _  = go cont (snd (coercionKind co))
189     go (StrictBind _ bs body se cont) _  = go cont (subst_ty se (exprType (mkLams bs body)))
190     go (StrictArg fn _ _ cont)        _  = go cont (funResultTy (exprType fn))
191     go (Select _ _ alts se cont)      _  = go cont (subst_ty se (coreAltsType alts))
192     go (ApplyTo _ arg se cont)        ty = go cont (apply_to_arg ty arg se)
193
194     apply_to_arg ty (Type ty_arg) se = applyTy ty (subst_ty se ty_arg)
195     apply_to_arg ty _             _  = funResultTy ty
196
197 -------------------
198 countValArgs :: SimplCont -> Int
199 countValArgs (ApplyTo _ (Type _) _ cont) = countValArgs cont
200 countValArgs (ApplyTo _ _        _ cont) = 1 + countValArgs cont
201 countValArgs _                           = 0
202
203 countArgs :: SimplCont -> Int
204 countArgs (ApplyTo _ _ _ cont) = 1 + countArgs cont
205 countArgs _                    = 0
206
207 contArgs :: SimplCont -> ([OutExpr], SimplCont)
208 -- Uses substitution to turn each arg into an OutExpr
209 contArgs cont = go [] cont
210   where
211     go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
212     go args cont                    = (reverse args, cont)
213
214 dropArgs :: Int -> SimplCont -> SimplCont
215 dropArgs 0 cont = cont
216 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
217 dropArgs n other                = pprPanic "dropArgs" (ppr n <+> ppr other)
218
219 --------------------
220 splitInlineCont :: SimplCont -> Maybe (SimplCont, SimplCont)
221 -- Returns Nothing if the continuation should dissolve an InlineMe Note
222 -- Return Just (c1,c2) otherwise, 
223 --      where c1 is the continuation to put inside the InlineMe 
224 --      and   c2 outside
225
226 -- Example: (__inline_me__ (/\a. e)) ty
227 --      Here we want to do the beta-redex without dissolving the InlineMe
228 -- See test simpl017 (and Trac #1627) for a good example of why this is important
229
230 splitInlineCont (ApplyTo dup (Type ty) se c)
231   | Just (c1, c2) <- splitInlineCont c = Just (ApplyTo dup (Type ty) se c1, c2)
232 splitInlineCont cont@(Stop {})         = Just (mkBoringStop, cont)
233 splitInlineCont cont@(StrictBind {})   = Just (mkBoringStop, cont)
234 splitInlineCont _                      = Nothing
235         -- NB: we dissolve an InlineMe in any strict context, 
236         --     not just function aplication.  
237         -- E.g.  foldr k z (__inline_me (case x of p -> build ...))
238         --     Here we want to get rid of the __inline_me__ so we
239         --     can float the case, and see foldr/build
240         --
241         -- However *not* in a strict RHS, else we get
242         --         let f = __inline_me__ (\x. e) in ...f...
243         -- Now if f is guaranteed to be called, hence a strict binding
244         -- we don't thereby want to dissolve the __inline_me__; for
245         -- example, 'f' might be a  wrapper, so we'd inline the worker
246 \end{code}
247
248
249 \begin{code}
250 interestingArg :: OutExpr -> Bool
251         -- An argument is interesting if it has *some* structure
252         -- We are here trying to avoid unfolding a function that
253         -- is applied only to variables that have no unfolding
254         -- (i.e. they are probably lambda bound): f x y z
255         -- There is little point in inlining f here.
256 interestingArg (Var v)           = hasSomeUnfolding (idUnfolding v)
257                                         -- Was: isValueUnfolding (idUnfolding v')
258                                         -- But that seems over-pessimistic
259                                  || isDataConWorkId v
260                                         -- This accounts for an argument like
261                                         -- () or [], which is definitely interesting
262 interestingArg (Type _)          = False
263 interestingArg (App fn (Type _)) = interestingArg fn
264 interestingArg (Note _ a)        = interestingArg a
265
266 -- Idea (from Sam B); I'm not sure if it's a good idea, so commented out for now
267 -- interestingArg expr | isUnLiftedType (exprType expr)
268 --        -- Unlifted args are only ever interesting if we know what they are
269 --  =                  case expr of
270 --                        Lit lit -> True
271 --                        _       -> False
272
273 interestingArg _                 = True
274         -- Consider     let x = 3 in f x
275         -- The substitution will contain (x -> ContEx 3), and we want to
276         -- to say that x is an interesting argument.
277         -- But consider also (\x. f x y) y
278         -- The substitution will contain (x -> ContEx y), and we want to say
279         -- that x is not interesting (assuming y has no unfolding)
280 \end{code}
281
282
283 Comment about interestingCallContext
284 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
285 We want to avoid inlining an expression where there can't possibly be
286 any gain, such as in an argument position.  Hence, if the continuation
287 is interesting (eg. a case scrutinee, application etc.) then we
288 inline, otherwise we don't.  
289
290 Previously some_benefit used to return True only if the variable was
291 applied to some value arguments.  This didn't work:
292
293         let x = _coerce_ (T Int) Int (I# 3) in
294         case _coerce_ Int (T Int) x of
295                 I# y -> ....
296
297 we want to inline x, but can't see that it's a constructor in a case
298 scrutinee position, and some_benefit is False.
299
300 Another example:
301
302 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
303
304 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
305
306 we'd really like to inline dMonadST here, but we *don't* want to
307 inline if the case expression is just
308
309         case x of y { DEFAULT -> ... }
310
311 since we can just eliminate this case instead (x is in WHNF).  Similar
312 applies when x is bound to a lambda expression.  Hence
313 contIsInteresting looks for case expressions with just a single
314 default case.
315
316
317 \begin{code}
318 interestingCallContext :: SimplCont -> CallCtxt
319 interestingCallContext cont
320   = interesting cont
321   where
322     interesting (Select _ bndr _ _ _)
323         | isDeadBinder bndr = CaseCtxt
324         | otherwise         = ArgCtxt False 2   -- If the binder is used, this
325                                                 -- is like a strict let
326                 
327     interesting (ApplyTo _ arg _ cont)
328         | isTypeArg arg = interesting cont
329         | otherwise     = ValAppCtxt    -- Can happen if we have (f Int |> co) y
330                                         -- If f has an INLINE prag we need to give it some
331                                         -- motivation to inline. See Note [Cast then apply]
332                                         -- in CoreUnfold
333
334     interesting (StrictArg _ cci _ _)   = cci
335     interesting (StrictBind {})         = BoringCtxt
336     interesting (Stop cci)              = cci
337     interesting (CoerceIt _ cont)       = interesting cont
338         -- If this call is the arg of a strict function, the context
339         -- is a bit interesting.  If we inline here, we may get useful
340         -- evaluation information to avoid repeated evals: e.g.
341         --      x + (y * z)
342         -- Here the contIsInteresting makes the '*' keener to inline,
343         -- which in turn exposes a constructor which makes the '+' inline.
344         -- Assuming that +,* aren't small enough to inline regardless.
345         --
346         -- It's also very important to inline in a strict context for things
347         -- like
348         --              foldr k z (f x)
349         -- Here, the context of (f x) is strict, and if f's unfolding is
350         -- a build it's *great* to inline it here.  So we must ensure that
351         -- the context for (f x) is not totally uninteresting.
352
353
354 -------------------
355 mkArgInfo :: Id
356           -> Int        -- Number of value args
357           -> SimplCont  -- Context of the cal
358           -> ArgInfo
359
360 mkArgInfo fun n_val_args call_cont
361   | n_val_args < idArity fun            -- Note [Unsaturated functions]
362   = ArgInfo { ai_rules = False
363             , ai_strs = vanilla_stricts 
364             , ai_discs = vanilla_discounts }
365   | otherwise
366   = ArgInfo { ai_rules = interestingArgContext fun call_cont
367             , ai_strs  = add_type_str (idType fun) arg_stricts
368             , ai_discs = arg_discounts }
369   where
370     vanilla_discounts, arg_discounts :: [Int]
371     vanilla_discounts = repeat 0
372     arg_discounts = case idUnfolding fun of
373                         CoreUnfolding _ _ _ _ _ (UnfoldIfGoodArgs _ discounts _ _)
374                               -> discounts ++ vanilla_discounts
375                         _     -> vanilla_discounts
376
377     vanilla_stricts, arg_stricts :: [Bool]
378     vanilla_stricts  = repeat False
379
380     arg_stricts
381       = case splitStrictSig (idNewStrictness fun) of
382           (demands, result_info)
383                 | not (demands `lengthExceeds` n_val_args)
384                 ->      -- Enough args, use the strictness given.
385                         -- For bottoming functions we used to pretend that the arg
386                         -- is lazy, so that we don't treat the arg as an
387                         -- interesting context.  This avoids substituting
388                         -- top-level bindings for (say) strings into 
389                         -- calls to error.  But now we are more careful about
390                         -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
391                    if isBotRes result_info then
392                         map isStrictDmd demands         -- Finite => result is bottom
393                    else
394                         map isStrictDmd demands ++ vanilla_stricts
395                | otherwise
396                -> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun) 
397                                 <+> ppr n_val_args <+> ppr demands ) 
398                    vanilla_stricts      -- Not enough args, or no strictness
399
400     add_type_str :: Type -> [Bool] -> [Bool]
401     -- If the function arg types are strict, record that in the 'strictness bits'
402     -- No need to instantiate because unboxed types (which dominate the strict
403     -- types) can't instantiate type variables.
404     -- add_type_str is done repeatedly (for each call); might be better 
405     -- once-for-all in the function
406     -- But beware primops/datacons with no strictness
407     add_type_str _ [] = []
408     add_type_str fun_ty strs            -- Look through foralls
409         | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty       -- Includes coercions
410         = add_type_str fun_ty' strs
411     add_type_str fun_ty (str:strs)      -- Add strict-type info
412         | Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
413         = (str || isStrictType arg_ty) : add_type_str fun_ty' strs
414     add_type_str _ strs
415         = strs
416
417 {- Note [Unsaturated functions]
418   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
419 Consider (test eyeball/inline4)
420         x = a:as
421         y = f x
422 where f has arity 2.  Then we do not want to inline 'x', because
423 it'll just be floated out again.  Even if f has lots of discounts
424 on its first argument -- it must be saturated for these to kick in
425 -}
426
427 interestingArgContext :: Id -> SimplCont -> Bool
428 -- If the argument has form (f x y), where x,y are boring,
429 -- and f is marked INLINE, then we don't want to inline f.
430 -- But if the context of the argument is
431 --      g (f x y) 
432 -- where g has rules, then we *do* want to inline f, in case it
433 -- exposes a rule that might fire.  Similarly, if the context is
434 --      h (g (f x x))
435 -- where h has rules, then we do want to inline f; hence the
436 -- call_cont argument to interestingArgContext
437 --
438 -- The interesting_arg_ctxt flag makes this happen; if it's
439 -- set, the inliner gets just enough keener to inline f 
440 -- regardless of how boring f's arguments are, if it's marked INLINE
441 --
442 -- The alternative would be to *always* inline an INLINE function,
443 -- regardless of how boring its context is; but that seems overkill
444 -- For example, it'd mean that wrapper functions were always inlined
445 interestingArgContext fn call_cont
446   = idHasRules fn || go call_cont
447   where
448     go (Select {})           = False
449     go (ApplyTo {})          = False
450     go (StrictArg _ cci _ _) = interesting cci
451     go (StrictBind {})       = False    -- ??
452     go (CoerceIt _ c)        = go c
453     go (Stop cci)            = interesting cci
454
455     interesting (ArgCtxt rules _) = rules
456     interesting _                 = False
457 \end{code}
458
459
460
461 %************************************************************************
462 %*                                                                      *
463 \subsection{Decisions about inlining}
464 %*                                                                      *
465 %************************************************************************
466
467 Inlining is controlled partly by the SimplifierMode switch.  This has two
468 settings:
469
470         SimplGently     (a) Simplifying before specialiser/full laziness
471                         (b) Simplifiying inside INLINE pragma
472                         (c) Simplifying the LHS of a rule
473                         (d) Simplifying a GHCi expression or Template 
474                                 Haskell splice
475
476         SimplPhase n _   Used at all other times
477
478 The key thing about SimplGently is that it does no call-site inlining.
479 Before full laziness we must be careful not to inline wrappers,
480 because doing so inhibits floating
481     e.g. ...(case f x of ...)...
482     ==> ...(case (case x of I# x# -> fw x#) of ...)...
483     ==> ...(case x of I# x# -> case fw x# of ...)...
484 and now the redex (f x) isn't floatable any more.
485
486 The no-inlining thing is also important for Template Haskell.  You might be 
487 compiling in one-shot mode with -O2; but when TH compiles a splice before
488 running it, we don't want to use -O2.  Indeed, we don't want to inline
489 anything, because the byte-code interpreter might get confused about 
490 unboxed tuples and suchlike.
491
492 INLINE pragmas
493 ~~~~~~~~~~~~~~
494 SimplGently is also used as the mode to simplify inside an InlineMe note.
495
496 \begin{code}
497 inlineMode :: SimplifierMode
498 inlineMode = SimplGently
499 \end{code}
500
501 It really is important to switch off inlinings inside such
502 expressions.  Consider the following example 
503
504         let f = \pq -> BIG
505         in
506         let g = \y -> f y y
507             {-# INLINE g #-}
508         in ...g...g...g...g...g...
509
510 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
511 and thence copied multiple times when g is inlined.
512
513
514 This function may be inlinined in other modules, so we
515 don't want to remove (by inlining) calls to functions that have
516 specialisations, or that may have transformation rules in an importing
517 scope.
518
519 E.g.    {-# INLINE f #-}
520                 f x = ...g...
521
522 and suppose that g is strict *and* has specialisations.  If we inline
523 g's wrapper, we deny f the chance of getting the specialised version
524 of g when f is inlined at some call site (perhaps in some other
525 module).
526
527 It's also important not to inline a worker back into a wrapper.
528 A wrapper looks like
529         wraper = inline_me (\x -> ...worker... )
530 Normally, the inline_me prevents the worker getting inlined into
531 the wrapper (initially, the worker's only call site!).  But,
532 if the wrapper is sure to be called, the strictness analyser will
533 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
534 continuation.  That's why the keep_inline predicate returns True for
535 ArgOf continuations.  It shouldn't do any harm not to dissolve the
536 inline-me note under these circumstances.
537
538 Note that the result is that we do very little simplification
539 inside an InlineMe.  
540
541         all xs = foldr (&&) True xs
542         any p = all . map p  {-# INLINE any #-}
543
544 Problem: any won't get deforested, and so if it's exported and the
545 importer doesn't use the inlining, (eg passes it as an arg) then we
546 won't get deforestation at all.  We havn't solved this problem yet!
547
548
549 preInlineUnconditionally
550 ~~~~~~~~~~~~~~~~~~~~~~~~
551 @preInlineUnconditionally@ examines a bndr to see if it is used just
552 once in a completely safe way, so that it is safe to discard the
553 binding inline its RHS at the (unique) usage site, REGARDLESS of how
554 big the RHS might be.  If this is the case we don't simplify the RHS
555 first, but just inline it un-simplified.
556
557 This is much better than first simplifying a perhaps-huge RHS and then
558 inlining and re-simplifying it.  Indeed, it can be at least quadratically
559 better.  Consider
560
561         x1 = e1
562         x2 = e2[x1]
563         x3 = e3[x2]
564         ...etc...
565         xN = eN[xN-1]
566
567 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
568 This can happen with cascades of functions too:
569
570         f1 = \x1.e1
571         f2 = \xs.e2[f1]
572         f3 = \xs.e3[f3]
573         ...etc...
574
575 THE MAIN INVARIANT is this:
576
577         ----  preInlineUnconditionally invariant -----
578    IF preInlineUnconditionally chooses to inline x = <rhs>
579    THEN doing the inlining should not change the occurrence
580         info for the free vars of <rhs>
581         ----------------------------------------------
582
583 For example, it's tempting to look at trivial binding like
584         x = y
585 and inline it unconditionally.  But suppose x is used many times,
586 but this is the unique occurrence of y.  Then inlining x would change
587 y's occurrence info, which breaks the invariant.  It matters: y
588 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
589
590
591 Even RHSs labelled InlineMe aren't caught here, because there might be
592 no benefit from inlining at the call site.
593
594 [Sept 01] Don't unconditionally inline a top-level thing, because that
595 can simply make a static thing into something built dynamically.  E.g.
596         x = (a,b)
597         main = \s -> h x
598
599 [Remember that we treat \s as a one-shot lambda.]  No point in
600 inlining x unless there is something interesting about the call site.
601
602 But watch out: if you aren't careful, some useful foldr/build fusion
603 can be lost (most notably in spectral/hartel/parstof) because the
604 foldr didn't see the build.  Doing the dynamic allocation isn't a big
605 deal, in fact, but losing the fusion can be.  But the right thing here
606 seems to be to do a callSiteInline based on the fact that there is
607 something interesting about the call site (it's strict).  Hmm.  That
608 seems a bit fragile.
609
610 Conclusion: inline top level things gaily until Phase 0 (the last
611 phase), at which point don't.
612
613 \begin{code}
614 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
615 preInlineUnconditionally env top_lvl bndr rhs
616   | not active             = False
617   | opt_SimplNoPreInlining = False
618   | otherwise = case idOccInfo bndr of
619                   IAmDead                    -> True    -- Happens in ((\x.1) v)
620                   OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
621                   _                          -> False
622   where
623     phase = getMode env
624     active = case phase of
625                    SimplGently    -> isAlwaysActive act
626                    SimplPhase n _ -> isActive n act
627     act = idInlineActivation bndr
628
629     try_once in_lam int_cxt     -- There's one textual occurrence
630         | not in_lam = isNotTopLevel top_lvl || early_phase
631         | otherwise  = int_cxt && canInlineInLam rhs
632
633 -- Be very careful before inlining inside a lambda, becuase (a) we must not 
634 -- invalidate occurrence information, and (b) we want to avoid pushing a
635 -- single allocation (here) into multiple allocations (inside lambda).  
636 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
637 --      || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
638 --      where 
639 --              is_cheap = exprIsCheap rhs
640 --              ok = is_cheap && int_cxt
641
642         --      int_cxt         The context isn't totally boring
643         -- E.g. let f = \ab.BIG in \y. map f xs
644         --      Don't want to substitute for f, because then we allocate
645         --      its closure every time the \y is called
646         -- But: let f = \ab.BIG in \y. map (f y) xs
647         --      Now we do want to substitute for f, even though it's not 
648         --      saturated, because we're going to allocate a closure for 
649         --      (f y) every time round the loop anyhow.
650
651         -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
652         -- so substituting rhs inside a lambda doesn't change the occ info.
653         -- Sadly, not quite the same as exprIsHNF.
654     canInlineInLam (Lit _)              = True
655     canInlineInLam (Lam b e)            = isRuntimeVar b || canInlineInLam e
656     canInlineInLam (Note _ e)           = canInlineInLam e
657     canInlineInLam _                    = False
658
659     early_phase = case phase of
660                         SimplPhase 0 _ -> False
661                         _              -> True
662 -- If we don't have this early_phase test, consider
663 --      x = length [1,2,3]
664 -- The full laziness pass carefully floats all the cons cells to
665 -- top level, and preInlineUnconditionally floats them all back in.
666 -- Result is (a) static allocation replaced by dynamic allocation
667 --           (b) many simplifier iterations because this tickles
668 --               a related problem; only one inlining per pass
669 -- 
670 -- On the other hand, I have seen cases where top-level fusion is
671 -- lost if we don't inline top level thing (e.g. string constants)
672 -- Hence the test for phase zero (which is the phase for all the final
673 -- simplifications).  Until phase zero we take no special notice of
674 -- top level things, but then we become more leery about inlining
675 -- them.  
676
677 \end{code}
678
679 postInlineUnconditionally
680 ~~~~~~~~~~~~~~~~~~~~~~~~~
681 @postInlineUnconditionally@ decides whether to unconditionally inline
682 a thing based on the form of its RHS; in particular if it has a
683 trivial RHS.  If so, we can inline and discard the binding altogether.
684
685 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
686 only have *forward* references Hence, it's safe to discard the binding
687         
688 NOTE: This isn't our last opportunity to inline.  We're at the binding
689 site right now, and we'll get another opportunity when we get to the
690 ocurrence(s)
691
692 Note that we do this unconditional inlining only for trival RHSs.
693 Don't inline even WHNFs inside lambdas; doing so may simply increase
694 allocation when the function is called. This isn't the last chance; see
695 NOTE above.
696
697 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
698 Because we don't even want to inline them into the RHS of constructor
699 arguments. See NOTE above
700
701 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
702 it's best to inline it anyway.  We often get a=E; b=a from desugaring,
703 with both a and b marked NOINLINE.  But that seems incompatible with
704 our new view that inlining is like a RULE, so I'm sticking to the 'active'
705 story for now.
706
707 \begin{code}
708 postInlineUnconditionally 
709     :: SimplEnv -> TopLevelFlag
710     -> InId             -- The binder (an OutId would be fine too)
711     -> OccInfo          -- From the InId
712     -> OutExpr
713     -> Unfolding
714     -> Bool
715 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
716   | not active             = False
717   | isLoopBreaker occ_info = False      -- If it's a loop-breaker of any kind, don't inline
718                                         -- because it might be referred to "earlier"
719   | isExportedId bndr      = False
720   | exprIsTrivial rhs      = True
721   | otherwise
722   = case occ_info of
723         -- The point of examining occ_info here is that for *non-values* 
724         -- that occur outside a lambda, the call-site inliner won't have
725         -- a chance (becuase it doesn't know that the thing
726         -- only occurs once).   The pre-inliner won't have gotten
727         -- it either, if the thing occurs in more than one branch
728         -- So the main target is things like
729         --      let x = f y in
730         --      case v of
731         --         True  -> case x of ...
732         --         False -> case x of ...
733         -- I'm not sure how important this is in practice
734       OneOcc in_lam _one_br int_cxt     -- OneOcc => no code-duplication issue
735         ->     smallEnoughToInline unfolding    -- Small enough to dup
736                         -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
737                         --
738                         -- NB: Do NOT inline arbitrarily big things, even if one_br is True
739                         -- Reason: doing so risks exponential behaviour.  We simplify a big
740                         --         expression, inline it, and simplify it again.  But if the
741                         --         very same thing happens in the big expression, we get 
742                         --         exponential cost!
743                         -- PRINCIPLE: when we've already simplified an expression once, 
744                         -- make sure that we only inline it if it's reasonably small.
745
746            &&  ((isNotTopLevel top_lvl && not in_lam) || 
747                         -- But outside a lambda, we want to be reasonably aggressive
748                         -- about inlining into multiple branches of case
749                         -- e.g. let x = <non-value> 
750                         --      in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... } 
751                         -- Inlining can be a big win if C3 is the hot-spot, even if
752                         -- the uses in C1, C2 are not 'interesting'
753                         -- An example that gets worse if you add int_cxt here is 'clausify'
754
755                 (isCheapUnfolding unfolding && int_cxt))
756                         -- isCheap => acceptable work duplication; in_lam may be true
757                         -- int_cxt to prevent us inlining inside a lambda without some 
758                         -- good reason.  See the notes on int_cxt in preInlineUnconditionally
759
760       IAmDead -> True   -- This happens; for example, the case_bndr during case of
761                         -- known constructor:  case (a,b) of x { (p,q) -> ... }
762                         -- Here x isn't mentioned in the RHS, so we don't want to
763                         -- create the (dead) let-binding  let x = (a,b) in ...
764
765       _ -> False
766
767 -- Here's an example that we don't handle well:
768 --      let f = if b then Left (\x.BIG) else Right (\y.BIG)
769 --      in \y. ....case f of {...} ....
770 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
771 -- But
772 --  - We can't preInlineUnconditionally because that woud invalidate
773 --    the occ info for b.
774 --  - We can't postInlineUnconditionally because the RHS is big, and
775 --    that risks exponential behaviour
776 --  - We can't call-site inline, because the rhs is big
777 -- Alas!
778
779   where
780     active = case getMode env of
781                    SimplGently    -> isAlwaysActive act
782                    SimplPhase n _ -> isActive n act
783     act = idInlineActivation bndr
784
785 activeInline :: SimplEnv -> OutId -> Bool
786 activeInline env id
787   = case getMode env of
788       SimplGently -> False
789         -- No inlining at all when doing gentle stuff,
790         -- except for local things that occur once (pre/postInlineUnconditionally)
791         -- The reason is that too little clean-up happens if you 
792         -- don't inline use-once things.   Also a bit of inlining is *good* for
793         -- full laziness; it can expose constant sub-expressions.
794         -- Example in spectral/mandel/Mandel.hs, where the mandelset 
795         -- function gets a useful let-float if you inline windowToViewport
796
797         -- NB: we used to have a second exception, for data con wrappers.
798         -- On the grounds that we use gentle mode for rule LHSs, and 
799         -- they match better when data con wrappers are inlined.
800         -- But that only really applies to the trivial wrappers (like (:)),
801         -- and they are now constructed as Compulsory unfoldings (in MkId)
802         -- so they'll happen anyway.
803
804       SimplPhase n _ -> isActive n act
805   where
806     act = idInlineActivation id
807
808 activeRule :: DynFlags -> SimplEnv -> Maybe (Activation -> Bool)
809 -- Nothing => No rules at all
810 activeRule dflags env
811   | not (dopt Opt_EnableRewriteRules dflags)
812   = Nothing     -- Rewriting is off
813   | otherwise
814   = case getMode env of
815         SimplGently    -> Just isAlwaysActive
816                         -- Used to be Nothing (no rules in gentle mode)
817                         -- Main motivation for changing is that I wanted
818                         --      lift String ===> ...
819                         -- to work in Template Haskell when simplifying
820                         -- splices, so we get simpler code for literal strings
821         SimplPhase n _ -> Just (isActive n)
822 \end{code}
823
824
825 %************************************************************************
826 %*                                                                      *
827         Rebuilding a lambda
828 %*                                                                      *
829 %************************************************************************
830
831 \begin{code}
832 mkLam :: SimplEnv -> [OutBndr] -> OutExpr -> SimplM OutExpr
833 -- mkLam tries three things
834 --      a) eta reduction, if that gives a trivial expression
835 --      b) eta expansion [only if there are some value lambdas]
836
837 mkLam _b [] body 
838   = return body
839 mkLam _env bndrs body
840   = do  { dflags <- getDOptsSmpl
841         ; mkLam' dflags bndrs body }
842   where
843     mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
844     mkLam' dflags bndrs (Cast body co)
845       | not (any bad bndrs)
846         -- Note [Casts and lambdas]
847       = do { lam <- mkLam' dflags bndrs body
848            ; return (mkCoerce (mkPiTypes bndrs co) lam) }
849       where
850         co_vars  = tyVarsOfType co
851         bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars      
852
853     mkLam' dflags bndrs body
854       | dopt Opt_DoEtaReduction dflags,
855         Just etad_lam <- tryEtaReduce bndrs body
856       = do { tick (EtaReduction (head bndrs))
857            ; return etad_lam }
858
859       | dopt Opt_DoLambdaEtaExpansion dflags,
860         any isRuntimeVar bndrs
861       = do { let body' = tryEtaExpansion dflags body
862            ; return (mkLams bndrs body') }
863    
864       | otherwise 
865       = return (mkLams bndrs body)
866 \end{code}
867
868 Note [Casts and lambdas]
869 ~~~~~~~~~~~~~~~~~~~~~~~~
870 Consider 
871         (\x. (\y. e) `cast` g1) `cast` g2
872 There is a danger here that the two lambdas look separated, and the 
873 full laziness pass might float an expression to between the two.
874
875 So this equation in mkLam' floats the g1 out, thus:
876         (\x. e `cast` g1)  -->  (\x.e) `cast` (tx -> g1)
877 where x:tx.
878
879 In general, this floats casts outside lambdas, where (I hope) they
880 might meet and cancel with some other cast:
881         \x. e `cast` co   ===>   (\x. e) `cast` (tx -> co)
882         /\a. e `cast` co  ===>   (/\a. e) `cast` (/\a. co)
883         /\g. e `cast` co  ===>   (/\g. e) `cast` (/\g. co)
884                           (if not (g `in` co))
885
886 Notice that it works regardless of 'e'.  Originally it worked only
887 if 'e' was itself a lambda, but in some cases that resulted in 
888 fruitless iteration in the simplifier.  A good example was when
889 compiling Text.ParserCombinators.ReadPrec, where we had a definition 
890 like    (\x. Get `cast` g)
891 where Get is a constructor with nonzero arity.  Then mkLam eta-expanded
892 the Get, and the next iteration eta-reduced it, and then eta-expanded 
893 it again.
894
895 Note also the side condition for the case of coercion binders.
896 It does not make sense to transform
897         /\g. e `cast` g  ==>  (/\g.e) `cast` (/\g.g)
898 because the latter is not well-kinded.
899
900 --      c) floating lets out through big lambdas 
901 --              [only if all tyvar lambdas, and only if this lambda
902 --               is the RHS of a let]
903
904 {-      Sept 01: I'm experimenting with getting the
905         full laziness pass to float out past big lambdsa
906  | all isTyVar bndrs,   -- Only for big lambdas
907    contIsRhs cont       -- Only try the rhs type-lambda floating
908                         -- if this is indeed a right-hand side; otherwise
909                         -- we end up floating the thing out, only for float-in
910                         -- to float it right back in again!
911  = do (floats, body') <- tryRhsTyLam env bndrs body
912       return (floats, mkLams bndrs body')
913 -}
914
915
916 %************************************************************************
917 %*                                                                      *
918                 Eta reduction
919 %*                                                                      *
920 %************************************************************************
921
922 Note [Eta reduction conditions]
923 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
924 We try for eta reduction here, but *only* if we get all the way to an
925 trivial expression.  We don't want to remove extra lambdas unless we
926 are going to avoid allocating this thing altogether.
927
928 There are some particularly delicate points here:
929
930 * Eta reduction is not valid in general:  
931         \x. bot  /=  bot
932   This matters, partly for old-fashioned correctness reasons but,
933   worse, getting it wrong can yield a seg fault. Consider
934         f = \x.f x
935         h y = case (case y of { True -> f `seq` True; False -> False }) of
936                 True -> ...; False -> ...
937
938   If we (unsoundly) eta-reduce f to get f=f, the strictness analyser
939   says f=bottom, and replaces the (f `seq` True) with just
940   (f `cast` unsafe-co).  BUT, as thing stand, 'f' got arity 1, and it
941   *keeps* arity 1 (perhaps also wrongly).  So CorePrep eta-expands 
942   the definition again, so that it does not termninate after all.
943   Result: seg-fault because the boolean case actually gets a function value.
944   See Trac #1947.
945
946   So it's important to to the right thing.
947
948 * Note [Arity care]: we need to be careful if we just look at f's
949   arity. Currently (Dec07), f's arity is visible in its own RHS (see
950   Note [Arity robustness] in SimplEnv) so we must *not* trust the
951   arity when checking that 'f' is a value.  Otherwise we will
952   eta-reduce
953       f = \x. f x
954   to
955       f = f
956   Which might change a terminiating program (think (f `seq` e)) to a 
957   non-terminating one.  So we check for being a loop breaker first.
958
959   However for GlobalIds we can look at the arity; and for primops we
960   must, since they have no unfolding.  
961
962 * Regardless of whether 'f' is a value, we always want to 
963   reduce (/\a -> f a) to f
964   This came up in a RULE: foldr (build (/\a -> g a))
965   did not match           foldr (build (/\b -> ...something complex...))
966   The type checker can insert these eta-expanded versions,
967   with both type and dictionary lambdas; hence the slightly 
968   ad-hoc isDictId
969
970 * Never *reduce* arity. For example
971       f = \xy. g x y
972   Then if h has arity 1 we don't want to eta-reduce because then
973   f's arity would decrease, and that is bad
974
975 These delicacies are why we don't use exprIsTrivial and exprIsHNF here.
976 Alas.
977
978 \begin{code}
979 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
980 tryEtaReduce bndrs body 
981   = go (reverse bndrs) body
982   where
983     incoming_arity = count isId bndrs
984
985     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
986     go []       fun           | ok_fun fun   = Just fun         -- Success!
987     go _        _                            = Nothing          -- Failure!
988
989         -- Note [Eta reduction conditions]
990     ok_fun (App fun (Type ty)) 
991         | not (any (`elemVarSet` tyVarsOfType ty) bndrs)
992         =  ok_fun fun
993     ok_fun (Var fun_id)
994         =  not (fun_id `elem` bndrs)
995         && (ok_fun_id fun_id || all ok_lam bndrs)
996     ok_fun _fun = False
997
998     ok_fun_id fun = fun_arity fun >= incoming_arity
999
1000     fun_arity fun             -- See Note [Arity care]
1001        | isLocalId fun && isLoopBreaker (idOccInfo fun) = 0
1002        | otherwise = idArity fun              
1003
1004     ok_lam v = isTyVar v || isDictId v
1005
1006     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
1007 \end{code}
1008
1009
1010 %************************************************************************
1011 %*                                                                      *
1012                 Eta expansion
1013 %*                                                                      *
1014 %************************************************************************
1015
1016
1017 We go for:
1018    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
1019                                  (n >= 0)
1020
1021 where (in both cases) 
1022
1023         * The xi can include type variables
1024
1025         * The yi are all value variables
1026
1027         * N is a NORMAL FORM (i.e. no redexes anywhere)
1028           wanting a suitable number of extra args.
1029
1030 The biggest reason for doing this is for cases like
1031
1032         f = \x -> case x of
1033                     True  -> \y -> e1
1034                     False -> \y -> e2
1035
1036 Here we want to get the lambdas together.  A good exmaple is the nofib
1037 program fibheaps, which gets 25% more allocation if you don't do this
1038 eta-expansion.
1039
1040 We may have to sandwich some coerces between the lambdas
1041 to make the types work.   exprEtaExpandArity looks through coerces
1042 when computing arity; and etaExpand adds the coerces as necessary when
1043 actually computing the expansion.
1044
1045 \begin{code}
1046 tryEtaExpansion :: DynFlags -> OutExpr -> OutExpr
1047 -- There is at least one runtime binder in the binders
1048 tryEtaExpansion dflags body
1049   = etaExpand fun_arity body
1050   where
1051     fun_arity = exprEtaExpandArity dflags body
1052 \end{code}
1053
1054
1055 %************************************************************************
1056 %*                                                                      *
1057 \subsection{Floating lets out of big lambdas}
1058 %*                                                                      *
1059 %************************************************************************
1060
1061 Note [Floating and type abstraction]
1062 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1063 Consider this:
1064         x = /\a. C e1 e2
1065 We'd like to float this to 
1066         y1 = /\a. e1
1067         y2 = /\a. e2
1068         x  = /\a. C (y1 a) (y2 a)
1069 for the usual reasons: we want to inline x rather vigorously.
1070
1071 You may think that this kind of thing is rare.  But in some programs it is
1072 common.  For example, if you do closure conversion you might get:
1073
1074         data a :-> b = forall e. (e -> a -> b) :$ e
1075
1076         f_cc :: forall a. a :-> a
1077         f_cc = /\a. (\e. id a) :$ ()
1078
1079 Now we really want to inline that f_cc thing so that the
1080 construction of the closure goes away. 
1081
1082 So I have elaborated simplLazyBind to understand right-hand sides that look
1083 like
1084         /\ a1..an. body
1085
1086 and treat them specially. The real work is done in SimplUtils.abstractFloats,
1087 but there is quite a bit of plumbing in simplLazyBind as well.
1088
1089 The same transformation is good when there are lets in the body:
1090
1091         /\abc -> let(rec) x = e in b
1092    ==>
1093         let(rec) x' = /\abc -> let x = x' a b c in e
1094         in 
1095         /\abc -> let x = x' a b c in b
1096
1097 This is good because it can turn things like:
1098
1099         let f = /\a -> letrec g = ... g ... in g
1100 into
1101         letrec g' = /\a -> ... g' a ...
1102         in
1103         let f = /\ a -> g' a
1104
1105 which is better.  In effect, it means that big lambdas don't impede
1106 let-floating.
1107
1108 This optimisation is CRUCIAL in eliminating the junk introduced by
1109 desugaring mutually recursive definitions.  Don't eliminate it lightly!
1110
1111 [May 1999]  If we do this transformation *regardless* then we can
1112 end up with some pretty silly stuff.  For example, 
1113
1114         let 
1115             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
1116         in ..
1117 becomes
1118         let y1 = /\s -> r1
1119             y2 = /\s -> r2
1120             st = /\s -> ...[y1 s/x1, y2 s/x2]
1121         in ..
1122
1123 Unless the "..." is a WHNF there is really no point in doing this.
1124 Indeed it can make things worse.  Suppose x1 is used strictly,
1125 and is of the form
1126
1127         x1* = case f y of { (a,b) -> e }
1128
1129 If we abstract this wrt the tyvar we then can't do the case inline
1130 as we would normally do.
1131
1132 That's why the whole transformation is part of the same process that
1133 floats let-bindings and constructor arguments out of RHSs.  In particular,
1134 it is guarded by the doFloatFromRhs call in simplLazyBind.
1135
1136
1137 \begin{code}
1138 abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
1139 abstractFloats main_tvs body_env body
1140   = ASSERT( notNull body_floats )
1141     do  { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats
1142         ; return (float_binds, CoreSubst.substExpr subst body) }
1143   where
1144     main_tv_set = mkVarSet main_tvs
1145     body_floats = getFloats body_env
1146     empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
1147
1148     abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
1149     abstract subst (NonRec id rhs)
1150       = do { (poly_id, poly_app) <- mk_poly tvs_here id
1151            ; let poly_rhs = mkLams tvs_here rhs'
1152                  subst'   = CoreSubst.extendIdSubst subst id poly_app
1153            ; return (subst', (NonRec poly_id poly_rhs)) }
1154       where
1155         rhs' = CoreSubst.substExpr subst rhs
1156         tvs_here | any isCoVar main_tvs = main_tvs      -- Note [Abstract over coercions]
1157                  | otherwise 
1158                  = varSetElems (main_tv_set `intersectVarSet` exprSomeFreeVars isTyVar rhs')
1159         
1160                 -- Abstract only over the type variables free in the rhs
1161                 -- wrt which the new binding is abstracted.  But the naive
1162                 -- approach of abstract wrt the tyvars free in the Id's type
1163                 -- fails. Consider:
1164                 --      /\ a b -> let t :: (a,b) = (e1, e2)
1165                 --                    x :: a     = fst t
1166                 --                in ...
1167                 -- Here, b isn't free in x's type, but we must nevertheless
1168                 -- abstract wrt b as well, because t's type mentions b.
1169                 -- Since t is floated too, we'd end up with the bogus:
1170                 --      poly_t = /\ a b -> (e1, e2)
1171                 --      poly_x = /\ a   -> fst (poly_t a *b*)
1172                 -- So for now we adopt the even more naive approach of
1173                 -- abstracting wrt *all* the tyvars.  We'll see if that
1174                 -- gives rise to problems.   SLPJ June 98
1175
1176     abstract subst (Rec prs)
1177        = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids
1178             ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
1179                   poly_rhss = [mkLams tvs_here (CoreSubst.substExpr subst' rhs) | rhs <- rhss]
1180             ; return (subst', Rec (poly_ids `zip` poly_rhss)) }
1181        where
1182          (ids,rhss) = unzip prs
1183                 -- For a recursive group, it's a bit of a pain to work out the minimal
1184                 -- set of tyvars over which to abstract:
1185                 --      /\ a b c.  let x = ...a... in
1186                 --                 letrec { p = ...x...q...
1187                 --                          q = .....p...b... } in
1188                 --                 ...
1189                 -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted
1190                 -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'.  
1191                 -- Since it's a pain, we just use the whole set, which is always safe
1192                 -- 
1193                 -- If you ever want to be more selective, remember this bizarre case too:
1194                 --      x::a = x
1195                 -- Here, we must abstract 'x' over 'a'.
1196          tvs_here = main_tvs
1197
1198     mk_poly tvs_here var
1199       = do { uniq <- getUniqueM
1200            ; let  poly_name = setNameUnique (idName var) uniq           -- Keep same name
1201                   poly_ty   = mkForAllTys tvs_here (idType var) -- But new type of course
1202                   poly_id   = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.lhs
1203                               mkLocalId poly_name poly_ty 
1204            ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
1205                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
1206                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1207                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
1208                 -- at already simplified code, so it doesn't matter
1209                 -- 
1210                 -- It's even right to retain single-occurrence or dead-var info:
1211                 -- Suppose we started with  /\a -> let x = E in B
1212                 -- where x occurs once in B. Then we transform to:
1213                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
1214                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
1215                 -- the occurrences of x' will be just the occurrences originally
1216                 -- pinned on x.
1217 \end{code}
1218
1219 Note [Abstract over coercions]
1220 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1221 If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the
1222 type variable a.  Rather than sort this mess out, we simply bale out and abstract
1223 wrt all the type variables if any of them are coercion variables.
1224
1225
1226 Historical note: if you use let-bindings instead of a substitution, beware of this:
1227
1228                 -- Suppose we start with:
1229                 --
1230                 --      x = /\ a -> let g = G in E
1231                 --
1232                 -- Then we'll float to get
1233                 --
1234                 --      x = let poly_g = /\ a -> G
1235                 --          in /\ a -> let g = poly_g a in E
1236                 --
1237                 -- But now the occurrence analyser will see just one occurrence
1238                 -- of poly_g, not inside a lambda, so the simplifier will
1239                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
1240                 -- (I used to think that the "don't inline lone occurrences" stuff
1241                 --  would stop this happening, but since it's the *only* occurrence,
1242                 --  PreInlineUnconditionally kicks in first!)
1243                 --
1244                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1245                 --           to appear many times.  (NB: mkInlineMe eliminates
1246                 --           such notes on trivial RHSs, so do it manually.)
1247
1248 %************************************************************************
1249 %*                                                                      *
1250                 prepareAlts
1251 %*                                                                      *
1252 %************************************************************************
1253
1254 prepareAlts tries these things:
1255
1256 1.  If several alternatives are identical, merge them into
1257     a single DEFAULT alternative.  I've occasionally seen this 
1258     making a big difference:
1259
1260         case e of               =====>     case e of
1261           C _ -> f x                         D v -> ....v....
1262           D v -> ....v....                   DEFAULT -> f x
1263           DEFAULT -> f x
1264
1265    The point is that we merge common RHSs, at least for the DEFAULT case.
1266    [One could do something more elaborate but I've never seen it needed.]
1267    To avoid an expensive test, we just merge branches equal to the *first*
1268    alternative; this picks up the common cases
1269         a) all branches equal
1270         b) some branches equal to the DEFAULT (which occurs first)
1271
1272 2.  Case merging:
1273        case e of b {             ==>   case e of b {
1274          p1 -> rhs1                      p1 -> rhs1
1275          ...                             ...
1276          pm -> rhsm                      pm -> rhsm
1277          _  -> case b of b' {            pn -> let b'=b in rhsn
1278                      pn -> rhsn          ...
1279                      ...                 po -> let b'=b in rhso
1280                      po -> rhso          _  -> let b'=b in rhsd
1281                      _  -> rhsd
1282        }  
1283     
1284     which merges two cases in one case when -- the default alternative of
1285     the outer case scrutises the same variable as the outer case This
1286     transformation is called Case Merging.  It avoids that the same
1287     variable is scrutinised multiple times.
1288
1289
1290 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1291
1292         x | p `is` 1 -> e1
1293           | p `is` 2 -> e2
1294         ...etc...
1295
1296 where @is@ was something like
1297         
1298         p `is` n = p /= (-1) && p == n
1299
1300 This gave rise to a horrible sequence of cases
1301
1302         case p of
1303           (-1) -> $j p
1304           1    -> e1
1305           DEFAULT -> $j p
1306
1307 and similarly in cascade for all the join points!
1308
1309 Note [Dead binders]
1310 ~~~~~~~~~~~~~~~~~~~~
1311 We do this *here*, looking at un-simplified alternatives, because we
1312 have to check that r doesn't mention the variables bound by the
1313 pattern in each alternative, so the binder-info is rather useful.
1314
1315 \begin{code}
1316 prepareAlts :: SimplEnv -> OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1317 prepareAlts env scrut case_bndr' alts
1318   = do  { dflags <- getDOptsSmpl
1319         ; alts <- combineIdenticalAlts case_bndr' alts
1320
1321         ; let (alts_wo_default, maybe_deflt) = findDefault alts
1322               alt_cons = [con | (con,_,_) <- alts_wo_default]
1323               imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1324                 -- "imposs_deflt_cons" are handled 
1325                 --   EITHER by the context, 
1326                 --   OR by a non-DEFAULT branch in this case expression.
1327
1328         ; default_alts <- prepareDefault dflags env case_bndr' mb_tc_app 
1329                                          imposs_deflt_cons maybe_deflt
1330
1331         ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1332               merged_alts = mergeAlts trimmed_alts default_alts
1333                 -- We need the mergeAlts in case the new default_alt 
1334                 -- has turned into a constructor alternative.
1335                 -- The merge keeps the inner DEFAULT at the front, if there is one
1336                 -- and interleaves the alternatives in the right order
1337
1338         ; return (imposs_deflt_cons, merged_alts) }
1339   where
1340     mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1341     Just (_, inst_tys) = mb_tc_app 
1342
1343     imposs_cons = case scrut of
1344                     Var v -> otherCons (idUnfolding v)
1345                     _     -> []
1346
1347     impossible_alt :: CoreAlt -> Bool
1348     impossible_alt (con, _, _) | con `elem` imposs_cons = True
1349     impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1350     impossible_alt _                   = False
1351
1352
1353 --------------------------------------------------
1354 --      1. Merge identical branches
1355 --------------------------------------------------
1356 combineIdenticalAlts :: OutId -> [InAlt] -> SimplM [InAlt]
1357
1358 combineIdenticalAlts case_bndr ((_con1,bndrs1,rhs1) : con_alts)
1359   | all isDeadBinder bndrs1,                    -- Remember the default 
1360     length filtered_alts < length con_alts      -- alternative comes first
1361         -- Also Note [Dead binders]
1362   = do  { tick (AltMerge case_bndr)
1363         ; return ((DEFAULT, [], rhs1) : filtered_alts) }
1364   where
1365     filtered_alts        = filter keep con_alts
1366     keep (_con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1367
1368 combineIdenticalAlts _ alts = return alts
1369
1370 -------------------------------------------------------------------------
1371 --                      Prepare the default alternative
1372 -------------------------------------------------------------------------
1373 prepareDefault :: DynFlags
1374                -> SimplEnv
1375                -> OutId         -- Case binder; need just for its type. Note that as an
1376                                 --   OutId, it has maximum information; this is important.
1377                                 --   Test simpl013 is an example
1378                -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1379                -> [AltCon]      -- These cons can't happen when matching the default
1380                -> Maybe InExpr  -- Rhs
1381                -> SimplM [InAlt]        -- Still unsimplified
1382                                         -- We use a list because it's what mergeAlts expects,
1383                                         -- And becuase case-merging can cause many to show up
1384
1385 ------- Merge nested cases ----------
1386 prepareDefault dflags env outer_bndr _bndr_ty imposs_cons (Just deflt_rhs)
1387   | dopt Opt_CaseMerge dflags
1388   , Case (Var inner_scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1389   , DoneId inner_scrut_var' <- substId env inner_scrut_var
1390         -- Remember, inner_scrut_var is an InId, but outer_bndr is an OutId
1391   , inner_scrut_var' == outer_bndr
1392         -- NB: the substId means that if the outer scrutinee was a 
1393         --     variable, and inner scrutinee is the same variable, 
1394         --     then inner_scrut_var' will be outer_bndr
1395         --     via the magic of simplCaseBinder
1396   = do  { tick (CaseMerge outer_bndr)
1397
1398         ; let munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1399         ; return [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts,
1400                                                not (con `elem` imposs_cons) ]
1401                 -- NB: filter out any imposs_cons.  Example:
1402                 --      case x of 
1403                 --        A -> e1
1404                 --        DEFAULT -> case x of 
1405                 --                      A -> e2
1406                 --                      B -> e3
1407                 -- When we merge, we must ensure that e1 takes 
1408                 -- precedence over e2 as the value for A!  
1409         }
1410         -- Warning: don't call prepareAlts recursively!
1411         -- Firstly, there's no point, because inner alts have already had
1412         -- mkCase applied to them, so they won't have a case in their default
1413         -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1414         -- in munge_rhs may put a case into the DEFAULT branch!
1415
1416
1417 --------- Fill in known constructor -----------
1418 prepareDefault _ _ case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1419   |     -- This branch handles the case where we are 
1420         -- scrutinisng an algebraic data type
1421     isAlgTyCon tycon            -- It's a data type, tuple, or unboxed tuples.  
1422   , not (isNewTyCon tycon)      -- We can have a newtype, if we are just doing an eval:
1423                                 --      case x of { DEFAULT -> e }
1424                                 -- and we don't want to fill in a default for them!
1425   , Just all_cons <- tyConDataCons_maybe tycon
1426   , not (null all_cons)         -- This is a tricky corner case.  If the data type has no constructors,
1427                                 -- which GHC allows, then the case expression will have at most a default
1428                                 -- alternative.  We don't want to eliminate that alternative, because the
1429                                 -- invariant is that there's always one alternative.  It's more convenient
1430                                 -- to leave     
1431                                 --      case x of { DEFAULT -> e }     
1432                                 -- as it is, rather than transform it to
1433                                 --      error "case cant match"
1434                                 -- which would be quite legitmate.  But it's a really obscure corner, and
1435                                 -- not worth wasting code on.
1436   , let imposs_data_cons = [con | DataAlt con <- imposs_cons]   -- We now know it's a data type 
1437         impossible con  = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1438   = case filterOut impossible all_cons of
1439         []    -> return []      -- Eliminate the default alternative
1440                                 -- altogether if it can't match
1441
1442         [con] ->        -- It matches exactly one constructor, so fill it in
1443                  do { tick (FillInCaseDefault case_bndr)
1444                     ; us <- getUniquesM
1445                     ; let (ex_tvs, co_tvs, arg_ids) =
1446                               dataConRepInstPat us con inst_tys
1447                     ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1448
1449         _ -> return [(DEFAULT, [], deflt_rhs)]
1450
1451   | debugIsOn, isAlgTyCon tycon, not (isOpenTyCon tycon), null (tyConDataCons tycon)
1452         -- This can legitimately happen for type families, so don't report that
1453   = pprTrace "prepareDefault" (ppr case_bndr <+> ppr tycon)
1454         $ return [(DEFAULT, [], deflt_rhs)]
1455
1456 --------- Catch-all cases -----------
1457 prepareDefault _dflags _env _case_bndr _bndr_ty _imposs_cons (Just deflt_rhs)
1458   = return [(DEFAULT, [], deflt_rhs)]
1459
1460 prepareDefault _dflags _env _case_bndr _bndr_ty _imposs_cons Nothing
1461   = return []   -- No default branch
1462 \end{code}
1463
1464
1465
1466 =================================================================================
1467
1468 mkCase tries these things
1469
1470 1.  Eliminate the case altogether if possible
1471
1472 2.  Case-identity:
1473
1474         case e of               ===> e
1475                 True  -> True;
1476                 False -> False
1477
1478     and similar friends.
1479
1480
1481 \begin{code}
1482 mkCase :: OutExpr -> OutId -> [OutAlt]  -- Increasing order
1483        -> SimplM OutExpr
1484
1485 --------------------------------------------------
1486 --      2. Identity case
1487 --------------------------------------------------
1488
1489 mkCase scrut case_bndr alts     -- Identity case
1490   | all identity_alt alts
1491   = do tick (CaseIdentity case_bndr)
1492        return (re_cast scrut)
1493   where
1494     identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1495
1496     check_eq DEFAULT       _    (Var v)   = v == case_bndr
1497     check_eq (LitAlt lit') _    (Lit lit) = lit == lit'
1498     check_eq (DataAlt con) args rhs       = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1499                                          || rhs `cheapEqExpr` Var case_bndr
1500     check_eq _ _ _ = False
1501
1502     arg_tys = map Type (tyConAppArgs (idType case_bndr))
1503
1504         -- We've seen this:
1505         --      case e of x { _ -> x `cast` c }
1506         -- And we definitely want to eliminate this case, to give
1507         --      e `cast` c
1508         -- So we throw away the cast from the RHS, and reconstruct
1509         -- it at the other end.  All the RHS casts must be the same
1510         -- if (all identity_alt alts) holds.
1511         -- 
1512         -- Don't worry about nested casts, because the simplifier combines them
1513     de_cast (Cast e _) = e
1514     de_cast e          = e
1515
1516     re_cast scrut = case head alts of
1517                         (_,_,Cast _ co) -> Cast scrut co
1518                         _               -> scrut
1519
1520
1521
1522 --------------------------------------------------
1523 --      Catch-all
1524 --------------------------------------------------
1525 mkCase scrut bndr alts = return (Case scrut bndr (coreAltsType alts) alts)
1526 \end{code}
1527
1528
1529 When adding auxiliary bindings for the case binder, it's worth checking if
1530 its dead, because it often is, and occasionally these mkCase transformations
1531 cascade rather nicely.
1532
1533 \begin{code}
1534 bindCaseBndr :: Id -> CoreExpr -> CoreExpr -> CoreExpr
1535 bindCaseBndr bndr rhs body
1536   | isDeadBinder bndr = body
1537   | otherwise         = bindNonRec bndr rhs body
1538 \end{code}