Completely new treatment of INLINE pragmas (big patch)
[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, 
29         exprIsHNF,exprOkForSpeculation, exprIsBig, 
30         exprIsConApp_maybe, 
31         exprBotStrictness_maybe,
32         rhsIsStatic,
33
34         -- * Arity and eta expansion
35         -- exprIsBottom,        Not used
36         manifestArity, exprArity, 
37         exprEtaExpandArity, etaExpand, 
38
39         -- * Expression and bindings size
40         coreBindsSize, exprSize,
41
42         -- * Hashing
43         hashExpr,
44
45         -- * Equality
46         cheapEqExpr, tcEqExpr, tcEqExprX,
47
48         -- * Manipulating data constructors and types
49         applyTypeToArgs, applyTypeToArg,
50         dataConOrigInstPat, dataConRepInstPat, dataConRepFSInstPat
51     ) where
52
53 #include "HsVersions.h"
54
55 import StaticFlags      ( opt_NoStateHack )
56 import CoreSyn
57 import CoreFVs
58 import PprCore
59 import Var
60 import SrcLoc
61 import VarSet
62 import VarEnv
63 import Name
64 import Module
65 #if mingw32_TARGET_OS
66 import Packages
67 #endif
68 import Literal
69 import DataCon
70 import PrimOp
71 import Id
72 import IdInfo
73 import NewDemand
74 import Type
75 import Coercion
76 import TyCon
77 import CostCentre
78 import BasicTypes
79 import Unique
80 import Outputable
81 import DynFlags
82 import TysPrim
83 import FastString
84 import Maybes
85 import Util
86 import Data.Word
87 import Data.Bits
88
89 import GHC.Exts         -- For `xori` 
90 \end{code}
91
92
93 %************************************************************************
94 %*                                                                      *
95 \subsection{Find the type of a Core atom/expression}
96 %*                                                                      *
97 %************************************************************************
98
99 \begin{code}
100 exprType :: CoreExpr -> Type
101 -- ^ Recover the type of a well-typed Core expression. Fails when
102 -- applied to the actual 'CoreSyn.Type' expression as it cannot
103 -- really be said to have a type
104 exprType (Var var)           = idType var
105 exprType (Lit lit)           = literalType lit
106 exprType (Let _ body)        = exprType body
107 exprType (Case _ _ ty _)     = ty
108 exprType (Cast _ co)         = snd (coercionKind co)
109 exprType (Note _ e)          = exprType e
110 exprType (Lam binder expr)   = mkPiType binder (exprType expr)
111 exprType e@(App _ _)
112   = case collectArgs e of
113         (fun, args) -> applyTypeToArgs e (exprType fun) args
114
115 exprType other = pprTrace "exprType" (pprCoreExpr other) alphaTy
116
117 coreAltType :: CoreAlt -> Type
118 -- ^ Returns the type of the alternatives right hand side
119 coreAltType (_,_,rhs) = exprType rhs
120
121 coreAltsType :: [CoreAlt] -> Type
122 -- ^ Returns the type of the first alternative, which should be the same as for all alternatives
123 coreAltsType (alt:_) = coreAltType alt
124 coreAltsType []      = panic "corAltsType"
125 \end{code}
126
127 \begin{code}
128 mkPiType  :: Var   -> Type -> Type
129 -- ^ Makes a @(->)@ type or a forall type, depending
130 -- on whether it is given a type variable or a term variable.
131 mkPiTypes :: [Var] -> Type -> Type
132 -- ^ 'mkPiType' for multiple type or value arguments
133
134 mkPiType v ty
135    | isId v    = mkFunTy (idType v) ty
136    | otherwise = mkForAllTy v ty
137
138 mkPiTypes vs ty = foldr mkPiType ty vs
139 \end{code}
140
141 \begin{code}
142 applyTypeToArg :: Type -> CoreExpr -> Type
143 -- ^ Determines the type resulting from applying an expression to a function with the given type
144 applyTypeToArg fun_ty (Type arg_ty) = applyTy fun_ty arg_ty
145 applyTypeToArg fun_ty _             = funResultTy fun_ty
146
147 applyTypeToArgs :: CoreExpr -> Type -> [CoreExpr] -> Type
148 -- ^ A more efficient version of 'applyTypeToArg' when we have several arguments.
149 -- The first argument is just for debugging, and gives some context
150 applyTypeToArgs _ op_ty [] = op_ty
151
152 applyTypeToArgs e op_ty (Type ty : args)
153   =     -- Accumulate type arguments so we can instantiate all at once
154     go [ty] args
155   where
156     go rev_tys (Type ty : args) = go (ty:rev_tys) args
157     go rev_tys rest_args        = applyTypeToArgs e op_ty' rest_args
158                                 where
159                                   op_ty' = applyTysD msg op_ty (reverse rev_tys)
160                                   msg = ptext (sLit "applyTypeToArgs") <+> 
161                                         panic_msg e op_ty
162
163 applyTypeToArgs e op_ty (_ : args)
164   = case (splitFunTy_maybe op_ty) of
165         Just (_, res_ty) -> applyTypeToArgs e res_ty args
166         Nothing -> pprPanic "applyTypeToArgs" (panic_msg e op_ty)
167
168 panic_msg :: CoreExpr -> Type -> SDoc
169 panic_msg e op_ty = pprCoreExpr e $$ ppr op_ty
170 \end{code}
171
172 %************************************************************************
173 %*                                                                      *
174 \subsection{Attaching notes}
175 %*                                                                      *
176 %************************************************************************
177
178 \begin{code}
179 -- | Wrap the given expression in the coercion, dropping identity coercions and coalescing nested coercions
180 mkCoerceI :: CoercionI -> CoreExpr -> CoreExpr
181 mkCoerceI IdCo e = e
182 mkCoerceI (ACo co) e = mkCoerce co e
183
184 -- | Wrap the given expression in the coercion safely, coalescing nested coercions
185 mkCoerce :: Coercion -> CoreExpr -> CoreExpr
186 mkCoerce co (Cast expr co2)
187   = ASSERT(let { (from_ty, _to_ty) = coercionKind co; 
188                  (_from_ty2, to_ty2) = coercionKind co2} in
189            from_ty `coreEqType` to_ty2 )
190     mkCoerce (mkTransCoercion co2 co) expr
191
192 mkCoerce co expr 
193   = let (from_ty, _to_ty) = coercionKind co in
194 --    if to_ty `coreEqType` from_ty
195 --    then expr
196 --    else 
197         ASSERT2(from_ty `coreEqType` (exprType expr), text "Trying to coerce" <+> text "(" <> ppr expr $$ text "::" <+> ppr (exprType expr) <> text ")" $$ ppr co $$ ppr (coercionKindPredTy co))
198          (Cast expr co)
199 \end{code}
200
201 \begin{code}
202 -- | Wraps the given expression in the cost centre unless
203 -- in a way that maximises their utility to the user
204 mkSCC :: CostCentre -> Expr b -> Expr b
205         -- Note: Nested SCC's *are* preserved for the benefit of
206         --       cost centre stack profiling
207 mkSCC _  (Lit lit)          = Lit lit
208 mkSCC cc (Lam x e)          = Lam x (mkSCC cc e)  -- Move _scc_ inside lambda
209 mkSCC cc (Note (SCC cc') e) = Note (SCC cc) (Note (SCC cc') e)
210 mkSCC cc (Note n e)         = Note n (mkSCC cc e) -- Move _scc_ inside notes
211 mkSCC cc (Cast e co)        = Cast (mkSCC cc e) co -- Move _scc_ inside cast
212 mkSCC cc expr               = Note (SCC cc) expr
213 \end{code}
214
215
216 %************************************************************************
217 %*                                                                      *
218 \subsection{Other expression construction}
219 %*                                                                      *
220 %************************************************************************
221
222 \begin{code}
223 bindNonRec :: Id -> CoreExpr -> CoreExpr -> CoreExpr
224 -- ^ @bindNonRec x r b@ produces either:
225 --
226 -- > let x = r in b
227 --
228 -- or:
229 --
230 -- > case r of x { _DEFAULT_ -> b }
231 --
232 -- depending on whether we have to use a @case@ or @let@
233 -- binding for the expression (see 'needsCaseBinding').
234 -- It's used by the desugarer to avoid building bindings
235 -- that give Core Lint a heart attack, although actually
236 -- the simplifier deals with them perfectly well. See
237 -- also 'MkCore.mkCoreLet'
238 bindNonRec bndr rhs body 
239   | needsCaseBinding (idType bndr) rhs = Case rhs bndr (exprType body) [(DEFAULT, [], body)]
240   | otherwise                          = Let (NonRec bndr rhs) body
241
242 -- | Tests whether we have to use a @case@ rather than @let@ binding for this expression
243 -- as per the invariants of 'CoreExpr': see "CoreSyn#let_app_invariant"
244 needsCaseBinding :: Type -> CoreExpr -> Bool
245 needsCaseBinding ty rhs = isUnLiftedType ty && not (exprOkForSpeculation rhs)
246         -- Make a case expression instead of a let
247         -- These can arise either from the desugarer,
248         -- or from beta reductions: (\x.e) (x +# y)
249 \end{code}
250
251 \begin{code}
252 mkAltExpr :: AltCon     -- ^ Case alternative constructor
253           -> [CoreBndr] -- ^ Things bound by the pattern match
254           -> [Type]     -- ^ The type arguments to the case alternative
255           -> CoreExpr
256 -- ^ This guy constructs the value that the scrutinee must have
257 -- given that you are in one particular branch of a case
258 mkAltExpr (DataAlt con) args inst_tys
259   = mkConApp con (map Type inst_tys ++ varsToCoreExprs args)
260 mkAltExpr (LitAlt lit) [] []
261   = Lit lit
262 mkAltExpr (LitAlt _) _ _ = panic "mkAltExpr LitAlt"
263 mkAltExpr DEFAULT _ _ = panic "mkAltExpr DEFAULT"
264 \end{code}
265
266
267 %************************************************************************
268 %*                                                                      *
269 \subsection{Taking expressions apart}
270 %*                                                                      *
271 %************************************************************************
272
273 The default alternative must be first, if it exists at all.
274 This makes it easy to find, though it makes matching marginally harder.
275
276 \begin{code}
277 -- | Extract the default case alternative
278 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
279 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null args ) (alts, Just rhs)
280 findDefault alts                        =                     (alts, Nothing)
281
282 -- | Find the case alternative corresponding to a particular 
283 -- constructor: panics if no such constructor exists
284 findAlt :: AltCon -> [CoreAlt] -> CoreAlt
285 findAlt con alts
286   = case alts of
287         (deflt@(DEFAULT,_,_):alts) -> go alts deflt
288         _                          -> go alts panic_deflt
289   where
290     panic_deflt = pprPanic "Missing alternative" (ppr con $$ vcat (map ppr alts))
291
292     go []                      deflt = deflt
293     go (alt@(con1,_,_) : alts) deflt
294       = case con `cmpAltCon` con1 of
295           LT -> deflt   -- Missed it already; the alts are in increasing order
296           EQ -> alt
297           GT -> ASSERT( not (con1 == DEFAULT) ) go alts deflt
298
299 isDefaultAlt :: CoreAlt -> Bool
300 isDefaultAlt (DEFAULT, _, _) = True
301 isDefaultAlt _               = False
302
303 ---------------------------------
304 mergeAlts :: [CoreAlt] -> [CoreAlt] -> [CoreAlt]
305 -- ^ Merge alternatives preserving order; alternatives in
306 -- the first argument shadow ones in the second
307 mergeAlts [] as2 = as2
308 mergeAlts as1 [] = as1
309 mergeAlts (a1:as1) (a2:as2)
310   = case a1 `cmpAlt` a2 of
311         LT -> a1 : mergeAlts as1      (a2:as2)
312         EQ -> a1 : mergeAlts as1      as2       -- Discard a2
313         GT -> a2 : mergeAlts (a1:as1) as2
314
315
316 ---------------------------------
317 trimConArgs :: AltCon -> [CoreArg] -> [CoreArg]
318 -- ^ Given:
319 --
320 -- > case (C a b x y) of
321 -- >        C b x y -> ...
322 --
323 -- We want to drop the leading type argument of the scrutinee
324 -- leaving the arguments to match agains the pattern
325
326 trimConArgs DEFAULT      args = ASSERT( null args ) []
327 trimConArgs (LitAlt _)   args = ASSERT( null args ) []
328 trimConArgs (DataAlt dc) args = dropList (dataConUnivTyVars dc) args
329 \end{code}
330
331
332 %************************************************************************
333 %*                                                                      *
334 \subsection{Figuring out things about expressions}
335 %*                                                                      *
336 %************************************************************************
337
338 @exprIsTrivial@ is true of expressions we are unconditionally happy to
339                 duplicate; simple variables and constants, and type
340                 applications.  Note that primop Ids aren't considered
341                 trivial unless 
342
343 There used to be a gruesome test for (hasNoBinding v) in the
344 Var case:
345         exprIsTrivial (Var v) | hasNoBinding v = idArity v == 0
346 The idea here is that a constructor worker, like \$wJust, is
347 really short for (\x -> \$wJust x), becuase \$wJust has no binding.
348 So it should be treated like a lambda.  Ditto unsaturated primops.
349 But now constructor workers are not "have-no-binding" Ids.  And
350 completely un-applied primops and foreign-call Ids are sufficiently
351 rare that I plan to allow them to be duplicated and put up with
352 saturating them.
353
354 SCC notes.  We do not treat (_scc_ "foo" x) as trivial, because 
355   a) it really generates code, (and a heap object when it's 
356      a function arg) to capture the cost centre
357   b) see the note [SCC-and-exprIsTrivial] in Simplify.simplLazyBind
358
359 \begin{code}
360 exprIsTrivial :: CoreExpr -> Bool
361 exprIsTrivial (Var _)          = True        -- See notes above
362 exprIsTrivial (Type _)         = True
363 exprIsTrivial (Lit lit)        = litIsTrivial lit
364 exprIsTrivial (App e arg)      = not (isRuntimeArg arg) && exprIsTrivial e
365 exprIsTrivial (Note (SCC _) _) = False       -- See notes above
366 exprIsTrivial (Note _       e) = exprIsTrivial e
367 exprIsTrivial (Cast e _)       = exprIsTrivial e
368 exprIsTrivial (Lam b body)     = not (isRuntimeVar b) && exprIsTrivial body
369 exprIsTrivial _                = False
370 \end{code}
371
372
373 @exprIsDupable@ is true of expressions that can be duplicated at a modest
374                 cost in code size.  This will only happen in different case
375                 branches, so there's no issue about duplicating work.
376
377                 That is, exprIsDupable returns True of (f x) even if
378                 f is very very expensive to call.
379
380                 Its only purpose is to avoid fruitless let-binding
381                 and then inlining of case join points
382
383
384 \begin{code}
385 exprIsDupable :: CoreExpr -> Bool
386 exprIsDupable (Type _)   = True
387 exprIsDupable (Var _)    = True
388 exprIsDupable (Lit lit)  = litIsDupable lit
389 exprIsDupable (Note _ e) = exprIsDupable e
390 exprIsDupable (Cast e _) = exprIsDupable e
391 exprIsDupable expr
392   = go expr 0
393   where
394     go (Var _)   _      = True
395     go (App f a) n_args =  n_args < dupAppSize
396                         && exprIsDupable a
397                         && go f (n_args+1)
398     go _         _      = False
399
400 dupAppSize :: Int
401 dupAppSize = 4          -- Size of application we are prepared to duplicate
402 \end{code}
403
404 @exprIsCheap@ looks at a Core expression and returns \tr{True} if
405 it is obviously in weak head normal form, or is cheap to get to WHNF.
406 [Note that that's not the same as exprIsDupable; an expression might be
407 big, and hence not dupable, but still cheap.]
408
409 By ``cheap'' we mean a computation we're willing to:
410         push inside a lambda, or
411         inline at more than one place
412 That might mean it gets evaluated more than once, instead of being
413 shared.  The main examples of things which aren't WHNF but are
414 ``cheap'' are:
415
416   *     case e of
417           pi -> ei
418         (where e, and all the ei are cheap)
419
420   *     let x = e in b
421         (where e and b are cheap)
422
423   *     op x1 ... xn
424         (where op is a cheap primitive operator)
425
426   *     error "foo"
427         (because we are happy to substitute it inside a lambda)
428
429 Notice that a variable is considered 'cheap': we can push it inside a lambda,
430 because sharing will make sure it is only evaluated once.
431
432 \begin{code}
433 exprIsCheap :: CoreExpr -> Bool
434 exprIsCheap (Lit _)           = True
435 exprIsCheap (Type _)          = True
436 exprIsCheap (Var _)           = True
437 exprIsCheap (Note _ e)        = exprIsCheap e
438 exprIsCheap (Cast e _)        = exprIsCheap e
439 exprIsCheap (Lam x e)         = isRuntimeVar x || exprIsCheap e
440 exprIsCheap (Case e _ _ alts) = exprIsCheap e && 
441                                 and [exprIsCheap rhs | (_,_,rhs) <- alts]
442         -- Experimentally, treat (case x of ...) as cheap
443         -- (and case __coerce x etc.)
444         -- This improves arities of overloaded functions where
445         -- there is only dictionary selection (no construction) involved
446 exprIsCheap (Let (NonRec x _) e)  
447       | isUnLiftedType (idType x) = exprIsCheap e
448       | otherwise                 = False
449         -- strict lets always have cheap right hand sides,
450         -- and do no allocation.
451
452 exprIsCheap other_expr  -- Applications and variables
453   = go other_expr []
454   where
455         -- Accumulate value arguments, then decide
456     go (App f a) val_args | isRuntimeArg a = go f (a:val_args)
457                           | otherwise      = go f val_args
458
459     go (Var _) [] = True        -- Just a type application of a variable
460                                 -- (f t1 t2 t3) counts as WHNF
461     go (Var f) args
462         = case globalIdDetails f of
463                 RecordSelId {} -> go_sel args
464                 ClassOpId _    -> go_sel args
465                 PrimOpId op    -> go_primop op args
466
467                 DataConWorkId _ -> go_pap args
468                 _ | length args < idArity f -> go_pap args
469
470                 _ -> isBottomingId f
471                         -- Application of a function which
472                         -- always gives bottom; we treat this as cheap
473                         -- because it certainly doesn't need to be shared!
474         
475     go _ _ = False
476  
477     --------------
478     go_pap args = all exprIsTrivial args
479         -- For constructor applications and primops, check that all
480         -- the args are trivial.  We don't want to treat as cheap, say,
481         --      (1:2:3:4:5:[])
482         -- We'll put up with one constructor application, but not dozens
483         
484     --------------
485     go_primop op args = primOpIsCheap op && all exprIsCheap args
486         -- In principle we should worry about primops
487         -- that return a type variable, since the result
488         -- might be applied to something, but I'm not going
489         -- to bother to check the number of args
490  
491     --------------
492     go_sel [arg] = exprIsCheap arg      -- I'm experimenting with making record selection
493     go_sel _     = False                -- look cheap, so we will substitute it inside a
494                                         -- lambda.  Particularly for dictionary field selection.
495                 -- BUT: Take care with (sel d x)!  The (sel d) might be cheap, but
496                 --      there's no guarantee that (sel d x) will be too.  Hence (n_val_args == 1)
497 \end{code}
498
499 \begin{code}
500 -- | 'exprOkForSpeculation' returns True of an expression that is:
501 --
502 --  * Safe to evaluate even if normal order eval might not 
503 --    evaluate the expression at all, or
504 --
505 --  * Safe /not/ to evaluate even if normal order would do so
506 --
507 -- Precisely, it returns @True@ iff:
508 --
509 --  * The expression guarantees to terminate, 
510 --
511 --  * soon, 
512 --
513 --  * without raising an exception,
514 --
515 --  * without causing a side effect (e.g. writing a mutable variable)
516 --
517 -- Note that if @exprIsHNF e@, then @exprOkForSpecuation e@.
518 -- As an example of the considerations in this test, consider:
519 --
520 -- > let x = case y# +# 1# of { r# -> I# r# }
521 -- > in E
522 --
523 -- being translated to:
524 --
525 -- > case y# +# 1# of { r# -> 
526 -- >    let x = I# r#
527 -- >    in E 
528 -- > }
529 -- 
530 -- We can only do this if the @y + 1@ is ok for speculation: it has no
531 -- side effects, and can't diverge or raise an exception.
532 exprOkForSpeculation :: CoreExpr -> Bool
533 exprOkForSpeculation (Lit _)     = True
534 exprOkForSpeculation (Type _)    = True
535     -- Tick boxes are *not* suitable for speculation
536 exprOkForSpeculation (Var v)     = isUnLiftedType (idType v)
537                                  && not (isTickBoxOp v)
538 exprOkForSpeculation (Note _ e)  = exprOkForSpeculation e
539 exprOkForSpeculation (Cast e _)  = exprOkForSpeculation e
540 exprOkForSpeculation other_expr
541   = case collectArgs other_expr of
542         (Var f, args) -> spec_ok (globalIdDetails f) args
543         _             -> False
544  
545   where
546     spec_ok (DataConWorkId _) _
547       = True    -- The strictness of the constructor has already
548                 -- been expressed by its "wrapper", so we don't need
549                 -- to take the arguments into account
550
551     spec_ok (PrimOpId op) args
552       | isDivOp op,             -- Special case for dividing operations that fail
553         [arg1, Lit lit] <- args -- only if the divisor is zero
554       = not (isZeroLit lit) && exprOkForSpeculation arg1
555                 -- Often there is a literal divisor, and this 
556                 -- can get rid of a thunk in an inner looop
557
558       | otherwise
559       = primOpOkForSpeculation op && 
560         all exprOkForSpeculation args
561                                 -- A bit conservative: we don't really need
562                                 -- to care about lazy arguments, but this is easy
563
564     spec_ok _ _ = False
565
566 -- | True of dyadic operators that can fail only if the second arg is zero!
567 isDivOp :: PrimOp -> Bool
568 -- This function probably belongs in PrimOp, or even in 
569 -- an automagically generated file.. but it's such a 
570 -- special case I thought I'd leave it here for now.
571 isDivOp IntQuotOp        = True
572 isDivOp IntRemOp         = True
573 isDivOp WordQuotOp       = True
574 isDivOp WordRemOp        = True
575 isDivOp IntegerQuotRemOp = True
576 isDivOp IntegerDivModOp  = True
577 isDivOp FloatDivOp       = True
578 isDivOp DoubleDivOp      = True
579 isDivOp _                = False
580 \end{code}
581
582 \begin{code}
583 {-      Never used -- omitting
584 -- | True of expressions that are guaranteed to diverge upon execution
585 exprIsBottom :: CoreExpr -> Bool        -- True => definitely bottom
586 exprIsBottom e = go 0 e
587                where
588                 -- n is the number of args
589                  go n (Note _ e)     = go n e
590                  go n (Cast e _)     = go n e
591                  go n (Let _ e)      = go n e
592                  go _ (Case e _ _ _) = go 0 e   -- Just check the scrut
593                  go n (App e _)      = go (n+1) e
594                  go n (Var v)        = idAppIsBottom v n
595                  go _ (Lit _)        = False
596                  go _ (Lam _ _)      = False
597                  go _ (Type _)       = False
598
599 idAppIsBottom :: Id -> Int -> Bool
600 idAppIsBottom id n_val_args = appIsBottom (idNewStrictness id) n_val_args
601 -}
602 \end{code}
603
604 \begin{code}
605
606 -- | This returns true for expressions that are certainly /already/ 
607 -- evaluated to /head/ normal form.  This is used to decide whether it's ok 
608 -- to change:
609 --
610 -- > case x of _ -> e
611 --
612 -- into:
613 --
614 -- > e
615 --
616 -- and to decide whether it's safe to discard a 'seq'.
617 -- So, it does /not/ treat variables as evaluated, unless they say they are.
618 -- However, it /does/ treat partial applications and constructor applications
619 -- as values, even if their arguments are non-trivial, provided the argument
620 -- type is lifted. For example, both of these are values:
621 --
622 -- > (:) (f x) (map f xs)
623 -- > map (...redex...)
624 --
625 -- Because 'seq' on such things completes immediately.
626 --
627 -- For unlifted argument types, we have to be careful:
628 --
629 -- > C (f x :: Int#)
630 --
631 -- Suppose @f x@ diverges; then @C (f x)@ is not a value. However this can't 
632 -- happen: see "CoreSyn#let_app_invariant". This invariant states that arguments of
633 -- unboxed type must be ok-for-speculation (or trivial).
634 exprIsHNF :: CoreExpr -> Bool           -- True => Value-lambda, constructor, PAP
635 exprIsHNF (Var v)       -- NB: There are no value args at this point
636   =  isDataConWorkId v  -- Catches nullary constructors, 
637                         --      so that [] and () are values, for example
638   || idArity v > 0      -- Catches (e.g.) primops that don't have unfoldings
639   || isEvaldUnfolding (idUnfolding v)
640         -- Check the thing's unfolding; it might be bound to a value
641         -- A worry: what if an Id's unfolding is just itself: 
642         -- then we could get an infinite loop...
643
644 exprIsHNF (Lit _)          = True
645 exprIsHNF (Type _)         = True       -- Types are honorary Values;
646                                         -- we don't mind copying them
647 exprIsHNF (Lam b e)        = isRuntimeVar b || exprIsHNF e
648 exprIsHNF (Note _ e)       = exprIsHNF e
649 exprIsHNF (Cast e _)       = exprIsHNF e
650 exprIsHNF (App e (Type _)) = exprIsHNF e
651 exprIsHNF (App e a)        = app_is_value e [a]
652 exprIsHNF _                = False
653
654 -- There is at least one value argument
655 app_is_value :: CoreExpr -> [CoreArg] -> Bool
656 app_is_value (Var fun) args
657   = idArity fun > valArgCount args      -- Under-applied function
658     ||  isDataConWorkId fun             --  or data constructor
659 app_is_value (Note _ f) as = app_is_value f as
660 app_is_value (Cast f _) as = app_is_value f as
661 app_is_value (App f a)  as = app_is_value f (a:as)
662 app_is_value _          _  = False
663 \end{code}
664
665 These InstPat functions go here to avoid circularity between DataCon and Id
666
667 \begin{code}
668 dataConRepInstPat, dataConOrigInstPat :: [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
669 dataConRepFSInstPat :: [FastString] -> [Unique] -> DataCon -> [Type] -> ([TyVar], [CoVar], [Id])
670
671 dataConRepInstPat   = dataConInstPat dataConRepArgTys (repeat ((fsLit "ipv")))
672 dataConRepFSInstPat = dataConInstPat dataConRepArgTys
673 dataConOrigInstPat  = dataConInstPat dc_arg_tys       (repeat ((fsLit "ipv")))
674   where 
675     dc_arg_tys dc = map mkPredTy (dataConEqTheta dc) ++ map mkPredTy (dataConDictTheta dc) ++ dataConOrigArgTys dc
676         -- Remember to include the existential dictionaries
677
678 dataConInstPat :: (DataCon -> [Type])      -- function used to find arg tys
679                   -> [FastString]          -- A long enough list of FSs to use for names
680                   -> [Unique]              -- An equally long list of uniques, at least one for each binder
681                   -> DataCon
682                   -> [Type]                -- Types to instantiate the universally quantified tyvars
683                -> ([TyVar], [CoVar], [Id]) -- Return instantiated variables
684 -- dataConInstPat arg_fun fss us con inst_tys returns a triple 
685 -- (ex_tvs, co_tvs, arg_ids),
686 --
687 --   ex_tvs are intended to be used as binders for existential type args
688 --
689 --   co_tvs are intended to be used as binders for coercion args and the kinds
690 --     of these vars have been instantiated by the inst_tys and the ex_tys
691 --     The co_tvs include both GADT equalities (dcEqSpec) and 
692 --     programmer-specified equalities (dcEqTheta)
693 --
694 --   arg_ids are indended to be used as binders for value arguments, 
695 --     and their types have been instantiated with inst_tys and ex_tys
696 --     The arg_ids include both dicts (dcDictTheta) and
697 --     programmer-specified arguments (after rep-ing) (deRepArgTys)
698 --
699 -- Example.
700 --  The following constructor T1
701 --
702 --  data T a where
703 --    T1 :: forall b. Int -> b -> T(a,b)
704 --    ...
705 --
706 --  has representation type 
707 --   forall a. forall a1. forall b. (a ~ (a1,b)) => 
708 --     Int -> b -> T a
709 --
710 --  dataConInstPat fss us T1 (a1',b') will return
711 --
712 --  ([a1'', b''], [c :: (a1', b')~(a1'', b'')], [x :: Int, y :: b''])
713 --
714 --  where the double-primed variables are created with the FastStrings and
715 --  Uniques given as fss and us
716 dataConInstPat arg_fun fss uniqs con inst_tys 
717   = (ex_bndrs, co_bndrs, arg_ids)
718   where 
719     univ_tvs = dataConUnivTyVars con
720     ex_tvs   = dataConExTyVars con
721     arg_tys  = arg_fun con
722     eq_spec  = dataConEqSpec con
723     eq_theta = dataConEqTheta con
724     eq_preds = eqSpecPreds eq_spec ++ eq_theta
725
726     n_ex = length ex_tvs
727     n_co = length eq_preds
728
729       -- split the Uniques and FastStrings
730     (ex_uniqs, uniqs')   = splitAt n_ex uniqs
731     (co_uniqs, id_uniqs) = splitAt n_co uniqs'
732
733     (ex_fss, fss')     = splitAt n_ex fss
734     (co_fss, id_fss)   = splitAt n_co fss'
735
736       -- Make existential type variables
737     ex_bndrs = zipWith3 mk_ex_var ex_uniqs ex_fss ex_tvs
738     mk_ex_var uniq fs var = mkTyVar new_name kind
739       where
740         new_name = mkSysTvName uniq fs
741         kind     = tyVarKind var
742
743       -- Make the instantiating substitution
744     subst = zipOpenTvSubst (univ_tvs ++ ex_tvs) (inst_tys ++ map mkTyVarTy ex_bndrs)
745
746       -- Make new coercion vars, instantiating kind
747     co_bndrs = zipWith3 mk_co_var co_uniqs co_fss eq_preds
748     mk_co_var uniq fs eq_pred = mkCoVar new_name co_kind
749        where
750          new_name = mkSysTvName uniq fs
751          co_kind  = substTy subst (mkPredTy eq_pred)
752
753       -- make value vars, instantiating types
754     mk_id_var uniq fs ty = mkUserLocal (mkVarOccFS fs) uniq (substTy subst ty) noSrcSpan
755     arg_ids = zipWith3 mk_id_var id_uniqs id_fss arg_tys
756
757 -- | Returns @Just (dc, [x1..xn])@ if the argument expression is 
758 -- a constructor application of the form @dc x1 .. xn@
759 exprIsConApp_maybe :: CoreExpr -> Maybe (DataCon, [CoreExpr])
760 exprIsConApp_maybe (Cast expr co)
761   =     -- Here we do the KPush reduction rule as described in the FC paper
762     case exprIsConApp_maybe expr of {
763         Nothing            -> Nothing ;
764         Just (dc, dc_args) -> 
765
766         -- The transformation applies iff we have
767         --      (C e1 ... en) `cast` co
768         -- where co :: (T t1 .. tn) ~ (T s1 ..sn)
769         -- That is, with a T at the top of both sides
770         -- The left-hand one must be a T, because exprIsConApp returned True
771         -- but the right-hand one might not be.  (Though it usually will.)
772
773     let (from_ty, to_ty)           = coercionKind co
774         (from_tc, from_tc_arg_tys) = splitTyConApp from_ty
775                 -- The inner one must be a TyConApp
776     in
777     case splitTyConApp_maybe to_ty of {
778         Nothing -> Nothing ;
779         Just (to_tc, to_tc_arg_tys) 
780                 | from_tc /= to_tc -> Nothing
781                 -- These two Nothing cases are possible; we might see 
782                 --      (C x y) `cast` (g :: T a ~ S [a]),
783                 -- where S is a type function.  In fact, exprIsConApp
784                 -- will probably not be called in such circumstances,
785                 -- but there't nothing wrong with it 
786
787                 | otherwise  ->
788     let
789         tc_arity = tyConArity from_tc
790
791         (univ_args, rest1)        = splitAt tc_arity dc_args
792         (ex_args, rest2)          = splitAt n_ex_tvs rest1
793         (co_args_spec, rest3)     = splitAt n_cos_spec rest2
794         (co_args_theta, val_args) = splitAt n_cos_theta rest3
795
796         arg_tys             = dataConRepArgTys dc
797         dc_univ_tyvars      = dataConUnivTyVars dc
798         dc_ex_tyvars        = dataConExTyVars dc
799         dc_eq_spec          = dataConEqSpec dc
800         dc_eq_theta         = dataConEqTheta dc
801         dc_tyvars           = dc_univ_tyvars ++ dc_ex_tyvars
802         n_ex_tvs            = length dc_ex_tyvars
803         n_cos_spec          = length dc_eq_spec
804         n_cos_theta         = length dc_eq_theta
805
806         -- Make the "theta" from Fig 3 of the paper
807         gammas              = decomposeCo tc_arity co
808         new_tys             = gammas ++ map (\ (Type t) -> t) ex_args
809         theta               = zipOpenTvSubst dc_tyvars new_tys
810
811           -- First we cast the existential coercion arguments
812         cast_co_spec (tv, ty) co 
813           = cast_co_theta (mkEqPred (mkTyVarTy tv, ty)) co
814         cast_co_theta eqPred (Type co) 
815           | (ty1, ty2) <- getEqPredTys eqPred
816           = Type $ mkSymCoercion (substTy theta ty1)
817                    `mkTransCoercion` co
818                    `mkTransCoercion` (substTy theta ty2)
819         new_co_args = zipWith cast_co_spec  dc_eq_spec  co_args_spec ++
820                       zipWith cast_co_theta dc_eq_theta co_args_theta
821   
822           -- ...and now value arguments
823         new_val_args = zipWith cast_arg arg_tys val_args
824         cast_arg arg_ty arg = mkCoerce (substTy theta arg_ty) arg
825
826     in
827     ASSERT( length univ_args == tc_arity )
828     ASSERT( from_tc == dataConTyCon dc )
829     ASSERT( and (zipWith coreEqType [t | Type t <- univ_args] from_tc_arg_tys) )
830     ASSERT( all isTypeArg (univ_args ++ ex_args) )
831     ASSERT2( equalLength val_args arg_tys, ppr dc $$ ppr dc_tyvars $$ ppr dc_ex_tyvars $$ ppr arg_tys $$ ppr dc_args $$ ppr univ_args $$ ppr ex_args $$ ppr val_args $$ ppr arg_tys  )
832
833     Just (dc, map Type to_tc_arg_tys ++ ex_args ++ new_co_args ++ new_val_args)
834     }}
835
836 {-
837 -- We do not want to tell the world that we have a
838 -- Cons, to *stop* Case of Known Cons, which removes
839 -- the TickBox.
840 exprIsConApp_maybe (Note (TickBox {}) expr)
841   = Nothing
842 exprIsConApp_maybe (Note (BinaryTickBox {}) expr)
843   = Nothing
844 -}
845
846 exprIsConApp_maybe (Note _ expr)
847   = exprIsConApp_maybe expr
848     -- We ignore all notes.  For example,
849     --          case _scc_ "foo" (C a b) of
850     --                  C a b -> e
851     -- should be optimised away, but it will be only if we look
852     -- through the SCC note.
853
854 exprIsConApp_maybe expr = analyse (collectArgs expr)
855   where
856     analyse (Var fun, args)
857         | Just con <- isDataConWorkId_maybe fun,
858           args `lengthAtLeast` dataConRepArity con
859                 -- Might be > because the arity excludes type args
860         = Just (con,args)
861
862         -- Look through unfoldings, but only cheap ones, because
863         -- we are effectively duplicating the unfolding
864     analyse (Var fun, [])
865         | let unf = idUnfolding fun,
866           isCheapUnfolding unf
867         = exprIsConApp_maybe (unfoldingTemplate unf)
868
869     analyse _ = Nothing
870 \end{code}
871
872
873
874 %************************************************************************
875 %*                                                                      *
876 \subsection{Eta reduction and expansion}
877 %*                                                                      *
878 %************************************************************************
879
880 \begin{code}
881 -- ^ The Arity returned is the number of value args the 
882 -- expression can be applied to without doing much work
883 exprEtaExpandArity :: DynFlags -> CoreExpr -> Arity
884 -- exprEtaExpandArity is used when eta expanding
885 --      e  ==>  \xy -> e x y
886 exprEtaExpandArity dflags e
887     = applyStateHack (exprType e) (arityDepth (arityType dicts_cheap e))
888   where
889     dicts_cheap = dopt Opt_DictsCheap dflags
890
891 exprBotStrictness_maybe :: CoreExpr -> Maybe (Arity, StrictSig)
892 -- A cheap and cheerful function that identifies bottoming functions
893 -- and gives them a suitable strictness signatures.  It's used during
894 -- float-out
895 exprBotStrictness_maybe e
896   = case arityType False e of
897         AT _ ATop -> Nothing
898         AT a ABot -> Just (a, mkStrictSig (mkTopDmdType (replicate a topDmd) BotRes))
899 \end{code}      
900
901
902 Note [Definition of arity]
903 ~~~~~~~~~~~~~~~~~~~~~~~~~~
904 The "arity" of an expression 'e' is n if
905    applying 'e' to *fewer* than n *value* arguments
906    converges rapidly
907
908 Or, to put it another way
909
910    there is no work lost in duplicating the partial
911    application (e x1 .. x(n-1))
912
913 In the divegent case, no work is lost by duplicating because if the thing
914 is evaluated once, that's the end of the program.
915
916 Or, to put it another way, in any context C
917
918    C[ (\x1 .. xn. e x1 .. xn) ]
919          is as efficient as
920    C[ e ]
921
922
923 It's all a bit more subtle than it looks:
924
925 Note [Arity of case expressions]
926 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
927 We treat the arity of 
928         case x of p -> \s -> ...
929 as 1 (or more) because for I/O ish things we really want to get that
930 \s to the top.  We are prepared to evaluate x each time round the loop
931 in order to get that.
932
933 This isn't really right in the presence of seq.  Consider
934         f = \x -> case x of
935                         True  -> \y -> x+y
936                         False -> \y -> x-y
937 Can we eta-expand here?  At first the answer looks like "yes of course", but
938 consider
939         (f bot) `seq` 1
940 This should diverge!  But if we eta-expand, it won't.   Again, we ignore this
941 "problem", because being scrupulous would lose an important transformation for
942 many programs.
943
944
945 1.  Note [One-shot lambdas]
946 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
947 Consider one-shot lambdas
948                 let x = expensive in \y z -> E
949 We want this to have arity 1 if the \y-abstraction is a 1-shot lambda.
950
951 3.  Note [Dealing with bottom]
952 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
953 Consider
954         f = \x -> error "foo"
955 Here, arity 1 is fine.  But if it is
956         f = \x -> case x of 
957                         True  -> error "foo"
958                         False -> \y -> x+y
959 then we want to get arity 2.  Technically, this isn't quite right, because
960         (f True) `seq` 1
961 should diverge, but it'll converge if we eta-expand f.  Nevertheless, we
962 do so; it improves some programs significantly, and increasing convergence
963 isn't a bad thing.  Hence the ABot/ATop in ArityType.
964
965
966 4. Note [Newtype arity]
967 ~~~~~~~~~~~~~~~~~~~~~~~~
968 Non-recursive newtypes are transparent, and should not get in the way.
969 We do (currently) eta-expand recursive newtypes too.  So if we have, say
970
971         newtype T = MkT ([T] -> Int)
972
973 Suppose we have
974         e = coerce T f
975 where f has arity 1.  Then: etaExpandArity e = 1; 
976 that is, etaExpandArity looks through the coerce.
977
978 When we eta-expand e to arity 1: eta_expand 1 e T
979 we want to get:                  coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
980
981 HOWEVER, note that if you use coerce bogusly you can ge
982         coerce Int negate
983 And since negate has arity 2, you might try to eta expand.  But you can't
984 decopose Int to a function type.   Hence the final case in eta_expand.
985
986
987 Note [The state-transformer hack]
988 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
989 Suppose we have 
990         f = e
991 where e has arity n.  Then, if we know from the context that f has
992 a usage type like
993         t1 -> ... -> tn -1-> t(n+1) -1-> ... -1-> tm -> ...
994 then we can expand the arity to m.  This usage type says that
995 any application (x e1 .. en) will be applied to uniquely to (m-n) more args
996 Consider f = \x. let y = <expensive> 
997                  in case x of
998                       True  -> foo
999                       False -> \(s:RealWorld) -> e
1000 where foo has arity 1.  Then we want the state hack to
1001 apply to foo too, so we can eta expand the case.
1002
1003 Then we expect that if f is applied to one arg, it'll be applied to two
1004 (that's the hack -- we don't really know, and sometimes it's false)
1005 See also Id.isOneShotBndr.
1006
1007 \begin{code}
1008 applyStateHack :: Type -> Arity -> Arity
1009 applyStateHack ty arity         -- Note [The state-transformer hack]
1010   | opt_NoStateHack = arity
1011   | otherwise       = go ty arity
1012   where
1013     go :: Type -> Arity -> Arity
1014     go ty arity         -- This case analysis should match that in eta_expand
1015         | Just (_, ty') <- splitForAllTy_maybe ty   = go ty' arity
1016
1017         | Just (tc,tys) <- splitTyConApp_maybe ty 
1018         , Just (ty', _) <- instNewTyCon_maybe tc tys
1019         , not (isRecursiveTyCon tc)                 = go ty' arity
1020                 -- Important to look through non-recursive newtypes, so that, eg 
1021                 --      (f x)   where f has arity 2, f :: Int -> IO ()
1022                 -- Here we want to get arity 1 for the result!
1023
1024         | Just (arg,res) <- splitFunTy_maybe ty
1025         , arity > 0 || isStateHackType arg = 1 + go res (arity-1)
1026                                                          
1027         | otherwise = WARN( arity > 0, ppr arity ) 0
1028 \end{code}
1029
1030
1031 -------------------- Main arity code ----------------------------
1032 \begin{code}
1033 -- If e has ArityType (AT as r), then the term 'e'
1034 --  * Must be applied to at least (length as) *value* args 
1035 --      before doing any significant work
1036 --  * It will not diverge before being applied to (length as) 
1037 --      value arguments
1038 --  * If 'r' is ABot, then it guarantees to eventually diverge if 
1039 --      applied to enough arguments (perhaps more than (length as)
1040
1041 data ArityType = AT Arity ArityRes
1042 data ArityRes  = ATop                   -- Know nothing
1043                | ABot                   -- Diverges
1044
1045 vanillaArityType :: ArityType
1046 vanillaArityType = AT 0 ATop    -- Totally uninformative
1047
1048 arityDepth :: ArityType -> Arity
1049 arityDepth (AT a _) = a
1050
1051 incArity :: ArityType -> ArityType
1052 incArity (AT a r) = AT (a+1) r
1053
1054 decArity :: ArityType -> ArityType
1055 decArity (AT 0 r) = AT 0     r
1056 decArity (AT a r) = AT (a-1) r
1057
1058 andArityType :: ArityType -> ArityType -> ArityType   -- Used for branches of a 'case'
1059 andArityType (AT a1 ATop) (AT a2 ATop) = AT (a1 `min` a2) ATop
1060 andArityType (AT _  ABot) (AT a2 ATop) = AT a2            ATop
1061 andArityType (AT a1 ATop) (AT _  ABot) = AT a1            ATop
1062 andArityType (AT a1 ABot) (AT a2 ABot) = AT (a1 `max` a2) ABot
1063
1064 trimArity :: Bool -> ArityType -> ArityType
1065 -- We have something like (let x = E in b), where b has the given
1066 -- arity type.  Then
1067 --      * If E is cheap we can push it inside as far as we like
1068 --      * If b eventually diverges, we allow ourselves to push inside
1069 --        arbitrarily, even though that is not quite right
1070 trimArity _cheap (AT a ABot) = AT a ABot
1071 trimArity True   (AT a ATop) = AT a ATop
1072 trimArity False  (AT _ ATop) = AT 0 ATop        -- Bale out
1073
1074 ---------------------------
1075 arityType :: Bool -> CoreExpr -> ArityType
1076 arityType _ (Var v)
1077   | Just strict_sig <- idNewStrictness_maybe v
1078   , (ds, res) <- splitStrictSig strict_sig
1079   , isBotRes res
1080   = AT (length ds) ABot -- Function diverges
1081   | otherwise
1082   = AT (idArity v) ATop
1083
1084         -- Lambdas; increase arity
1085 arityType dicts_cheap (Lam x e)
1086   | isId x    = incArity (arityType dicts_cheap e)
1087   | otherwise = arityType dicts_cheap e
1088
1089         -- Applications; decrease arity
1090 arityType dicts_cheap (App fun (Type _))
1091    = arityType dicts_cheap fun
1092 arityType dicts_cheap (App fun arg )
1093    = trimArity (exprIsCheap arg) (decArity (arityType dicts_cheap fun))
1094
1095         -- Case/Let; keep arity if either the expression is cheap
1096         -- or it's a 1-shot lambda
1097         -- The former is not really right for Haskell
1098         --      f x = case x of { (a,b) -> \y. e }
1099         --  ===>
1100         --      f x y = case x of { (a,b) -> e }
1101         -- The difference is observable using 'seq'
1102 arityType dicts_cheap (Case scrut _ _ alts)
1103   = trimArity (exprIsCheap scrut)
1104               (foldr1 andArityType [arityType dicts_cheap rhs | (_,_,rhs) <- alts])
1105
1106 arityType dicts_cheap (Let b e) 
1107   = trimArity (cheap_bind b) (arityType dicts_cheap e)
1108   where
1109     cheap_bind (NonRec b e) = is_cheap (b,e)
1110     cheap_bind (Rec prs)    = all is_cheap prs
1111     is_cheap (b,e) = (dicts_cheap && isDictId b) || exprIsCheap e
1112         -- If the experimental -fdicts-cheap flag is on, we eta-expand through
1113         -- dictionary bindings.  This improves arities. Thereby, it also
1114         -- means that full laziness is less prone to floating out the
1115         -- application of a function to its dictionary arguments, which
1116         -- can thereby lose opportunities for fusion.  Example:
1117         --      foo :: Ord a => a -> ...
1118         --      foo = /\a \(d:Ord a). let d' = ...d... in \(x:a). ....
1119         --              -- So foo has arity 1
1120         --
1121         --      f = \x. foo dInt $ bar x
1122         --
1123         -- The (foo DInt) is floated out, and makes ineffective a RULE 
1124         --      foo (bar x) = ...
1125         --
1126         -- One could go further and make exprIsCheap reply True to any
1127         -- dictionary-typed expression, but that's more work.
1128
1129 arityType dicts_cheap (Note _ e) = arityType dicts_cheap e
1130 arityType dicts_cheap (Cast e _) = arityType dicts_cheap e
1131 arityType _           _          = vanillaArityType
1132 \end{code}
1133
1134
1135 \begin{code}
1136 -- | @etaExpand n us e ty@ returns an expression with
1137 -- the same meaning as @e@, but with arity @n@.
1138 --
1139 -- Given:
1140 --
1141 -- > e' = etaExpand n us e ty
1142 --
1143 -- We should have that:
1144 --
1145 -- > ty = exprType e = exprType e'
1146 etaExpand :: Arity              -- ^ Result should have this number of value args
1147           -> [Unique]           -- ^ Uniques to assign to the new binders
1148           -> CoreExpr           -- ^ Expression to expand
1149           -> Type               -- ^ Type of expression to expand
1150           -> CoreExpr
1151 -- Note that SCCs are not treated specially.  If we have
1152 --      etaExpand 2 (\x -> scc "foo" e)
1153 --      = (\xy -> (scc "foo" e) y)
1154 -- So the costs of evaluating 'e' (not 'e y') are attributed to "foo"
1155
1156 etaExpand n us expr ty
1157   | manifestArity expr >= n = expr              -- The no-op case
1158   | otherwise               = eta_expand n us expr ty
1159
1160 -- manifestArity sees how many leading value lambdas there are
1161 manifestArity :: CoreExpr -> Arity
1162 manifestArity (Lam v e) | isId v    = 1 + manifestArity e
1163                         | otherwise = manifestArity e
1164 manifestArity (Note _ e)            = manifestArity e
1165 manifestArity (Cast e _)            = manifestArity e
1166 manifestArity _                     = 0
1167
1168 -- etaExpand deals with for-alls. For example:
1169 --              etaExpand 1 E
1170 -- where  E :: forall a. a -> a
1171 -- would return
1172 --      (/\b. \y::a -> E b y)
1173 --
1174 -- It deals with coerces too, though they are now rare
1175 -- so perhaps the extra code isn't worth it
1176 eta_expand :: Int -> [Unique] -> CoreExpr -> Type -> CoreExpr
1177
1178 eta_expand n _ expr _
1179   | n == 0    -- Saturated, so nothing to do
1180   = expr
1181
1182         -- Short cut for the case where there already
1183         -- is a lambda; no point in gratuitously adding more
1184 eta_expand n us (Lam v body) ty
1185   | isTyVar v
1186   = Lam v (eta_expand n us body (applyTy ty (mkTyVarTy v)))
1187
1188   | otherwise
1189   = Lam v (eta_expand (n-1) us body (funResultTy ty))
1190
1191 -- We used to have a special case that stepped inside Coerces here,
1192 -- thus:  eta_expand n us (Note note@(Coerce _ ty) e) _  
1193 --              = Note note (eta_expand n us e ty)
1194 -- BUT this led to an infinite loop
1195 -- Example:     newtype T = MkT (Int -> Int)
1196 --      eta_expand 1 (coerce (Int->Int) e)
1197 --      --> coerce (Int->Int) (eta_expand 1 T e)
1198 --              by the bogus eqn
1199 --      --> coerce (Int->Int) (coerce T 
1200 --              (\x::Int -> eta_expand 1 (coerce (Int->Int) e)))
1201 --              by the splitNewType_maybe case below
1202 --      and round we go
1203
1204 eta_expand n us expr ty
1205   = ASSERT2 (exprType expr `coreEqType` ty, ppr (exprType expr) $$ ppr ty)
1206     case splitForAllTy_maybe ty of { 
1207           Just (tv,ty') -> 
1208
1209               Lam lam_tv (eta_expand n us2 (App expr (Type (mkTyVarTy lam_tv))) (substTyWith [tv] [mkTyVarTy lam_tv] ty'))
1210                   where 
1211                     lam_tv = setVarName tv (mkSysTvName uniq (fsLit "etaT"))
1212                         -- Using tv as a base retains its tyvar/covar-ness
1213                     (uniq:us2) = us 
1214         ; Nothing ->
1215   
1216         case splitFunTy_maybe ty of {
1217           Just (arg_ty, res_ty) -> Lam arg1 (eta_expand (n-1) us2 (App expr (Var arg1)) res_ty)
1218                                 where
1219                                    arg1       = mkSysLocal (fsLit "eta") uniq arg_ty
1220                                    (uniq:us2) = us
1221                                    
1222         ; Nothing ->
1223
1224                 -- Given this:
1225                 --      newtype T = MkT ([T] -> Int)
1226                 -- Consider eta-expanding this
1227                 --      eta_expand 1 e T
1228                 -- We want to get
1229                 --      coerce T (\x::[T] -> (coerce ([T]->Int) e) x)
1230
1231         case splitNewTypeRepCo_maybe ty of {
1232           Just(ty1,co) -> mkCoerce (mkSymCoercion co) 
1233                                    (eta_expand n us (mkCoerce co expr) ty1) ;
1234           Nothing  -> 
1235
1236         -- We have an expression of arity > 0, but its type isn't a function
1237         -- This *can* legitmately happen: e.g.  coerce Int (\x. x)
1238         -- Essentially the programmer is playing fast and loose with types
1239         -- (Happy does this a lot).  So we simply decline to eta-expand.
1240         -- Otherwise we'd end up with an explicit lambda having a non-function type
1241         expr
1242         }}}
1243 \end{code}
1244
1245 exprArity is a cheap-and-cheerful version of exprEtaExpandArity.
1246 It tells how many things the expression can be applied to before doing
1247 any work.  It doesn't look inside cases, lets, etc.  The idea is that
1248 exprEtaExpandArity will do the hard work, leaving something that's easy
1249 for exprArity to grapple with.  In particular, Simplify uses exprArity to
1250 compute the ArityInfo for the Id. 
1251
1252 Originally I thought that it was enough just to look for top-level lambdas, but
1253 it isn't.  I've seen this
1254
1255         foo = PrelBase.timesInt
1256
1257 We want foo to get arity 2 even though the eta-expander will leave it
1258 unchanged, in the expectation that it'll be inlined.  But occasionally it
1259 isn't, because foo is blacklisted (used in a rule).  
1260
1261 Similarly, see the ok_note check in exprEtaExpandArity.  So 
1262         f = __inline_me (\x -> e)
1263 won't be eta-expanded.
1264
1265 And in any case it seems more robust to have exprArity be a bit more intelligent.
1266 But note that   (\x y z -> f x y z)
1267 should have arity 3, regardless of f's arity.
1268
1269 Note [exprArity invariant]
1270 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1271 exprArity has the following invariant:
1272         (exprArity e) = n, then manifestArity (etaExpand e n) = n
1273
1274 That is, if exprArity says "the arity is n" then etaExpand really can get
1275 "n" manifest lambdas to the top.
1276
1277 Why is this important?  Because 
1278   - In TidyPgm we use exprArity to fix the *final arity* of 
1279     each top-level Id, and in
1280   - In CorePrep we use etaExpand on each rhs, so that the visible lambdas
1281     actually match that arity, which in turn means
1282     that the StgRhs has the right number of lambdas
1283
1284 An alternative would be to do the eta-expansion in TidyPgm, at least
1285 for top-level bindings, in which case we would not need the trim_arity
1286 in exprArity.  That is a less local change, so I'm going to leave it for today!
1287
1288
1289 \begin{code}
1290 -- | An approximate, fast, version of 'exprEtaExpandArity'
1291 exprArity :: CoreExpr -> Arity
1292 exprArity e = go e
1293   where
1294     go (Var v)                   = idArity v
1295     go (Lam x e) | isId x        = go e + 1
1296                  | otherwise     = go e
1297     go (Note _ e)                = go e
1298     go (Cast e co)               = trim_arity (go e) 0 (snd (coercionKind co))
1299     go (App e (Type _))          = go e
1300     go (App f a) | exprIsCheap a = (go f - 1) `max` 0
1301         -- NB: exprIsCheap a!  
1302         --      f (fac x) does not have arity 2, 
1303         --      even if f has arity 3!
1304         -- NB: `max 0`!  (\x y -> f x) has arity 2, even if f is
1305         --               unknown, hence arity 0
1306     go _                           = 0
1307
1308         -- Note [exprArity invariant]
1309     trim_arity n a ty
1310         | n==a                                        = a
1311         | Just (_, ty') <- splitForAllTy_maybe ty     = trim_arity n a     ty'
1312         | Just (_, ty') <- splitFunTy_maybe ty        = trim_arity n (a+1) ty'
1313         | Just (ty',_)  <- splitNewTypeRepCo_maybe ty = trim_arity n a     ty'
1314         | otherwise                                   = a
1315 \end{code}
1316
1317 %************************************************************************
1318 %*                                                                      *
1319 \subsection{Equality}
1320 %*                                                                      *
1321 %************************************************************************
1322
1323 \begin{code}
1324 -- | A cheap equality test which bales out fast!
1325 --      If it returns @True@ the arguments are definitely equal,
1326 --      otherwise, they may or may not be equal.
1327 --
1328 -- See also 'exprIsBig'
1329 cheapEqExpr :: Expr b -> Expr b -> Bool
1330
1331 cheapEqExpr (Var v1)   (Var v2)   = v1==v2
1332 cheapEqExpr (Lit lit1) (Lit lit2) = lit1 == lit2
1333 cheapEqExpr (Type t1)  (Type t2)  = t1 `coreEqType` t2
1334
1335 cheapEqExpr (App f1 a1) (App f2 a2)
1336   = f1 `cheapEqExpr` f2 && a1 `cheapEqExpr` a2
1337
1338 cheapEqExpr (Cast e1 t1) (Cast e2 t2)
1339   = e1 `cheapEqExpr` e2 && t1 `coreEqCoercion` t2
1340
1341 cheapEqExpr _ _ = False
1342
1343 exprIsBig :: Expr b -> Bool
1344 -- ^ Returns @True@ of expressions that are too big to be compared by 'cheapEqExpr'
1345 exprIsBig (Lit _)      = False
1346 exprIsBig (Var _)      = False
1347 exprIsBig (Type _)     = False
1348 exprIsBig (Lam _ e)    = exprIsBig e
1349 exprIsBig (App f a)    = exprIsBig f || exprIsBig a
1350 exprIsBig (Cast e _)   = exprIsBig e    -- Hopefully coercions are not too big!
1351 exprIsBig _            = True
1352 \end{code}
1353
1354
1355 \begin{code}
1356 tcEqExpr :: CoreExpr -> CoreExpr -> Bool
1357 -- ^ A kind of shallow equality used in rule matching, so does 
1358 -- /not/ look through newtypes or predicate types
1359
1360 tcEqExpr e1 e2 = tcEqExprX rn_env e1 e2
1361   where
1362     rn_env = mkRnEnv2 (mkInScopeSet (exprFreeVars e1 `unionVarSet` exprFreeVars e2))
1363
1364 tcEqExprX :: RnEnv2 -> CoreExpr -> CoreExpr -> Bool
1365 tcEqExprX env (Var v1)     (Var v2)     = rnOccL env v1 == rnOccR env v2
1366 tcEqExprX _   (Lit lit1)   (Lit lit2)   = lit1 == lit2
1367 tcEqExprX env (App f1 a1)  (App f2 a2)  = tcEqExprX env f1 f2 && tcEqExprX env a1 a2
1368 tcEqExprX env (Lam v1 e1)  (Lam v2 e2)  = tcEqExprX (rnBndr2 env v1 v2) e1 e2
1369 tcEqExprX env (Let (NonRec v1 r1) e1)
1370               (Let (NonRec v2 r2) e2)   = tcEqExprX env r1 r2 
1371                                        && tcEqExprX (rnBndr2 env v1 v2) e1 e2
1372 tcEqExprX env (Let (Rec ps1) e1)
1373               (Let (Rec ps2) e2)        =  equalLength ps1 ps2
1374                                         && and (zipWith eq_rhs ps1 ps2)
1375                                         && tcEqExprX env' e1 e2
1376                                      where
1377                                        env' = foldl2 rn_bndr2 env ps2 ps2
1378                                        rn_bndr2 env (b1,_) (b2,_) = rnBndr2 env b1 b2
1379                                        eq_rhs       (_,r1) (_,r2) = tcEqExprX env' r1 r2
1380 tcEqExprX env (Case e1 v1 t1 a1)
1381               (Case e2 v2 t2 a2)     =  tcEqExprX env e1 e2
1382                                      && tcEqTypeX env t1 t2                      
1383                                      && equalLength a1 a2
1384                                      && and (zipWith (eq_alt env') a1 a2)
1385                                      where
1386                                        env' = rnBndr2 env v1 v2
1387
1388 tcEqExprX env (Note n1 e1)  (Note n2 e2)  = eq_note env n1 n2 && tcEqExprX env e1 e2
1389 tcEqExprX env (Cast e1 co1) (Cast e2 co2) = tcEqTypeX env co1 co2 && tcEqExprX env e1 e2
1390 tcEqExprX env (Type t1)     (Type t2)     = tcEqTypeX env t1 t2
1391 tcEqExprX _   _             _             = False
1392
1393 eq_alt :: RnEnv2 -> CoreAlt -> CoreAlt -> Bool
1394 eq_alt env (c1,vs1,r1) (c2,vs2,r2) = c1==c2 && tcEqExprX (rnBndrs2 env vs1  vs2) r1 r2
1395
1396 eq_note :: RnEnv2 -> Note -> Note -> Bool
1397 eq_note _ (SCC cc1)     (SCC cc2)      = cc1 == cc2
1398 eq_note _ (CoreNote s1) (CoreNote s2)  = s1 == s2
1399 eq_note _ _             _              = False
1400 \end{code}
1401
1402
1403 %************************************************************************
1404 %*                                                                      *
1405 \subsection{The size of an expression}
1406 %*                                                                      *
1407 %************************************************************************
1408
1409 \begin{code}
1410 coreBindsSize :: [CoreBind] -> Int
1411 coreBindsSize bs = foldr ((+) . bindSize) 0 bs
1412
1413 exprSize :: CoreExpr -> Int
1414 -- ^ A measure of the size of the expressions, strictly greater than 0
1415 -- It also forces the expression pretty drastically as a side effect
1416 exprSize (Var v)         = v `seq` 1
1417 exprSize (Lit lit)       = lit `seq` 1
1418 exprSize (App f a)       = exprSize f + exprSize a
1419 exprSize (Lam b e)       = varSize b + exprSize e
1420 exprSize (Let b e)       = bindSize b + exprSize e
1421 exprSize (Case e b t as) = seqType t `seq` exprSize e + varSize b + 1 + foldr ((+) . altSize) 0 as
1422 exprSize (Cast e co)     = (seqType co `seq` 1) + exprSize e
1423 exprSize (Note n e)      = noteSize n + exprSize e
1424 exprSize (Type t)        = seqType t `seq` 1
1425
1426 noteSize :: Note -> Int
1427 noteSize (SCC cc)       = cc `seq` 1
1428 noteSize (CoreNote s)   = s `seq` 1  -- hdaume: core annotations
1429  
1430 varSize :: Var -> Int
1431 varSize b  | isTyVar b = 1
1432            | otherwise = seqType (idType b)             `seq`
1433                          megaSeqIdInfo (idInfo b)       `seq`
1434                          1
1435
1436 varsSize :: [Var] -> Int
1437 varsSize = sum . map varSize
1438
1439 bindSize :: CoreBind -> Int
1440 bindSize (NonRec b e) = varSize b + exprSize e
1441 bindSize (Rec prs)    = foldr ((+) . pairSize) 0 prs
1442
1443 pairSize :: (Var, CoreExpr) -> Int
1444 pairSize (b,e) = varSize b + exprSize e
1445
1446 altSize :: CoreAlt -> Int
1447 altSize (c,bs,e) = c `seq` varsSize bs + exprSize e
1448 \end{code}
1449
1450
1451 %************************************************************************
1452 %*                                                                      *
1453 \subsection{Hashing}
1454 %*                                                                      *
1455 %************************************************************************
1456
1457 \begin{code}
1458 hashExpr :: CoreExpr -> Int
1459 -- ^ Two expressions that hash to the same @Int@ may be equal (but may not be)
1460 -- Two expressions that hash to the different Ints are definitely unequal.
1461 --
1462 -- The emphasis is on a crude, fast hash, rather than on high precision.
1463 -- 
1464 -- But unequal here means \"not identical\"; two alpha-equivalent 
1465 -- expressions may hash to the different Ints.
1466 --
1467 -- We must be careful that @\\x.x@ and @\\y.y@ map to the same hash code,
1468 -- (at least if we want the above invariant to be true).
1469
1470 hashExpr e = fromIntegral (hash_expr (1,emptyVarEnv) e .&. 0x7fffffff)
1471              -- UniqFM doesn't like negative Ints
1472
1473 type HashEnv = (Int, VarEnv Int)  -- Hash code for bound variables
1474
1475 hash_expr :: HashEnv -> CoreExpr -> Word32
1476 -- Word32, because we're expecting overflows here, and overflowing
1477 -- signed types just isn't cool.  In C it's even undefined.
1478 hash_expr env (Note _ e)              = hash_expr env e
1479 hash_expr env (Cast e _)              = hash_expr env e
1480 hash_expr env (Var v)                 = hashVar env v
1481 hash_expr _   (Lit lit)               = fromIntegral (hashLiteral lit)
1482 hash_expr env (App f e)               = hash_expr env f * fast_hash_expr env e
1483 hash_expr env (Let (NonRec b r) e)    = hash_expr (extend_env env b) e * fast_hash_expr env r
1484 hash_expr env (Let (Rec ((b,_):_)) e) = hash_expr (extend_env env b) e
1485 hash_expr env (Case e _ _ _)          = hash_expr env e
1486 hash_expr env (Lam b e)               = hash_expr (extend_env env b) e
1487 hash_expr _   (Type _)                = WARN(True, text "hash_expr: type") 1
1488 -- Shouldn't happen.  Better to use WARN than trace, because trace
1489 -- prevents the CPR optimisation kicking in for hash_expr.
1490
1491 fast_hash_expr :: HashEnv -> CoreExpr -> Word32
1492 fast_hash_expr env (Var v)      = hashVar env v
1493 fast_hash_expr env (Type t)     = fast_hash_type env t
1494 fast_hash_expr _   (Lit lit)    = fromIntegral (hashLiteral lit)
1495 fast_hash_expr env (Cast e _)   = fast_hash_expr env e
1496 fast_hash_expr env (Note _ e)   = fast_hash_expr env e
1497 fast_hash_expr env (App _ a)    = fast_hash_expr env a  -- A bit idiosyncratic ('a' not 'f')!
1498 fast_hash_expr _   _            = 1
1499
1500 fast_hash_type :: HashEnv -> Type -> Word32
1501 fast_hash_type env ty 
1502   | Just tv <- getTyVar_maybe ty            = hashVar env tv
1503   | Just (tc,tys) <- splitTyConApp_maybe ty = let hash_tc = fromIntegral (hashName (tyConName tc))
1504                                               in foldr (\t n -> fast_hash_type env t + n) hash_tc tys
1505   | otherwise                               = 1
1506
1507 extend_env :: HashEnv -> Var -> (Int, VarEnv Int)
1508 extend_env (n,env) b = (n+1, extendVarEnv env b n)
1509
1510 hashVar :: HashEnv -> Var -> Word32
1511 hashVar (_,env) v
1512  = fromIntegral (lookupVarEnv env v `orElse` hashName (idName v))
1513 \end{code}
1514
1515 %************************************************************************
1516 %*                                                                      *
1517 \subsection{Determining non-updatable right-hand-sides}
1518 %*                                                                      *
1519 %************************************************************************
1520
1521 Top-level constructor applications can usually be allocated
1522 statically, but they can't if the constructor, or any of the
1523 arguments, come from another DLL (because we can't refer to static
1524 labels in other DLLs).
1525
1526 If this happens we simply make the RHS into an updatable thunk, 
1527 and 'execute' it rather than allocating it statically.
1528
1529 \begin{code}
1530 -- | This function is called only on *top-level* right-hand sides.
1531 -- Returns @True@ if the RHS can be allocated statically in the output,
1532 -- with no thunks involved at all.
1533 rhsIsStatic :: PackageId -> CoreExpr -> Bool
1534 -- It's called (i) in TidyPgm.hasCafRefs to decide if the rhs is, or
1535 -- refers to, CAFs; (ii) in CoreToStg to decide whether to put an
1536 -- update flag on it and (iii) in DsExpr to decide how to expand
1537 -- list literals
1538 --
1539 -- The basic idea is that rhsIsStatic returns True only if the RHS is
1540 --      (a) a value lambda
1541 --      (b) a saturated constructor application with static args
1542 --
1543 -- BUT watch out for
1544 --  (i) Any cross-DLL references kill static-ness completely
1545 --      because they must be 'executed' not statically allocated
1546 --      ("DLL" here really only refers to Windows DLLs, on other platforms,
1547 --      this is not necessary)
1548 --
1549 -- (ii) We treat partial applications as redexes, because in fact we 
1550 --      make a thunk for them that runs and builds a PAP
1551 --      at run-time.  The only appliations that are treated as 
1552 --      static are *saturated* applications of constructors.
1553
1554 -- We used to try to be clever with nested structures like this:
1555 --              ys = (:) w ((:) w [])
1556 -- on the grounds that CorePrep will flatten ANF-ise it later.
1557 -- But supporting this special case made the function much more 
1558 -- complicated, because the special case only applies if there are no 
1559 -- enclosing type lambdas:
1560 --              ys = /\ a -> Foo (Baz ([] a))
1561 -- Here the nested (Baz []) won't float out to top level in CorePrep.
1562 --
1563 -- But in fact, even without -O, nested structures at top level are 
1564 -- flattened by the simplifier, so we don't need to be super-clever here.
1565 --
1566 -- Examples
1567 --
1568 --      f = \x::Int. x+7        TRUE
1569 --      p = (True,False)        TRUE
1570 --
1571 --      d = (fst p, False)      FALSE because there's a redex inside
1572 --                              (this particular one doesn't happen but...)
1573 --
1574 --      h = D# (1.0## /## 2.0##)        FALSE (redex again)
1575 --      n = /\a. Nil a                  TRUE
1576 --
1577 --      t = /\a. (:) (case w a of ...) (Nil a)  FALSE (redex)
1578 --
1579 --
1580 -- This is a bit like CoreUtils.exprIsHNF, with the following differences:
1581 --    a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
1582 --
1583 --    b) (C x xs), where C is a contructor is updatable if the application is
1584 --         dynamic
1585 -- 
1586 --    c) don't look through unfolding of f in (f x).
1587
1588 rhsIsStatic _this_pkg rhs = is_static False rhs
1589   where
1590   is_static :: Bool     -- True <=> in a constructor argument; must be atomic
1591           -> CoreExpr -> Bool
1592   
1593   is_static False (Lam b e) = isRuntimeVar b || is_static False e
1594   
1595   is_static _      (Note (SCC _) _) = False
1596   is_static in_arg (Note _ e)       = is_static in_arg e
1597   is_static in_arg (Cast e _)       = is_static in_arg e
1598   
1599   is_static _      (Lit lit)
1600     = case lit of
1601         MachLabel _ _ -> False
1602         _             -> True
1603         -- A MachLabel (foreign import "&foo") in an argument
1604         -- prevents a constructor application from being static.  The
1605         -- reason is that it might give rise to unresolvable symbols
1606         -- in the object file: under Linux, references to "weak"
1607         -- symbols from the data segment give rise to "unresolvable
1608         -- relocation" errors at link time This might be due to a bug
1609         -- in the linker, but we'll work around it here anyway. 
1610         -- SDM 24/2/2004
1611   
1612   is_static in_arg other_expr = go other_expr 0
1613    where
1614     go (Var f) n_val_args
1615 #if mingw32_TARGET_OS
1616         | not (isDllName _this_pkg (idName f))
1617 #endif
1618         =  saturated_data_con f n_val_args
1619         || (in_arg && n_val_args == 0)  
1620                 -- A naked un-applied variable is *not* deemed a static RHS
1621                 -- E.g.         f = g
1622                 -- Reason: better to update so that the indirection gets shorted
1623                 --         out, and the true value will be seen
1624                 -- NB: if you change this, you'll break the invariant that THUNK_STATICs
1625                 --     are always updatable.  If you do so, make sure that non-updatable
1626                 --     ones have enough space for their static link field!
1627
1628     go (App f a) n_val_args
1629         | isTypeArg a                    = go f n_val_args
1630         | not in_arg && is_static True a = go f (n_val_args + 1)
1631         -- The (not in_arg) checks that we aren't in a constructor argument;
1632         -- if we are, we don't allow (value) applications of any sort
1633         -- 
1634         -- NB. In case you wonder, args are sometimes not atomic.  eg.
1635         --   x = D# (1.0## /## 2.0##)
1636         -- can't float because /## can fail.
1637
1638     go (Note (SCC _) _) _          = False
1639     go (Note _ f)       n_val_args = go f n_val_args
1640     go (Cast e _)       n_val_args = go e n_val_args
1641
1642     go _                _          = False
1643
1644     saturated_data_con f n_val_args
1645         = case isDataConWorkId_maybe f of
1646             Just dc -> n_val_args == dataConRepArity dc
1647             Nothing -> False
1648 \end{code}