Simplify.lhs 86.8 KB
Newer Older
1
%
2
% (c) The AQUA Project, Glasgow University, 1993-1998
3 4 5 6
%
\section[Simplify]{The main module of the simplifier}

\begin{code}
7
module Simplify ( simplTopBinds, simplExpr ) where
8

9
#include "HsVersions.h"
10

simonpj@microsoft.com's avatar
Wibble  
simonpj@microsoft.com committed
11
import DynFlags
12
import SimplMonad
Ian Lynagh's avatar
Ian Lynagh committed
13 14
import Type hiding      ( substTy, extendTvSubst )
import SimplEnv
15
import SimplUtils
16
import MkId		( rUNTIME_ERROR_ID )
17
import FamInstEnv	( FamInstEnv )
18
import Id
19
import Var
20 21
import IdInfo
import Coercion
Ian Lynagh's avatar
Ian Lynagh committed
22 23
import FamInstEnv       ( topNormaliseType )
import DataCon          ( dataConRepStrictness, dataConUnivTyVars )
24
import CoreSyn
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
25
import NewDemand        ( isStrictDmd, splitStrictSig )
Ian Lynagh's avatar
Ian Lynagh committed
26 27
import PprCore          ( pprParendExpr, pprCoreExpr )
import CoreUnfold       ( mkUnfolding, callSiteInline, CallCtxt(..) )
28
import CoreUtils
29
import Rules            ( lookupRule, getRules )
Ian Lynagh's avatar
Ian Lynagh committed
30 31 32 33 34 35 36 37
import BasicTypes       ( isMarkedStrict )
import CostCentre       ( currentCCS )
import TysPrim          ( realWorldStatePrimTy )
import PrelInfo         ( realWorldPrimId )
import BasicTypes       ( TopLevelFlag(..), isTopLevel,
                          RecFlag(..), isNonRuleLoopBreaker )
import Maybes           ( orElse )
import Data.List        ( mapAccumL )
38 39
import MonadUtils	( foldlM )
import StaticFlags	( opt_PassCaseBndrToJoinPoints )
40
import Outputable
41
import FastString
42 43 44
\end{code}


45 46
The guts of the simplifier is in this module, but the driver loop for
the simplifier is in SimplCore.lhs.
47 48


49
-----------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
50
        *** IMPORTANT NOTE ***
51 52 53 54 55 56
-----------------------------------------
The simplifier used to guarantee that the output had no shadowing, but
it does not do so any more.   (Actually, it never did!)  The reason is
documented with simplifyArgs.


57
-----------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
58
        *** IMPORTANT NOTE ***
59 60 61 62 63 64 65 66 67 68
-----------------------------------------
Many parts of the simplifier return a bunch of "floats" as well as an
expression. This is wrapped as a datatype SimplUtils.FloatsWith.

All "floats" are let-binds, not case-binds, but some non-rec lets may
be unlifted (with RHS ok-for-speculation).



-----------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
69
        ORGANISATION OF FUNCTIONS
70 71 72 73 74 75
-----------------------------------------
simplTopBinds
  - simplify all top-level binders
  - for NonRec, call simplRecOrTopPair
  - for Rec,    call simplRecBind

Ian Lynagh's avatar
Ian Lynagh committed
76 77 78

        ------------------------------
simplExpr (applied lambda)      ==> simplNonRecBind
79 80 81
simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
simplExpr (Let (Rec ...)    ..) ==> simplify binders; simplRecBind

Ian Lynagh's avatar
Ian Lynagh committed
82 83
        ------------------------------
simplRecBind    [binders already simplfied]
84 85 86 87
  - use simplRecOrTopPair on each pair in turn

simplRecOrTopPair [binder already simplified]
  Used for: recursive bindings (top level and nested)
Ian Lynagh's avatar
Ian Lynagh committed
88 89
            top-level non-recursive bindings
  Returns:
90 91 92 93 94
  - check for PreInlineUnconditionally
  - simplLazyBind

simplNonRecBind
  Used for: non-top-level non-recursive bindings
Ian Lynagh's avatar
Ian Lynagh committed
95 96 97
            beta reductions (which amount to the same thing)
  Because it can deal with strict arts, it takes a
        "thing-inside" and returns an expression
98 99 100 101

  - check for PreInlineUnconditionally
  - simplify binder, including its IdInfo
  - if strict binding
Ian Lynagh's avatar
Ian Lynagh committed
102 103 104
        simplStrictArg
        mkAtomicArgs
        completeNonRecX
105
    else
Ian Lynagh's avatar
Ian Lynagh committed
106 107
        simplLazyBind
        addFloats
108

Ian Lynagh's avatar
Ian Lynagh committed
109
simplNonRecX:   [given a *simplified* RHS, but an *unsimplified* binder]
110 111 112 113
  Used for: binding case-binder and constr args in a known-constructor case
  - check for PreInLineUnconditionally
  - simplify binder
  - completeNonRecX
Ian Lynagh's avatar
Ian Lynagh committed
114 115 116

        ------------------------------
simplLazyBind:  [binder already simplified, RHS not]
117
  Used for: recursive bindings (top level and nested)
Ian Lynagh's avatar
Ian Lynagh committed
118 119 120
            top-level non-recursive bindings
            non-top-level, but *lazy* non-recursive bindings
        [must not be strict or unboxed]
121
  Returns floats + an augmented environment, not an expression
Ian Lynagh's avatar
Ian Lynagh committed
122 123
  - substituteIdInfo and add result to in-scope
        [so that rules are available in rec rhs]
124 125 126
  - simplify rhs
  - mkAtomicArgs
  - float if exposes constructor or PAP
127
  - completeBind
128 129


Ian Lynagh's avatar
Ian Lynagh committed
130
completeNonRecX:        [binder and rhs both simplified]
131
  - if the the thing needs case binding (unlifted and not ok-for-spec)
Ian Lynagh's avatar
Ian Lynagh committed
132
        build a Case
133
   else
Ian Lynagh's avatar
Ian Lynagh committed
134 135
        completeBind
        addFloats
136

Ian Lynagh's avatar
Ian Lynagh committed
137 138
completeBind:   [given a simplified RHS]
        [used for both rec and non-rec bindings, top level and not]
