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