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