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