Ensure exprIsCheap/exprIsExpandable deal with Cast properly
[ghc-hetmet.git] / compiler / coreSyn / CoreUtils.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 Utility functions on @Core@ syntax
7
8 \begin{code}
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 -- for details
15
16 -- | Commonly useful utilites for manipulating the Core language
17 module CoreUtils (
18         -- * Constructing expressions
19         mkSCC, mkCoerce, mkCoerceI,
20         bindNonRec, needsCaseBinding,
21         mkAltExpr, mkPiType, mkPiTypes,
22
23         -- * Taking expressions apart
24         findDefault, findAlt, isDefaultAlt, mergeAlts, trimConArgs,
25
26         -- * Properties of expressions
27         exprType, coreAltType, coreAltsType,
28         exprIsDupable, exprIsTrivial, exprIsBottom,
29         exprIsCheap, exprIsExpandable, exprIsCheap', CheapAppFun,
30         exprIsHNF, exprOkForSpeculation, exprIsBig, exprIsConLike,
31         rhsIsStatic, isCheapApp, isExpandableApp,
32
33         -- * Expression and bindings size
34         coreBindsSize, exprSize,
35
36         -- * Hashing
37         hashExpr,
38
39         -- * Equality
40         cheapEqExpr, eqExpr, eqExprX,
41
42         -- * Eta reduction
43         tryEtaReduce,
44
45         -- * Manipulating data constructors and types
46         applyTypeToArgs, applyTypeToArg,
47         dataConOrigInstPat, dataConRepInstPat, dataConRepFSInstPat
48     ) where
49
50 #include "HsVersions.h"
51
52 import CoreSyn
53 import PprCore
54 import Var
55 import SrcLoc
56 import VarEnv
57 import VarSet
58 import Name
59 import Literal
60 import DataCon
61 import PrimOp
62 import Id
63 import IdInfo
64 import TcType   ( isPredTy )
65 import Type
66 import Coercion
67 import TyCon
68 import CostCentre
69 import Unique
70 import Outputable
71 import TysPrim
72 import FastString
73 import Maybes
74 import Util
75 import Data.Word
76 import Data.Bits
77 \end{code}
78
79
80 %************************************************************************
81 %*                                                                      *
82 \subsection{Find the type of a Core atom/expression}
83 %*                                                                      *
84 %************************************************************************
85
86 \begin{code}
87 exprType :: CoreExpr -> Type
88 -- ^ Recover the type of a well-typed Core expression. Fails when
89 -- applied to the actual 'CoreSyn.Type' expression as it cannot
90 -- really be said to have a type
91 exprType (Var var)           = idType var
92 exprType (Lit lit)           = literalType lit
93 exprType (Let _ body)        = exprType body
94 exprType (Case _ _ ty _)     = ty
95 exprType (Cast _ co)         = snd (coercionKind co)
96 exprType (Note _ e)          = exprType e
97 exprType (Lam binder expr)   = mkPiType binder (exprType expr)
98 exprType e@(App _ _)
99   = case collectArgs e of
100         (fun, args) -> applyTypeToArgs e (exprType fun) args
101
102 exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
103
104 coreAltType :: CoreAlt -> Type
105 -- ^ Returns the type of the alternatives right hand side
106 coreAltType (_,bs,rhs) 
107   | any bad_binder bs = expandTypeSynonyms ty
108   | otherwise         = ty    -- Note [Existential variables and silly type synonyms]
109   where
110     ty           = exprType rhs
111     free_tvs     = tyVarsOfType ty
112     bad_binder b = isTyCoVar b && b `elemVarSet` free_tvs
113
114 coreAltsType :: [CoreAlt] -> Type
115 -- ^ Returns the type of the first alternative, which should be the same as for all alternatives
116 coreAltsType (alt:_) = coreAltType alt
117 coreAltsType []      = panic "corAltsType"
118 \end{code}
119
120 Note [Existential variables and silly type synonyms]
121 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
122 Consider
123         data T = forall a. T (Funny a)
124         type Funny a = Bool
125         f :: T -> Bool
126         f (T x) = x
127
128 Now, the type of 'x' is (Funny a), where 'a' is existentially quantified.
129 That means that 'exprType' and 'coreAltsType' may give a result that *appears*
130 to mention an out-of-scope type variable.  See Trac #3409 for a more real-world
131 example.
132
133 Various possibilities suggest themselves:
134
135  - Ignore the problem, and make Lint not complain about such variables
136
137  - Expand all type synonyms (or at least all those that discard arguments)
138       This is tricky, because at least for top-level things we want to
139       retain the type the user originally specified.
140
141  - Expand synonyms on the fly, when the problem arises. That is what
142    we are doing here.  It's not too expensive, I think.
143
144 \begin{code}
145 mkPiType  :: EvVar -> Type -> Type
146 -- ^ Makes a @(->)@ type or a forall type, depending
147 -- on whether it is given a type variable or a term variable.
148 mkPiTypes :: [EvVar] -> Type -> Type
149 -- ^ 'mkPiType' for multiple type or value arguments
150
151 mkPiType v ty
152    | isId v    = mkFunTy (idType v) ty
153    | otherwise = mkForAllTy v ty
154
155 mkPiTypes vs ty = foldr mkPiType ty vs
156 \end{code}
157
158 \begin{code}
159 applyTypeToArg :: Type -> CoreExpr -> Type
160 -- ^ Determines the type resulting from applying an expression to a function with the given type
161 applyTypeToArg fun_ty (Type arg_ty) = applyTy fun_ty arg_ty
162 applyTypeToArg fun_ty _             = funResultTy fun_ty
163
164 applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
165 -- ^ A more efficient version of 'applyTypeToArg' when we have several arguments.
166 -- The first argument is just for debugging, and gives some context
167 applyTypeToArgs _ op_ty [] = op_ty
168
169 applyTypeToArgs e op_ty (Type ty : args)
170   =     -- Accumulate type arguments so we can instantiate all at once
171     go [ty] args
172   where
173     go rev_tys (Type ty : args) = go (ty:rev_tys) args
174     go rev_tys rest_args        = applyTypeToArgs e op_ty' rest_args
175                                 where
176                                   op_ty' = applyTysD msg op_ty (reverse rev_tys)
177                                   msg = ptext (sLit "applyTypeToArgs") <+> 
178                                         panic_msg e op_ty
179
180 applyTypeToArgs e op_ty (_ : args)
181   = case (splitFunTy_maybe op_ty) of
182         Just (_, res_ty) -> applyTypeToArgs e res_ty args
183         Nothing -> pprPanic "applyTypeToArgs" (panic_msg e op_ty)
184
185 panic_msg :: CoreExpr -> Type -> SDoc
186 panic_msg e op_ty = pprCoreExpr e $$ ppr op_ty
187 \end{code}
188
189 %************************************************************************
190 %*                                                                      *
191 \subsection{Attaching notes}
192 %*                                                                      *
193 %************************************************************************
194
195 \begin{code}
196 -- | Wrap the given expression in the coercion, dropping identity coercions and coalescing nested coercions
197 mkCoerceI :: CoercionI -> CoreExpr -> CoreExpr
198 mkCoerceI (IdCo _) e = e
199 mkCoerceI (ACo co) e = mkCoerce co e
200
201 -- | Wrap the given expression in the coercion safely, coalescing nested coercions
202 mkCoerce :: Coercion -> CoreExpr -> CoreExpr
203 mkCoerce co (Cast expr co2)
204   = ASSERT(let { (from_ty, _to_ty) = coercionKind co; 
205                  (_from_ty2, to_ty2) = coercionKind co2} in
206            from_ty `coreEqType` to_ty2 )
207     mkCoerce (mkTransCoercion co2 co) expr
208
209 mkCoerce co expr 
210   = let (from_ty, _to_ty) = coercionKind co in
211 --    if to_ty `coreEqType` from_ty
212 --    then expr
213 --    else 
214         WARN(not (from_ty `coreEqType` exprType expr), text "Trying to coerce" <+> text "(" <> ppr expr $$ text "::" <+> ppr (exprType expr) <> text ")" $$ ppr co $$ pprEqPred (coercionKind co))
215          (Cast expr co)
216 \end{code}
217
218 \begin{code}
219 -- | Wraps the given expression in the cost centre unless
220 -- in a way that maximises their utility to the user
221 mkSCC :: CostCentre -> Expr b -> Expr b
222         -- Note: Nested SCC's *are* preserved for the benefit of
223         --       cost centre stack profiling
224 mkSCC _  (Lit lit)          = Lit lit
225 mkSCC cc (Lam x e)          = Lam x (mkSCC cc e)  -- Move _scc_ inside lambda
226 mkSCC cc (Note (SCC cc') e) = Note (SCC cc) (Note (SCC cc') e)
227 mkSCC cc (Note n e)         = Note n (mkSCC cc e) -- Move _scc_ inside notes
228 mkSCC cc (Cast e co)        = Cast (mkSCC cc e) co -- Move _scc_ inside cast
229 mkSCC cc expr               = Note (SCC cc) expr
230 \end{code}
231
232
233 %************************************************************************
234 %*                                                                      *
235 \subsection{Other expression construction}
236 %*                                                                      *
237 %************************************************************************
238
239 \begin{code}
240 bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
241 -- ^ @bindNonRec x r b@ produces either:
242 --
243 -- > let x = r in b
244 --
245 -- or:
246 --
247 -- > case r of x { _DEFAULT_ -> b }
248 --
249 -- depending on whether we have to use a @case@ or @let@
250 -- binding for the expression (see 'needsCaseBinding').
251 -- It's used by the desugarer to avoid building bindings
252 -- that give Core Lint a heart attack, although actually
253 -- the simplifier deals with them perfectly well. See
254 -- also 'MkCore.mkCoreLet'
255 bindNonRec bndr rhs body 
256   | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
257   | otherwise                          = Let (NonRec bndr rhs) body
258
259 -- | Tests whether we have to use a @case@ rather than @let@ binding for this expression
260 -- as per the invariants of 'CoreExpr': see "CoreSyn#let_app_invariant"
261 needsCaseBinding :: Type -> CoreExpr -> Bool
262 needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
263         -- Make a case expression instead of a let
264         -- These can arise either from the desugarer,
265         -- or from beta reductions: (\x.e) (x +# y)
266 \end{code}
267
268 \begin{code}
269 mkAltExpr :: AltCon     -- ^ Case alternative constructor
270           -> [CoreBndr] -- ^ Things bound by the pattern match
271           -> [Type]     -- ^ The type arguments to the case alternative
272           -> CoreExpr
273 -- ^ This guy constructs the value that the scrutinee must have
274 -- given that you are in one particular branch of a case
275 mkAltExpr (DataAlt con) args inst_tys
276   = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
277 mkAltExpr (LitAlt lit) [] []
278   = Lit lit
279 mkAltExpr (LitAlt _) _ _ = panic "mkAltExpr LitAlt"
280 mkAltExpr DEFAULT _ _ = panic "mkAltExpr DEFAULT"
281 \end{code}
282
283
284 %************************************************************************
285 %*                                                                      *
286 \subsection{Taking expressions apart}
287 %*                                                                      *
288 %************************************************************************
289
290 The default alternative must be first, if it exists at all.
291 This makes it easy to find, though it makes matching marginally harder.
292
293 \begin{code}
294 -- | Extract the default case alternative
295 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
296 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
297 findDefault alts                        =                     (alts, Nothing)
298
299 isDefaultAlt :: CoreAlt -> Bool
300 isDefaultAlt (DEFAULT, _, _) = True
301 isDefaultAlt _               = False
302
303
304 -- | Find the case alternative corresponding to a particular 
305 -- constructor: panics if no such constructor exists
306 findAlt :: AltCon -> [CoreAlt] -> Maybe CoreAlt
307     -- A "Nothing" result *is* legitmiate
308     -- See Note [Unreachable code]
309 findAlt con alts
310   = case alts of
311         (deflt@(DEFAULT,_,_):alts) -> go alts (Just deflt)
312         _                          -> go alts Nothing
313   where
314     go []                     deflt = deflt
315     go (alt@(con1,_,_) : alts) deflt
316       = case con `cmpAltCon` con1 of
317           LT -> deflt   -- Missed it already; the alts are in increasing order
318           EQ -> Just alt
319           GT -> ASSERT( not (con1 == DEFAULT) ) go alts deflt
320
321 ---------------------------------
322 mergeAlts :: [CoreAlt] -> [CoreAlt] -> [CoreAlt]
323 -- ^ Merge alternatives preserving order; alternatives in
324 -- the first argument shadow ones in the second
325 mergeAlts [] as2 = as2
326 mergeAlts as1 [] = as1
327 mergeAlts (a1:as1) (a2:as2)
328   = case a1 `cmpAlt` a2 of
329         LT -> a1 : mergeAlts as1      (a2:as2)
330         EQ -> a1 : mergeAlts as1      as2       -- Discard a2
331         GT -> a2 : mergeAlts (a1:as1) as2
332
333
334 ---------------------------------
335 trimConArgs :: AltCon -> [CoreArg] -> [CoreArg]
336 -- ^ Given:
337 --
338 -- > case (C a b x y) of
339 -- >        C b x y -> ...
340 --
341 -- We want to drop the leading type argument of the scrutinee
342 -- leaving the arguments to match agains the pattern
343
344 trimConArgs DEFAULT      args = ASSERT( null args ) []
345 trimConArgs (LitAlt _)   args = ASSERT( null args ) []
346 trimConArgs (DataAlt dc) args = dropList (dataConUnivTyVars dc) args
347 \end{code}
348
349 Note [Unreachable code]
350 ~~~~~~~~~~~~~~~~~~~~~~~
351 It is possible (although unusual) for GHC to find a case expression
352 that cannot match.  For example: 
353
354      data Col = Red | Green | Blue
355      x = Red
356      f v = case x of 
357               Red -> ...
358               _ -> ...(case x of { Green -> e1; Blue -> e2 })...
359
360 Suppose that for some silly reason, x isn't substituted in the case
361 expression.  (Perhaps there's a NOINLINE on it, or profiling SCC stuff
362 gets in the way; cf Trac #3118.)  Then the full-lazines pass might produce
363 this
364
365      x = Red
366      lvl = case x of { Green -> e1; Blue -> e2 })
367      f v = case x of 
368              Red -> ...
369              _ -> ...lvl...
370
371 Now if x gets inlined, we won't be able to find a matching alternative
372 for 'Red'.  That's because 'lvl' is unreachable.  So rather than crashing
373 we generate (error "Inaccessible alternative").
374
375 Similar things can happen (augmented by GADTs) when the Simplifier
376 filters down the matching alternatives in Simplify.rebuildCase.
377
378
379 %************************************************************************
380 %*                                                                      *
381              exprIsTrivial
382 %*                                                                      *
383 %************************************************************************
384
385 Note [exprIsTrivial]
386 ~~~~~~~~~~~~~~~~~~~~
387 @exprIsTrivial@ is true of expressions we are unconditionally happy to
388                 duplicate; simple variables and constants, and type
389                 applications.  Note that primop Ids aren't considered
390                 trivial unless 
391
392 Note [Variable are trivial]
393 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
394 There used to be a gruesome test for (hasNoBinding v) in the
395 Var case:
396         exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
397 The idea here is that a constructor worker, like \$wJust, is
398 really short for (\x -> \$wJust x), becuase \$wJust has no binding.
399 So it should be treated like a lambda.  Ditto unsaturated primops.
400 But now constructor workers are not "have-no-binding" Ids.  And
401 completely un-applied primops and foreign-call Ids are sufficiently
402 rare that I plan to allow them to be duplicated and put up with
403 saturating them.
404
405 Note [SCCs are trivial]
406 ~~~~~~~~~~~~~~~~~~~~~~~
407 We used not to treat (_scc_ "foo" x) as trivial, because it really
408 generates code, (and a heap object when it's a function arg) to
409 capture the cost centre.  However, the profiling system discounts the
410 allocation costs for such "boxing thunks" whereas the extra costs of
411 *not* inlining otherwise-trivial bindings can be high, and are hard to
412 discount.
413
414 \begin{code}
415 exprIsTrivial :: CoreExpr -> Bool
416 exprIsTrivial (Var _)          = True        -- See Note [Variables are trivial]
417 exprIsTrivial (Type _)         = True
418 exprIsTrivial (Lit lit)        = litIsTrivial lit
419 exprIsTrivial (App e arg)      = not (isRuntimeArg arg) && exprIsTrivial e
420 exprIsTrivial (Note _       e) = exprIsTrivial e  -- See Note [SCCs are trivial]
421 exprIsTrivial (Cast e _)       = exprIsTrivial e
422 exprIsTrivial (Lam b body)     = not (isRuntimeVar b) && exprIsTrivial body
423 exprIsTrivial _                = False
424 \end{code}
425
426 exprIsBottom is a very cheap and cheerful function; it may return
427 False for bottoming expressions, but it never costs much to ask.
428 See also CoreArity.exprBotStrictness_maybe, but that's a bit more 
429 expensive.
430
431 \begin{code}
432 exprIsBottom :: CoreExpr -> Bool
433 exprIsBottom e 
434   = go 0 e
435   where
436     go n (Var v) = isBottomingId v &&  n >= idArity v 
437     go n (App e a) | isTypeArg a = go n e 
438                    | otherwise   = go (n+1) e 
439     go n (Note _ e)              = go n e     
440     go n (Cast e _)              = go n e
441     go n (Let _ e)               = go n e
442     go _ _                       = False
443 \end{code}
444
445
446 %************************************************************************
447 %*                                                                      *
448              exprIsDupable
449 %*                                                                      *
450 %************************************************************************
451
452 Note [exprIsDupable]
453 ~~~~~~~~~~~~~~~~~~~~
454 @exprIsDupable@ is true of expressions that can be duplicated at a modest
455                 cost in code size.  This will only happen in different case
456                 branches, so there's no issue about duplicating work.
457
458                 That is, exprIsDupable returns True of (f x) even if
459                 f is very very expensive to call.
460
461                 Its only purpose is to avoid fruitless let-binding
462                 and then inlining of case join points
463
464
465 \begin{code}
466 exprIsDupable :: CoreExpr -> Bool
467 exprIsDupable e
468   = isJust (go dupAppSize e)
469   where
470     go :: Int -> CoreExpr -> Maybe Int
471     go n (Type {}) = Just n
472     go n (Var {})  = decrement n
473     go n (Note _ e) = go n e
474     go n (Cast e _) = go n e
475     go n (App f a) | Just n' <- go n a = go n' f
476     go n (Lit lit) | litIsDupable lit = decrement n
477     go _ _ = Nothing
478
479     decrement :: Int -> Maybe Int
480     decrement 0 = Nothing
481     decrement n = Just (n-1)
482
483 dupAppSize :: Int
484 dupAppSize = 6   -- Size of term we are prepared to duplicate
485 \end{code}
486
487 %************************************************************************
488 %*                                                                      *
489              exprIsCheap, exprIsExpandable
490 %*                                                                      *
491 %************************************************************************
492
493 Note [exprIsCheap]   See also Note [Interaction of exprIsCheap and lone variables]
494 ~~~~~~~~~~~~~~~~~~   in CoreUnfold.lhs
495 @exprIsCheap@ looks at a Core expression and returns \tr{True} if
496 it is obviously in weak head normal form, or is cheap to get to WHNF.
497 [Note that that's not the same as exprIsDupable; an expression might be
498 big, and hence not dupable, but still cheap.]
499
500 By ``cheap'' we mean a computation we're willing to:
501         push inside a lambda, or
502         inline at more than one place
503 That might mean it gets evaluated more than once, instead of being
504 shared.  The main examples of things which aren't WHNF but are
505 ``cheap'' are:
506
507   *     case e of
508           pi -> ei
509         (where e, and all the ei are cheap)
510
511   *     let x = e in b
512         (where e and b are cheap)
513
514   *     op x1 ... xn
515         (where op is a cheap primitive operator)
516
517   *     error "foo"
518         (because we are happy to substitute it inside a lambda)
519
520 Notice that a variable is considered 'cheap': we can push it inside a lambda,
521 because sharing will make sure it is only evaluated once.
522
523 Note [exprIsCheap and exprIsHNF]
524 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
525 Note that exprIsHNF does not imply exprIsCheap.  Eg
526         let x = fac 20 in Just x
527 This responds True to exprIsHNF (you can discard a seq), but
528 False to exprIsCheap.
529
530 \begin{code}
531 exprIsCheap :: CoreExpr -> Bool
532 exprIsCheap = exprIsCheap' isCheapApp
533
534 exprIsExpandable :: CoreExpr -> Bool
535 exprIsExpandable = exprIsCheap' isExpandableApp -- See Note [CONLIKE pragma] in BasicTypes
536
537 type CheapAppFun = Id -> Int -> Bool
538 exprIsCheap' :: CheapAppFun -> CoreExpr -> Bool
539 exprIsCheap' _          (Lit _)   = True
540 exprIsCheap' _          (Type _)  = True
541 exprIsCheap' _          (Var _)   = True
542 exprIsCheap' good_app (Note _ e)  = exprIsCheap' good_app e
543 exprIsCheap' good_app (Cast e _)  = exprIsCheap' good_app e
544 exprIsCheap' good_app (Lam x e)   = isRuntimeVar x
545                                  || exprIsCheap' good_app e
546
547 exprIsCheap' good_app (Case e _ _ alts) = exprIsCheap' good_app e && 
548                                           and [exprIsCheap' good_app rhs | (_,_,rhs) <- alts]
549         -- Experimentally, treat (case x of ...) as cheap
550         -- (and case __coerce x etc.)
551         -- This improves arities of overloaded functions where
552         -- there is only dictionary selection (no construction) involved
553
554 exprIsCheap' good_app (Let (NonRec x _) e)  
555   | isUnLiftedType (idType x) = exprIsCheap' good_app e
556   | otherwise                 = False
557         -- Strict lets always have cheap right hand sides,
558         -- and do no allocation, so just look at the body
559         -- Non-strict lets do allocation so we don't treat them as cheap
560         -- See also 
561
562 exprIsCheap' good_app other_expr        -- Applications and variables
563   = go other_expr []
564   where
565         -- Accumulate value arguments, then decide
566     go (Cast e _) val_args                 = go e val_args
567     go (App f a) val_args | isRuntimeArg a = go f (a:val_args)
568                           | otherwise      = go f val_args
569
570     go (Var _) [] = True        -- Just a type application of a variable
571                                 -- (f t1 t2 t3) counts as WHNF
572     go (Var f) args
573         = case idDetails f of
574                 RecSelId {}                  -> go_sel args
575                 ClassOpId {}                 -> go_sel args
576                 PrimOpId op                  -> go_primop op args
577                 _ | good_app f (length args) -> go_pap args
578                   | isBottomingId f          -> True
579                   | otherwise                -> False
580                         -- Application of a function which
581                         -- always gives bottom; we treat this as cheap
582                         -- because it certainly doesn't need to be shared!
583         
584     go _ _ = False
585  
586     --------------
587     go_pap args = all exprIsTrivial args
588         -- For constructor applications and primops, check that all
589         -- the args are trivial.  We don't want to treat as cheap, say,
590         --      (1:2:3:4:5:[])
591         -- We'll put up with one constructor application, but not dozens
592         
593     --------------
594     go_primop op args = primOpIsCheap op && all (exprIsCheap' good_app) args
595         -- In principle we should worry about primops
596         -- that return a type variable, since the result
597         -- might be applied to something, but I'm not going
598         -- to bother to check the number of args
599  
600     --------------
601     go_sel [arg] = exprIsCheap' good_app arg    -- I'm experimenting with making record selection
602     go_sel _     = False                -- look cheap, so we will substitute it inside a
603                                         -- lambda.  Particularly for dictionary field selection.
604                 -- BUT: Take care with (sel d x)!  The (sel d) might be cheap, but
605                 --      there's no guarantee that (sel d x) will be too.  Hence (n_val_args == 1)
606
607 isCheapApp :: CheapAppFun
608 isCheapApp fn n_val_args
609   = isDataConWorkId fn 
610   || n_val_args < idArity fn
611
612 isExpandableApp :: CheapAppFun
613 isExpandableApp fn n_val_args
614   =  isConLikeId fn
615   || n_val_args < idArity fn
616   || go n_val_args (idType fn)
617   where
618   -- See if all the arguments are PredTys (implicit params or classes)
619   -- If so we'll regard it as expandable; see Note [Expandable overloadings]
620      go 0 _ = True
621      go n_val_args ty 
622        | Just (_, ty) <- splitForAllTy_maybe ty   = go n_val_args ty
623        | Just (arg, ty) <- splitFunTy_maybe ty
624        , isPredTy arg                             = go (n_val_args-1) ty
625        | otherwise                                = False
626 \end{code}
627
628 Note [Expandable overloadings]
629 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
630 Suppose the user wrote this
631    {-# RULE  forall x. foo (negate x) = h x #-}
632    f x = ....(foo (negate x))....
633 He'd expect the rule to fire. But since negate is overloaded, we might
634 get this:
635     f = \d -> let n = negate d in \x -> ...foo (n x)...
636 So we treat the application of a function (negate in this case) to a
637 *dictionary* as expandable.  In effect, every function is CONLIKE when
638 it's applied only to dictionaries.
639
640
641 %************************************************************************
642 %*                                                                      *
643              exprOkForSpeculation
644 %*                                                                      *
645 %************************************************************************
646
647 \begin{code}
648 -- | 'exprOkForSpeculation' returns True of an expression that is:
649 --
650 --  * Safe to evaluate even if normal order eval might not 
651 --    evaluate the expression at all, or
652 --
653 --  * Safe /not/ to evaluate even if normal order would do so
654 --
655 -- It is usually called on arguments of unlifted type, but not always
656 -- In particular, Simplify.rebuildCase calls it on lifted types
657 -- when a 'case' is a plain 'seq'. See the example in 
658 -- Note [exprOkForSpeculation: case expressions] below
659 --
660 -- Precisely, it returns @True@ iff:
661 --
662 --  * The expression guarantees to terminate, 
663 --  * soon, 
664 --  * without raising an exception,
665 --  * without causing a side effect (e.g. writing a mutable variable)
666 --
667 -- Note that if @exprIsHNF e@, then @exprOkForSpecuation e@.
668 -- As an example of the considerations in this test, consider:
669 --
670 -- > let x = case y# +# 1# of { r# -> I# r# }
671 -- > in E
672 --
673 -- being translated to:
674 --
675 -- > case y# +# 1# of { r# -> 
676 -- >    let x = I# r#
677 -- >    in E 
678 -- > }
679 -- 
680 -- We can only do this if the @y + 1@ is ok for speculation: it has no
681 -- side effects, and can't diverge or raise an exception.
682 exprOkForSpeculation :: CoreExpr -> Bool
683 exprOkForSpeculation (Lit _)     = True
684 exprOkForSpeculation (Type _)    = True
685
686 exprOkForSpeculation (Var v)     
687   | isTickBoxOp v = False     -- Tick boxes are *not* suitable for speculation
688   | otherwise     =  isUnLiftedType (idType v)  -- c.f. the Var case of exprIsHNF
689                   || isDataConWorkId v          -- Nullary constructors
690                   || idArity v > 0              -- Functions
691                   || isEvaldUnfolding (idUnfolding v)   -- Let-bound values
692
693 exprOkForSpeculation (Note _ e)  = exprOkForSpeculation e
694 exprOkForSpeculation (Cast e _)  = exprOkForSpeculation e
695
696 exprOkForSpeculation (Case e _ _ alts) 
697   =  exprOkForSpeculation e  -- Note [exprOkForSpeculation: case expressions]
698   && all (\(_,_,rhs) -> exprOkForSpeculation rhs) alts
699
700 exprOkForSpeculation other_expr
701   = case collectArgs other_expr of
702         (Var f, args) -> spec_ok (idDetails f) args
703         _             -> False
704  
705   where
706     spec_ok (DataConWorkId _) _
707       = True    -- The strictness of the constructor has already
708                 -- been expressed by its "wrapper", so we don't need
709                 -- to take the arguments into account
710
711     spec_ok (PrimOpId op) args
712       | isDivOp op,             -- Special case for dividing operations that fail
713         [arg1, Lit lit] <- args -- only if the divisor is zero
714       = not (isZeroLit lit) && exprOkForSpeculation arg1
715                 -- Often there is a literal divisor, and this 
716                 -- can get rid of a thunk in an inner looop
717
718       | DataToTagOp <- op      -- See Note [dataToTag speculation]
719       = True
720
721       | otherwise
722       = primOpOkForSpeculation op && 
723         all exprOkForSpeculation args
724                                 -- A bit conservative: we don't really need
725                                 -- to care about lazy arguments, but this is easy
726
727     spec_ok (DFunId _ new_type) _ = not new_type
728          -- DFuns terminate, unless the dict is implemented with a newtype
729          -- in which case they may not
730
731     spec_ok _ _ = False
732
733 -- | True of dyadic operators that can fail only if the second arg is zero!
734 isDivOp :: PrimOp -> Bool
735 -- This function probably belongs in PrimOp, or even in 
736 -- an automagically generated file.. but it's such a 
737 -- special case I thought I'd leave it here for now.
738 isDivOp IntQuotOp        = True
739 isDivOp IntRemOp         = True
740 isDivOp WordQuotOp       = True
741 isDivOp WordRemOp        = True
742 isDivOp FloatDivOp       = True
743 isDivOp DoubleDivOp      = True
744 isDivOp _                = False
745 \end{code}
746
747 Note [exprOkForSpeculation: case expressions]
748 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
749 It's always sound for exprOkForSpeculation to return False, and we
750 don't want it to take too long, so it bales out on complicated-looking
751 terms.  Notably lets, which can be stacked very deeply; and in any 
752 case the argument of exprOkForSpeculation is usually in a strict context,
753 so any lets will have been floated away.
754
755 However, we keep going on case-expressions.  An example like this one
756 showed up in DPH code (Trac #3717):
757     foo :: Int -> Int
758     foo 0 = 0
759     foo n = (if n < 5 then 1 else 2) `seq` foo (n-1)
760
761 If exprOkForSpeculation doesn't look through case expressions, you get this:
762     T.$wfoo =
763       \ (ww :: GHC.Prim.Int#) ->
764         case ww of ds {
765           __DEFAULT -> case (case <# ds 5 of _ {
766                           GHC.Types.False -> lvl1;
767                           GHC.Types.True -> lvl})
768                        of _ { __DEFAULT ->
769                        T.$wfoo (GHC.Prim.-# ds_XkE 1) };
770           0 -> 0
771         }
772
773 The inner case is redundant, and should be nuked.
774
775 Note [dataToTag speculation]
776 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
777 Is this OK?
778    f x = let v::Int# = dataToTag# x
779          in ...
780 We say "yes", even though 'x' may not be evaluated.  Reasons
781
782   * dataToTag#'s strictness means that its argument often will be
783     evaluated, but FloatOut makes that temporarily untrue
784          case x of y -> let v = dataToTag# y in ...
785     -->
786          case x of y -> let v = dataToTag# x in ...
787     Note that we look at 'x' instead of 'y' (this is to improve
788     floating in FloatOut).  So Lint complains.    
789  
790     Moreover, it really *might* improve floating to let the
791     v-binding float out
792          
793   * CorePrep makes sure dataToTag#'s argument is evaluated, just
794     before code gen.  Until then, it's not guaranteed
795
796
797 %************************************************************************
798 %*                                                                      *
799              exprIsHNF, exprIsConLike
800 %*                                                                      *
801 %************************************************************************
802
803 \begin{code}
804 -- Note [exprIsHNF]             See also Note [exprIsCheap and exprIsHNF]
805 -- ~~~~~~~~~~~~~~~~
806 -- | exprIsHNF returns true for expressions that are certainly /already/ 
807 -- evaluated to /head/ normal form.  This is used to decide whether it's ok 
808 -- to change:
809 --
810 -- > case x of _ -> e
811 --
812 --    into:
813 --
814 -- > e
815 --
816 -- and to decide whether it's safe to discard a 'seq'.
817 -- 
818 -- So, it does /not/ treat variables as evaluated, unless they say they are.
819 -- However, it /does/ treat partial applications and constructor applications
820 -- as values, even if their arguments are non-trivial, provided the argument
821 -- type is lifted. For example, both of these are values:
822 --
823 -- > (:) (f x) (map f xs)
824 -- > map (...redex...)
825 --
826 -- because 'seq' on such things completes immediately.
827 --
828 -- For unlifted argument types, we have to be careful:
829 --
830 -- > C (f x :: Int#)
831 --
832 -- Suppose @f x@ diverges; then @C (f x)@ is not a value. However this can't 
833 -- happen: see "CoreSyn#let_app_invariant". This invariant states that arguments of
834 -- unboxed type must be ok-for-speculation (or trivial).
835 exprIsHNF :: CoreExpr -> Bool           -- True => Value-lambda, constructor, PAP
836 exprIsHNF = exprIsHNFlike isDataConWorkId isEvaldUnfolding
837 \end{code}
838
839 \begin{code}
840 -- | Similar to 'exprIsHNF' but includes CONLIKE functions as well as
841 -- data constructors. Conlike arguments are considered interesting by the
842 -- inliner.
843 exprIsConLike :: CoreExpr -> Bool       -- True => lambda, conlike, PAP
844 exprIsConLike = exprIsHNFlike isConLikeId isConLikeUnfolding
845
846 -- | Returns true for values or value-like expressions. These are lambdas,
847 -- constructors / CONLIKE functions (as determined by the function argument)
848 -- or PAPs.
849 --
850 exprIsHNFlike :: (Var -> Bool) -> (Unfolding -> Bool) -> CoreExpr -> Bool
851 exprIsHNFlike is_con is_con_unf = is_hnf_like
852   where
853     is_hnf_like (Var v) -- NB: There are no value args at this point
854       =  is_con v       -- Catches nullary constructors, 
855                         --      so that [] and () are values, for example
856       || idArity v > 0  -- Catches (e.g.) primops that don't have unfoldings
857       || is_con_unf (idUnfolding v)
858         -- Check the thing's unfolding; it might be bound to a value
859         -- We don't look through loop breakers here, which is a bit conservative
860         -- but otherwise I worry that if an Id's unfolding is just itself, 
861         -- we could get an infinite loop
862
863     is_hnf_like (Lit _)          = True
864     is_hnf_like (Type _)         = True       -- Types are honorary Values;
865                                               -- we don't mind copying them
866     is_hnf_like (Lam b e)        = isRuntimeVar b || is_hnf_like e
867     is_hnf_like (Note _ e)       = is_hnf_like e
868     is_hnf_like (Cast e _)       = is_hnf_like e
869     is_hnf_like (App e (Type _)) = is_hnf_like e
870     is_hnf_like (App e a)        = app_is_value e [a]
871     is_hnf_like (Let _ e)        = is_hnf_like e  -- Lazy let(rec)s don't affect us
872     is_hnf_like _                = False
873
874     -- There is at least one value argument
875     app_is_value :: CoreExpr -> [CoreArg] -> Bool
876     app_is_value (Var fun) args
877       = idArity fun > valArgCount args    -- Under-applied function
878         || is_con fun                     --  or constructor-like
879     app_is_value (Note _ f) as = app_is_value f as
880     app_is_value (Cast f _) as = app_is_value f as
881     app_is_value (App f a)  as = app_is_value f (a:as)
882     app_is_value _          _  = False
883 \end{code}
884
885
886 %************************************************************************
887 %*                                                                      *
888              Instantiating data constructors
889 %*                                                                      *
890 %************************************************************************
891
892 These InstPat functions go here to avoid circularity between DataCon and Id
893
894 \begin{code}
895 dataConRepInstPat, dataConOrigInstPat :: [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
896 dataConRepFSInstPat :: [FastString] -> [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
897
898 dataConRepInstPat   = dataConInstPat dataConRepArgTys (repeat ((fsLit "ipv")))
899 dataConRepFSInstPat = dataConInstPat dataConRepArgTys
900 dataConOrigInstPat  = dataConInstPat dc_arg_tys       (repeat ((fsLit "ipv")))
901   where 
902     dc_arg_tys dc = map mkPredTy (dataConEqTheta dc) ++ map mkPredTy (dataConDictTheta dc) ++ dataConOrigArgTys dc
903         -- Remember to include the existential dictionaries
904
905 dataConInstPat :: (DataCon -> [Type])      -- function used to find arg tys
906                   -> [FastString]          -- A long enough list of FSs to use for names
907                   -> [Unique]              -- An equally long list of uniques, at least one for each binder
908                   -> DataCon
909                   -> [Type]                -- Types to instantiate the universally quantified tyvars
910                -> ([TyVar], [CoVar], [Id]) -- Return instantiated variables
911 -- dataConInstPat arg_fun fss us con inst_tys returns a triple 
912 -- (ex_tvs, co_tvs, arg_ids),
913 --
914 --   ex_tvs are intended to be used as binders for existential type args
915 --
916 --   co_tvs are intended to be used as binders for coercion args and the kinds
917 --     of these vars have been instantiated by the inst_tys and the ex_tys
918 --     The co_tvs include both GADT equalities (dcEqSpec) and 
919 --     programmer-specified equalities (dcEqTheta)
920 --
921 --   arg_ids are indended to be used as binders for value arguments, 
922 --     and their types have been instantiated with inst_tys and ex_tys
923 --     The arg_ids include both dicts (dcDictTheta) and
924 --     programmer-specified arguments (after rep-ing) (deRepArgTys)
925 --
926 -- Example.
927 --  The following constructor T1
928 --
929 --  data T a where
930 --    T1 :: forall b. Int -> b -> T(a,b)
931 --    ...
932 --
933 --  has representation type 
934 --   forall a. forall a1. forall b. (a ~ (a1,b)) => 
935 --     Int -> b -> T a
936 --
937 --  dataConInstPat fss us T1 (a1',b') will return
938 --
939 --  ([a1'', b''], [c :: (a1', b')~(a1'', b'')], [x :: Int, y :: b''])
940 --
941 --  where the double-primed variables are created with the FastStrings and
942 --  Uniques given as fss and us
943 dataConInstPat arg_fun fss uniqs con inst_tys 
944   = (ex_bndrs, co_bndrs, arg_ids)
945   where 
946     univ_tvs = dataConUnivTyVars con
947     ex_tvs   = dataConExTyVars con
948     arg_tys  = arg_fun con
949     eq_spec  = dataConEqSpec con
950     eq_theta = dataConEqTheta con
951     eq_preds = eqSpecPreds eq_spec ++ eq_theta
952
953     n_ex = length ex_tvs
954     n_co = length eq_preds
955
956       -- split the Uniques and FastStrings
957     (ex_uniqs, uniqs')   = splitAt n_ex uniqs
958     (co_uniqs, id_uniqs) = splitAt n_co uniqs'
959
960     (ex_fss, fss')     = splitAt n_ex fss
961     (co_fss, id_fss)   = splitAt n_co fss'
962
963       -- Make existential type variables
964     ex_bndrs = zipWith3 mk_ex_var ex_uniqs ex_fss ex_tvs
965     mk_ex_var uniq fs var = mkTyVar new_name kind
966       where
967         new_name = mkSysTvName uniq fs
968         kind     = tyVarKind var
969
970       -- Make the instantiating substitution
971     subst = zipOpenTvSubst (univ_tvs ++ ex_tvs) (inst_tys ++ map mkTyVarTy ex_bndrs)
972
973       -- Make new coercion vars, instantiating kind
974     co_bndrs = zipWith3 mk_co_var co_uniqs co_fss eq_preds
975     mk_co_var uniq fs eq_pred = mkCoVar new_name co_kind
976        where
977          new_name = mkSysTvName uniq fs
978          co_kind  = substTy subst (mkPredTy eq_pred)
979
980       -- make value vars, instantiating types
981     mk_id_var uniq fs ty = mkUserLocal (mkVarOccFS fs) uniq (substTy subst ty) noSrcSpan
982     arg_ids = zipWith3 mk_id_var id_uniqs id_fss arg_tys
983
984 \end{code}
985
986 %************************************************************************
987 %*                                                                      *
988          Equality
989 %*                                                                      *
990 %************************************************************************
991
992 \begin{code}
993 -- | A cheap equality test which bales out fast!
994 --      If it returns @True@ the arguments are definitely equal,
995 --      otherwise, they may or may not be equal.
996 --
997 -- See also 'exprIsBig'
998 cheapEqExpr :: Expr b -> Expr b -> Bool
999
1000 cheapEqExpr (Var v1)   (Var v2)   = v1==v2
1001 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
1002 cheapEqExpr (Type t1)  (Type t2)  = t1 `coreEqType` t2
1003
1004 cheapEqExpr (App f1 a1) (App f2 a2)
1005   = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
1006
1007 cheapEqExpr (Cast e1 t1) (Cast e2 t2)
1008   = e1 `cheapEqExpr` e2 && t1 `coreEqCoercion` t2
1009
1010 cheapEqExpr _ _ = False
1011 \end{code}
1012
1013 \begin{code}
1014 exprIsBig :: Expr b -> Bool
1015 -- ^ Returns @True@ of expressions that are too big to be compared by 'cheapEqExpr'
1016 exprIsBig (Lit _)      = False
1017 exprIsBig (Var _)      = False
1018 exprIsBig (Type _)     = False
1019 exprIsBig (Lam _ e)    = exprIsBig e
1020 exprIsBig (App f a)    = exprIsBig f || exprIsBig a
1021 exprIsBig (Cast e _)   = exprIsBig e    -- Hopefully coercions are not too big!
1022 exprIsBig _            = True
1023 \end{code}
1024
1025 \begin{code}
1026 eqExpr :: InScopeSet -> CoreExpr -> CoreExpr -> Bool
1027 -- Compares for equality, modulo alpha
1028 eqExpr in_scope e1 e2
1029   = eqExprX id_unf (mkRnEnv2 in_scope) e1 e2
1030   where
1031     id_unf _ = noUnfolding      -- Don't expand
1032 \end{code}
1033     
1034 \begin{code}
1035 eqExprX :: IdUnfoldingFun -> RnEnv2 -> CoreExpr -> CoreExpr -> Bool
1036 -- ^ Compares expressions for equality, modulo alpha.
1037 -- Does /not/ look through newtypes or predicate types
1038 -- Used in rule matching, and also CSE
1039
1040 eqExprX id_unfolding_fun env e1 e2
1041   = go env e1 e2
1042   where
1043     go env (Var v1) (Var v2)
1044       | rnOccL env v1 == rnOccR env v2
1045       = True
1046
1047     -- The next two rules expand non-local variables
1048     -- C.f. Note [Expanding variables] in Rules.lhs
1049     -- and  Note [Do not expand locally-bound variables] in Rules.lhs
1050     go env (Var v1) e2
1051       | not (locallyBoundL env v1)
1052       , Just e1' <- expandUnfolding_maybe (id_unfolding_fun (lookupRnInScope env v1))
1053       = go (nukeRnEnvL env) e1' e2
1054
1055     go env e1 (Var v2)
1056       | not (locallyBoundR env v2)
1057       , Just e2' <- expandUnfolding_maybe (id_unfolding_fun (lookupRnInScope env v2))
1058       = go (nukeRnEnvR env) e1 e2'
1059
1060     go _   (Lit lit1)    (Lit lit2)    = lit1 == lit2
1061     go env (Type t1)     (Type t2)     = tcEqTypeX env t1 t2
1062     go env (Cast e1 co1) (Cast e2 co2) = tcEqTypeX env co1 co2 && go env e1 e2
1063     go env (App f1 a1)   (App f2 a2)   = go env f1 f2 && go env a1 a2
1064     go env (Note n1 e1)  (Note n2 e2)  = go_note n1 n2 && go env e1 e2
1065
1066     go env (Lam b1 e1)  (Lam b2 e2)  
1067       =  tcEqTypeX env (varType b1) (varType b2)   -- False for Id/TyVar combination
1068       && go (rnBndr2 env b1 b2) e1 e2
1069
1070     go env (Let (NonRec v1 r1) e1) (Let (NonRec v2 r2) e2) 
1071       =  go env r1 r2  -- No need to check binder types, since RHSs match
1072       && go (rnBndr2 env v1 v2) e1 e2
1073
1074     go env (Let (Rec ps1) e1) (Let (Rec ps2) e2) 
1075       = all2 (go env') rs1 rs2 && go env' e1 e2
1076       where
1077         (bs1,rs1) = unzip ps1      
1078         (bs2,rs2) = unzip ps2
1079         env' = rnBndrs2 env bs1 bs2
1080
1081     go env (Case e1 b1 _ a1) (Case e2 b2 _ a2)
1082       =  go env e1 e2
1083       && tcEqTypeX env (idType b1) (idType b2)
1084       && all2 (go_alt (rnBndr2 env b1 b2)) a1 a2
1085
1086     go _ _ _ = False
1087
1088     -----------
1089     go_alt env (c1, bs1, e1) (c2, bs2, e2)
1090       = c1 == c2 && go (rnBndrs2 env bs1 bs2) e1 e2
1091
1092     -----------
1093     go_note (SCC cc1)     (SCC cc2)      = cc1 == cc2
1094     go_note (CoreNote s1) (CoreNote s2)  = s1 == s2
1095     go_note _             _              = False
1096 \end{code}
1097
1098 Auxiliary functions
1099
1100 \begin{code}
1101 locallyBoundL, locallyBoundR :: RnEnv2 -> Var -> Bool
1102 locallyBoundL rn_env v = inRnEnvL rn_env v
1103 locallyBoundR rn_env v = inRnEnvR rn_env v
1104 \end{code}
1105
1106
1107 %************************************************************************
1108 %*                                                                      *
1109 \subsection{The size of an expression}
1110 %*                                                                      *
1111 %************************************************************************
1112
1113 \begin{code}
1114 coreBindsSize :: [CoreBind] -> Int
1115 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
1116
1117 exprSize :: CoreExpr -> Int
1118 -- ^ A measure of the size of the expressions, strictly greater than 0
1119 -- It also forces the expression pretty drastically as a side effect
1120 exprSize (Var v)         = v `seq` 1
1121 exprSize (Lit lit)       = lit `seq` 1
1122 exprSize (App f a)       = exprSize f + exprSize a
1123 exprSize (Lam b e)       = varSize b + exprSize e
1124 exprSize (Let b e)       = bindSize b + exprSize e
1125 exprSize (Case e b t as) = seqType t `seq` exprSize e + varSize b + 1 + foldr ((+) . altSize) 0 as
1126 exprSize (Cast e co)     = (seqType co `seq` 1) + exprSize e
1127 exprSize (Note n e)      = noteSize n + exprSize e
1128 exprSize (Type t)        = seqType t `seq` 1
1129
1130 noteSize :: Note -> Int
1131 noteSize (SCC cc)       = cc `seq` 1
1132 noteSize (CoreNote s)   = s `seq` 1  -- hdaume: core annotations
1133  
1134 varSize :: Var -> Int
1135 varSize b  | isTyCoVar b = 1
1136            | otherwise = seqType (idType b)             `seq`
1137                          megaSeqIdInfo (idInfo b)       `seq`
1138                          1
1139
1140 varsSize :: [Var] -> Int
1141 varsSize = sum . map varSize
1142
1143 bindSize :: CoreBind -> Int
1144 bindSize (NonRec b e) = varSize b + exprSize e
1145 bindSize (Rec prs)    = foldr ((+) . pairSize) 0 prs
1146
1147 pairSize :: (Var, CoreExpr) -> Int
1148 pairSize (b,e) = varSize b + exprSize e
1149
1150 altSize :: CoreAlt -> Int
1151 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
1152 \end{code}
1153
1154
1155 %************************************************************************
1156 %*                                                                      *
1157 \subsection{Hashing}
1158 %*                                                                      *
1159 %************************************************************************
1160
1161 \begin{code}
1162 hashExpr :: CoreExpr -> Int
1163 -- ^ Two expressions that hash to the same @Int@ may be equal (but may not be)
1164 -- Two expressions that hash to the different Ints are definitely unequal.
1165 --
1166 -- The emphasis is on a crude, fast hash, rather than on high precision.
1167 -- 
1168 -- But unequal here means \"not identical\"; two alpha-equivalent 
1169 -- expressions may hash to the different Ints.
1170 --
1171 -- We must be careful that @\\x.x@ and @\\y.y@ map to the same hash code,
1172 -- (at least if we want the above invariant to be true).
1173
1174 hashExpr e = fromIntegral (hash_expr (1,emptyVarEnv) e .&. 0x7fffffff)
1175              -- UniqFM doesn't like negative Ints
1176
1177 type HashEnv = (Int, VarEnv Int)  -- Hash code for bound variables
1178
1179 hash_expr :: HashEnv -> CoreExpr -> Word32
1180 -- Word32, because we're expecting overflows here, and overflowing
1181 -- signed types just isn't cool.  In C it's even undefined.
1182 hash_expr env (Note _ e)              = hash_expr env e
1183 hash_expr env (Cast e _)              = hash_expr env e
1184 hash_expr env (Var v)                 = hashVar env v
1185 hash_expr _   (Lit lit)               = fromIntegral (hashLiteral lit)
1186 hash_expr env (App f e)               = hash_expr env f * fast_hash_expr env e
1187 hash_expr env (Let (NonRec b r) e)    = hash_expr (extend_env env b) e * fast_hash_expr env r
1188 hash_expr env (Let (Rec ((b,_):_)) e) = hash_expr (extend_env env b) e
1189 hash_expr env (Case e _ _ _)          = hash_expr env e
1190 hash_expr env (Lam b e)               = hash_expr (extend_env env b) e
1191 hash_expr _   (Type _)                = WARN(True, text "hash_expr: type") 1
1192 -- Shouldn't happen.  Better to use WARN than trace, because trace
1193 -- prevents the CPR optimisation kicking in for hash_expr.
1194
1195 fast_hash_expr :: HashEnv -> CoreExpr -> Word32
1196 fast_hash_expr env (Var v)      = hashVar env v
1197 fast_hash_expr env (Type t)     = fast_hash_type env t
1198 fast_hash_expr _   (Lit lit)    = fromIntegral (hashLiteral lit)
1199 fast_hash_expr env (Cast e _)   = fast_hash_expr env e
1200 fast_hash_expr env (Note _ e)   = fast_hash_expr env e
1201 fast_hash_expr env (App _ a)    = fast_hash_expr env a  -- A bit idiosyncratic ('a' not 'f')!
1202 fast_hash_expr _   _            = 1
1203
1204 fast_hash_type :: HashEnv -> Type -> Word32
1205 fast_hash_type env ty 
1206   | Just tv <- getTyVar_maybe ty            = hashVar env tv
1207   | Just (tc,tys) <- splitTyConApp_maybe ty = let hash_tc = fromIntegral (hashName (tyConName tc))
1208                                               in foldr (\t n -> fast_hash_type env t + n) hash_tc tys
1209   | otherwise                               = 1
1210
1211 extend_env :: HashEnv -> Var -> (Int, VarEnv Int)
1212 extend_env (n,env) b = (n+1, extendVarEnv env b n)
1213
1214 hashVar :: HashEnv -> Var -> Word32
1215 hashVar (_,env) v
1216  = fromIntegral (lookupVarEnv env v `orElse` hashName (idName v))
1217 \end{code}
1218
1219
1220 %************************************************************************
1221 %*                                                                      *
1222                 Eta reduction
1223 %*                                                                      *
1224 %************************************************************************
1225
1226 Note [Eta reduction conditions]
1227 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1228 We try for eta reduction here, but *only* if we get all the way to an
1229 trivial expression.  We don't want to remove extra lambdas unless we
1230 are going to avoid allocating this thing altogether.
1231
1232 There are some particularly delicate points here:
1233
1234 * Eta reduction is not valid in general:  
1235         \x. bot  /=  bot
1236   This matters, partly for old-fashioned correctness reasons but,
1237   worse, getting it wrong can yield a seg fault. Consider
1238         f = \x.f x
1239         h y = case (case y of { True -> f `seq` True; False -> False }) of
1240                 True -> ...; False -> ...
1241
1242   If we (unsoundly) eta-reduce f to get f=f, the strictness analyser
1243   says f=bottom, and replaces the (f `seq` True) with just
1244   (f `cast` unsafe-co).  BUT, as thing stand, 'f' got arity 1, and it
1245   *keeps* arity 1 (perhaps also wrongly).  So CorePrep eta-expands 
1246   the definition again, so that it does not termninate after all.
1247   Result: seg-fault because the boolean case actually gets a function value.
1248   See Trac #1947.
1249
1250   So it's important to to the right thing.
1251
1252 * Note [Arity care]: we need to be careful if we just look at f's
1253   arity. Currently (Dec07), f's arity is visible in its own RHS (see
1254   Note [Arity robustness] in SimplEnv) so we must *not* trust the
1255   arity when checking that 'f' is a value.  Otherwise we will
1256   eta-reduce
1257       f = \x. f x
1258   to
1259       f = f
1260   Which might change a terminiating program (think (f `seq` e)) to a 
1261   non-terminating one.  So we check for being a loop breaker first.
1262
1263   However for GlobalIds we can look at the arity; and for primops we
1264   must, since they have no unfolding.  
1265
1266 * Regardless of whether 'f' is a value, we always want to 
1267   reduce (/\a -> f a) to f
1268   This came up in a RULE: foldr (build (/\a -> g a))
1269   did not match           foldr (build (/\b -> ...something complex...))
1270   The type checker can insert these eta-expanded versions,
1271   with both type and dictionary lambdas; hence the slightly 
1272   ad-hoc isDictId
1273
1274 * Never *reduce* arity. For example
1275       f = \xy. g x y
1276   Then if h has arity 1 we don't want to eta-reduce because then
1277   f's arity would decrease, and that is bad
1278
1279 These delicacies are why we don't use exprIsTrivial and exprIsHNF here.
1280 Alas.
1281
1282 Note [Eta reduction with casted arguments]
1283 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1284 Consider  
1285     (\(x:t3). f (x |> g)) :: t3 -> t2
1286   where
1287     f :: t1 -> t2
1288     g :: t3 ~ t1
1289 This should be eta-reduced to
1290
1291     f |> (sym g -> t2)
1292
1293 So we need to accumulate a coercion, pushing it inward (past
1294 variable arguments only) thus:
1295    f (x |> co_arg) |> co  -->  (f |> (sym co_arg -> co)) x
1296    f (x:t)         |> co  -->  (f |> (t -> co)) x
1297    f @ a           |> co  -->  (f |> (forall a.co)) @ a
1298    f @ (g:t1~t2)   |> co  -->  (f |> (t1~t2 => co)) @ (g:t1~t2)
1299 These are the equations for ok_arg.
1300
1301 It's true that we could also hope to eta reduce these:
1302     (\xy. (f x |> g) y)
1303     (\xy. (f x y) |> g)
1304 But the simplifier pushes those casts outwards, so we don't
1305 need to address that here.
1306
1307 \begin{code}
1308 tryEtaReduce :: [Var] -> CoreExpr -> Maybe CoreExpr
1309 tryEtaReduce bndrs body 
1310   = go (reverse bndrs) body (IdCo (exprType body))
1311   where
1312     incoming_arity = count isId bndrs
1313
1314     go :: [Var]            -- Binders, innermost first, types [a3,a2,a1]
1315        -> CoreExpr         -- Of type tr
1316        -> CoercionI        -- Of type tr ~ ts
1317        -> Maybe CoreExpr   -- Of type a1 -> a2 -> a3 -> ts
1318     -- See Note [Eta reduction with casted arguments]
1319     -- for why we have an accumulating coercion
1320     go [] fun co
1321       | ok_fun fun = Just (mkCoerceI co fun)
1322
1323     go (b : bs) (App fun arg) co
1324       | Just co' <- ok_arg b arg co
1325       = go bs fun co'
1326
1327     go _ _ _  = Nothing         -- Failure!
1328
1329     ---------------
1330     -- Note [Eta reduction conditions]
1331     ok_fun (App fun (Type ty)) 
1332         | not (any (`elemVarSet` tyVarsOfType ty) bndrs)
1333         =  ok_fun fun
1334     ok_fun (Var fun_id)
1335         =  not (fun_id `elem` bndrs)
1336         && (ok_fun_id fun_id || all ok_lam bndrs)
1337     ok_fun _fun = False
1338
1339     ---------------
1340     ok_fun_id fun = fun_arity fun >= incoming_arity
1341
1342     ---------------
1343     fun_arity fun             -- See Note [Arity care]
1344        | isLocalId fun && isLoopBreaker (idOccInfo fun) = 0
1345        | otherwise = idArity fun              
1346
1347     ---------------
1348     ok_lam v = isTyCoVar v || isDictId v
1349
1350     ---------------
1351     ok_arg :: Var               -- Of type bndr_t
1352            -> CoreExpr          -- Of type arg_t
1353            -> CoercionI         -- Of kind (t1~t2)
1354            -> Maybe CoercionI   -- Of type (arg_t -> t1 ~  bndr_t -> t2)
1355                                 --   (and similarly for tyvars, coercion args)
1356     -- See Note [Eta reduction with casted arguments]
1357     ok_arg bndr (Type ty) co
1358        | Just tv <- getTyVar_maybe ty
1359        , bndr == tv  = Just (mkForAllTyCoI tv co)
1360     ok_arg bndr (Var v) co
1361        | bndr == v   = Just (mkFunTyCoI (IdCo (idType bndr)) co)
1362     ok_arg bndr (Cast (Var v) co_arg) co
1363        | bndr == v  = Just (mkFunTyCoI (ACo (mkSymCoercion co_arg)) co)
1364        -- The simplifier combines multiple casts into one, 
1365        -- so we can have a simple-minded pattern match here
1366     ok_arg _ _ _ = Nothing
1367 \end{code}
1368
1369
1370 %************************************************************************
1371 %*                                                                      *
1372 \subsection{Determining non-updatable right-hand-sides}
1373 %*                                                                      *
1374 %************************************************************************
1375
1376 Top-level constructor applications can usually be allocated
1377 statically, but they can't if the constructor, or any of the
1378 arguments, come from another DLL (because we can't refer to static
1379 labels in other DLLs).
1380
1381 If this happens we simply make the RHS into an updatable thunk, 
1382 and 'execute' it rather than allocating it statically.
1383
1384 \begin{code}
1385 -- | This function is called only on *top-level* right-hand sides.
1386 -- Returns @True@ if the RHS can be allocated statically in the output,
1387 -- with no thunks involved at all.
1388 rhsIsStatic :: (Name -> Bool) -> CoreExpr -> Bool
1389 -- It's called (i) in TidyPgm.hasCafRefs to decide if the rhs is, or
1390 -- refers to, CAFs; (ii) in CoreToStg to decide whether to put an
1391 -- update flag on it and (iii) in DsExpr to decide how to expand
1392 -- list literals
1393 --
1394 -- The basic idea is that rhsIsStatic returns True only if the RHS is
1395 --      (a) a value lambda
1396 --      (b) a saturated constructor application with static args
1397 --
1398 -- BUT watch out for
1399 --  (i) Any cross-DLL references kill static-ness completely
1400 --      because they must be 'executed' not statically allocated
1401 --      ("DLL" here really only refers to Windows DLLs, on other platforms,
1402 --      this is not necessary)
1403 --
1404 -- (ii) We treat partial applications as redexes, because in fact we 
1405 --      make a thunk for them that runs and builds a PAP
1406 --      at run-time.  The only appliations that are treated as 
1407 --      static are *saturated* applications of constructors.
1408
1409 -- We used to try to be clever with nested structures like this:
1410 --              ys = (:) w ((:) w [])
1411 -- on the grounds that CorePrep will flatten ANF-ise it later.
1412 -- But supporting this special case made the function much more 
1413 -- complicated, because the special case only applies if there are no 
1414 -- enclosing type lambdas:
1415 --              ys = /\ a -> Foo (Baz ([] a))
1416 -- Here the nested (Baz []) won't float out to top level in CorePrep.
1417 --
1418 -- But in fact, even without -O, nested structures at top level are 
1419 -- flattened by the simplifier, so we don't need to be super-clever here.
1420 --
1421 -- Examples
1422 --
1423 --      f = \x::Int. x+7        TRUE
1424 --      p = (True,False)        TRUE
1425 --
1426 --      d = (fst p, False)      FALSE because there's a redex inside
1427 --                              (this particular one doesn't happen but...)
1428 --
1429 --      h = D# (1.0## /## 2.0##)        FALSE (redex again)
1430 --      n = /\a. Nil a                  TRUE
1431 --
1432 --      t = /\a. (:) (case w a of ...) (Nil a)  FALSE (redex)
1433 --
1434 --
1435 -- This is a bit like CoreUtils.exprIsHNF, with the following differences:
1436 --    a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
1437 --
1438 --    b) (C x xs), where C is a contructor is updatable if the application is
1439 --         dynamic
1440 -- 
1441 --    c) don't look through unfolding of f in (f x).
1442
1443 rhsIsStatic _is_dynamic_name rhs = is_static False rhs
1444   where
1445   is_static :: Bool     -- True <=> in a constructor argument; must be atomic
1446           -> CoreExpr -> Bool
1447   
1448   is_static False (Lam b e)   = isRuntimeVar b || is_static False e
1449   is_static in_arg (Note n e) = notSccNote n && is_static in_arg e
1450   is_static in_arg (Cast e _) = is_static in_arg e
1451   
1452   is_static _      (Lit lit)
1453     = case lit of
1454         MachLabel _ _ _ -> False
1455         _             -> True
1456         -- A MachLabel (foreign import "&foo") in an argument
1457         -- prevents a constructor application from being static.  The
1458         -- reason is that it might give rise to unresolvable symbols
1459         -- in the object file: under Linux, references to "weak"
1460         -- symbols from the data segment give rise to "unresolvable
1461         -- relocation" errors at link time This might be due to a bug
1462         -- in the linker, but we'll work around it here anyway. 
1463         -- SDM 24/2/2004
1464   
1465   is_static in_arg other_expr = go other_expr 0
1466    where
1467     go (Var f) n_val_args
1468 #if mingw32_TARGET_OS
1469         | not (_is_dynamic_name (idName f))
1470 #endif
1471         =  saturated_data_con f n_val_args
1472         || (in_arg && n_val_args == 0)  
1473                 -- A naked un-applied variable is *not* deemed a static RHS
1474                 -- E.g.         f = g
1475                 -- Reason: better to update so that the indirection gets shorted
1476                 --         out, and the true value will be seen
1477                 -- NB: if you change this, you'll break the invariant that THUNK_STATICs
1478                 --     are always updatable.  If you do so, make sure that non-updatable
1479                 --     ones have enough space for their static link field!
1480
1481     go (App f a) n_val_args
1482         | isTypeArg a                    = go f n_val_args
1483         | not in_arg && is_static True a = go f (n_val_args + 1)
1484         -- The (not in_arg) checks that we aren't in a constructor argument;
1485         -- if we are, we don't allow (value) applications of any sort
1486         -- 
1487         -- NB. In case you wonder, args are sometimes not atomic.  eg.
1488         --   x = D# (1.0## /## 2.0##)
1489         -- can't float because /## can fail.
1490
1491     go (Note n f) n_val_args = notSccNote n && go f n_val_args
1492     go (Cast e _) n_val_args = go e n_val_args
1493     go _          _          = False
1494
1495     saturated_data_con f n_val_args
1496         = case isDataConWorkId_maybe f of
1497             Just dc -> n_val_args == dataConRepArity dc
1498             Nothing -> False
1499 \end{code}