5f00a8e9e7c939dac3d22317591fb1f8890f9ac9
[ghc-hetmet.git] / ghc / compiler / simplCore / Simplify.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1996
3 %
4 \section[Simplify]{The main module of the simplifier}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module Simplify ( simplTopBinds, simplExpr, simplBind ) where
10
11 IMP_Ubiq(){-uitous-}
12 IMPORT_DELOOPER(SmplLoop)               -- paranoia checking
13 IMPORT_1_3(List(partition))
14
15 import BinderInfo
16 import CmdLineOpts      ( SimplifierSwitch(..) )
17 import ConFold          ( completePrim )
18 import CoreUnfold       ( Unfolding, SimpleUnfolding, mkFormSummary, FormSummary(..) )
19 import CostCentre       ( isSccCountCostCentre, cmpCostCentre )
20 import CoreSyn
21 import CoreUtils        ( coreExprType, nonErrorRHSs, maybeErrorApp,
22                           unTagBinders, squashableDictishCcExpr
23                         )
24 import Id               ( idType, idWantsToBeINLINEd,
25                           getIdDemandInfo, addIdDemandInfo,
26                           GenId{-instance NamedThing-}
27                         )
28 import IdInfo           ( willBeDemanded, DemandInfo )
29 import Literal          ( isNoRepLit )
30 import Maybes           ( maybeToBool )
31 import Name             ( isLocallyDefined )
32 import PprStyle         ( PprStyle(..) )
33 import PprType          ( GenType{-instance Outputable-} )
34 import Pretty           ( ppAbove )
35 import PrimOp           ( primOpOkForSpeculation, PrimOp(..) )
36 import SimplCase        ( simplCase, bindLargeRhs )
37 import SimplEnv
38 import SimplMonad
39 import SimplVar         ( completeVar )
40 import SimplUtils
41 import Type             ( mkTyVarTy, mkTyVarTys, mkAppTy,
42                           splitFunTy, getFunTy_maybe, eqTy
43                         )
44 import TysWiredIn       ( realWorldStateTy )
45 import Util             ( isSingleton, zipEqual, panic, pprPanic, assertPanic )
46 \end{code}
47
48 The controlling flags, and what they do
49 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
50
51 passes:
52 ------
53 -fsimplify              = run the simplifier
54 -ffloat-inwards         = runs the float lets inwards pass
55 -ffloat                 = runs the full laziness pass
56                           (ToDo: rename to -ffull-laziness)
57 -fupdate-analysis       = runs update analyser
58 -fstrictness            = runs strictness analyser
59 -fsaturate-apps         = saturates applications (eta expansion)
60
61 options:
62 -------
63 -ffloat-past-lambda     = OK to do full laziness.
64                           (ToDo: remove, as the full laziness pass is
65                                  useless without this flag, therefore
66                                  it is unnecessary. Just -ffull-laziness
67                                  should be kept.)
68
69 -ffloat-lets-ok         = OK to float lets out of lets if the enclosing
70                           let is strict or if the floating will expose
71                           a WHNF [simplifier].
72
73 -ffloat-primops-ok      = OK to float out of lets cases whose scrutinee
74                           is a primop that cannot fail [simplifier].
75
76 -fcode-duplication-ok   = allows the previous option to work on cases with
77                           multiple branches [simplifier].
78
79 -flet-to-case           = does let-to-case transformation [simplifier].
80
81 -fcase-of-case          = does case of case transformation [simplifier].
82
83 -fpedantic-bottoms      = does not allow:
84                              case x of y -> e  ===>  e[x/y]
85                           (which may turn bottom into non-bottom)
86
87
88                         NOTES ON INLINING
89                         ~~~~~~~~~~~~~~~~~
90
91 Inlining is one of the delicate aspects of the simplifier.  By
92 ``inlining'' we mean replacing an occurrence of a variable ``x'' by
93 the RHS of x's definition.  Thus
94
95         let x = e in ...x...    ===>   let x = e in ...e...
96
97 We have two mechanisms for inlining:
98
99 1.  Unconditional.  The occurrence analyser has pinned an (OneOcc
100 FunOcc NoDupDanger NotInsideSCC n) flag on the variable, saying ``it's
101 certainly safe to inline this variable, and to drop its binding''.
102 (...Umm... if n <= 1; if n > 1, it is still safe, provided you are
103 happy to be duplicating code...) When it encounters such a beast, the
104 simplifer binds the variable to its RHS (in the id_env) and continues.
105 It doesn't even look at the RHS at that stage.  It also drops the
106 binding altogether.
107
108 2.  Conditional.  In all other situations, the simplifer simplifies
109 the RHS anyway, and keeps the new binding.  It also binds the new
110 (cloned) variable to a ``suitable'' Unfolding in the UnfoldEnv.
111
112 Here, ``suitable'' might mean NoUnfolding (if the occurrence
113 info is ManyOcc and the RHS is not a manifest HNF, or UnfoldAlways (if
114 the variable has an INLINE pragma on it).  The idea is that anything
115 in the UnfoldEnv is safe to use, but also has an enclosing binding if
116 you decide not to use it.
117
118 Head normal forms
119 ~~~~~~~~~~~~~~~~~
120 We *never* put a non-HNF unfolding in the UnfoldEnv except in the
121 INLINE-pragma case.
122
123 At one time I thought it would be OK to put non-HNF unfoldings in for
124 variables which occur only once [if they got inlined at that
125 occurrence the RHS of the binding would become dead, so no duplication
126 would occur].   But consider:
127 @
128         let x = <expensive>
129             f = \y -> ...y...y...y...
130         in f x
131 @
132 Now, it seems that @x@ appears only once, but even so it is NOT safe
133 to put @x@ in the UnfoldEnv, because @f@ will be inlined, and will
134 duplicate the references to @x@.
135
136 Because of this, the "unconditional-inline" mechanism above is the
137 only way in which non-HNFs can get inlined.
138
139 INLINE pragmas
140 ~~~~~~~~~~~~~~
141
142 When a variable has an INLINE pragma on it --- which includes wrappers
143 produced by the strictness analyser --- we treat it rather carefully.
144
145 For a start, we are careful not to substitute into its RHS, because
146 that might make it BIG, and the user said "inline exactly this", not
147 "inline whatever you get after inlining other stuff inside me".  For
148 example
149
150         let f = BIG
151         in {-# INLINE y #-} y = f 3
152         in ...y...y...
153
154 Here we don't want to substitute BIG for the (single) occurrence of f,
155 because then we'd duplicate BIG when we inline'd y.  (Exception:
156 things in the UnfoldEnv with UnfoldAlways flags, which originated in
157 other INLINE pragmas.)
158
159 So, we clean out the UnfoldEnv of all SimpleUnfolding inlinings before
160 going into such an RHS.
161
162 What about imports?  They don't really matter much because we only
163 inline relatively small things via imports.
164
165 We augment the the UnfoldEnv with UnfoldAlways guidance if there's an
166 INLINE pragma.  We also do this for the RHSs of recursive decls,
167 before looking at the recursive decls. That way we achieve the effect
168 of inlining a wrapper in the body of its worker, in the case of a
169 mutually-recursive worker/wrapper split.
170
171
172 %************************************************************************
173 %*                                                                      *
174 \subsection[Simplify-simplExpr]{The main function: simplExpr}
175 %*                                                                      *
176 %************************************************************************
177
178 At the top level things are a little different.
179
180   * No cloning (not allowed for exported Ids, unnecessary for the others)
181
182   * No floating.   Case floating is obviously out.  Let floating is
183         theoretically OK, but dangerous because of space leaks.
184         The long-distance let-floater lifts these lets.
185
186 \begin{code}
187 simplTopBinds :: SimplEnv -> [InBinding] -> SmplM [OutBinding]
188
189 simplTopBinds env [] = returnSmpl []
190
191 -- Dead code is now discarded by the occurrence analyser,
192
193 simplTopBinds env (NonRec binder@(in_id,occ_info) rhs : binds)
194   =     -- No cloning necessary at top level
195         -- Process the binding
196     simplRhsExpr env binder rhs         `thenSmpl` \ rhs' ->
197     completeNonRec env binder rhs'      `thenSmpl` \ (new_env, binds1') ->
198
199         -- Process the other bindings
200     simplTopBinds new_env binds `thenSmpl` \ binds2' ->
201
202         -- Glue together and return ...
203     returnSmpl (binds1' ++ binds2')
204
205 simplTopBinds env (Rec pairs : binds)
206   = simplRecursiveGroup env ids pairs   `thenSmpl` \ (bind', new_env) ->
207
208         -- Process the other bindings
209     simplTopBinds new_env binds         `thenSmpl` \ binds' ->
210
211         -- Glue together and return
212     returnSmpl (bind' : binds')
213   where
214     ids = [id | (binder@(id,_), rhs) <- pairs]  -- No cloning necessary at top level
215 \end{code}
216
217 %************************************************************************
218 %*                                                                      *
219 \subsection[Simplify-simplExpr]{The main function: simplExpr}
220 %*                                                                      *
221 %************************************************************************
222
223
224 \begin{code}
225 simplExpr :: SimplEnv
226           -> InExpr -> [OutArg]
227           -> SmplM OutExpr
228 \end{code}
229
230 The expression returned has the same meaning as the input expression
231 applied to the specified arguments.
232
233
234 Variables
235 ~~~~~~~~~
236 Check if there's a macro-expansion, and if so rattle on.  Otherwise do
237 the more sophisticated stuff.
238
239 \begin{code}
240 simplExpr env (Var v) args
241   = case (lookupId env v) of
242       LitArg lit                -- A boring old literal
243         -> ASSERT( null args )
244            returnSmpl (Lit lit)
245
246       VarArg var        -- More interesting!  An id!
247         -> completeVar env var args
248                                 -- Either Id is in the local envt, or it's a global.
249                                 -- In either case we don't need to apply the type
250                                 -- environment to it.
251 \end{code}
252
253 Literals
254 ~~~~~~~~
255
256 \begin{code}
257 simplExpr env (Lit l) [] = returnSmpl (Lit l)
258 #ifdef DEBUG
259 simplExpr env (Lit l) _  = panic "simplExpr:Lit with argument"
260 #endif
261 \end{code}
262
263 Primitive applications are simple.
264 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
265
266 NB: Prim expects an empty argument list! (Because it should be
267 saturated and not higher-order. ADR)
268
269 \begin{code}
270 simplExpr env (Prim op prim_args) args
271   = ASSERT (null args)
272     let
273         prim_args' = [simplArg env prim_arg | prim_arg <- prim_args]
274         op'        = simpl_op op
275     in
276     completePrim env op' prim_args'
277   where
278     -- PrimOps just need any types in them renamed.
279
280     simpl_op (CCallOp label is_asm may_gc arg_tys result_ty)
281       = let
282             arg_tys'    = map (simplTy env) arg_tys
283             result_ty'  = simplTy env result_ty
284         in
285         CCallOp label is_asm may_gc arg_tys' result_ty'
286
287     simpl_op other_op = other_op
288 \end{code}
289
290 Constructor applications
291 ~~~~~~~~~~~~~~~~~~~~~~~~
292 Nothing to try here.  We only reuse constructors when they appear as the
293 rhs of a let binding (see completeLetBinding).
294
295 \begin{code}
296 simplExpr env (Con con con_args) args
297   = ASSERT( null args )
298     returnSmpl (Con con [simplArg env con_arg | con_arg <- con_args])
299 \end{code}
300
301
302 Applications are easy too:
303 ~~~~~~~~~~~~~~~~~~~~~~~~~~
304 Just stuff 'em in the arg stack
305
306 \begin{code}
307 simplExpr env (App fun arg) args
308   = simplExpr env fun (simplArg env arg : args)
309 \end{code}
310
311 Type lambdas
312 ~~~~~~~~~~~~
313
314 We only eta-reduce a type lambda if all type arguments in the body can
315 be eta-reduced. This requires us to collect up all tyvar parameters so
316 we can pass them all to @mkTyLamTryingEta@.
317
318 \begin{code}
319 simplExpr env (Lam (TyBinder tyvar) body) (TyArg ty : args)
320   = -- ASSERT(not (isPrimType ty))
321     tick TyBetaReduction        `thenSmpl_`
322     simplExpr (extendTyEnv env tyvar ty) body args
323
324 simplExpr env tylam@(Lam (TyBinder tyvar) body) []
325   = do_tylambdas env [] tylam
326   where
327     do_tylambdas env tyvars' (Lam (TyBinder tyvar) body)
328       =   -- Clone the type variable
329         cloneTyVarSmpl tyvar            `thenSmpl` \ tyvar' ->
330         let
331             new_env = extendTyEnv env tyvar (mkTyVarTy tyvar')
332         in
333         do_tylambdas new_env (tyvar':tyvars') body
334
335     do_tylambdas env tyvars' body
336       = simplExpr env body []           `thenSmpl` \ body' ->
337         returnSmpl (
338            (if switchIsSet env SimplDoEtaReduction
339            then mkTyLamTryingEta
340            else mkTyLam) (reverse tyvars')  body'
341         )
342
343 #ifdef DEBUG
344 simplExpr env (Lam (TyBinder _) _) (_ : _)
345   = panic "simplExpr:TyLam with non-TyArg"
346 #endif
347 \end{code}
348
349
350 Ordinary lambdas
351 ~~~~~~~~~~~~~~~~
352
353 There's a complication with lambdas that aren't saturated.
354 Suppose we have:
355
356         (\x. \y. ...x...)
357
358 If we did nothing, x is used inside the \y, so would be marked
359 as dangerous to dup.  But in the common case where the abstraction
360 is applied to two arguments this is over-pessimistic.
361 So instead we don't take account of the \y when dealing with x's usage;
362 instead, the simplifier is careful when partially applying lambdas.
363
364 \begin{code}
365 simplExpr env expr@(Lam (ValBinder binder) body) orig_args
366   = go 0 env expr orig_args
367   where
368     go n env (Lam (ValBinder binder) body) (val_arg : args)
369       | isValArg val_arg                -- The lambda has an argument
370       = tick BetaReduction      `thenSmpl_`
371         go (n+1) (extendIdEnvWithAtom env binder val_arg) body args
372
373     go n env expr@(Lam (ValBinder binder) body) args
374         -- The lambda is un-saturated, so we must zap the occurrence info
375         -- on the arguments we've already beta-reduced into the body of the lambda
376       = ASSERT( null args )     -- Value lambda must match value argument!
377         let
378             new_env = markDangerousOccs env (take n orig_args)
379         in
380         simplValLam new_env expr 0 {- Guaranteed applied to at least 0 args! -}
381
382     go n env non_val_lam_expr args      -- The lambda had enough arguments
383       = simplExpr env non_val_lam_expr args
384 \end{code}
385
386
387 Let expressions
388 ~~~~~~~~~~~~~~~
389
390 \begin{code}
391 simplExpr env (Let bind body) args
392   = simplBind env bind (\env -> simplExpr env body args)
393                        (computeResultType env body args)
394 \end{code}
395
396 Case expressions
397 ~~~~~~~~~~~~~~~~
398
399 \begin{code}
400 simplExpr env expr@(Case scrut alts) args
401   = simplCase env scrut alts (\env rhs -> simplExpr env rhs args)
402                              (computeResultType env expr args)
403 \end{code}
404
405
406 Coercions
407 ~~~~~~~~~
408 \begin{code}
409 simplExpr env (Coerce coercion ty body) args
410   = simplCoerce env coercion ty body args 
411 \end{code}
412
413
414 Set-cost-centre
415 ~~~~~~~~~~~~~~~
416
417 1) Eliminating nested sccs ...
418 We must be careful to maintain the scc counts ...
419
420 \begin{code}
421 simplExpr env (SCC cc1 (SCC cc2 expr)) args
422   | not (isSccCountCostCentre cc2) && case cmpCostCentre cc1 cc2 of { EQ_ -> True; _ -> False }
423         -- eliminate inner scc if no call counts and same cc as outer
424   = simplExpr env (SCC cc1 expr) args
425
426   | not (isSccCountCostCentre cc2) && not (isSccCountCostCentre cc1)
427         -- eliminate outer scc if no call counts associated with either ccs
428   = simplExpr env (SCC cc2 expr) args
429 \end{code}
430
431 2) Moving sccs inside lambdas ...
432   
433 \begin{code}
434 simplExpr env (SCC cc (Lam binder@(ValBinder _) body)) args
435   | not (isSccCountCostCentre cc)
436         -- move scc inside lambda only if no call counts
437   = simplExpr env (Lam binder (SCC cc body)) args
438
439 simplExpr env (SCC cc (Lam binder body)) args
440         -- always ok to move scc inside type/usage lambda
441   = simplExpr env (Lam binder (SCC cc body)) args
442 \end{code}
443
444 3) Eliminating dict sccs ...
445
446 \begin{code}
447 simplExpr env (SCC cc expr) args
448   | squashableDictishCcExpr cc expr
449         -- eliminate dict cc if trivial dict expression
450   = simplExpr env expr args
451 \end{code}
452
453 4) Moving arguments inside the body of an scc ...
454 This moves the cost of doing the application inside the scc
455 (which may include the cost of extracting methods etc)
456
457 \begin{code}
458 simplExpr env (SCC cost_centre body) args
459   = let
460         new_env = setEnclosingCC env cost_centre
461     in
462     simplExpr new_env body args         `thenSmpl` \ body' ->
463     returnSmpl (SCC cost_centre body')
464 \end{code}
465
466 %************************************************************************
467 %*                                                                      *
468 \subsection{Simplify RHS of a Let/Letrec}
469 %*                                                                      *
470 %************************************************************************
471
472 simplRhsExpr does arity-expansion.  That is, given:
473
474         * a right hand side /\ tyvars -> \a1 ... an -> e
475         * the information (stored in BinderInfo) that the function will always
476           be applied to at least k arguments
477
478 it transforms the rhs to
479
480         /\tyvars -> \a1 ... an b(n+1) ... bk -> (e b(n+1) ... bk)
481
482 This is a Very Good Thing!
483
484 \begin{code}
485 simplRhsExpr
486         :: SimplEnv
487         -> InBinder
488         -> InExpr
489         -> SmplM OutExpr
490
491 simplRhsExpr env binder@(id,occ_info) rhs
492   | dont_eta_expand rhs
493   = simplExpr rhs_env rhs []
494
495   | otherwise   -- Have a go at eta expansion
496   =     -- Deal with the big lambda part
497     ASSERT( null uvars )        -- For now
498
499     mapSmpl cloneTyVarSmpl tyvars                       `thenSmpl` \ tyvars' ->
500     let
501         lam_env  = extendTyEnvList rhs_env (zipEqual "simplRhsExpr" tyvars (mkTyVarTys tyvars'))
502     in
503         -- Deal with the little lambda part
504         -- Note that we call simplLam even if there are no binders,
505         -- in case it can do arity expansion.
506     simplValLam lam_env body (getBinderInfoArity occ_info)      `thenSmpl` \ lambda' ->
507
508         -- Put it back together
509     returnSmpl (
510        (if switchIsSet env SimplDoEtaReduction
511        then mkTyLamTryingEta
512        else mkTyLam) tyvars' lambda'
513     )
514   where
515
516     rhs_env | not (switchIsSet env IgnoreINLINEPragma) &&
517               idWantsToBeINLINEd id
518             = switchOffInlining env
519             | otherwise 
520             = env
521
522         -- Switch off all inlining in the RHS of things that have an INLINE pragma.
523         -- They are going to be inlined wherever they are used, and then all the
524         -- inlining will take effect.  Meanwhile, there isn't
525         -- much point in doing anything to the as-yet-un-INLINEd rhs.
526         -- It's very important to switch off inlining!  Consider:
527         --
528         -- let f = \pq -> BIG
529         -- in
530         -- let g = \y -> f y y
531         --     {-# INLINE g #-}
532         -- in ...g...g...g...g...g...
533         --
534         -- Now, if that's the ONLY occurrence of f, it will be inlined inside g,
535         -- and thence copied multiple times when g is inlined.
536
537         -- Andy disagrees! Example:
538         --      all xs = foldr (&&) True xs
539         --      any p = all . map p  {-# INLINE any #-}
540         --
541         -- Problem: any won't get deforested, and so if it's exported and
542         -- the importer doesn't use the inlining, (eg passes it as an arg)
543         -- then we won't get deforestation at all.
544         -- We havn't solved this problem yet!
545
546     (uvars, tyvars, body) = collectUsageAndTyBinders rhs
547
548         -- dont_eta_expand prevents eta expansion in silly situations.
549         -- For example, consider the defn
550         --      x = y
551         -- It would be silly to eta expand the "y", because it would just
552         -- get eta-reduced back to y.  Furthermore, if this was a top level defn,
553         -- and x was exported, then the defn won't be eliminated, so this
554         -- silly expand/reduce cycle will happen every time, which makes the
555         -- simplifier loop!.
556         -- The solution is to not even try eta expansion unless the rhs looks
557         -- non-trivial.
558     dont_eta_expand (Lit _)     = True
559     dont_eta_expand (Var _)     = True
560     dont_eta_expand (Con _ _)   = True
561     dont_eta_expand (App f a)
562       | notValArg    a          = dont_eta_expand f
563     dont_eta_expand (Lam x b)
564       | notValBinder x          = dont_eta_expand b
565     dont_eta_expand _           = False
566 \end{code}
567
568
569 %************************************************************************
570 %*                                                                      *
571 \subsection{Simplify a lambda abstraction}
572 %*                                                                      *
573 %************************************************************************
574
575 Simplify (\binders -> body) trying eta expansion and reduction, given that
576 the abstraction will always be applied to at least min_no_of_args.
577
578 \begin{code}
579 simplValLam env expr min_no_of_args
580   | not (switchIsSet env SimplDoLambdaEtaExpansion) ||  -- Bale out if eta expansion off
581     null binders                                    ||  -- or it's a thunk
582     null potential_extra_binder_tys                 ||  -- or ain't a function
583     no_of_extra_binders <= 0                            -- or no extra binders needed
584   = cloneIds env binders                `thenSmpl` \ binders' ->
585     let
586         new_env = extendIdEnvWithClones env binders binders'
587     in
588     simplExpr new_env body []           `thenSmpl` \ body' ->
589     returnSmpl (
590       (if switchIsSet new_env SimplDoEtaReduction
591        then mkValLamTryingEta
592        else mkValLam) binders' body'
593     )
594
595   | otherwise                           -- Eta expansion possible
596   = tick EtaExpansion                   `thenSmpl_`
597     cloneIds env binders                `thenSmpl` \ binders' ->
598     let
599         new_env = extendIdEnvWithClones env binders binders'
600     in
601     newIds extra_binder_tys                             `thenSmpl` \ extra_binders' ->
602     simplExpr new_env body (map VarArg extra_binders')  `thenSmpl` \ body' ->
603     returnSmpl (
604       (if switchIsSet new_env SimplDoEtaReduction
605        then mkValLamTryingEta
606        else mkValLam) (binders' ++ extra_binders') body'
607     )
608
609   where
610     (binders,body) = collectValBinders expr
611     (potential_extra_binder_tys, res_ty)
612         = splitFunTy (simplTy env (coreExprType (unTagBinders body)))
613         -- Note: it's possible that simplValLam will be applied to something
614         -- with a forall type.  Eg when being applied to the rhs of
615         --              let x = wurble
616         -- where wurble has a forall-type, but no big lambdas at the top.
617         -- We could be clever an insert new big lambdas, but we don't bother.
618
619     extra_binder_tys = take no_of_extra_binders potential_extra_binder_tys
620
621     no_of_extra_binders =       -- First, use the info about how many args it's
622                                 -- always applied to in its scope
623                            (min_no_of_args - length binders)
624
625                                 -- Next, try seeing if there's a lambda hidden inside
626                                 -- something cheap
627                            `max`
628                            etaExpandCount body
629
630                                 -- Finally, see if it's a state transformer, in which
631                                 -- case we eta-expand on principle! This can waste work,
632                                 -- but usually doesn't
633                            `max`
634                            case potential_extra_binder_tys of
635                                 [ty] | ty `eqTy` realWorldStateTy -> 1
636                                 other                             -> 0
637
638 \end{code}
639
640
641
642 %************************************************************************
643 %*                                                                      *
644 \subsection[Simplify-coerce]{Coerce expressions}
645 %*                                                                      *
646 %************************************************************************
647
648 \begin{code}
649 -- (coerce (case s of p -> r)) args ==> case s of p -> (coerce r) args
650 simplCoerce env coercion ty expr@(Case scrut alts) args
651   = simplCase env scrut alts (\env rhs -> simplCoerce env coercion ty rhs args)
652                              (computeResultType env expr args)
653
654 -- (coerce (let defns in b)) args  ==> let defns' in (coerce b) args
655 simplCoerce env coercion ty (Let bind body) args
656   = simplBind env bind (\env -> simplCoerce env coercion ty body args)
657                        (computeResultType env body args)
658
659 -- Default case
660 simplCoerce env coercion ty expr args
661   = simplExpr env expr []       `thenSmpl` \ expr' ->
662     returnSmpl (mkGenApp (mkCoerce coercion (simplTy env ty) expr') args)
663   where
664
665         -- Try cancellation; we do this "on the way up" because
666         -- I think that's where it'll bite best
667     mkCoerce (CoerceOut con1) ty1 (Coerce (CoerceIn  con2) ty2 body) | con1 == con2 = body
668     mkCoerce coercion ty  body = Coerce coercion ty body
669 \end{code}
670
671
672 %************************************************************************
673 %*                                                                      *
674 \subsection[Simplify-let]{Let-expressions}
675 %*                                                                      *
676 %************************************************************************
677
678 \begin{code}
679 simplBind :: SimplEnv
680           -> InBinding
681           -> (SimplEnv -> SmplM OutExpr)
682           -> OutType
683           -> SmplM OutExpr
684 \end{code}
685
686 When floating cases out of lets, remember this:
687
688         let x* = case e of alts
689         in <small expr>
690
691 where x* is sure to be demanded or e is a cheap operation that cannot
692 fail, e.g. unboxed addition.  Here we should be prepared to duplicate
693 <small expr>.  A good example:
694
695         let x* = case y of
696                    p1 -> build e1
697                    p2 -> build e2
698         in
699         foldr c n x*
700 ==>
701         case y of
702           p1 -> foldr c n (build e1)
703           p2 -> foldr c n (build e2)
704
705 NEW: We use the same machinery that we use for case-of-case to
706 *always* do case floating from let, that is we let bind and abstract
707 the original let body, and let the occurrence analyser later decide
708 whether the new let should be inlined or not. The example above
709 becomes:
710
711 ==>
712       let join_body x' = foldr c n x'
713         in case y of
714         p1 -> let x* = build e1
715                 in join_body x*
716         p2 -> let x* = build e2
717                 in join_body x*
718
719 note that join_body is a let-no-escape.
720 In this particular example join_body will later be inlined,
721 achieving the same effect.
722 ToDo: check this is OK with andy
723
724
725
726 \begin{code}
727 -- Dead code is now discarded by the occurrence analyser,
728
729 simplBind env (NonRec binder@(id,occ_info) rhs) body_c body_ty
730   = simpl_bind env rhs
731   where
732     -- Try let-to-case; see notes below about let-to-case
733     simpl_bind env rhs | will_be_demanded &&
734                          try_let_to_case &&
735                          type_ok_for_let_to_case rhs_ty &&
736                          rhs_is_whnf    -- note: WHNF, but not bottom,  (comment below)
737       = tick Let2Case                           `thenSmpl_`
738         mkIdentityAlts rhs_ty                   `thenSmpl` \ id_alts ->
739         simplCase env rhs id_alts (\env rhs -> simpl_bind env rhs) body_ty
740
741     -- Try let-from-let
742     simpl_bind env (Let bind rhs) | let_floating_ok
743       = tick LetFloatFromLet                    `thenSmpl_`
744         simplBind env (fix_up_demandedness will_be_demanded bind)
745                       (\env -> simpl_bind env rhs) body_ty
746
747     -- Try case-from-let; this deals with a strict let of error too
748     simpl_bind env (Case scrut alts) | will_be_demanded || 
749                                        (float_primops && is_cheap_prim_app scrut)
750       = tick CaseFloatFromLet                           `thenSmpl_`
751
752         -- First, bind large let-body if necessary
753         if ok_to_dup || isSingleton (nonErrorRHSs alts)
754         then
755             simplCase env scrut alts (\env rhs -> simpl_bind env rhs) body_ty
756         else
757             bindLargeRhs env [binder] body_ty body_c    `thenSmpl` \ (extra_binding, new_body) ->
758             let
759                 body_c' = \env -> simplExpr env new_body []
760                 case_c  = \env rhs -> simplBind env (NonRec binder rhs) body_c' body_ty
761             in
762             simplCase env scrut alts case_c body_ty     `thenSmpl` \ case_expr ->
763             returnSmpl (Let extra_binding case_expr)
764
765     -- None of the above; simplify rhs and tidy up
766     simpl_bind env rhs
767       = simplRhsExpr env binder rhs     `thenSmpl` \ rhs' ->
768         completeNonRec env binder rhs'  `thenSmpl` \ (new_env, binds) ->
769         body_c new_env                  `thenSmpl` \ body' ->
770         returnSmpl (mkCoLetsAny binds body')
771
772
773         -- All this stuff is computed at the start of the simpl_bind loop
774     float_lets                = switchIsSet env SimplFloatLetsExposingWHNF
775     float_primops             = switchIsSet env SimplOkToFloatPrimOps
776     ok_to_dup                 = switchIsSet env SimplOkToDupCode
777     always_float_let_from_let = switchIsSet env SimplAlwaysFloatLetsFromLets
778     try_let_to_case           = switchIsSet env SimplLetToCase
779     no_float                  = switchIsSet env SimplNoLetFromStrictLet
780
781     will_be_demanded = willBeDemanded (getIdDemandInfo id)
782     rhs_ty           = idType id
783
784     rhs_is_whnf = case mkFormSummary rhs of
785                         VarForm -> True
786                         ValueForm -> True
787                         other -> False
788
789     let_floating_ok  = (will_be_demanded && not no_float) ||
790                        always_float_let_from_let ||
791                        floatExposesHNF float_lets float_primops ok_to_dup rhs
792 \end{code}
793
794 Let to case
795 ~~~~~~~~~~~
796 It's important to try let-to-case before floating. Consider
797
798         let a*::Int = case v of {p1->e1; p2->e2}
799         in b
800
801 (The * means that a is sure to be demanded.)
802 If we do case-floating first we get this:
803
804         let k = \a* -> b
805         in case v of
806                 p1-> let a*=e1 in k a
807                 p2-> let a*=e2 in k a
808
809 Now watch what happens if we do let-to-case first:
810
811         case (case v of {p1->e1; p2->e2}) of
812           Int a# -> let a*=I# a# in b
813 ===>
814         let k = \a# -> let a*=I# a# in b
815         in case v of
816                 p1 -> case e1 of I# a# -> k a#
817                 p1 -> case e1 of I# a# -> k a#
818
819 The latter is clearly better.  (Remember the reboxing let-decl for a
820 is likely to go away, because after all b is strict in a.)
821
822 We do not do let to case for WHNFs, e.g.
823
824           let x = a:b in ...
825           =/=>
826           case a:b of x in ...
827
828 as this is less efficient.  but we don't mind doing let-to-case for
829 "bottom", as that will allow us to remove more dead code, if anything:
830
831           let x = error in ...
832           ===>
833           case error  of x -> ...
834           ===>
835           error
836
837 Notice that let to case occurs only if x is used strictly in its body
838 (obviously).
839
840
841 Letrec expressions
842 ~~~~~~~~~~~~~~~~~~
843
844 Simplify each RHS, float any let(recs) from the RHSs (if let-floating is
845 on and it'll expose a HNF), and bang the whole resulting mess together
846 into a huge letrec.
847
848 1. Any "macros" should be expanded.  The main application of this
849 macro-expansion is:
850
851         letrec
852                 f = ....g...
853                 g = ....f...
854         in
855         ....f...
856
857 Here we would like the single call to g to be inlined.
858
859 We can spot this easily, because g will be tagged as having just one
860 occurrence.  The "inlineUnconditionally" predicate is just what we want.
861
862 A worry: could this lead to non-termination?  For example:
863
864         letrec
865                 f = ...g...
866                 g = ...f...
867                 h = ...h...
868         in
869         ..h..
870
871 Here, f and g call each other (just once) and neither is used elsewhere.
872 But it's OK:
873
874 * the occurrence analyser will drop any (sub)-group that isn't used at
875   all.
876
877 * If the group is used outside itself (ie in the "in" part), then there
878   can't be a cyle.
879
880 ** IMPORTANT: check that NewOccAnal has the property that a group of
881    bindings like the above has f&g dropped.! ***
882
883
884 2. We'd also like to pull out any top-level let(rec)s from the
885 rhs of the defns:
886
887         letrec
888                 f = let h = ... in \x -> ....h...f...h...
889         in
890         ...f...
891 ====>
892         letrec
893                 h = ...
894                 f = \x -> ....h...f...h...
895         in
896         ...f...
897
898 But floating cases is less easy?  (Don't for now; ToDo?)
899
900
901 3.  We'd like to arrange that the RHSs "know" about members of the
902 group that are bound to constructors.  For example:
903
904     let rec
905        d.Eq      = (==,/=)
906        f a b c d = case d.Eq of (h,_) -> let x = (a,b); y = (c,d) in not (h x y)
907        /= a b    = unpack tuple a, unpack tuple b, call f
908     in d.Eq
909
910 here, by knowing about d.Eq in f's rhs, one could get rid of
911 the case (and break out the recursion completely).
912 [This occurred with more aggressive inlining threshold (4),
913 nofib/spectral/knights]
914
915 How to do it?
916         1: we simplify constructor rhss first.
917         2: we record the "known constructors" in the environment
918         3: we simplify the other rhss, with the knowledge about the constructors
919
920
921
922 \begin{code}
923 simplBind env (Rec pairs) body_c body_ty
924   =     -- Do floating, if necessary
925     let
926         floated_pairs | do_floating = float_pairs pairs
927                       | otherwise   = pairs
928
929         ticks         | do_floating = length floated_pairs - length pairs
930                       | otherwise   = 0
931
932         binders       = map fst floated_pairs
933     in
934     tickN LetFloatFromLet ticks         `thenSmpl_` 
935                 -- It's important to increment the tick counts if we
936                 -- do any floating.  A situation where this turns out
937                 -- to be important is this:
938                 -- Float in produces:
939                 --      letrec  x = let y = Ey in Ex
940                 --      in B
941                 -- Now floating gives this:
942                 --      letrec x = Ex
943                 --             y = Ey
944                 --      in B
945                 --- We now want to iterate once more in case Ey doesn't
946                 -- mention x, in which case the y binding can be pulled
947                 -- out as an enclosing let(rec), which in turn gives
948                 -- the strictness analyser more chance.
949
950     cloneIds env binders                        `thenSmpl` \ ids' ->
951     let
952        env_w_clones = extendIdEnvWithClones env binders ids'
953     in
954     simplRecursiveGroup env ids' floated_pairs  `thenSmpl` \ (binding, new_env) ->
955
956     body_c new_env                              `thenSmpl` \ body' ->
957
958     returnSmpl (Let binding body')
959
960   where
961     ------------ Floating stuff -------------------
962
963     float_lets                = switchIsSet env SimplFloatLetsExposingWHNF
964     always_float_let_from_let = switchIsSet env SimplAlwaysFloatLetsFromLets
965     do_floating               = float_lets || always_float_let_from_let
966
967     float_pairs pairs = concat (map float_pair pairs)
968
969     float_pair (binder, rhs)
970         | always_float_let_from_let ||
971           floatExposesHNF True False False rhs
972         = (binder,rhs') : pairs'
973
974         | otherwise
975         = [(binder,rhs)]
976         where
977           (pairs', rhs') = do_float rhs
978
979         -- Float just pulls out any top-level let(rec) bindings
980     do_float :: InExpr -> ([(InBinder,InExpr)], InExpr)
981     do_float (Let (Rec pairs) body)     = (float_pairs pairs    ++ pairs', body')
982                                             where
983                                               (pairs', body') = do_float body
984     do_float (Let (NonRec id rhs) body) = (float_pair (id,rhs) ++ pairs', body')
985                                             where
986                                               (pairs', body') = do_float body
987     do_float other                          = ([], other)
988
989 simplRecursiveGroup env new_ids pairs 
990   =     -- Add unfoldings to the new_ids corresponding to their RHS
991     let
992        occs            = [occ | ((_,occ), _) <- pairs]
993        new_ids_w_pairs = zipEqual "simplRecGp" new_ids pairs
994        rhs_env         = foldl extendEnvForRecBinding 
995                                env new_ids_w_pairs
996     in
997
998     mapSmpl (\(binder,rhs) -> simplRhsExpr rhs_env binder rhs) pairs    `thenSmpl` \ new_rhss ->
999
1000     let
1001        new_pairs           = zipEqual "simplRecGp" new_ids new_rhss
1002        occs_w_new_pairs = zipEqual "simplRecGp" occs new_pairs
1003        new_env             = foldl (\env (occ_info,(new_id,new_rhs)) -> 
1004                                     extendEnvGivenBinding env occ_info new_id new_rhs)
1005                                    env occs_w_new_pairs
1006     in
1007     returnSmpl (Rec new_pairs, new_env)
1008 \end{code}
1009
1010
1011 @completeLet@ looks at the simplified post-floating RHS of the
1012 let-expression, and decides what to do.  There's one interesting
1013 aspect to this, namely constructor reuse.  Consider
1014 @
1015         f = \x -> case x of
1016                     (y:ys) -> y:ys
1017                     []     -> ...
1018 @
1019 Is it a good idea to replace the rhs @y:ys@ with @x@?  This depends a
1020 bit on the compiler technology, but in general I believe not. For
1021 example, here's some code from a real program:
1022 @
1023 const.Int.max.wrk{-s2516-} =
1024     \ upk.s3297#  upk.s3298# ->
1025         let {
1026           a.s3299 :: Int
1027           _N_ {-# U(P) #-}
1028           a.s3299 = I#! upk.s3297#
1029         } in
1030           case (const.Int._tagCmp.wrk{-s2513-} upk.s3297# upk.s3298#) of {
1031             _LT -> I#! upk.s3298#
1032             _EQ -> a.s3299
1033             _GT -> a.s3299
1034           }
1035 @
1036 The a.s3299 really isn't doing much good.  We'd be better off inlining
1037 it.  (Actually, let-no-escapery means it isn't as bad as it looks.)
1038
1039 So the current strategy is to inline all known-form constructors, and
1040 only do the reverse (turn a constructor application back into a
1041 variable) when we find a let-expression:
1042 @
1043         let x = C a1 .. an
1044         in
1045         ... (let y = C a1 .. an in ...) ...
1046 @
1047 where it is always good to ditch the binding for y, and replace y by
1048 x.  That's just what completeLetBinding does.
1049
1050
1051 \begin{code}
1052         -- Sigh: rather disgusting case for coercions. We want to 
1053         -- ensure that all let-bound Coerces have atomic bodies, so
1054         -- they can freely be inlined.
1055 completeNonRec env binder@(_,occ_info) (Coerce coercion ty rhs)
1056   = (case rhs of
1057         Var v -> returnSmpl (env, [], rhs)
1058         Lit l -> returnSmpl (env, [], rhs)
1059         other -> newId (coreExprType rhs)                       `thenSmpl` \ inner_id ->
1060                  completeNonRec env 
1061                         (inner_id, dangerousArgOcc) rhs         `thenSmpl` \ (env1, extra_bind) ->
1062                 -- Dangerous occ because, like constructor args,
1063                 -- it can be duplicated easily
1064                 let
1065                 atomic_rhs = case lookupId env1 inner_id of
1066                                 LitArg l -> Lit l
1067                                 VarArg v -> Var v
1068                 in
1069                 returnSmpl (env1, extra_bind, atomic_rhs)
1070      )                          `thenSmpl` \ (env1, extra_bind, atomic_rhs) ->
1071         -- Tiresome to do all this, but we must treat the lit/var cases specially
1072         -- or we get a tick for atomic rhs when effectively it's a no-op.
1073
1074      cloneId env1 binder                                  `thenSmpl` \ new_id ->
1075      let 
1076         new_rhs = Coerce coercion ty atomic_rhs
1077         env2    = extendIdEnvWithClone env1 binder new_id
1078         new_env = extendEnvGivenBinding env2 occ_info new_id new_rhs
1079      in
1080      returnSmpl (new_env, extra_bind ++ [NonRec new_id new_rhs])
1081         
1082 completeNonRec env binder new_rhs
1083   -- See if RHS is an atom, or a reusable constructor
1084   | maybeToBool maybe_atomic_rhs
1085   = let
1086         new_env = extendIdEnvWithAtom env binder rhs_atom
1087     in
1088     tick atom_tick_type                 `thenSmpl_`
1089     returnSmpl (new_env, [])
1090   where
1091     maybe_atomic_rhs                = exprToAtom env new_rhs
1092     Just (rhs_atom, atom_tick_type) = maybe_atomic_rhs
1093
1094 completeNonRec env binder@(_,occ_info) new_rhs
1095   = cloneId env binder                  `thenSmpl` \ new_id ->
1096     let
1097         env1    = extendIdEnvWithClone env binder new_id
1098         new_env = extendEnvGivenBinding env1 occ_info new_id new_rhs
1099     in
1100     returnSmpl (new_env, [NonRec new_id new_rhs])
1101 \end{code}
1102
1103 %************************************************************************
1104 %*                                                                      *
1105 \subsection[Simplify-atoms]{Simplifying atoms}
1106 %*                                                                      *
1107 %************************************************************************
1108
1109 \begin{code}
1110 simplArg :: SimplEnv -> InArg -> OutArg
1111
1112 simplArg env (LitArg lit) = LitArg lit
1113 simplArg env (TyArg  ty)  = TyArg  (simplTy env ty)
1114 simplArg env (VarArg id)  = lookupId env id
1115 \end{code}
1116
1117
1118 \begin{code}
1119 exprToAtom env (Var var) 
1120   = Just (VarArg var, AtomicRhs)
1121
1122 exprToAtom env (Lit lit) 
1123   | not (isNoRepLit lit)
1124   = Just (LitArg lit, AtomicRhs)
1125
1126 exprToAtom env (Con con con_args)
1127   | switchIsSet env SimplReuseCon
1128   -- Look out for
1129   --    let v = C args
1130   --    in
1131   --- ...(let w = C same-args in ...)...
1132   -- Then use v instead of w.    This may save
1133   -- re-constructing an existing constructor.
1134   = case (lookForConstructor env con con_args) of
1135                   Nothing  -> Nothing
1136                   Just var -> Just (VarArg var, ConReused)
1137
1138 exprToAtom env other
1139   = Nothing
1140 \end{code}
1141
1142 %************************************************************************
1143 %*                                                                      *
1144 \subsection[Simplify-quickies]{Some local help functions}
1145 %*                                                                      *
1146 %************************************************************************
1147
1148
1149 \begin{code}
1150 -- fix_up_demandedness switches off the willBeDemanded Info field
1151 -- for bindings floated out of a non-demanded let
1152 fix_up_demandedness True {- Will be demanded -} bind
1153    = bind       -- Simple; no change to demand info needed
1154 fix_up_demandedness False {- May not be demanded -} (NonRec binder rhs)
1155    = NonRec (un_demandify binder) rhs
1156 fix_up_demandedness False {- May not be demanded -} (Rec pairs)
1157    = Rec [(un_demandify binder, rhs) | (binder,rhs) <- pairs]
1158
1159 un_demandify (id, occ_info) = (id `addIdDemandInfo` noInfo, occ_info)
1160
1161 is_cheap_prim_app (Prim op _) = primOpOkForSpeculation op
1162 is_cheap_prim_app other       = False
1163
1164 computeResultType :: SimplEnv -> InExpr -> [OutArg] -> OutType
1165 computeResultType env expr args
1166   = go expr_ty' args
1167   where
1168     expr_ty  = coreExprType (unTagBinders expr)
1169     expr_ty' = simplTy env expr_ty
1170
1171     go ty [] = ty
1172     go ty (TyArg ty_arg : args) = go (mkAppTy ty ty_arg) args
1173     go ty (a:args) | isValArg a = case (getFunTy_maybe ty) of
1174                                     Just (_, res_ty) -> go res_ty args
1175                                     Nothing          -> panic "computeResultType"
1176 \end{code}
1177