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