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