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