CoreUtils.hs 84.8 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1 2 3 4
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998

Simon Marlow's avatar
Simon Marlow committed
5 6

Utility functions on @Core@ syntax
Austin Seipp's avatar
Austin Seipp committed
7
-}
8

9 10
{-# LANGUAGE CPP #-}

batterseapower's avatar
batterseapower committed
11
-- | Commonly useful utilites for manipulating the Core language
12
module CoreUtils (
13
        -- * Constructing expressions
14
        mkCast,
Peter Wortmann's avatar
Peter Wortmann committed
15
        mkTick, mkTicks, mkTickNoHNF, tickHNFArgs,
Simon Marlow's avatar
Simon Marlow committed
16
        bindNonRec, needsCaseBinding,
17
        mkAltExpr,
18

19
        -- * Taking expressions apart
20 21 22
        findDefault, addDefault, findAlt, isDefaultAlt,
        mergeAlts, trimConArgs,
        filterAlts, combineIdenticalAlts, refineDefaultAlt,
23

24
        -- * Properties of expressions
Simon Marlow's avatar
Simon Marlow committed
25
        exprType, coreAltType, coreAltsType,
26
        exprIsDupable, exprIsTrivial, getIdFromTrivialExpr, exprIsBottom,
27
        exprIsCheap, exprIsExpandable, exprIsCheap', CheapAppFun,
28
        exprIsHNF, exprOkForSpeculation, exprOkForSideEffects, exprIsWorkFree,
29 30
        exprIsBig, exprIsConLike,
        rhsIsStatic, isCheapApp, isExpandableApp,
31

32
        -- * Equality
Peter Wortmann's avatar
Peter Wortmann committed
33
        cheapEqExpr, cheapEqExpr', eqExpr,
Peter Wortmann's avatar
Peter Wortmann committed
34
        diffExpr, diffBinds,
35

36 37
        -- * Eta reduction
        tryEtaReduce,
38

39
        -- * Manipulating data constructors and types
40
        exprToType, exprToCoercion_maybe,
41
        applyTypeToArgs, applyTypeToArg,
Peter Wortmann's avatar
Peter Wortmann committed
42
        dataConRepInstPat, dataConRepFSInstPat,
43
        isEmptyTy,
Peter Wortmann's avatar
Peter Wortmann committed
44 45

        -- * Working with ticks
46 47
        stripTicksTop, stripTicksTopE, stripTicksTopT,
        stripTicksE, stripTicksT
48
    ) where
49

50
#include "HsVersions.h"
51

52
import CoreSyn
Simon Marlow's avatar
Simon Marlow committed
53
import PprCore
54
import CoreFVs( exprFreeVars )
Simon Marlow's avatar
Simon Marlow committed
55 56
import Var
import SrcLoc
57
import VarEnv
58
import VarSet
Simon Marlow's avatar
Simon Marlow committed
59 60 61 62 63 64 65 66 67 68
import Name
import Literal
import DataCon
import PrimOp
import Id
import IdInfo
import Type
import Coercion
import TyCon
import Unique
69
import Outputable
Simon Marlow's avatar
Simon Marlow committed
70
import TysPrim
71
import DynFlags
Simon Marlow's avatar
Simon Marlow committed
72
import FastString
73
import Maybes
74
import ListSetOps       ( minusList )
75
import Platform
Simon Marlow's avatar
Simon Marlow committed
76
import Util
77
import Pair
Peter Wortmann's avatar
Peter Wortmann committed
78
import Data.Function       ( on )
79
import Data.List
Peter Wortmann's avatar
Peter Wortmann committed
80
import Data.Ord            ( comparing )
Peter Wortmann's avatar
Peter Wortmann committed
81
import OrdList
82

Austin Seipp's avatar
Austin Seipp committed
83 84 85
{-
************************************************************************
*                                                                      *
86
\subsection{Find the type of a Core atom/expression}
Austin Seipp's avatar
Austin Seipp committed
87 88 89
*                                                                      *
************************************************************************
-}
90

91
exprType :: CoreExpr -> Type
batterseapower's avatar
batterseapower committed
92 93 94
-- ^ Recover the type of a well-typed Core expression. Fails when
-- applied to the actual 'CoreSyn.Type' expression as it cannot
-- really be said to have a type
95 96 97
exprType (Var var)           = idType var
exprType (Lit lit)           = literalType lit
exprType (Coercion co)       = coercionType co
Austin Seipp's avatar
Austin Seipp committed
98
exprType (Let bind body)
99 100 101
  | NonRec tv rhs <- bind    -- See Note [Type bindings]
  , Type ty <- rhs           = substTyWith [tv] [ty] (exprType body)
  | otherwise                = exprType body
102
exprType (Case _ _ ty _)     = ty
103
exprType (Cast _ co)         = pSnd (coercionKind co)
104
exprType (Tick _ e)          = exprType e
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
105
exprType (Lam binder expr)   = mkPiType binder (exprType expr)
106
exprType e@(App _ _)
107
  = case collectArgs e of
108
        (fun, args) -> applyTypeToArgs e (exprType fun) args
109

110
exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
111

112
coreAltType :: CoreAlt -> Type
batterseapower's avatar
batterseapower committed
113
-- ^ Returns the type of the alternatives right hand side
114
coreAltType (_,bs,rhs)
115 116 117 118
  | any bad_binder bs = expandTypeSynonyms ty
  | otherwise         = ty    -- Note [Existential variables and silly type synonyms]
  where
    ty           = exprType rhs
119 120
    free_tvs     = tyCoVarsOfType ty
    bad_binder b = b `elemVarSet` free_tvs
121 122

coreAltsType :: [CoreAlt] -> Type
batterseapower's avatar
batterseapower committed
123
-- ^ Returns the type of the first alternative, which should be the same as for all alternatives
124
coreAltsType (alt:_) = coreAltType alt
125
coreAltsType []      = panic "corAltsType"
126

Austin Seipp's avatar
Austin Seipp committed
127
{-
128 129 130 131 132 133
Note [Type bindings]
~~~~~~~~~~~~~~~~~~~~
Core does allow type bindings, although such bindings are
not much used, except in the output of the desuguarer.
Example:
     let a = Int in (\x:a. x)
Austin Seipp's avatar
Austin Seipp committed
134
Given this, exprType must be careful to substitute 'a' in the
135 136
result type (Trac #8522).

137 138 139
Note [Existential variables and silly type synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
140 141 142 143
        data T = forall a. T (Funny a)
        type Funny a = Bool
        f :: T -> Bool
        f (T x) = x
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

Now, the type of 'x' is (Funny a), where 'a' is existentially quantified.
That means that 'exprType' and 'coreAltsType' may give a result that *appears*
to mention an out-of-scope type variable.  See Trac #3409 for a more real-world
example.

Various possibilities suggest themselves:

 - Ignore the problem, and make Lint not complain about such variables

 - Expand all type synonyms (or at least all those that discard arguments)
      This is tricky, because at least for top-level things we want to
      retain the type the user originally specified.

 - Expand synonyms on the fly, when the problem arises. That is what
   we are doing here.  It's not too expensive, I think.

161 162
Note that there might be existentially quantified coercion variables, too.
-}
163

164
-- Not defined with applyTypeToArg because you can't print from CoreSyn.
165
applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
batterseapower's avatar
batterseapower committed
166 167
-- ^ A more efficient version of 'applyTypeToArg' when we have several arguments.
-- The first argument is just for debugging, and gives some context
168 169
applyTypeToArgs e op_ty args
  = go op_ty args
170
  where
171 172 173 174 175
    go op_ty []                   = op_ty
    go op_ty (Type ty : args)     = go_ty_args op_ty [ty] args
    go op_ty (Coercion co : args) = go_ty_args op_ty [mkCoercionTy co] args
    go op_ty (_ : args)           | Just (_, res_ty) <- splitFunTy_maybe op_ty
                                  = go res_ty args
176 177 178
    go _ _ = pprPanic "applyTypeToArgs" panic_msg

    -- go_ty_args: accumulate type arguments so we can instantiate all at once
Simon Peyton Jones's avatar
Simon Peyton Jones committed
179
    go_ty_args op_ty rev_tys (Type ty : args)
180
       = go_ty_args op_ty (ty:rev_tys) args
181 182
    go_ty_args op_ty rev_tys (Coercion co : args)
       = go_ty_args op_ty (mkCoercionTy co : rev_tys) args
183 184
    go_ty_args op_ty rev_tys args
       = go (applyTysD panic_msg_w_hdr op_ty (reverse rev_tys)) args
Simon Peyton Jones's avatar
Simon Peyton Jones committed
185

186 187 188 189
    panic_msg_w_hdr = hang (ptext (sLit "applyTypeToArgs")) 2 panic_msg
    panic_msg = vcat [ ptext (sLit "Expression:") <+> pprCoreExpr e
                     , ptext (sLit "Type:") <+> ppr op_ty
                     , ptext (sLit "Args:") <+> ppr args ]
190

191

Austin Seipp's avatar
Austin Seipp committed
192 193 194
{-
************************************************************************
*                                                                      *
195
\subsection{Attaching notes}
Austin Seipp's avatar
Austin Seipp committed
196 197 198
*                                                                      *
************************************************************************
-}
199

200 201
-- | Wrap the given expression in the coercion safely, dropping
-- identity coercions and coalescing nested coercions
202
mkCast :: CoreExpr -> Coercion -> CoreExpr
203 204 205 206 207 208
mkCast e co
  | ASSERT2( coercionRole co == Representational
           , ptext (sLit "coercion") <+> ppr co <+> ptext (sLit "passed to mkCast")
             <+> ppr e <+> ptext (sLit "has wrong role") <+> ppr (coercionRole co) )
    isReflCo co
  = e
209

Austin Seipp's avatar
Austin Seipp committed
210
mkCast (Coercion e_co) co
211
  | isCoercionType (pSnd (coercionKind co))
212 213 214
       -- The guard here checks that g has a (~#) on both sides,
       -- otherwise decomposeCo fails.  Can in principle happen
       -- with unsafeCoerce
215
  = Coercion (mkCoCast e_co co)
216 217

mkCast (Cast expr co2) co
218 219 220 221 222 223
  = WARN(let { Pair  from_ty  _to_ty  = coercionKind co;
               Pair _from_ty2  to_ty2 = coercionKind co2} in
            not (from_ty `eqType` to_ty2),
             vcat ([ ptext (sLit "expr:") <+> ppr expr
                   , ptext (sLit "co2:") <+> ppr co2
                   , ptext (sLit "co:") <+> ppr co ]) )
224
    mkCast expr (mkTransCo co2 co)
225

Peter Wortmann's avatar
Peter Wortmann committed
226 227 228
mkCast (Tick t expr) co
   = Tick t (mkCast expr co)

229
mkCast expr co
230
  = let Pair from_ty _to_ty = coercionKind co in
231 232 233 234 235
    WARN( not (from_ty `eqType` exprType expr),
          text "Trying to coerce" <+> text "(" <> ppr expr
          $$ text "::" <+> ppr (exprType expr) <> text ")"
          $$ ppr co $$ ppr (coercionType co) )
    (Cast expr co)
236

237 238 239
-- | Wraps the given expression in the source annotation, dropping the
-- annotation if possible.
mkTick :: Tickish Id -> CoreExpr -> CoreExpr
Peter Wortmann's avatar
Peter Wortmann committed
240 241 242 243 244
mkTick t orig_expr = mkTick' id id orig_expr
 where
  -- Some ticks (cost-centres) can be split in two, with the
  -- non-counting part having laxer placement properties.
  canSplit = tickishCanSplit t && tickishPlace (mkNoCount t) /= tickishPlace t
245

Peter Wortmann's avatar
Peter Wortmann committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
  mkTick' :: (CoreExpr -> CoreExpr) -- ^ apply after adding tick (float through)
          -> (CoreExpr -> CoreExpr) -- ^ apply before adding tick (float with)
          -> CoreExpr               -- ^ current expression
          -> CoreExpr
  mkTick' top rest expr = case expr of

    -- Cost centre ticks should never be reordered relative to each
    -- other. Therefore we can stop whenever two collide.
    Tick t2 e
      | ProfNote{} <- t2, ProfNote{} <- t -> top $ Tick t $ rest expr

    -- Otherwise we assume that ticks of different placements float
    -- through each other.
      | tickishPlace t2 /= tickishPlace t -> mkTick' (top . Tick t2) rest e

    -- For annotations this is where we make sure to not introduce
    -- redundant ticks.
      | tickishContains t t2              -> mkTick' top rest e
      | tickishContains t2 t              -> orig_expr
      | otherwise                         -> mkTick' top (rest . Tick t2) e

    -- Ticks don't care about types, so we just float all ticks
    -- through them. Note that it's not enough to check for these
    -- cases top-level. While mkTick will never produce Core with type
    -- expressions below ticks, such constructs can be the result of
    -- unfoldings. We therefore make an effort to put everything into
    -- the right place no matter what we start with.
    Cast e co   -> mkTick' (top . flip Cast co) rest e
    Coercion co -> Coercion co

    Lam x e
      -- Always float through type lambdas. Even for non-type lambdas,
      -- floating is allowed for all but the most strict placement rule.
      | not (isRuntimeVar x) || tickishPlace t /= PlaceRuntime
      -> mkTick' (top . Lam x) rest e

      -- If it is both counting and scoped, we split the tick into its
      -- two components, often allowing us to keep the counting tick on
      -- the outside of the lambda and push the scoped tick inside.
      -- The point of this is that the counting tick can probably be
      -- floated, and the lambda may then be in a position to be
      -- beta-reduced.
      | canSplit
      -> top $ Tick (mkNoScope t) $ rest $ Lam x $ mkTick (mkNoCount t) e

    App f arg
      -- Always float through type applications.
      | not (isRuntimeArg arg)
      -> mkTick' (top . flip App arg) rest f

      -- We can also float through constructor applications, placement
      -- permitting. Again we can split.
      | isSaturatedConApp expr && (tickishPlace t==PlaceCostCentre || canSplit)
      -> if tickishPlace t == PlaceCostCentre
         then top $ rest $ tickHNFArgs t expr
         else top $ Tick (mkNoScope t) $ rest $ tickHNFArgs (mkNoCount t) expr

    Var x
Simon Marlow's avatar
Simon Marlow committed
304
      | notFunction && tickishPlace t == PlaceCostCentre
Peter Wortmann's avatar
Peter Wortmann committed
305
      -> orig_expr
Simon Marlow's avatar
Simon Marlow committed
306
      | notFunction && canSplit
Peter Wortmann's avatar
Peter Wortmann committed
307
      -> top $ Tick (mkNoScope t) $ rest expr
Simon Marlow's avatar
Simon Marlow committed
308 309 310 311 312 313 314 315
      where
        -- SCCs can be eliminated on variables provided the variable
        -- is not a function.  In these cases the SCC makes no difference:
        -- the cost of evaluating the variable will be attributed to its
        -- definition site.  When the variable refers to a function, however,
        -- an SCC annotation on the variable affects the cost-centre stack
        -- when the function is called, so we must retain those.
        notFunction = not (isFunTy (idType x))
Peter Wortmann's avatar
Peter Wortmann committed
316 317 318 319 320 321 322 323 324 325

    Lit{}
      | tickishPlace t == PlaceCostCentre
      -> orig_expr

    -- Catch-all: Annotate where we stand
    _any -> top $ Tick t $ rest expr

mkTicks :: [Tickish Id] -> CoreExpr -> CoreExpr
mkTicks ticks expr = foldr mkTick expr ticks
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346

isSaturatedConApp :: CoreExpr -> Bool
isSaturatedConApp e = go e []
  where go (App f a) as = go f (a:as)
        go (Var fun) args
           = isConLikeId fun && idArity fun == valArgCount args
        go (Cast f _) as = go f as
        go _ _ = False

mkTickNoHNF :: Tickish Id -> CoreExpr -> CoreExpr
mkTickNoHNF t e
  | exprIsHNF e = tickHNFArgs t e
  | otherwise   = mkTick t e

-- push a tick into the arguments of a HNF (call or constructor app)
tickHNFArgs :: Tickish Id -> CoreExpr -> CoreExpr
tickHNFArgs t e = push t e
 where
  push t (App f (Type u)) = App (push t f) (Type u)
  push t (App f arg) = App (push t f) (mkTick t arg)
  push _t e = e
347

Peter Wortmann's avatar
Peter Wortmann committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
-- | Strip ticks satisfying a predicate from top of an expression
stripTicksTop :: (Tickish Id -> Bool) -> Expr b -> ([Tickish Id], Expr b)
stripTicksTop p = go []
  where go ts (Tick t e) | p t = go (t:ts) e
        go ts other            = (reverse ts, other)

-- | Strip ticks satisfying a predicate from top of an expression,
-- returning the remaining expresion
stripTicksTopE :: (Tickish Id -> Bool) -> Expr b -> Expr b
stripTicksTopE p = go
  where go (Tick t e) | p t = go e
        go other            = other

-- | Strip ticks satisfying a predicate from top of an expression,
-- returning the ticks
stripTicksTopT :: (Tickish Id -> Bool) -> Expr b -> [Tickish Id]
stripTicksTopT p = go []
  where go ts (Tick t e) | p t = go (t:ts) e
        go ts _                = ts

-- | Completely strip ticks satisfying a predicate from an
-- expression. Note this is O(n) in the size of the expression!
370 371 372 373 374 375 376
stripTicksE :: (Tickish Id -> Bool) -> Expr b -> Expr b
stripTicksE p expr = go expr
  where go (App e a)        = App (go e) (go a)
        go (Lam b e)        = Lam b (go e)
        go (Let b e)        = Let (go_bs b) (go e)
        go (Case e b t as)  = Case (go e) b t (map go_a as)
        go (Cast e c)       = Cast (go e) c
Peter Wortmann's avatar
Peter Wortmann committed
377
        go (Tick t e)
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
          | p t             = go e
          | otherwise       = Tick t (go e)
        go other            = other
        go_bs (NonRec b e)  = NonRec b (go e)
        go_bs (Rec bs)      = Rec (map go_b bs)
        go_b (b, e)         = (b, go e)
        go_a (c,bs,e)       = (c,bs, go e)

stripTicksT :: (Tickish Id -> Bool) -> Expr b -> [Tickish Id]
stripTicksT p expr = fromOL $ go expr
  where go (App e a)        = go e `appOL` go a
        go (Lam _ e)        = go e
        go (Let b e)        = go_bs b `appOL` go e
        go (Case e _ _ as)  = go e `appOL` concatOL (map go_a as)
        go (Cast e _)       = go e
        go (Tick t e)
          | p t             = t `consOL` go e
          | otherwise       = go e
        go _                = nilOL
        go_bs (NonRec _ e)  = go e
        go_bs (Rec bs)      = concatOL (map go_b bs)
        go_b (_, e)         = go e
        go_a (_, _, e)      = go e
Peter Wortmann's avatar
Peter Wortmann committed
401

Austin Seipp's avatar
Austin Seipp committed
402 403 404
{-
************************************************************************
*                                                                      *
405
\subsection{Other expression construction}
Austin Seipp's avatar
Austin Seipp committed
406 407 408
*                                                                      *
************************************************************************
-}
409 410

bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
batterseapower's avatar
batterseapower committed
411 412 413 414 415 416 417
-- ^ @bindNonRec x r b@ produces either:
--
-- > let x = r in b
--
-- or:
--
-- > case r of x { _DEFAULT_ -> b }
418
--
batterseapower's avatar
batterseapower committed
419 420
-- depending on whether we have to use a @case@ or @let@
-- binding for the expression (see 'needsCaseBinding').
421
-- It's used by the desugarer to avoid building bindings
batterseapower's avatar
batterseapower committed
422 423 424
-- that give Core Lint a heart attack, although actually
-- the simplifier deals with them perfectly well. See
-- also 'MkCore.mkCoreLet'
425
bindNonRec bndr rhs body
batterseapower's avatar
batterseapower committed
426
  | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
427
  | otherwise                          = Let (NonRec bndr rhs) body
428

batterseapower's avatar
batterseapower committed
429 430
-- | Tests whether we have to use a @case@ rather than @let@ binding for this expression
-- as per the invariants of 'CoreExpr': see "CoreSyn#let_app_invariant"
431
needsCaseBinding :: Type -> CoreExpr -> Bool
432
needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
433 434 435
        -- Make a case expression instead of a let
        -- These can arise either from the desugarer,
        -- or from beta reductions: (\x.e) (x +# y)
436

batterseapower's avatar
batterseapower committed
437 438 439 440 441 442
mkAltExpr :: AltCon     -- ^ Case alternative constructor
          -> [CoreBndr] -- ^ Things bound by the pattern match
          -> [Type]     -- ^ The type arguments to the case alternative
          -> CoreExpr
-- ^ This guy constructs the value that the scrutinee must have
-- given that you are in one particular branch of a case
443
mkAltExpr (DataAlt con) args inst_tys
444
  = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
445 446
mkAltExpr (LitAlt lit) [] []
  = Lit lit
447 448
mkAltExpr (LitAlt _) _ _ = panic "mkAltExpr LitAlt"
mkAltExpr DEFAULT _ _ = panic "mkAltExpr DEFAULT"
449

Austin Seipp's avatar
Austin Seipp committed
450 451 452
{-
************************************************************************
*                                                                      *
453
               Operations oer case alternatives
Austin Seipp's avatar
Austin Seipp committed
454 455
*                                                                      *
************************************************************************
456

457 458
The default alternative must be first, if it exists at all.
This makes it easy to find, though it makes matching marginally harder.
Austin Seipp's avatar
Austin Seipp committed
459
-}
460

batterseapower's avatar
batterseapower committed
461
-- | Extract the default case alternative
462
findDefault :: [(AltCon, [a], b)] -> ([(AltCon, [a], b)], Maybe b)
463
findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
464
findDefault alts                        =                     (alts, Nothing)
465

466 467 468 469
addDefault :: [(AltCon, [a], b)] -> Maybe b -> [(AltCon, [a], b)]
addDefault alts Nothing    = alts
addDefault alts (Just rhs) = (DEFAULT, [], rhs) : alts

470
isDefaultAlt :: (AltCon, a, b) -> Bool
471 472 473
isDefaultAlt (DEFAULT, _, _) = True
isDefaultAlt _               = False

474
-- | Find the case alternative corresponding to a particular
batterseapower's avatar
batterseapower committed
475
-- constructor: panics if no such constructor exists
476
findAlt :: AltCon -> [(AltCon, a, b)] -> Maybe (AltCon, a, b)
477 478
    -- A "Nothing" result *is* legitmiate
    -- See Note [Unreachable code]
479
findAlt con alts
480
  = case alts of
481
        (deflt@(DEFAULT,_,_):alts) -> go alts (Just deflt)
482
        _                          -> go alts Nothing
483
  where
484
    go []                     deflt = deflt
485
    go (alt@(con1,_,_) : alts) deflt
486 487 488 489
      = case con `cmpAltCon` con1 of
          LT -> deflt   -- Missed it already; the alts are in increasing order
          EQ -> Just alt
          GT -> ASSERT( not (con1 == DEFAULT) ) go alts deflt
490

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
{- Note [Unreachable code]
~~~~~~~~~~~~~~~~~~~~~~~~~~
It is possible (although unusual) for GHC to find a case expression
that cannot match.  For example:

     data Col = Red | Green | Blue
     x = Red
     f v = case x of
              Red -> ...
              _ -> ...(case x of { Green -> e1; Blue -> e2 })...

Suppose that for some silly reason, x isn't substituted in the case
expression.  (Perhaps there's a NOINLINE on it, or profiling SCC stuff
gets in the way; cf Trac #3118.)  Then the full-lazines pass might produce
this

     x = Red
     lvl = case x of { Green -> e1; Blue -> e2 })
     f v = case x of
             Red -> ...
             _ -> ...lvl...

Now if x gets inlined, we won't be able to find a matching alternative
for 'Red'.  That's because 'lvl' is unreachable.  So rather than crashing
we generate (error "Inaccessible alternative").

Similar things can happen (augmented by GADTs) when the Simplifier
filters down the matching alternatives in Simplify.rebuildCase.
-}

521
---------------------------------
522
mergeAlts :: [(AltCon, a, b)] -> [(AltCon, a, b)] -> [(AltCon, a, b)]
batterseapower's avatar
batterseapower committed
523 524
-- ^ Merge alternatives preserving order; alternatives in
-- the first argument shadow ones in the second
525 526 527 528
mergeAlts [] as2 = as2
mergeAlts as1 [] = as1
mergeAlts (a1:as1) (a2:as2)
  = case a1 `cmpAlt` a2 of
529 530 531
        LT -> a1 : mergeAlts as1      (a2:as2)
        EQ -> a1 : mergeAlts as1      as2       -- Discard a2
        GT -> a2 : mergeAlts (a1:as1) as2
532 533 534 535


---------------------------------
trimConArgs :: AltCon -> [CoreArg] -> [CoreArg]
batterseapower's avatar
batterseapower committed
536 537 538 539 540 541
-- ^ Given:
--
-- > case (C a b x y) of
-- >        C b x y -> ...
--
-- We want to drop the leading type argument of the scrutinee
Herbert Valerio Riedel's avatar
Herbert Valerio Riedel committed
542
-- leaving the arguments to match against the pattern
543 544

trimConArgs DEFAULT      args = ASSERT( null args ) []
545
trimConArgs (LitAlt _)   args = ASSERT( null args ) []
546
trimConArgs (DataAlt dc) args = dropList (dataConUnivTyVars dc) args
547

548 549
filterAlts :: TyCon                -- ^ Type constructor of scrutinee's type (used to prune possibilities)
           -> [Type]               -- ^ And its type arguments
Simon Peyton Jones's avatar
Simon Peyton Jones committed
550
           -> [AltCon]             -- ^ 'imposs_cons': constructors known to be impossible due to the form of the scrutinee
551
           -> [(AltCon, [Var], a)] -- ^ Alternatives
552
           -> ([AltCon], [(AltCon, [Var], a)])
553
             -- Returns:
Austin Seipp's avatar
Austin Seipp committed
554
             --  1. Constructors that will never be encountered by the
Simon Peyton Jones's avatar
Simon Peyton Jones committed
555
             --     *default* case (if any).  A superset of imposs_cons
556
             --  2. The new alternatives, trimmed by
Simon Peyton Jones's avatar
Simon Peyton Jones committed
557 558 559 560
             --        a) remove imposs_cons
             --        b) remove constructors which can't match because of GADTs
             --      and with the DEFAULT expanded to a DataAlt if there is exactly
             --      remaining constructor that can match
561 562 563
             --
             -- NB: the final list of alternatives may be empty:
             -- This is a tricky corner case.  If the data type has no constructors,
Austin Seipp's avatar
Austin Seipp committed
564
             -- which GHC allows, or if the imposs_cons covers all constructors (after taking
Simon Peyton Jones's avatar
Simon Peyton Jones committed
565
             -- account of GADTs), then no alternatives can match.
566 567 568 569
             --
             -- If callers need to preserve the invariant that there is always at least one branch
             -- in a "case" statement then they will need to manually add a dummy case branch that just
             -- calls "error" or similar.
570 571
filterAlts _tycon inst_tys imposs_cons alts
  = (imposs_deflt_cons, addDefault trimmed_alts maybe_deflt)
572 573 574
  where
    (alts_wo_default, maybe_deflt) = findDefault alts
    alt_cons = [con | (con,_,_) <- alts_wo_default]
575

576
    trimmed_alts = filterOut (impossible_alt inst_tys) alts_wo_default
577

578
    imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
Austin Seipp's avatar
Austin Seipp committed
579 580
         -- "imposs_deflt_cons" are handled
         --   EITHER by the context,
581 582 583 584 585 586
         --   OR by a non-DEFAULT branch in this case expression.

    impossible_alt :: [Type] -> (AltCon, a, b) -> Bool
    impossible_alt _ (con, _, _) | con `elem` imposs_cons = True
    impossible_alt inst_tys (DataAlt con, _, _) = dataConCannotMatch inst_tys con
    impossible_alt _  _                         = False
587

588 589 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
refineDefaultAlt :: [Unique] -> TyCon -> [Type] -> [AltCon] -> [CoreAlt] -> (Bool, [CoreAlt])
-- Refine the default alterantive to a DataAlt,
-- if there is a unique way to do so
refineDefaultAlt us tycon tys imposs_deflt_cons all_alts
  | (DEFAULT,_,rhs) : rest_alts <- all_alts
  , isAlgTyCon tycon            -- It's a data type, tuple, or unboxed tuples.
  , not (isNewTyCon tycon)      -- We can have a newtype, if we are just doing an eval:
                                --      case x of { DEFAULT -> e }
                                -- and we don't want to fill in a default for them!
  , Just all_cons <- tyConDataCons_maybe tycon
  , let imposs_data_cons = [con | DataAlt con <- imposs_deflt_cons]   -- We now know it's a data type
        impossible con   = con `elem` imposs_data_cons || dataConCannotMatch tys con
  = case filterOut impossible all_cons of
       -- Eliminate the default alternative
       -- altogether if it can't match:
       []    -> (False, rest_alts)

       -- It matches exactly one constructor, so fill it in:
       [con] -> (True, mergeAlts rest_alts [(DataAlt con, ex_tvs ++ arg_ids, rhs)])
                       -- We need the mergeAlts to keep the alternatives in the right order
             where
                (ex_tvs, arg_ids) = dataConRepInstPat us con tys

       -- It matches more than one, so do nothing
       _  -> (False, all_alts)

  | debugIsOn, isAlgTyCon tycon, null (tyConDataCons tycon)
  , not (isFamilyTyCon tycon || isAbstractTyCon tycon)
        -- Check for no data constructors
        -- This can legitimately happen for abstract types and type families,
        -- so don't report that
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
619
  = (False, all_alts)
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686

  | otherwise      -- The common case
  = (False, all_alts)

{- Note [Combine identical alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If several alternatives are identical, merge them into a single
DEFAULT alternative.  I've occasionally seen this making a big
difference:

     case e of               =====>     case e of
       C _ -> f x                         D v -> ....v....
       D v -> ....v....                   DEFAULT -> f x
       DEFAULT -> f x

The point is that we merge common RHSs, at least for the DEFAULT case.
[One could do something more elaborate but I've never seen it needed.]
To avoid an expensive test, we just merge branches equal to the *first*
alternative; this picks up the common cases
     a) all branches equal
     b) some branches equal to the DEFAULT (which occurs first)

The case where Combine Identical Alternatives transformation showed up
was like this (base/Foreign/C/Err/Error.hs):

        x | p `is` 1 -> e1
          | p `is` 2 -> e2
        ...etc...

where @is@ was something like

        p `is` n = p /= (-1) && p == n

This gave rise to a horrible sequence of cases

        case p of
          (-1) -> $j p
          1    -> e1
          DEFAULT -> $j p

and similarly in cascade for all the join points!

NB: it's important that all this is done in [InAlt], *before* we work
on the alternatives themselves, because Simpify.simplAlt may zap the
occurrence info on the binders in the alternatives, which in turn
defeats combineIdenticalAlts (see Trac #7360).

Note [Care with impossible-constructors when combining alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have (Trac #10538)
   data T = A | B | C

   ... case x::T of
         DEFAULT -> e1
         A -> e2
         B -> e1

When calling combineIdentialAlts, we'll have computed that the "impossible
constructors" for the DEFAULT alt is {A,B}, since if x is A or B we'll
take the other alternatives.  But suppose we combine B into the DEFAULT,
to get
   ... case x::T of
         DEFAULT -> e1
         A -> e2
Then we must be careful to trim the impossible constructors to just {A},
else we risk compiling 'e1' wrong!
-}
687 688


689 690 691 692 693 694 695 696 697 698 699 700
combineIdenticalAlts :: [AltCon] -> [CoreAlt] -> (Bool, [AltCon], [CoreAlt])
-- See Note [Combine identical alternatives]
-- See Note [Care with impossible-constructors when combining alternatives]
-- True <=> we did some combining, result is a single DEFAULT alternative
combineIdenticalAlts imposs_cons ((_con1,bndrs1,rhs1) : con_alts)
  | all isDeadBinder bndrs1    -- Remember the default
  , not (null eliminated_alts) -- alternative comes first
  = (True, imposs_cons', deflt_alt : filtered_alts)
  where
    (eliminated_alts, filtered_alts) = partition identical_to_alt1 con_alts
    deflt_alt = (DEFAULT, [], mkTicks (concat tickss) rhs1)
    imposs_cons' = imposs_cons `minusList` map fstOf3 eliminated_alts
701

702 703 704
    cheapEqTicked e1 e2 = cheapEqExpr' tickishFloatable e1 e2
    identical_to_alt1 (_con,bndrs,rhs)
      = all isDeadBinder bndrs && rhs `cheapEqTicked` rhs1
705
    tickss = map (stripTicksT tickishFloatable . thdOf3) eliminated_alts
706

707 708
combineIdenticalAlts imposs_cons alts
  = (False, imposs_cons, alts)
709

710
{- *********************************************************************
Austin Seipp's avatar
Austin Seipp committed
711
*                                                                      *
712
             exprIsTrivial
Austin Seipp's avatar
Austin Seipp committed
713 714
*                                                                      *
************************************************************************
715

716 717
Note [exprIsTrivial]
~~~~~~~~~~~~~~~~~~~~
718
@exprIsTrivial@ is true of expressions we are unconditionally happy to
719 720 721
                duplicate; simple variables and constants, and type
                applications.  Note that primop Ids aren't considered
                trivial unless
722

723 724
Note [Variable are trivial]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
725 726
There used to be a gruesome test for (hasNoBinding v) in the
Var case:
727
        exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
batterseapower's avatar
batterseapower committed
728
The idea here is that a constructor worker, like \$wJust, is
Gabor Greif's avatar
typos  
Gabor Greif committed
729
really short for (\x -> \$wJust x), because \$wJust has no binding.
730 731 732 733 734 735
So it should be treated like a lambda.  Ditto unsaturated primops.
But now constructor workers are not "have-no-binding" Ids.  And
completely un-applied primops and foreign-call Ids are sufficiently
rare that I plan to allow them to be duplicated and put up with
saturating them.

736 737
Note [Tick trivial]
~~~~~~~~~~~~~~~~~~~
Peter Wortmann's avatar
Peter Wortmann committed
738 739 740 741
Ticks are only trivial if they are pure annotations. If we treat
"tick<n> x" as trivial, it will be inlined inside lambdas and the
entry count will be skewed, for example.  Furthermore "scc<n> x" will
turn into just "x" in mkTick.
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759

Note [Empty case is trivial]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The expression (case (x::Int) Bool of {}) is just a type-changing
case used when we are sure that 'x' will not return.  See
Note [Empty case alternatives] in CoreSyn.

If the scrutinee is trivial, then so is the whole expression; and the
CoreToSTG pass in fact drops the case expression leaving only the
scrutinee.

Having more trivial expressions is good.  Moreover, if we don't treat
it as trivial we may land up with let-bindings like
   let v = case x of {} in ...
and after CoreToSTG that gives
   let v = x in ...
and that confuses the code generator (Trac #11155). So best to kill
it off at source.
Austin Seipp's avatar
Austin Seipp committed
760
-}
761

762
exprIsTrivial :: CoreExpr -> Bool
763
exprIsTrivial (Var _)          = True        -- See Note [Variables are trivial]
Peter Wortmann's avatar
Peter Wortmann committed
764
exprIsTrivial (Type _)         = True
765
exprIsTrivial (Coercion _)     = True
766 767
exprIsTrivial (Lit lit)        = litIsTrivial lit
exprIsTrivial (App e arg)      = not (isRuntimeArg arg) && exprIsTrivial e
Peter Wortmann's avatar
Peter Wortmann committed
768 769
exprIsTrivial (Tick t e)       = not (tickishIsCode t) && exprIsTrivial e
                                 -- See Note [Tick trivial]
770 771
exprIsTrivial (Cast e _)       = exprIsTrivial e
exprIsTrivial (Lam b body)     = not (isRuntimeVar b) && exprIsTrivial body
772
exprIsTrivial (Case e _ _ [])  = exprIsTrivial e  -- See Note [Empty case is trivial]
773
exprIsTrivial _                = False
774

Austin Seipp's avatar
Austin Seipp committed
775
{-
776 777 778 779
When substituting in a breakpoint we need to strip away the type cruft
from a trivial expression and get back to the Id.  The invariant is
that the expression we're substituting was originally trivial
according to exprIsTrivial.
Austin Seipp's avatar
Austin Seipp committed
780
-}
781 782 783 784 785

getIdFromTrivialExpr :: CoreExpr -> Id
getIdFromTrivialExpr e = go e
  where go (Var v) = v
        go (App f t) | not (isRuntimeArg t) = go f
786
        go (Tick t e) | not (tickishIsCode t) = go e
787 788 789 790
        go (Cast e _) = go e
        go (Lam b e) | not (isRuntimeVar b) = go e
        go e = pprPanic "getIdFromTrivialExpr" (ppr e)

Austin Seipp's avatar
Austin Seipp committed
791
{-
792
exprIsBottom is a very cheap and cheerful function; it may return
793 794
False for bottoming expressions, but it never costs much to ask.  See
also CoreArity.exprBotStrictness_maybe, but that's a bit more
795
expensive.
Austin Seipp's avatar
Austin Seipp committed
796
-}
797 798

exprIsBottom :: CoreExpr -> Bool
799
-- See Note [Bottoming expressions]
800
exprIsBottom e
801 802 803
  | isEmptyTy (exprType e)
  = True
  | otherwise
804 805
  = go 0 e
  where
806 807 808
    go n (Var v) = isBottomingId v &&  n >= idArity v
    go n (App e a) | isTypeArg a = go n e
                   | otherwise   = go (n+1) e
809
    go n (Tick _ e)              = go n e
810 811
    go n (Cast e _)              = go n e
    go n (Let _ e)               = go n e
812
    go n (Lam v e) | isTyVar v   = go n e
813
    go _ _                       = False
814

815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
{- Note [Bottoming expressions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A bottoming expression is guaranteed to diverge, or raise an
exception.  We can test for it in two different ways, and exprIsBottom
checks for both of these situations:

* Visibly-bottom computations.  For example
      (error Int "Hello")
  is visibly bottom.  The strictness analyser also finds out if
  a function diverges or raises an exception, and puts that info
  in its strictness signature.

* Empty types.  If a type is empty, its only inhabitant is bottom.
  For example:
      data T
      f :: T -> Bool
      f = \(x:t). case x of Bool {}
  Since T has no data constructors, the case alternatives are of course
  empty.  However note that 'x' is not bound to a visibly-bottom value;
  it's the *type* that tells us it's going to diverge.

A GADT may also be empty even though it has constructors:
        data T a where
          T1 :: a -> T Bool
          T2 :: T Int
        ...(case (x::T Char) of {})...
Here (T Char) is uninhabited.  A more realistic case is (Int ~ Bool),
which is likewise uninhabited.


Austin Seipp's avatar
Austin Seipp committed
845 846
************************************************************************
*                                                                      *
847
             exprIsDupable
Austin Seipp's avatar
Austin Seipp committed
848 849
*                                                                      *
************************************************************************
850 851 852

Note [exprIsDupable]
~~~~~~~~~~~~~~~~~~~~
853 854 855
@exprIsDupable@ is true of expressions that can be duplicated at a modest
                cost in code size.  This will only happen in different case
                branches, so there's no issue about duplicating work.
856

857 858
                That is, exprIsDupable returns True of (f x) even if
                f is very very expensive to call.
859

860 861
                Its only purpose is to avoid fruitless let-binding
                and then inlining of case join points
Austin Seipp's avatar
Austin Seipp committed
862
-}
863

864 865
exprIsDupable :: DynFlags -> CoreExpr -> Bool
exprIsDupable dflags e
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
866
  = isJust (go dupAppSize e)
867
  where
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
868
    go :: Int -> CoreExpr -> Maybe Int
869 870 871
    go n (Type {})     = Just n
    go n (Coercion {}) = Just n
    go n (Var {})      = decrement n
872
    go n (Tick _ e)    = go n e
873
    go n (Cast e _)    = go n e
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
874
    go n (App f a) | Just n' <- go n a = go n' f
875
    go n (Lit lit) | litIsDupable dflags lit = decrement n
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
876 877 878 879 880
    go _ _ = Nothing

    decrement :: Int -> Maybe Int
    decrement 0 = Nothing
    decrement n = Just (n-1)
881 882

dupAppSize :: Int
883 884 885 886
dupAppSize = 8   -- Size of term we are prepared to duplicate
                 -- This is *just* big enough to make test MethSharing
                 -- inline enough join points.  Really it should be
                 -- smaller, and could be if we fixed Trac #4960.
887

Austin Seipp's avatar
Austin Seipp committed
888 889 890
{-
************************************************************************
*                                                                      *
891
             exprIsCheap, exprIsExpandable
Austin Seipp's avatar
Austin Seipp committed
892 893
*                                                                      *
************************************************************************
894

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
Note [exprIsWorkFree]
~~~~~~~~~~~~~~~~~~~~~
exprIsWorkFree is used when deciding whether to inline something; we
don't inline it if doing so might duplicate work, by peeling off a
complete copy of the expression.  Here we do not want even to
duplicate a primop (Trac #5623):
   eg   let x = a #+ b in x +# x
   we do not want to inline/duplicate x

Previously we were a bit more liberal, which led to the primop-duplicating
problem.  However, being more conservative did lead to a big regression in
one nofib benchmark, wheel-sieve1.  The situation looks like this:

   let noFactor_sZ3 :: GHC.Types.Int -> GHC.Types.Bool
       noFactor_sZ3 = case s_adJ of _ { GHC.Types.I# x_aRs ->
         case GHC.Prim.<=# x_aRs 2 of _ {
           GHC.Types.False -> notDivBy ps_adM qs_adN;
           GHC.Types.True -> lvl_r2Eb }}
       go = \x. ...(noFactor (I# y))....(go x')...

The function 'noFactor' is heap-allocated and then called.  Turns out
that 'notDivBy' is strict in its THIRD arg, but that is invisible to
the caller of noFactor, which therefore cannot do w/w and
heap-allocates noFactor's argument.  At the moment (May 12) we are just
Austin Seipp's avatar
Austin Seipp committed
919 920
going to put up with this, because the previous more aggressive inlining
(which treated 'noFactor' as work-free) was duplicating primops, which
921
in turn was making inner loops of array calculations runs slow (#5623)
Austin Seipp's avatar
Austin Seipp committed
922
-}
923 924 925 926 927 928 929 930 931

exprIsWorkFree :: CoreExpr -> Bool
-- See Note [exprIsWorkFree]
exprIsWorkFree e = go 0 e
  where    -- n is the number of value arguments
    go _ (Lit {})                     = True
    go _ (Type {})                    = True
    go _ (Coercion {})                = True
    go n (Cast e _)                   = go n e
Austin Seipp's avatar
Austin Seipp committed
932
    go n (Case scrut _ _ alts)        = foldl (&&) (exprIsWorkFree scrut)
933 934 935
                                              [ go n rhs | (_,_,rhs) <- alts ]
         -- See Note [Case expressions are work-free]
    go _ (Let {})                     = False
936
    go n (Var v)                      = isCheapApp v n
937 938 939 940 941 942 943
    go n (Tick t e) | tickishCounts t = False
                    | otherwise       = go n e
    go n (Lam x e)  | isRuntimeVar x = n==0 || go (n-1) e
                    | otherwise      = go n e
    go n (App f e)  | isRuntimeArg e = exprIsWorkFree e && go (n+1) f
                    | otherwise      = go n f

Austin Seipp's avatar
Austin Seipp committed
944
{-
945 946 947 948 949 950 951 952 953
Note [Case expressions are work-free]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Are case-expressions work-free?  Consider
    let v = case x of (p,q) -> p
        go = \y -> ...case v of ...
Should we inline 'v' at its use site inside the loop?  At the moment
we do.  I experimented with saying that case are *not* work-free, but
that increased allocation slightly.  It's a fairly small effect, and at
the moment we go for the slightly more aggressive version which treats
Krzysztof Gogolewski's avatar
Typos  
Krzysztof Gogolewski committed
954
(case x of ....) as work-free if the alternatives are.
955 956


957
Note [exprIsCheap]   See also Note [Interaction of exprIsCheap and lone variables]
958
~~~~~~~~~~~~~~~~~~   in CoreUnfold.hs
959 960 961 962
@exprIsCheap@ looks at a Core expression and returns \tr{True} if
it is obviously in weak head normal form, or is cheap to get to WHNF.
[Note that that's not the same as exprIsDupable; an expression might be
big, and hence not dupable, but still cheap.]
963 964

By ``cheap'' we mean a computation we're willing to:
965 966
        push inside a lambda, or
        inline at more than one place
967 968 969
That might mean it gets evaluated more than once, instead of being
shared.  The main examples of things which aren't WHNF but are
``cheap'' are:
970

971 972 973
  *     case e of
          pi -> ei
        (where e, and all the ei are cheap)
974

975 976
  *     let x = e in b
        (where e and b are cheap)
977

978 979
  *     op x1 ... xn
        (where op is a cheap primitive operator)
980

981 982
  *     error "foo"
        (because we are happy to substitute it inside a lambda)
983

984 985 986
Notice that a variable is considered 'cheap': we can push it inside a lambda,
because sharing will make sure it is only evaluated once.

987 988 989
Note [exprIsCheap and exprIsHNF]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Note that exprIsHNF does not imply exprIsCheap.  Eg
990
        let x = fac 20 in Just x
991 992
This responds True to exprIsHNF (you can discard a seq), but
False to exprIsCheap.
Austin Seipp's avatar
Austin Seipp committed
993
-}
994

995
exprIsCheap :: CoreExpr -> Bool
996
exprIsCheap = exprIsCheap' isCheapApp
997 998

exprIsExpandable :: CoreExpr -> Bool
999
exprIsExpandable = exprIsCheap' isExpandableApp -- See Note [CONLIKE pragma] in BasicTypes
1000

1001
exprIsCheap' :: CheapAppFun -> CoreExpr -> Bool
1002
exprIsCheap' _        (Lit _)      = True
1003
exprIsCheap' _        (Type _)    = True
1004 1005 1006 1007 1008
exprIsCheap' _        (Coercion _) = True
exprIsCheap' _        (Var _)      = True
exprIsCheap' good_app (Cast e _)   = exprIsCheap' good_app e
exprIsCheap' good_app (Lam x e)    = isRuntimeVar x
                                  || exprIsCheap' good_app e
1009