139 140 141 142 143 144 145 146
  - try PostInlineUnconditionally
  - add unfolding [this is the only place we add an unfolding]
  - add arity



Right hand sides and arguments
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Ian Lynagh's avatar
Ian Lynagh committed
147 148 149
In many ways we want to treat
        (a) the right hand side of a let(rec), and
        (b) a function argument
150 151 152
in the same way.  But not always!  In particular, we would
like to leave these arguments exactly as they are, so they
will match a RULE more easily.
Ian Lynagh's avatar
Ian Lynagh committed
153 154 155

        f (g x, h x)
        g (+ x)
156 157 158 159

It's harder to make the rule match if we ANF-ise the constructor,
or eta-expand the PAP:

Ian Lynagh's avatar
Ian Lynagh committed
160 161
        f (let { a = g x; b = h x } in (a,b))
        g (\y. + x y)
162 163 164

On the other hand if we see the let-defns

Ian Lynagh's avatar
Ian Lynagh committed
165 166
        p = (g x, h x)
        q = + x
167 168

then we *do* want to ANF-ise and eta-expand, so that p and q
Ian Lynagh's avatar
Ian Lynagh committed
169
can be safely inlined.
170 171 172 173 174

Even floating lets out is a bit dubious.  For let RHS's we float lets
out if that exposes a value, so that the value can be inlined more vigorously.
For example

Ian Lynagh's avatar
Ian Lynagh committed
175
        r = let x = e in (x,x)
176 177 178 179 180 181 182 183 184 185 186 187 188 189

Here, if we float the let out we'll expose a nice constructor. We did experiments
that showed this to be a generally good thing.  But it was a bad thing to float
lets out unconditionally, because that meant they got allocated more often.

For function arguments, there's less reason to expose a constructor (it won't
get inlined).  Just possibly it might make a rule match, but I'm pretty skeptical.
So for the moment we don't float lets out of function arguments either.


Eta expansion
~~~~~~~~~~~~~~
For eta expansion, we want to catch things like

Ian Lynagh's avatar
Ian Lynagh committed
190
        case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
191 192 193 194 195

If the \x was on the RHS of a let, we'd eta expand to bring the two
lambdas together.  And in general that's a good thing to do.  Perhaps
we should eta expand wherever we find a (value) lambda?  Then the eta
expansion at a let RHS can concentrate solely on the PAP case.
196 197


198
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
199
%*                                                                      *
200
\subsection{Bindings}
Ian Lynagh's avatar
Ian Lynagh committed
201
%*                                                                      *
202 203 204
%************************************************************************

\begin{code}
205
simplTopBinds :: SimplEnv -> [InBind] -> SimplM [OutBind]
206

Ian Lynagh's avatar
Ian Lynagh committed
207
simplTopBinds env0 binds0
Ian Lynagh's avatar
Ian Lynagh committed
208 209 210 211
  = do  {       -- Put all the top-level binders into scope at the start
                -- so that if a transformation rule has unexpectedly brought
                -- anything into scope, then we don't get a complaint about that.
                -- It's rather as if the top-level binders were imported.
Ian Lynagh's avatar
Ian Lynagh committed
212
        ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
Ian Lynagh's avatar
Ian Lynagh committed
213 214 215
        ; dflags <- getDOptsSmpl
        ; let dump_flag = dopt Opt_D_dump_inlinings dflags ||
                          dopt Opt_D_dump_rule_firings dflags
Ian Lynagh's avatar
Ian Lynagh committed
216
        ; env2 <- simpl_binds dump_flag env1 binds0
Ian Lynagh's avatar
Ian Lynagh committed
217
        ; freeTick SimplifierDone
Ian Lynagh's avatar
Ian Lynagh committed
218
        ; return (getFloats env2) }
219
  where
Ian Lynagh's avatar
Ian Lynagh committed
220 221 222 223 224 225
        -- We need to track the zapped top-level binders, because
        -- they should have their fragile IdInfo zapped (notably occurrence info)
        -- That's why we run down binds and bndrs' simultaneously.
        --
        -- The dump-flag emits a trace for each top-level binding, which
        -- helps to locate the tracing for inlining and rule firing
226
    simpl_binds :: Bool -> SimplEnv -> [InBind] -> SimplM SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
227 228
    simpl_binds _    env []           = return env
    simpl_binds dump env (bind:binds) = do { env' <- trace_bind dump bind $
Ian Lynagh's avatar
Ian Lynagh committed
229 230
                                                     simpl_bind env bind
                                           ; simpl_binds dump env' binds }
231

Ian Lynagh's avatar
Ian Lynagh committed
232 233
    trace_bind True  bind = pprTrace "SimplBind" (ppr (bindersOf bind))
    trace_bind False _    = \x -> x
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
234

235 236
    simpl_bind env (Rec pairs)  = simplRecBind      env  TopLevel pairs
    simpl_bind env (NonRec b r) = simplRecOrTopPair env' TopLevel b b' r
Ian Lynagh's avatar
Ian Lynagh committed
237 238
        where
          (env', b') = addBndrRules env b (lookupRecBndr env b)
239 240 241 242
\end{code}


%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
243
%*                                                                      *
244
\subsection{Lazy bindings}
Ian Lynagh's avatar
Ian Lynagh committed
245
%*                                                                      *
246 247 248
%************************************************************************

simplRecBind is used for
Ian Lynagh's avatar
Ian Lynagh committed
249
        * recursive bindings only
250 251 252

\begin{code}
simplRecBind :: SimplEnv -> TopLevelFlag
Ian Lynagh's avatar
Ian Lynagh committed
253 254
             -> [(InId, InExpr)]
             -> SimplM SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
255 256 257 258 259
simplRecBind env0 top_lvl pairs0
  = do  { let (env_with_info, triples) = mapAccumL add_rules env0 pairs0
        ; env1 <- go (zapFloats env_with_info) triples
        ; return (env0 `addRecFloats` env1) }
        -- addFloats adds the floats from env1,
Thomas Schilling's avatar
Thomas Schilling committed
260
        -- _and_ updates env0 with the in-scope set from env1
261
  where
262
    add_rules :: SimplEnv -> (InBndr,InExpr) -> (SimplEnv, (InBndr, OutBndr, InExpr))
Ian Lynagh's avatar
Ian Lynagh committed
263
        -- Add the (substituted) rules to the binder
264
    add_rules env (bndr, rhs) = (env', (bndr, bndr', rhs))
Ian Lynagh's avatar
Ian Lynagh committed
265 266
        where
          (env', bndr') = addBndrRules env bndr (lookupRecBndr env bndr)
267

268
    go env [] = return env
Ian Lynagh's avatar
Ian Lynagh committed
269

270
    go env ((old_bndr, new_bndr, rhs) : pairs)
Ian Lynagh's avatar
Ian Lynagh committed
271 272
        = do { env' <- simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
             ; go env' pairs }
273 274
\end{code}

275
simplOrTopPair is used for
Ian Lynagh's avatar
Ian Lynagh committed
276 277
        * recursive bindings (whether top level or not)
        * top-level non-recursive bindings
278 279 280 281 282

It assumes the binder has already been simplified, but not its IdInfo.

\begin{code}
simplRecOrTopPair :: SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
283 284 285
                  -> TopLevelFlag
                  -> InId -> OutBndr -> InExpr  -- Binder and rhs
                  -> SimplM SimplEnv    -- Returns an env that includes the binding
286

287
simplRecOrTopPair env top_lvl old_bndr new_bndr rhs
Ian Lynagh's avatar
Ian Lynagh committed
288 289 290
  | preInlineUnconditionally env top_lvl old_bndr rhs   -- Check for unconditional inline
  = do  { tick (PreInlineUnconditionally old_bndr)
        ; return (extendIdSubst env old_bndr (mkContEx env rhs)) }
291 292

  | otherwise
Ian Lynagh's avatar
Ian Lynagh committed
293 294
  = simplLazyBind env top_lvl Recursive old_bndr new_bndr rhs env
        -- May not actually be recursive, but it doesn't matter
295 296 297 298
\end{code}


simplLazyBind is used for
299 300
  * [simplRecOrTopPair] recursive bindings (whether top level or not)
  * [simplRecOrTopPair] top-level non-recursive bindings
Ian Lynagh's avatar
Ian Lynagh committed
301
  * [simplNonRecE]      non-top-level *lazy* non-recursive bindings
302 303

Nota bene:
Ian Lynagh's avatar
Ian Lynagh committed
304
    1. It assumes that the binder is *already* simplified,
305
       and is in scope, and its IdInfo too, except unfolding
306 307 308 309 310 311 312 313

    2. It assumes that the binder type is lifted.

    3. It does not check for pre-inline-unconditionallly;
       that should have been done already.

\begin{code}
simplLazyBind :: SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
314 315 316 317 318
              -> TopLevelFlag -> RecFlag
              -> InId -> OutId          -- Binder, both pre-and post simpl
                                        -- The OutId has IdInfo, except arity, unfolding
              -> InExpr -> SimplEnv     -- The RHS and its environment
              -> SimplM SimplEnv
319

320
simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
Ian Lynagh's avatar
Ian Lynagh committed
321
  = do  { let   rhs_env     = rhs_se `setInScope` env
322 323 324 325 326 327 328 329 330 331
		(tvs, body) = case collectTyBinders rhs of
			        (tvs, body) | not_lam body -> (tvs,body)
					    | otherwise	   -> ([], rhs)
		not_lam (Lam _ _) = False
		not_lam _	  = True
			-- Do not do the "abstract tyyvar" thing if there's
			-- a lambda inside, becuase it defeats eta-reduction
			--    f = /\a. \x. g a x  
			-- should eta-reduce

Ian Lynagh's avatar
Ian Lynagh committed
332
        ; (body_env, tvs') <- simplBinders rhs_env tvs
333
                -- See Note [Floating and type abstraction] in SimplUtils
Ian Lynagh's avatar
Ian Lynagh committed
334

335 336
        -- Simplify the RHS
        ; (body_env1, body1) <- simplExprF body_env body mkBoringStop
Ian Lynagh's avatar
Ian Lynagh committed
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

        -- ANF-ise a constructor or PAP rhs
        ; (body_env2, body2) <- prepareRhs body_env1 body1

        ; (env', rhs')
            <-  if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
                then                            -- No floating, just wrap up!
                     do { rhs' <- mkLam tvs' (wrapFloats body_env2 body2)
                        ; return (env, rhs') }

                else if null tvs then           -- Simple floating
                     do { tick LetFloatFromLet
                        ; return (addFloats env body_env2, body2) }

                else                            -- Do type-abstraction first
                     do { tick LetFloatFromLet
                        ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
                        ; rhs' <- mkLam tvs' body3
355
                        ; let env' = foldl (addPolyBind top_lvl) env poly_binds
356
                        ; return (env', rhs') }
Ian Lynagh's avatar
Ian Lynagh committed
357 358

        ; completeBind env' top_lvl bndr bndr1 rhs' }
359
\end{code}
360

Ian Lynagh's avatar
Ian Lynagh committed
361
A specialised variant of simplNonRec used when the RHS is already simplified,
362 363 364 365
notably in knownCon.  It uses case-binding where necessary.

\begin{code}
simplNonRecX :: SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
366 367 368
             -> InId            -- Old binder
             -> OutExpr         -- Simplified RHS
             -> SimplM SimplEnv
369 370

simplNonRecX env bndr new_rhs
371 372 373
  | isDeadBinder bndr	-- Not uncommon; e.g. case (a,b) of b { (p,q) -> p }
  = return env		-- 		 Here b is dead, and we avoid creating
  | otherwise		--		 the binding b = (a,b)
Ian Lynagh's avatar
Ian Lynagh committed
374
  = do  { (env', bndr') <- simplBinder env bndr
375
        ; completeNonRecX env' (isStrictId bndr) bndr bndr' new_rhs }
376 377

completeNonRecX :: SimplEnv
378
                -> Bool
Ian Lynagh's avatar
Ian Lynagh committed
379 380 381 382
                -> InId                 -- Old binder
                -> OutId                -- New binder
                -> OutExpr              -- Simplified RHS
                -> SimplM SimplEnv
383

384
completeNonRecX env is_strict old_bndr new_bndr new_rhs
Ian Lynagh's avatar
Ian Lynagh committed
385 386
  = do  { (env1, rhs1) <- prepareRhs (zapFloats env) new_rhs
        ; (env2, rhs2) <-
387
                if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
Ian Lynagh's avatar
Ian Lynagh committed
388 389 390 391
                then do { tick LetFloatFromLet
                        ; return (addFloats env env1, rhs1) }   -- Add the floats to the main env
                else return (env, wrapFloats env1 rhs1)         -- Wrap the floats around the RHS
        ; completeBind env2 NotTopLevel old_bndr new_bndr rhs2 }
392 393 394 395
\end{code}

{- No, no, no!  Do not try preInlineUnconditionally in completeNonRecX
   Doing so risks exponential behaviour, because new_rhs has been simplified once already
Ian Lynagh's avatar
Ian Lynagh committed
396
   In the cases described by the folowing commment, postInlineUnconditionally will
397
   catch many of the relevant cases.
Ian Lynagh's avatar
Ian Lynagh committed
398 399 400 401 402 403 404 405
        -- This happens; for example, the case_bndr during case of
        -- known constructor:  case (a,b) of x { (p,q) -> ... }
        -- Here x isn't mentioned in the RHS, so we don't want to
        -- create the (dead) let-binding  let x = (a,b) in ...
        --
        -- Similarly, single occurrences can be inlined vigourously
        -- e.g.  case (f x, g y) of (a,b) -> ....
        -- If a,b occur once we can avoid constructing the let binding for them.
406

407
   Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
Ian Lynagh's avatar
Ian Lynagh committed
408 409 410 411 412 413
        -- Consider     case I# (quotInt# x y) of
        --                I# v -> let w = J# v in ...
        -- If we gaily inline (quotInt# x y) for v, we end up building an
        -- extra thunk:
        --                let w = J# (quotInt# x y) in ...
        -- because quotInt# can fail.
414

415 416 417 418
  | preInlineUnconditionally env NotTopLevel bndr new_rhs
  = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
-}

419
----------------------------------
420
prepareRhs takes a putative RHS, checks whether it's a PAP or
Ian Lynagh's avatar
Ian Lynagh committed
421
constructor application and, if so, converts it to ANF, so that the
422
resulting thing can be inlined more easily.  Thus
Ian Lynagh's avatar
Ian Lynagh committed
423
        x = (f a, g b)
424
becomes
Ian Lynagh's avatar
Ian Lynagh committed
425 426 427
        t1 = f a
        t2 = g b
        x = (t1,t2)
428

429
We also want to deal well cases like this
Ian Lynagh's avatar
Ian Lynagh committed
430
        v = (f e1 `cast` co) e2
431
Here we want to make e1,e2 trivial and get
Ian Lynagh's avatar
Ian Lynagh committed
432
        x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
433 434
That's what the 'go' loop in prepareRhs does

435 436 437
\begin{code}
prepareRhs :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
-- Adds new floats to the env iff that allows us to return a good RHS
Ian Lynagh's avatar
Ian Lynagh committed
438
prepareRhs env (Cast rhs co)    -- Note [Float coercions]
Ian Lynagh's avatar
Ian Lynagh committed
439
  | (ty1, _ty2) <- coercionKind co       -- Do *not* do this if rhs has an unlifted type
Ian Lynagh's avatar
Ian Lynagh committed
440 441 442
  , not (isUnLiftedType ty1)            -- see Note [Float coercions (unlifted)]
  = do  { (env', rhs') <- makeTrivial env rhs
        ; return (env', Cast rhs' co) }
443

Ian Lynagh's avatar
Ian Lynagh committed
444 445 446
prepareRhs env0 rhs0
  = do  { (_is_val, env1, rhs1) <- go 0 env0 rhs0
        ; return (env1, rhs1) }
447
  where
448
    go n_val_args env (Cast rhs co)
Ian Lynagh's avatar
Ian Lynagh committed
449 450
        = do { (is_val, env', rhs') <- go n_val_args env rhs
             ; return (is_val, env', Cast rhs' co) }
451
    go n_val_args env (App fun (Type ty))
Ian Lynagh's avatar
Ian Lynagh committed
452 453
        = do { (is_val, env', rhs') <- go n_val_args env fun
             ; return (is_val, env', App rhs' (Type ty)) }
454
    go n_val_args env (App fun arg)
Ian Lynagh's avatar
Ian Lynagh committed
455 456 457 458 459
        = do { (is_val, env', fun') <- go (n_val_args+1) env fun
             ; case is_val of
                True -> do { (env'', arg') <- makeTrivial env' arg
                           ; return (True, env'', App fun' arg') }
                False -> return (False, env, App fun arg) }
460
    go n_val_args env (Var fun)
Ian Lynagh's avatar
Ian Lynagh committed
461 462 463 464 465
        = return (is_val, env, Var fun)
        where
          is_val = n_val_args > 0       -- There is at least one arg
                                        -- ...and the fun a constructor or PAP
                 && (isDataConWorkId fun || n_val_args < idArity fun)
Ian Lynagh's avatar
Ian Lynagh committed
466
    go _ env other
Ian Lynagh's avatar
Ian Lynagh committed
467
        = return (False, env, other)
468 469
\end{code}

470

471 472 473
Note [Float coercions]
~~~~~~~~~~~~~~~~~~~~~~
When we find the binding
Ian Lynagh's avatar
Ian Lynagh committed
474
        x = e `cast` co
475
we'd like to transform it to
Ian Lynagh's avatar
Ian Lynagh committed
476 477
        x' = e
        x = x `cast` co         -- A trivial binding
478 479 480 481 482 483 484 485 486 487 488 489 490
There's a chance that e will be a constructor application or function, or something
like that, so moving the coerion to the usage site may well cancel the coersions
and lead to further optimisation.  Example:

     data family T a :: *
     data instance T Int = T Int

     foo :: Int -> Int -> Int
     foo m n = ...
        where
          x = T m
          go 0 = 0
          go n = case x of { T m -> go (n-m) }
Ian Lynagh's avatar
Ian Lynagh committed
491
                -- This case should optimise
492

493 494
Note [Float coercions (unlifted)]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Ian Lynagh's avatar
Ian Lynagh committed
495
BUT don't do [Float coercions] if 'e' has an unlifted type.
496 497
This *can* happen:

Ian Lynagh's avatar
Ian Lynagh committed
498 499
     foo :: Int = (error (# Int,Int #) "urk")
                  `cast` CoUnsafe (# Int,Int #) Int
500 501 502

If do the makeTrivial thing to the error call, we'll get
    foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
Ian Lynagh's avatar
Ian Lynagh committed
503
But 'v' isn't in scope!
504 505

These strange casts can happen as a result of case-of-case
Ian Lynagh's avatar
Ian Lynagh committed
506 507
        bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
                (# p,q #) -> p+q
508

509 510 511 512 513 514 515

\begin{code}
makeTrivial :: SimplEnv -> OutExpr -> SimplM (SimplEnv, OutExpr)
-- Binds the expression to a variable, if it's not trivial, returning the variable
makeTrivial env expr
  | exprIsTrivial expr
  = return (env, expr)
Ian Lynagh's avatar
Ian Lynagh committed
516
  | otherwise           -- See Note [Take care] below
Ian Lynagh's avatar
Ian Lynagh committed
517
  = do  { var <- newId (fsLit "a") (exprType expr)
518
        ; env' <- completeNonRecX env False var var expr
519 520 521 522 523
--	  pprTrace "makeTrivial" (vcat [ppr var <+> ppr (exprArity (substExpr env' (Var var)))
--	  	   		       , ppr expr
--	  	   		       , ppr (substExpr env' (Var var))
--				       , ppr (idArity (fromJust (lookupInScope (seInScope env') var))) ]) $
	; return (env', substExpr env' (Var var)) }
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
524 525 526 527 528 529 530
	-- The substitution is needed becase we're constructing a new binding
	--     a = rhs
	-- And if rhs is of form (rhs1 |> co), then we might get
	--     a1 = rhs1
	--     a = a1 |> co
	-- and now a's RHS is trivial and can be substituted out, and that
	-- is what completeNonRecX will do
531
\end{code}
532 533


534
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
535
%*                                                                      *
536
\subsection{Completing a lazy binding}
Ian Lynagh's avatar
Ian Lynagh committed
537
%*                                                                      *
538 539
%************************************************************************

540 541 542 543 544
completeBind
  * deals only with Ids, not TyVars
  * takes an already-simplified binder and RHS
  * is used for both recursive and non-recursive bindings
  * is used for both top-level and non-top-level bindings
545 546 547 548 549 550 551 552

It does the following:
  - tries discarding a dead binding
  - tries PostInlineUnconditionally
  - add unfolding [this is the only place we add an unfolding]
  - add arity

It does *not* attempt to do let-to-case.  Why?  Because it is used for
Ian Lynagh's avatar
Ian Lynagh committed
553
  - top-level bindings (when let-to-case is impossible)
554
  - many situations where the "rhs" is known to be a WHNF
Ian Lynagh's avatar
Ian Lynagh committed
555
                (so let-to-case is inappropriate).
556

557 558
Nor does it do the atomic-argument thing

559
\begin{code}
560
completeBind :: SimplEnv
Ian Lynagh's avatar
Ian Lynagh committed
561 562 563 564 565 566 567
             -> TopLevelFlag            -- Flag stuck into unfolding
             -> InId                    -- Old binder
             -> OutId -> OutExpr        -- New binder and RHS
             -> SimplM SimplEnv
-- completeBind may choose to do its work
--      * by extending the substitution (e.g. let x = y in ...)
--      * or by adding to the floats in the envt
568 569

completeBind env top_lvl old_bndr new_bndr new_rhs
570
  | postInlineUnconditionally env top_lvl new_bndr occ_info new_rhs unfolding
Ian Lynagh's avatar
Ian Lynagh committed
571 572 573 574 575 576
                -- Inline and discard the binding
  = do  { tick (PostInlineUnconditionally old_bndr)
        ; -- pprTrace "postInlineUnconditionally" (ppr old_bndr <+> ppr new_bndr <+> ppr new_rhs) $
          return (extendIdSubst env old_bndr (DoneEx new_rhs)) }
        -- Use the substitution to make quite, quite sure that the
        -- substitution will happen, since we are going to discard the binding
577

578 579 580 581 582 583 584 585
  | otherwise
  = return (addNonRecWithUnf env new_bndr new_rhs unfolding wkr)
  where
    unfolding | omit_unfolding = NoUnfolding
	      | otherwise      = mkUnfolding  (isTopLevel top_lvl) new_rhs
    old_info    = idInfo old_bndr
    occ_info    = occInfo old_info
    wkr		= substWorker env (workerInfo old_info)
586 587 588 589
    omit_unfolding = isNonRuleLoopBreaker occ_info 
		   --       or not (activeInline env old_bndr)
    		   -- Do *not* trim the unfolding in SimplGently, else
		   -- the specialiser can't see it!
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624

-----------------
addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplEnv
-- Add a new binding to the environment, complete with its unfolding
-- but *do not* do postInlineUnconditionally, because we have already
-- processed some of the scope of the binding
-- We still want the unfolding though.  Consider
--	let 
--	      x = /\a. let y = ... in Just y
--	in body
-- Then we float the y-binding out (via abstractFloats and addPolyBind)
-- but 'x' may well then be inlined in 'body' in which case we'd like the 
-- opportunity to inline 'y' too.

addPolyBind top_lvl env (NonRec poly_id rhs)
  = addNonRecWithUnf env poly_id rhs unfolding NoWorker
  where
    unfolding | not (activeInline env poly_id) = NoUnfolding
	      | otherwise		       = mkUnfolding (isTopLevel top_lvl) rhs
		-- addNonRecWithInfo adds the new binding in the
		-- proper way (ie complete with unfolding etc),
		-- and extends the in-scope set

addPolyBind _ env bind@(Rec _) = extendFloats env bind
		-- Hack: letrecs are more awkward, so we extend "by steam"
		-- without adding unfoldings etc.  At worst this leads to
		-- more simplifier iterations

-----------------
addNonRecWithUnf :: SimplEnv
             	  -> OutId -> OutExpr        -- New binder and RHS
		  -> Unfolding -> WorkerInfo -- and unfolding
             	  -> SimplEnv
-- Add suitable IdInfo to the Id, add the binding to the floats, and extend the in-scope set
addNonRecWithUnf env new_bndr rhs unfolding wkr
625
  = ASSERT( isId new_bndr )
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
626 627
    WARN( new_arity < old_arity || new_arity < dmd_arity, 
          (ppr final_id <+> ppr old_arity <+> ppr new_arity <+> ppr dmd_arity) $$ ppr rhs )
628
    final_id `seq`      -- This seq forces the Id, and hence its IdInfo,
629 630 631 632
	                -- and hence any inner substitutions
    addNonRec env final_id rhs
	-- The addNonRec adds it to the in-scope set too
  where
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
633 634 635
	dmd_arity = length $ fst $ splitStrictSig $ idNewStrictness new_bndr
	old_arity = idArity new_bndr

Ian Lynagh's avatar
Ian Lynagh committed
636
        --      Arity info
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
637 638
	new_arity = exprArity rhs
        new_bndr_info = idInfo new_bndr `setArityInfo` new_arity
Ian Lynagh's avatar
Ian Lynagh committed
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661

        --      Unfolding info
        -- Add the unfolding *only* for non-loop-breakers
        -- Making loop breakers not have an unfolding at all
        -- means that we can avoid tests in exprIsConApp, for example.
        -- This is important: if exprIsConApp says 'yes' for a recursive
        -- thing, then we can get into an infinite loop

        --      Demand info
        -- If the unfolding is a value, the demand info may
        -- go pear-shaped, so we nuke it.  Example:
        --      let x = (a,b) in
        --      case x of (p,q) -> h p q x
        -- Here x is certainly demanded. But after we've nuked
        -- the case, we'll get just
        --      let x = (a,b) in h a b x
        -- and now x is not demanded (I'm assuming h is lazy)
        -- This really happens.  Similarly
        --      let f = \x -> e in ...f..f...
        -- After inlining f at some of its call sites the original binding may
        -- (for example) be no longer strictly demanded.
        -- The solution here is a bit ad hoc...
        info_w_unf = new_bndr_info `setUnfoldingInfo` unfolding
662
				   `setWorkerInfo`    wkr
Ian Lynagh's avatar
Ian Lynagh committed
663

664
        final_info | isEvaldUnfolding unfolding = zapDemandInfo info_w_unf `orElse` info_w_unf
Ian Lynagh's avatar
Ian Lynagh committed
665
                   | otherwise                  = info_w_unf
666
	
Ian Lynagh's avatar
Ian Lynagh committed
667
        final_id = new_bndr `setIdInfo` final_info
SamB's avatar
SamB committed
668
\end{code}
669 670 671



672
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
673
%*                                                                      *
674
\subsection[Simplify-simplExpr]{The main function: simplExpr}
Ian Lynagh's avatar
Ian Lynagh committed
675
%*                                                                      *
676 677
%************************************************************************

678 679 680 681 682 683
The reason for this OutExprStuff stuff is that we want to float *after*
simplifying a RHS, not before.  If we do so naively we get quadratic
behaviour as things float out.

To see why it's important to do it after, consider this (real) example:

Ian Lynagh's avatar
Ian Lynagh committed
684 685
        let t = f x
        in fst t
686
==>
Ian Lynagh's avatar
Ian Lynagh committed
687 688 689 690
        let t = let a = e1
                    b = e2
                in (a,b)
        in fst t
691
==>
Ian Lynagh's avatar
Ian Lynagh committed
692 693 694 695 696
        let a = e1
            b = e2
            t = (a,b)
        in
        a       -- Can't inline a this round, cos it appears twice
697
==>
Ian Lynagh's avatar
Ian Lynagh committed
698
        e1
699 700 701 702

Each of the ==> steps is a round of simplification.  We'd save a
whole round if we float first.  This can cascade.  Consider

Ian Lynagh's avatar
Ian Lynagh committed
703 704
        let f = g d
        in \x -> ...f...
705
==>
Ian Lynagh's avatar
Ian Lynagh committed
706 707
        let f = let d1 = ..d.. in \y -> e
        in \x -> ...f...
708
==>
Ian Lynagh's avatar
Ian Lynagh committed
709 710
        let d1 = ..d..
        in \x -> ...(\y ->e)...
711

Ian Lynagh's avatar
Ian Lynagh committed
712
Only in this second round can the \y be applied, and it
713 714 715
might do the same again.


716
\begin{code}
717
simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
718
simplExpr env expr = simplExprC env expr mkBoringStop
719

720
simplExprC :: SimplEnv -> CoreExpr -> SimplCont -> SimplM CoreExpr
Ian Lynagh's avatar
Ian Lynagh committed
721 722
        -- Simplify an expression, given a continuation
simplExprC env expr cont
723
  = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seFloats env) ) $
Ian Lynagh's avatar
Ian Lynagh committed
724 725 726 727
    do  { (env', expr') <- simplExprF (zapFloats env) expr cont
        ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
          -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
          -- pprTrace "simplExprC ret4" (ppr (seFloats env')) $
728 729 730 731
          return (wrapFloats env' expr') }

--------------------------------------------------
simplExprF :: SimplEnv -> InExpr -> SimplCont
Ian Lynagh's avatar
Ian Lynagh committed
732
           -> SimplM (SimplEnv, OutExpr)
733

Ian Lynagh's avatar
Ian Lynagh committed
734
simplExprF env e cont
735 736
  = -- pprTrace "simplExprF" (ppr e $$ ppr cont $$ ppr (seTvSubst env) $$ ppr (seIdSubst env) {- $$ ppr (seFloats env) -} ) $
    simplExprF' env e cont
Ian Lynagh's avatar
Ian Lynagh committed
737

Ian Lynagh's avatar
Ian Lynagh committed
738 739
simplExprF' :: SimplEnv -> InExpr -> SimplCont
            -> SimplM (SimplEnv, OutExpr)
Ian Lynagh's avatar
Ian Lynagh committed
740
simplExprF' env (Var v)        cont = simplVar env v cont
741 742 743 744
simplExprF' env (Lit lit)      cont = rebuild env (Lit lit) cont
simplExprF' env (Note n expr)  cont = simplNote env n expr cont
simplExprF' env (Cast body co) cont = simplCast env body co cont
simplExprF' env (App fun arg)  cont = simplExprF env fun $
Ian Lynagh's avatar
Ian Lynagh committed
745
                                      ApplyTo NoDup arg env cont
746

Ian Lynagh's avatar
Ian Lynagh committed
747
simplExprF' env expr@(Lam _ _) cont
748
  = simplLam env (map zap bndrs) body cont
Ian Lynagh's avatar
Ian Lynagh committed
749 750 751 752 753 754
        -- The main issue here is under-saturated lambdas
        --   (\x1. \x2. e) arg1
        -- Here x1 might have "occurs-once" occ-info, because occ-info
        -- is computed assuming that a group of lambdas is applied
        -- all at once.  If there are too few args, we must zap the
        -- occ-info.
755 756 757 758
  where
    n_args   = countArgs cont
    n_params = length bndrs
    (bndrs, body) = collectBinders expr
Ian Lynagh's avatar
Ian Lynagh committed
759 760 761 762 763
    zap | n_args >= n_params = \b -> b
        | otherwise          = \b -> if isTyVar b then b
                                     else zapLamIdInfo b
        -- NB: we count all the args incl type args
        -- so we must count all the binders (incl type lambdas)
764

765
simplExprF' env (Type ty) cont
766
  = ASSERT( contIsRhsOrArg cont )
Ian Lynagh's avatar
Ian Lynagh committed
767 768
    do  { ty' <- simplType env ty
        ; rebuild env (Type ty') cont }
769

770
simplExprF' env (Case scrut bndr _ alts) cont
771
  | not (switchIsOn (getSwitchChecker env) NoCaseOfCase)
Ian Lynagh's avatar
Ian Lynagh committed
772
  =     -- Simplify the scrutinee with a Select continuation
773
    simplExprF env scrut (Select NoDup bndr alts env cont)
774

775
  | otherwise
Ian Lynagh's avatar
Ian Lynagh committed
776 777 778 779
  =     -- If case-of-case is off, simply simplify the case expression
        -- in a vanilla Stop context, and rebuild the result around it
    do  { case_expr' <- simplExprC env scrut case_cont
        ; rebuild env case_expr' cont }
780
  where
781
    case_cont = Select NoDup bndr alts env mkBoringStop
782

783
simplExprF' env (Let (Rec pairs) body) cont
Ian Lynagh's avatar
Ian Lynagh committed
784
  = do  { env' <- simplRecBndrs env (map fst pairs)
Ian Lynagh's avatar
Ian Lynagh committed
785 786
                -- NB: bndrs' don't have unfoldings or rules
                -- We add them as we go down
787

Ian Lynagh's avatar
Ian Lynagh committed
788 789
        ; env'' <- simplRecBind env' NotTopLevel pairs
        ; simplExprF env'' body cont }
790

791 792
simplExprF' env (Let (NonRec bndr rhs) body) cont
  = simplNonRecE env bndr (rhs, env) ([], body) cont
793 794

---------------------------------
795
simplType :: SimplEnv -> InType -> SimplM OutType
Ian Lynagh's avatar
Ian Lynagh committed
796
        -- Kept monadic just so we can do the seqType
797
simplType env ty
798
  = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
799
    seqType new_ty   `seq`   return new_ty
800
  where
801
    new_ty = substTy env ty
802 803 804
\end{code}


805
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
806
%*                                                                      *
807
\subsection{The main rebuilder}
Ian Lynagh's avatar
Ian Lynagh committed
808
%*                                                                      *
809 810 811 812 813 814
%************************************************************************

\begin{code}
rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
-- At this point the substitution in the SimplEnv should be irrelevant
-- only the in-scope set and floats should matter
Ian Lynagh's avatar
Ian Lynagh committed
815 816 817
rebuild env expr cont0
  = -- pprTrace "rebuild" (ppr expr $$ ppr cont0 $$ ppr (seFloats env)) $
    case cont0 of
Ian Lynagh's avatar
Ian Lynagh committed
818 819
      Stop {}                      -> return (env, expr)
      CoerceIt co cont             -> rebuild env (mkCoerce co expr) cont
820
      Select _ bndr alts se cont   -> rebuildCase (se `setFloats` env) expr bndr alts cont
821
      StrictArg fun _ info cont    -> rebuildCall env (fun `App` expr) info cont
822
      StrictBind b bs body se cont -> do { env' <- simplNonRecX (se `setFloats` env) b expr
Ian Lynagh's avatar
Ian Lynagh committed
823 824 825
                                         ; simplLam env' bs body cont }
      ApplyTo _ arg se cont        -> do { arg' <- simplExpr (se `setInScope` env) arg
                                         ; rebuild env (App expr arg') cont }
826 827 828
\end{code}


829
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
830
%*                                                                      *
831
\subsection{Lambdas}
Ian Lynagh's avatar
Ian Lynagh committed
832
%*                                                                      *
833 834 835
%************************************************************************

\begin{code}
836
simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
Ian Lynagh's avatar
Ian Lynagh committed
837
          -> SimplM (SimplEnv, OutExpr)
Ian Lynagh's avatar
Ian Lynagh committed
838 839 840
simplCast env body co0 cont0
  = do  { co1 <- simplType env co0
        ; simplExprF env body (addCoerce co1 cont0) }
841
  where
842 843
       addCoerce co cont = add_coerce co (coercionKind co) cont

Ian Lynagh's avatar
Ian Lynagh committed
844
       add_coerce _co (s1, k1) cont     -- co :: ty~ty
Ian Lynagh's avatar
Ian Lynagh committed
845
         | s1 `coreEqType` k1 = cont    -- is a no-op
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
846

Ian Lynagh's avatar
Ian Lynagh committed
847 848
       add_coerce co1 (s1, _k2) (CoerceIt co2 cont)
         | (_l1, t1) <- coercionKind co2
849
		-- 	e |> (g1 :: S1~L) |> (g2 :: L~T1)
Ian Lynagh's avatar
Ian Lynagh committed
850
                -- ==>
851 852
                --      e,                       if T1=T2
                --      e |> (g1 . g2 :: T1~T2)  otherwise
Ian Lynagh's avatar
Ian Lynagh committed
853 854 855 856 857 858
                --
                -- For example, in the initial form of a worker
                -- we may find  (coerce T (coerce S (\x.e))) y
                -- and we'd like it to simplify to e[y/x] in one round
                -- of simplification
         , s1 `coreEqType` t1  = cont            -- The coerces cancel out
859
         | otherwise           = CoerceIt (mkTransCoercion co1 co2) cont
Ian Lynagh's avatar
Ian Lynagh committed
860

Ian Lynagh's avatar
Ian Lynagh committed
861
       add_coerce co (s1s2, _t1t2) (ApplyTo dup (Type arg_ty) arg_se cont)
862
                -- (f |> g) ty  --->   (f ty) |> (g @ ty)
Ian Lynagh's avatar
Ian Lynagh committed
863 864 865 866 867
                -- This implements the PushT rule from the paper
         | Just (tyvar,_) <- splitForAllTy_maybe s1s2
         , not (isCoVar tyvar)
         = ApplyTo dup (Type ty') (zapSubstEnv env) (addCoerce (mkInstCoercion co ty') cont)
         where
868
           ty' = substTy (arg_se `setInScope` env) arg_ty
869

Ian Lynagh's avatar
Ian Lynagh committed
870
        -- ToDo: the PushC rule is not implemented at all
871

Ian Lynagh's avatar
Ian Lynagh committed
872
       add_coerce co (s1s2, _t1t2) (ApplyTo dup arg arg_se cont)
873
         | not (isTypeArg arg)  -- This implements the Push rule from the paper
Ian Lynagh's avatar
Ian Lynagh committed
874
         , isFunTy s1s2   -- t1t2 must be a function type, becuase it's applied
875
                --      (e |> (g :: s1s2 ~ t1->t2)) f
Ian Lynagh's avatar
Ian Lynagh committed
876
                -- ===>
877 878
                --      (e (f |> (arg g :: t1~s1))
		--	|> (res g :: s2->t2)
Ian Lynagh's avatar
Ian Lynagh committed
879
                --
880
                -- t1t2 must be a function type, t1->t2, because it's applied
Ian Lynagh's avatar
Ian Lynagh committed
881 882 883 884 885 886 887 888
                -- to something but s1s2 might conceivably not be
                --
                -- When we build the ApplyTo we can't mix the out-types
                -- with the InExpr in the argument, so we simply substitute
                -- to make it all consistent.  It's a bit messy.
                -- But it isn't a common case.
                --
                -- Example of use: Trac #995
889
         = ApplyTo dup new_arg (zapSubstEnv env) (addCoerce co2 cont)
890
         where
891 892 893
           -- we split coercion t1->t2 ~ s1->s2 into t1 ~ s1 and
           -- t2 ~ s2 with left and right on the curried form:
           --    (->) t1 t2 ~ (->) s1 s2
894
           [co1, co2] = decomposeCo 2 co
895
           new_arg    = mkCoerce (mkSymCoercion co1) arg'
896
           arg'       = substExpr (arg_se `setInScope` env) arg
897

898
       add_coerce co _ cont = CoerceIt co cont
899 900
\end{code}

901

902
%************************************************************************
Ian Lynagh's avatar
Ian Lynagh committed
903
%*                                                                      *
904
\subsection{Lambdas}
Ian Lynagh's avatar
Ian Lynagh committed
905
%*                                                                      *
906
%************************************************************************
907 908

\begin{code}
909
simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
Ian Lynagh's avatar
Ian Lynagh committed
910
         -> SimplM (SimplEnv, OutExpr)
911 912

simplLam env [] body cont = simplExprF env body cont
913

914
        -- Beta reduction
915
simplLam env (bndr:bndrs) body (ApplyTo _ arg arg_se cont)
Ian Lynagh's avatar
Ian Lynagh committed
916 917
  = do  { tick (BetaReduction bndr)
        ; simplNonRecE env bndr (arg, arg_se) (bndrs, body) cont }
918

Ian Lynagh's avatar
Ian Lynagh committed
919
        -- Not enough args, so there are real lambdas left to put in the result
920
simplLam env bndrs body cont
Ian Lynagh's avatar
Ian Lynagh committed
921 922
  = do  { (env', bndrs') <- simplLamBndrs env bndrs
        ; body' <- simplExpr env' body
Ian Lynagh's avatar
Ian Lynagh committed
923
        ; new_lam <- mkLam bndrs' body'
Ian Lynagh's avatar
Ian Lynagh committed
924
        ; rebuild env' new_lam cont }
925 926

------------------
Ian Lynagh's avatar
Ian Lynagh committed
927 928 929
simplNonRecE :: SimplEnv
             -> InId                    -- The binder
             -> (InExpr, SimplEnv)      -- Rhs of binding (or arg of lambda)
930
             -> ([InBndr], InExpr)      -- Body of the let/lambda
Ian Lynagh's avatar
Ian Lynagh committed
931 932 933
                                        --      \xs.e
             -> SimplCont
             -> SimplM (SimplEnv, OutExpr)
934 935 936 937 938 939 940 941 942 943

-- simplNonRecE is used for
--  * non-top-level non-recursive lets in expressions
--  * beta reduction
--
-- It deals with strict bindings, via the StrictBind continuation,
-- which may abort the whole process
--
-- The "body" of the binding comes as a pair of ([InId],InExpr)
-- representing a lambda; so we recurse back to simplLam
Ian Lynagh's avatar
Ian Lynagh committed
944 945
-- Why?  Because of the binder-occ-info-zapping done before
--       the call to simplLam in simplExprF (Lam ...)
946

947 948
	-- First deal with type applications and type lets
	--   (/\a. e) (Type ty)   and   (let a = Type ty in e)
949
simplNonRecE env bndr (Type ty_arg, rhs_se) (bndrs, body) cont
950 951
  = ASSERT( isTyVar bndr )
    do	{ ty_arg' <- simplType (rhs_se `setInScope` env) ty_arg
952 953
	; simplLam (extendTvSubst env bndr ty_arg') bndrs body cont }

954 955
simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
  | preInlineUnconditionally env NotTopLevel bndr rhs
Ian Lynagh's avatar
Ian Lynagh committed
956 957
  = do  { tick (PreInlineUnconditionally bndr)
        ; simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
958

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
959
  | isStrictId bndr