Haddock fix in the vectoriser
[ghc-hetmet.git] / compiler / coreSyn / CoreSyn.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 \begin{code}
7 {-# LANGUAGE DeriveDataTypeable, DeriveFunctor #-}
8
9 -- | CoreSyn holds all the main data types for use by for the Glasgow Haskell Compiler midsection
10 module CoreSyn (
11         -- * Main data types
12         Expr(..), Alt, Bind(..), AltCon(..), Arg, Note(..),
13         CoreExpr, CoreAlt, CoreBind, CoreArg, CoreBndr,
14         TaggedExpr, TaggedAlt, TaggedBind, TaggedArg, TaggedBndr(..),
15
16         -- ** 'Expr' construction
17         mkLets, mkLams,
18         mkApps, mkTyApps, mkCoApps, mkVarApps,
19         
20         mkIntLit, mkIntLitInt,
21         mkWordLit, mkWordLitWord,
22         mkCharLit, mkStringLit,
23         mkFloatLit, mkFloatLitFloat,
24         mkDoubleLit, mkDoubleLitDouble,
25         
26         mkConApp, mkTyBind, mkCoBind,
27         varToCoreExpr, varsToCoreExprs,
28
29         isId, cmpAltCon, cmpAlt, ltAlt,
30         
31         -- ** Simple 'Expr' access functions and predicates
32         bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts, 
33         collectBinders, collectTyBinders, collectValBinders, collectTyAndValBinders,
34         collectArgs, coreExprCc, flattenBinds, 
35
36         isValArg, isTypeArg, isTyCoArg, valArgCount, valBndrCount,
37         isRuntimeArg, isRuntimeVar,
38         notSccNote,
39
40         -- * Unfolding data types
41         Unfolding(..),  UnfoldingGuidance(..), UnfoldingSource(..),
42         DFunArg(..), dfunArgExprs,
43
44         -- ** Constructing 'Unfolding's
45         noUnfolding, evaldUnfolding, mkOtherCon,
46         unSaturatedOk, needSaturated, boringCxtOk, boringCxtNotOk,
47         
48         -- ** Predicates and deconstruction on 'Unfolding'
49         unfoldingTemplate, setUnfoldingTemplate, expandUnfolding_maybe,
50         maybeUnfoldingTemplate, otherCons, unfoldingArity,
51         isValueUnfolding, isEvaldUnfolding, isCheapUnfolding,
52         isExpandableUnfolding, isConLikeUnfolding, isCompulsoryUnfolding,
53         isStableUnfolding, isStableCoreUnfolding_maybe,
54         isClosedUnfolding, hasSomeUnfolding, 
55         canUnfold, neverUnfoldGuidance, isStableSource,
56
57         -- * Strictness
58         seqExpr, seqExprs, seqUnfolding, 
59
60         -- * Annotated expression data types
61         AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt,
62         
63         -- ** Operations on annotated expressions
64         collectAnnArgs,
65
66         -- ** Operations on annotations
67         deAnnotate, deAnnotate', deAnnAlt, collectAnnBndrs,
68
69         -- * Core rule data types
70         CoreRule(..),   -- CoreSubst, CoreTidy, CoreFVs, PprCore only
71         RuleName, IdUnfoldingFun,
72         
73         -- ** Operations on 'CoreRule's 
74         seqRules, ruleArity, ruleName, ruleIdName, ruleActivation,
75         setRuleIdName,
76         isBuiltinRule, isLocalRule,
77
78         -- * Core vectorisation declarations data type
79         CoreVect(..)
80     ) where
81
82 #include "HsVersions.h"
83
84 import CostCentre
85 import Var
86 import Type
87 import Coercion
88 import Name
89 import Literal
90 import DataCon
91 import BasicTypes
92 import FastString
93 import Outputable
94 import Util
95
96 import Data.Data
97 import Data.Word
98
99 infixl 4 `mkApps`, `mkTyApps`, `mkVarApps`, `App`, `mkCoApps`
100 -- Left associative, so that we can say (f `mkTyApps` xs `mkVarApps` ys)
101 \end{code}
102
103 %************************************************************************
104 %*                                                                      *
105 \subsection{The main data types}
106 %*                                                                      *
107 %************************************************************************
108
109 These data types are the heart of the compiler
110
111 \begin{code}
112 -- | This is the data type that represents GHCs core intermediate language. Currently
113 -- GHC uses System FC <http://research.microsoft.com/~simonpj/papers/ext-f/> for this purpose,
114 -- which is closely related to the simpler and better known System F <http://en.wikipedia.org/wiki/System_F>.
115 --
116 -- We get from Haskell source to this Core language in a number of stages:
117 --
118 -- 1. The source code is parsed into an abstract syntax tree, which is represented
119 --    by the data type 'HsExpr.HsExpr' with the names being 'RdrName.RdrNames'
120 --
121 -- 2. This syntax tree is /renamed/, which attaches a 'Unique.Unique' to every 'RdrName.RdrName'
122 --    (yielding a 'Name.Name') to disambiguate identifiers which are lexically identical. 
123 --    For example, this program:
124 --
125 -- @
126 --      f x = let f x = x + 1
127 --            in f (x - 2)
128 -- @
129 --
130 --    Would be renamed by having 'Unique's attached so it looked something like this:
131 --
132 -- @
133 --      f_1 x_2 = let f_3 x_4 = x_4 + 1
134 --                in f_3 (x_2 - 2)
135 -- @
136 --
137 -- 3. The resulting syntax tree undergoes type checking (which also deals with instantiating
138 --    type class arguments) to yield a 'HsExpr.HsExpr' type that has 'Id.Id' as it's names.
139 --
140 -- 4. Finally the syntax tree is /desugared/ from the expressive 'HsExpr.HsExpr' type into
141 --    this 'Expr' type, which has far fewer constructors and hence is easier to perform
142 --    optimization, analysis and code generation on.
143 --
144 -- The type parameter @b@ is for the type of binders in the expression tree.
145 data Expr b
146   = Var   Id                            -- ^ Variables
147
148   | Lit   Literal                       -- ^ Primitive literals
149
150   | App   (Expr b) (Arg b)              -- ^ Applications: note that the argument may be a 'Type'.
151                                         --
152                                         -- See "CoreSyn#let_app_invariant" for another invariant
153
154   | Lam   b (Expr b)                    -- ^ Lambda abstraction
155
156   | Let   (Bind b) (Expr b)             -- ^ Recursive and non recursive @let@s. Operationally
157                                         -- this corresponds to allocating a thunk for the things
158                                         -- bound and then executing the sub-expression.
159                                         -- 
160                                         -- #top_level_invariant#
161                                         -- #letrec_invariant#
162                                         --
163                                         -- The right hand sides of all top-level and recursive @let@s
164                                         -- /must/ be of lifted type (see "Type#type_classification" for
165                                         -- the meaning of /lifted/ vs. /unlifted/).
166                                         --
167                                         -- #let_app_invariant#
168                                         -- The right hand side of of a non-recursive 'Let' 
169                                         -- _and_ the argument of an 'App',
170                                         -- /may/ be of unlifted type, but only if the expression 
171                                         -- is ok-for-speculation.  This means that the let can be floated 
172                                         -- around without difficulty. For example, this is OK:
173                                         --
174                                         -- > y::Int# = x +# 1#
175                                         --
176                                         -- But this is not, as it may affect termination if the 
177                                         -- expression is floated out:
178                                         --
179                                         -- > y::Int# = fac 4#
180                                         --
181                                         -- In this situation you should use @case@ rather than a @let@. The function
182                                         -- 'CoreUtils.needsCaseBinding' can help you determine which to generate, or
183                                         -- alternatively use 'MkCore.mkCoreLet' rather than this constructor directly,
184                                         -- which will generate a @case@ if necessary
185                                         --
186                                         -- #type_let#
187                                         -- We allow a /non-recursive/ let to bind a type variable, thus:
188                                         --
189                                         -- > Let (NonRec tv (Type ty)) body
190                                         --
191                                         -- This can be very convenient for postponing type substitutions until
192                                         -- the next run of the simplifier.
193                                         --
194                                         -- At the moment, the rest of the compiler only deals with type-let
195                                         -- in a Let expression, rather than at top level.  We may want to revist
196                                         -- this choice.
197
198   | Case  (Expr b) b Type [Alt b]       -- ^ Case split. Operationally this corresponds to evaluating
199                                         -- the scrutinee (expression examined) to weak head normal form
200                                         -- and then examining at most one level of resulting constructor (i.e. you
201                                         -- cannot do nested pattern matching directly with this).
202                                         --
203                                         -- The binder gets bound to the value of the scrutinee,
204                                         -- and the 'Type' must be that of all the case alternatives
205                                         --
206                                         -- #case_invariants#
207                                         -- This is one of the more complicated elements of the Core language, 
208                                         -- and comes with a number of restrictions:
209                                         --
210                                         -- The 'DEFAULT' case alternative must be first in the list, 
211                                         -- if it occurs at all.
212                                         --
213                                         -- The remaining cases are in order of increasing 
214                                         --      tag     (for 'DataAlts') or
215                                         --      lit     (for 'LitAlts').
216                                         -- This makes finding the relevant constructor easy, 
217                                         -- and makes comparison easier too.
218                                         --
219                                         -- The list of alternatives must be exhaustive. An /exhaustive/ case 
220                                         -- does not necessarily mention all constructors:
221                                         --
222                                         -- @
223                                         --      data Foo = Red | Green | Blue
224                                         -- ... case x of 
225                                         --      Red   -> True
226                                         --      other -> f (case x of 
227                                         --                      Green -> ...
228                                         --                      Blue  -> ... ) ...
229                                         -- @
230                                         --
231                                         -- The inner case does not need a @Red@ alternative, because @x@ 
232                                         -- can't be @Red@ at that program point.
233
234   | Cast  (Expr b) Coercion             -- ^ Cast an expression to a particular type. 
235                                         -- This is used to implement @newtype@s (a @newtype@ constructor or 
236                                         -- destructor just becomes a 'Cast' in Core) and GADTs.
237
238   | Note  Note (Expr b)                 -- ^ Notes. These allow general information to be
239                                         -- added to expressions in the syntax tree
240
241   | Type  Type                          -- ^ A type: this should only show up at the top
242                                         -- level of an Arg
243     
244   | Coercion Coercion                   -- ^ A coercion
245   deriving (Data, Typeable)
246
247 -- | Type synonym for expressions that occur in function argument positions.
248 -- Only 'Arg' should contain a 'Type' at top level, general 'Expr' should not
249 type Arg b = Expr b
250
251 -- | A case split alternative. Consists of the constructor leading to the alternative,
252 -- the variables bound from the constructor, and the expression to be executed given that binding.
253 -- The default alternative is @(DEFAULT, [], rhs)@
254 type Alt b = (AltCon, [b], Expr b)
255
256 -- | A case alternative constructor (i.e. pattern match)
257 data AltCon = DataAlt DataCon   -- ^ A plain data constructor: @case e of { Foo x -> ... }@.
258                                 -- Invariant: the 'DataCon' is always from a @data@ type, and never from a @newtype@
259             | LitAlt  Literal   -- ^ A literal: @case e of { 1 -> ... }@
260             | DEFAULT           -- ^ Trivial alternative: @case e of { _ -> ... }@
261          deriving (Eq, Ord, Data, Typeable)
262
263 -- | Binding, used for top level bindings in a module and local bindings in a @let@.
264 data Bind b = NonRec b (Expr b)
265             | Rec [(b, (Expr b))]
266   deriving (Data, Typeable)
267 \end{code}
268
269 -------------------------- CoreSyn INVARIANTS ---------------------------
270
271 Note [CoreSyn top-level invariant]
272 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
273 See #toplevel_invariant#
274
275 Note [CoreSyn letrec invariant]
276 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
277 See #letrec_invariant#
278
279 Note [CoreSyn let/app invariant]
280 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
281 See #let_app_invariant#
282
283 This is intially enforced by DsUtils.mkCoreLet and mkCoreApp
284
285 Note [CoreSyn case invariants]
286 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
287 See #case_invariants#
288
289 Note [CoreSyn let goal]
290 ~~~~~~~~~~~~~~~~~~~~~~~
291 * The simplifier tries to ensure that if the RHS of a let is a constructor
292   application, its arguments are trivial, so that the constructor can be
293   inlined vigorously.
294
295
296 Note [Type let]
297 ~~~~~~~~~~~~~~~
298 See #type_let#
299
300 \begin{code}
301
302 -- | Allows attaching extra information to points in expressions rather than e.g. identifiers.
303 data Note
304   = SCC CostCentre      -- ^ A cost centre annotation for profiling
305   | CoreNote String     -- ^ A generic core annotation, propagated but not used by GHC
306   deriving (Data, Typeable)
307 \end{code}
308
309
310 %************************************************************************
311 %*                                                                      *
312 \subsection{Transformation rules}
313 %*                                                                      *
314 %************************************************************************
315
316 The CoreRule type and its friends are dealt with mainly in CoreRules,
317 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
318
319 \begin{code}
320 -- | A 'CoreRule' is:
321 --
322 -- * \"Local\" if the function it is a rule for is defined in the
323 --   same module as the rule itself.
324 --
325 -- * \"Orphan\" if nothing on the LHS is defined in the same module
326 --   as the rule itself
327 data CoreRule
328   = Rule { 
329         ru_name :: RuleName,            -- ^ Name of the rule, for communication with the user
330         ru_act  :: Activation,          -- ^ When the rule is active
331
332         -- Rough-matching stuff
333         -- see comments with InstEnv.Instance( is_cls, is_rough )
334         ru_fn    :: Name,               -- ^ Name of the 'Id.Id' at the head of this rule
335         ru_rough :: [Maybe Name],       -- ^ Name at the head of each argument to the left hand side
336         
337         -- Proper-matching stuff
338         -- see comments with InstEnv.Instance( is_tvs, is_tys )
339         ru_bndrs :: [CoreBndr],         -- ^ Variables quantified over
340         ru_args  :: [CoreExpr],         -- ^ Left hand side arguments
341         
342         -- And the right-hand side
343         ru_rhs   :: CoreExpr,           -- ^ Right hand side of the rule
344                                         -- Occurrence info is guaranteed correct
345                                         -- See Note [OccInfo in unfoldings and rules]
346
347         -- Locality
348         ru_auto :: Bool,        -- ^ @True@  <=> this rule is auto-generated
349                                 --   @False@ <=> generated at the users behest
350                                 --   Main effect: reporting of orphan-hood
351
352         ru_local :: Bool        -- ^ @True@ iff the fn at the head of the rule is
353                                 -- defined in the same module as the rule
354                                 -- and is not an implicit 'Id' (like a record selector,
355                                 -- class operation, or data constructor)
356
357                 -- NB: ru_local is *not* used to decide orphan-hood
358                 --      c.g. MkIface.coreRuleToIfaceRule
359     }
360
361   -- | Built-in rules are used for constant folding
362   -- and suchlike.  They have no free variables.
363   | BuiltinRule {               
364         ru_name  :: RuleName,   -- ^ As above
365         ru_fn    :: Name,       -- ^ As above
366         ru_nargs :: Int,        -- ^ Number of arguments that 'ru_try' consumes,
367                                 -- if it fires, including type arguments
368         ru_try  :: IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
369                 -- ^ This function does the rewrite.  It given too many
370                 -- arguments, it simply discards them; the returned 'CoreExpr'
371                 -- is just the rewrite of 'ru_fn' applied to the first 'ru_nargs' args
372     }
373                 -- See Note [Extra args in rule matching] in Rules.lhs
374
375 type IdUnfoldingFun = Id -> Unfolding
376 -- A function that embodies how to unfold an Id if you need
377 -- to do that in the Rule.  The reason we need to pass this info in
378 -- is that whether an Id is unfoldable depends on the simplifier phase
379
380 isBuiltinRule :: CoreRule -> Bool
381 isBuiltinRule (BuiltinRule {}) = True
382 isBuiltinRule _                = False
383
384 -- | The number of arguments the 'ru_fn' must be applied 
385 -- to before the rule can match on it
386 ruleArity :: CoreRule -> Int
387 ruleArity (BuiltinRule {ru_nargs = n}) = n
388 ruleArity (Rule {ru_args = args})      = length args
389
390 ruleName :: CoreRule -> RuleName
391 ruleName = ru_name
392
393 ruleActivation :: CoreRule -> Activation
394 ruleActivation (BuiltinRule { })       = AlwaysActive
395 ruleActivation (Rule { ru_act = act }) = act
396
397 -- | The 'Name' of the 'Id.Id' at the head of the rule left hand side
398 ruleIdName :: CoreRule -> Name
399 ruleIdName = ru_fn
400
401 isLocalRule :: CoreRule -> Bool
402 isLocalRule = ru_local
403
404 -- | Set the 'Name' of the 'Id.Id' at the head of the rule left hand side
405 setRuleIdName :: Name -> CoreRule -> CoreRule
406 setRuleIdName nm ru = ru { ru_fn = nm }
407 \end{code}
408
409
410 %************************************************************************
411 %*                                                                      *
412 \subsection{Vectorisation declarations}
413 %*                                                                      *
414 %************************************************************************
415
416 Representation of desugared vectorisation declarations that are fed to the vectoriser (via
417 'ModGuts').
418
419 \begin{code}
420 data CoreVect = Vect Id (Maybe CoreExpr)
421 \end{code}
422
423
424 %************************************************************************
425 %*                                                                      *
426                 Unfoldings
427 %*                                                                      *
428 %************************************************************************
429
430 The @Unfolding@ type is declared here to avoid numerous loops
431
432 \begin{code}
433 -- | Records the /unfolding/ of an identifier, which is approximately the form the
434 -- identifier would have if we substituted its definition in for the identifier.
435 -- This type should be treated as abstract everywhere except in "CoreUnfold"
436 data Unfolding
437   = NoUnfolding        -- ^ We have no information about the unfolding
438
439   | OtherCon [AltCon]  -- ^ It ain't one of these constructors.
440                        -- @OtherCon xs@ also indicates that something has been evaluated
441                        -- and hence there's no point in re-evaluating it.
442                        -- @OtherCon []@ is used even for non-data-type values
443                        -- to indicated evaluated-ness.  Notably:
444                        --
445                        -- > data C = C !(Int -> Int)
446                        -- > case x of { C f -> ... }
447                        --
448                        -- Here, @f@ gets an @OtherCon []@ unfolding.
449
450   | DFunUnfolding       -- The Unfolding of a DFunId  
451                         -- See Note [DFun unfoldings]
452                         --     df = /\a1..am. \d1..dn. MkD (op1 a1..am d1..dn)
453                         --                                 (op2 a1..am d1..dn)
454
455         Arity           -- Arity = m+n, the *total* number of args 
456                         --   (unusually, both type and value) to the dfun
457
458         DataCon         -- The dictionary data constructor (possibly a newtype datacon)
459
460         [DFunArg CoreExpr]  -- Specification of superclasses and methods, in positional order
461
462   | CoreUnfolding {             -- An unfolding for an Id with no pragma, 
463                                 -- or perhaps a NOINLINE pragma
464                                 -- (For NOINLINE, the phase, if any, is in the 
465                                 -- InlinePragInfo for this Id.)
466         uf_tmpl       :: CoreExpr,        -- Template; occurrence info is correct
467         uf_src        :: UnfoldingSource, -- Where the unfolding came from
468         uf_is_top     :: Bool,          -- True <=> top level binding
469         uf_arity      :: Arity,         -- Number of value arguments expected
470         uf_is_value   :: Bool,          -- exprIsHNF template (cached); it is ok to discard 
471                                         --      a `seq` on this variable
472         uf_is_conlike :: Bool,          -- True <=> applicn of constructor or CONLIKE function
473                                         --      Cached version of exprIsConLike
474         uf_is_cheap   :: Bool,          -- True <=> doesn't waste (much) work to expand 
475                                         --          inside an inlining
476                                         --      Cached version of exprIsCheap
477         uf_expandable :: Bool,          -- True <=> can expand in RULE matching
478                                         --      Cached version of exprIsExpandable
479         uf_guidance   :: UnfoldingGuidance      -- Tells about the *size* of the template.
480     }
481   -- ^ An unfolding with redundant cached information. Parameters:
482   --
483   --  uf_tmpl: Template used to perform unfolding; 
484   --           NB: Occurrence info is guaranteed correct: 
485   --               see Note [OccInfo in unfoldings and rules]
486   --
487   --  uf_is_top: Is this a top level binding?
488   --
489   --  uf_is_value: 'exprIsHNF' template (cached); it is ok to discard a 'seq' on
490   --     this variable
491   --
492   --  uf_is_cheap:  Does this waste only a little work if we expand it inside an inlining?
493   --     Basically this is a cached version of 'exprIsCheap'
494   --
495   --  uf_guidance:  Tells us about the /size/ of the unfolding template
496
497 ------------------------------------------------
498 data DFunArg e   -- Given (df a b d1 d2 d3)
499   = DFunPolyArg  e      -- Arg is (e a b d1 d2 d3)
500   | DFunConstArg e      -- Arg is e, which is constant
501   | DFunLamArg   Int    -- Arg is one of [a,b,d1,d2,d3], zero indexed
502   deriving( Functor )
503
504   -- 'e' is often CoreExpr, which are usually variables, but can
505   -- be trivial expressions instead (e.g. a type application).
506
507 dfunArgExprs :: [DFunArg e] -> [e]
508 dfunArgExprs [] = []
509 dfunArgExprs (DFunPolyArg  e : as) = e : dfunArgExprs as
510 dfunArgExprs (DFunConstArg e : as) = e : dfunArgExprs as
511 dfunArgExprs (DFunLamArg {}  : as) =     dfunArgExprs as
512
513
514 ------------------------------------------------
515 data UnfoldingSource
516   = InlineRhs          -- The current rhs of the function
517                        -- Replace uf_tmpl each time around
518
519   | InlineStable       -- From an INLINE or INLINABLE pragma 
520                        --   INLINE     if guidance is UnfWhen
521                        --   INLINABLE  if guidance is UnfIfGoodArgs/UnfoldNever
522                        -- (well, technically an INLINABLE might be made
523                        -- UnfWhen if it was small enough, and then
524                        -- it will behave like INLINE outside the current
525                        -- module, but that is the way automatic unfoldings
526                        -- work so it is consistent with the intended
527                        -- meaning of INLINABLE).
528                        --
529                        -- uf_tmpl may change, but only as a result of
530                        -- gentle simplification, it doesn't get updated
531                        -- to the current RHS during compilation as with
532                        -- InlineRhs.
533                        --
534                        -- See Note [InlineRules]
535
536   | InlineCompulsory   -- Something that *has* no binding, so you *must* inline it
537                        -- Only a few primop-like things have this property 
538                        -- (see MkId.lhs, calls to mkCompulsoryUnfolding).
539                        -- Inline absolutely always, however boring the context.
540
541   | InlineWrapper Id   -- This unfolding is a the wrapper in a 
542                        --     worker/wrapper split from the strictness analyser
543                        -- The Id is the worker-id
544                        -- Used to abbreviate the uf_tmpl in interface files
545                        --       which don't need to contain the RHS; 
546                        --       it can be derived from the strictness info
547
548
549
550 -- | 'UnfoldingGuidance' says when unfolding should take place
551 data UnfoldingGuidance
552   = UnfWhen {   -- Inline without thinking about the *size* of the uf_tmpl
553                 -- Used (a) for small *and* cheap unfoldings
554                 --      (b) for INLINE functions 
555                 -- See Note [INLINE for small functions] in CoreUnfold
556       ug_unsat_ok  :: Bool,     -- True <=> ok to inline even if unsaturated
557       ug_boring_ok :: Bool      -- True <=> ok to inline even if the context is boring
558                 -- So True,True means "always"
559     }
560
561   | UnfIfGoodArgs {     -- Arose from a normal Id; the info here is the
562                         -- result of a simple analysis of the RHS
563
564       ug_args ::  [Int],  -- Discount if the argument is evaluated.
565                           -- (i.e., a simplification will definitely
566                           -- be possible).  One elt of the list per *value* arg.
567
568       ug_size :: Int,     -- The "size" of the unfolding.
569
570       ug_res :: Int       -- Scrutinee discount: the discount to substract if the thing is in
571     }                     -- a context (case (thing args) of ...),
572                           -- (where there are the right number of arguments.)
573
574   | UnfNever        -- The RHS is big, so don't inline it
575 \end{code}
576
577
578 Note [DFun unfoldings]
579 ~~~~~~~~~~~~~~~~~~~~~~
580 The Arity in a DFunUnfolding is total number of args (type and value)
581 that the DFun needs to produce a dictionary.  That's not necessarily 
582 related to the ordinary arity of the dfun Id, esp if the class has
583 one method, so the dictionary is represented by a newtype.  Example
584
585      class C a where { op :: a -> Int }
586      instance C a -> C [a] where op xs = op (head xs)
587
588 The instance translates to
589
590      $dfCList :: forall a. C a => C [a]  -- Arity 2!
591      $dfCList = /\a.\d. $copList {a} d |> co
592  
593      $copList :: forall a. C a => [a] -> Int  -- Arity 2!
594      $copList = /\a.\d.\xs. op {a} d (head xs)
595
596 Now we might encounter (op (dfCList {ty} d) a1 a2)
597 and we want the (op (dfList {ty} d)) rule to fire, because $dfCList
598 has all its arguments, even though its (value) arity is 2.  That's
599 why we record the number of expected arguments in the DFunUnfolding.
600
601 Note that although it's an Arity, it's most convenient for it to give
602 the *total* number of arguments, both type and value.  See the use
603 site in exprIsConApp_maybe.
604
605 \begin{code}
606 -- Constants for the UnfWhen constructor
607 needSaturated, unSaturatedOk :: Bool
608 needSaturated = False
609 unSaturatedOk = True
610
611 boringCxtNotOk, boringCxtOk :: Bool
612 boringCxtOk    = True
613 boringCxtNotOk = False
614
615 ------------------------------------------------
616 noUnfolding :: Unfolding
617 -- ^ There is no known 'Unfolding'
618 evaldUnfolding :: Unfolding
619 -- ^ This unfolding marks the associated thing as being evaluated
620
621 noUnfolding    = NoUnfolding
622 evaldUnfolding = OtherCon []
623
624 mkOtherCon :: [AltCon] -> Unfolding
625 mkOtherCon = OtherCon
626
627 seqUnfolding :: Unfolding -> ()
628 seqUnfolding (CoreUnfolding { uf_tmpl = e, uf_is_top = top, 
629                 uf_is_value = b1, uf_is_cheap = b2, 
630                 uf_expandable = b3, uf_is_conlike = b4,
631                 uf_arity = a, uf_guidance = g})
632   = seqExpr e `seq` top `seq` b1 `seq` a `seq` b2 `seq` b3 `seq` b4 `seq` seqGuidance g
633
634 seqUnfolding _ = ()
635
636 seqGuidance :: UnfoldingGuidance -> ()
637 seqGuidance (UnfIfGoodArgs ns n b) = n `seq` sum ns `seq` b `seq` ()
638 seqGuidance _                      = ()
639 \end{code}
640
641 \begin{code}
642 isStableSource :: UnfoldingSource -> Bool
643 -- Keep the unfolding template
644 isStableSource InlineCompulsory   = True
645 isStableSource InlineStable       = True
646 isStableSource (InlineWrapper {}) = True
647 isStableSource InlineRhs          = False
648  
649 -- | Retrieves the template of an unfolding: panics if none is known
650 unfoldingTemplate :: Unfolding -> CoreExpr
651 unfoldingTemplate = uf_tmpl
652
653 setUnfoldingTemplate :: Unfolding -> CoreExpr -> Unfolding
654 setUnfoldingTemplate unf rhs = unf { uf_tmpl = rhs }
655
656 -- | Retrieves the template of an unfolding if possible
657 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
658 maybeUnfoldingTemplate (CoreUnfolding { uf_tmpl = expr })       = Just expr
659 maybeUnfoldingTemplate _                                        = Nothing
660
661 -- | The constructors that the unfolding could never be: 
662 -- returns @[]@ if no information is available
663 otherCons :: Unfolding -> [AltCon]
664 otherCons (OtherCon cons) = cons
665 otherCons _               = []
666
667 -- | Determines if it is certainly the case that the unfolding will
668 -- yield a value (something in HNF): returns @False@ if unsure
669 isValueUnfolding :: Unfolding -> Bool
670         -- Returns False for OtherCon
671 isValueUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald
672 isValueUnfolding _                                          = False
673
674 -- | Determines if it possibly the case that the unfolding will
675 -- yield a value. Unlike 'isValueUnfolding' it returns @True@
676 -- for 'OtherCon'
677 isEvaldUnfolding :: Unfolding -> Bool
678         -- Returns True for OtherCon
679 isEvaldUnfolding (OtherCon _)                               = True
680 isEvaldUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald
681 isEvaldUnfolding _                                          = False
682
683 -- | @True@ if the unfolding is a constructor application, the application
684 -- of a CONLIKE function or 'OtherCon'
685 isConLikeUnfolding :: Unfolding -> Bool
686 isConLikeUnfolding (OtherCon _)                             = True
687 isConLikeUnfolding (CoreUnfolding { uf_is_conlike = con })  = con
688 isConLikeUnfolding _                                        = False
689
690 -- | Is the thing we will unfold into certainly cheap?
691 isCheapUnfolding :: Unfolding -> Bool
692 isCheapUnfolding (CoreUnfolding { uf_is_cheap = is_cheap }) = is_cheap
693 isCheapUnfolding _                                          = False
694
695 isExpandableUnfolding :: Unfolding -> Bool
696 isExpandableUnfolding (CoreUnfolding { uf_expandable = is_expable }) = is_expable
697 isExpandableUnfolding _                                              = False
698
699 expandUnfolding_maybe :: Unfolding -> Maybe CoreExpr
700 -- Expand an expandable unfolding; this is used in rule matching 
701 --   See Note [Expanding variables] in Rules.lhs
702 -- The key point here is that CONLIKE things can be expanded
703 expandUnfolding_maybe (CoreUnfolding { uf_expandable = True, uf_tmpl = rhs }) = Just rhs
704 expandUnfolding_maybe _                                                       = Nothing
705
706 isStableCoreUnfolding_maybe :: Unfolding -> Maybe UnfoldingSource
707 isStableCoreUnfolding_maybe (CoreUnfolding { uf_src = src })
708    | isStableSource src   = Just src
709 isStableCoreUnfolding_maybe _ = Nothing
710
711 isCompulsoryUnfolding :: Unfolding -> Bool
712 isCompulsoryUnfolding (CoreUnfolding { uf_src = InlineCompulsory }) = True
713 isCompulsoryUnfolding _                                             = False
714
715 isStableUnfolding :: Unfolding -> Bool
716 -- True of unfoldings that should not be overwritten 
717 -- by a CoreUnfolding for the RHS of a let-binding
718 isStableUnfolding (CoreUnfolding { uf_src = src }) = isStableSource src
719 isStableUnfolding (DFunUnfolding {})               = True
720 isStableUnfolding _                                = False
721
722 unfoldingArity :: Unfolding -> Arity
723 unfoldingArity (CoreUnfolding { uf_arity = arity }) = arity
724 unfoldingArity _                                    = panic "unfoldingArity"
725
726 isClosedUnfolding :: Unfolding -> Bool          -- No free variables
727 isClosedUnfolding (CoreUnfolding {}) = False
728 isClosedUnfolding (DFunUnfolding {}) = False
729 isClosedUnfolding _                  = True
730
731 -- | Only returns False if there is no unfolding information available at all
732 hasSomeUnfolding :: Unfolding -> Bool
733 hasSomeUnfolding NoUnfolding = False
734 hasSomeUnfolding _           = True
735
736 neverUnfoldGuidance :: UnfoldingGuidance -> Bool
737 neverUnfoldGuidance UnfNever = True
738 neverUnfoldGuidance _        = False
739
740 canUnfold :: Unfolding -> Bool
741 canUnfold (CoreUnfolding { uf_guidance = g }) = not (neverUnfoldGuidance g)
742 canUnfold _                                   = False
743 \end{code}
744
745 Note [InlineRules]
746 ~~~~~~~~~~~~~~~~~
747 When you say 
748       {-# INLINE f #-}
749       f x = <rhs>
750 you intend that calls (f e) are replaced by <rhs>[e/x] So we
751 should capture (\x.<rhs>) in the Unfolding of 'f', and never meddle
752 with it.  Meanwhile, we can optimise <rhs> to our heart's content,
753 leaving the original unfolding intact in Unfolding of 'f'. For example
754         all xs = foldr (&&) True xs
755         any p = all . map p  {-# INLINE any #-}
756 We optimise any's RHS fully, but leave the InlineRule saying "all . map p",
757 which deforests well at the call site.
758
759 So INLINE pragma gives rise to an InlineRule, which captures the original RHS.
760
761 Moreover, it's only used when 'f' is applied to the
762 specified number of arguments; that is, the number of argument on 
763 the LHS of the '=' sign in the original source definition. 
764 For example, (.) is now defined in the libraries like this
765    {-# INLINE (.) #-}
766    (.) f g = \x -> f (g x)
767 so that it'll inline when applied to two arguments. If 'x' appeared
768 on the left, thus
769    (.) f g x = f (g x)
770 it'd only inline when applied to three arguments.  This slightly-experimental
771 change was requested by Roman, but it seems to make sense.
772
773 See also Note [Inlining an InlineRule] in CoreUnfold.
774
775
776 Note [OccInfo in unfoldings and rules]
777 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
778 In unfoldings and rules, we guarantee that the template is occ-analysed,
779 so that the occurence info on the binders is correct.  This is important,
780 because the Simplifier does not re-analyse the template when using it. If
781 the occurrence info is wrong
782   - We may get more simpifier iterations than necessary, because
783     once-occ info isn't there
784   - More seriously, we may get an infinite loop if there's a Rec
785     without a loop breaker marked
786
787
788 %************************************************************************
789 %*                                                                      *
790 \subsection{The main data type}
791 %*                                                                      *
792 %************************************************************************
793
794 \begin{code}
795 -- The Ord is needed for the FiniteMap used in the lookForConstructor
796 -- in SimplEnv.  If you declared that lookForConstructor *ignores*
797 -- constructor-applications with LitArg args, then you could get
798 -- rid of this Ord.
799
800 instance Outputable AltCon where
801   ppr (DataAlt dc) = ppr dc
802   ppr (LitAlt lit) = ppr lit
803   ppr DEFAULT      = ptext (sLit "__DEFAULT")
804
805 instance Show AltCon where
806   showsPrec p con = showsPrecSDoc p (ppr con)
807
808 cmpAlt :: Alt b -> Alt b -> Ordering
809 cmpAlt (con1, _, _) (con2, _, _) = con1 `cmpAltCon` con2
810
811 ltAlt :: Alt b -> Alt b -> Bool
812 ltAlt a1 a2 = (a1 `cmpAlt` a2) == LT
813
814 cmpAltCon :: AltCon -> AltCon -> Ordering
815 -- ^ Compares 'AltCon's within a single list of alternatives
816 cmpAltCon DEFAULT      DEFAULT     = EQ
817 cmpAltCon DEFAULT      _           = LT
818
819 cmpAltCon (DataAlt d1) (DataAlt d2) = dataConTag d1 `compare` dataConTag d2
820 cmpAltCon (DataAlt _)  DEFAULT      = GT
821 cmpAltCon (LitAlt  l1) (LitAlt  l2) = l1 `compare` l2
822 cmpAltCon (LitAlt _)   DEFAULT      = GT
823
824 cmpAltCon con1 con2 = WARN( True, text "Comparing incomparable AltCons" <+> 
825                                   ppr con1 <+> ppr con2 )
826                       LT
827 \end{code}
828
829 %************************************************************************
830 %*                                                                      *
831 \subsection{Useful synonyms}
832 %*                                                                      *
833 %************************************************************************
834
835 \begin{code}
836 -- | The common case for the type of binders and variables when
837 -- we are manipulating the Core language within GHC
838 type CoreBndr = Var
839 -- | Expressions where binders are 'CoreBndr's
840 type CoreExpr = Expr CoreBndr
841 -- | Argument expressions where binders are 'CoreBndr's
842 type CoreArg  = Arg  CoreBndr
843 -- | Binding groups where binders are 'CoreBndr's
844 type CoreBind = Bind CoreBndr
845 -- | Case alternatives where binders are 'CoreBndr's
846 type CoreAlt  = Alt  CoreBndr
847 \end{code}
848
849 %************************************************************************
850 %*                                                                      *
851 \subsection{Tagging}
852 %*                                                                      *
853 %************************************************************************
854
855 \begin{code}
856 -- | Binders are /tagged/ with a t
857 data TaggedBndr t = TB CoreBndr t       -- TB for "tagged binder"
858
859 type TaggedBind t = Bind (TaggedBndr t)
860 type TaggedExpr t = Expr (TaggedBndr t)
861 type TaggedArg  t = Arg  (TaggedBndr t)
862 type TaggedAlt  t = Alt  (TaggedBndr t)
863
864 instance Outputable b => Outputable (TaggedBndr b) where
865   ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
866
867 instance Outputable b => OutputableBndr (TaggedBndr b) where
868   pprBndr _ b = ppr b   -- Simple
869 \end{code}
870
871
872 %************************************************************************
873 %*                                                                      *
874 \subsection{Core-constructing functions with checking}
875 %*                                                                      *
876 %************************************************************************
877
878 \begin{code}
879 -- | Apply a list of argument expressions to a function expression in a nested fashion. Prefer to
880 -- use 'CoreUtils.mkCoreApps' if possible
881 mkApps    :: Expr b -> [Arg b]  -> Expr b
882 -- | Apply a list of type argument expressions to a function expression in a nested fashion
883 mkTyApps  :: Expr b -> [Type]   -> Expr b
884 -- | Apply a list of coercion argument expressions to a function expression in a nested fashion
885 mkCoApps  :: Expr b -> [Coercion] -> Expr b
886 -- | Apply a list of type or value variables to a function expression in a nested fashion
887 mkVarApps :: Expr b -> [Var] -> Expr b
888 -- | Apply a list of argument expressions to a data constructor in a nested fashion. Prefer to
889 -- use 'MkCore.mkCoreConApps' if possible
890 mkConApp      :: DataCon -> [Arg b] -> Expr b
891
892 mkApps    f args = foldl App                       f args
893 mkTyApps  f args = foldl (\ e a -> App e (Type a)) f args
894 mkCoApps  f args = foldl (\ e a -> App e (Coercion a)) f args
895 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
896 mkConApp con args = mkApps (Var (dataConWorkId con)) args
897
898
899 -- | Create a machine integer literal expression of type @Int#@ from an @Integer@.
900 -- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
901 mkIntLit      :: Integer -> Expr b
902 -- | Create a machine integer literal expression of type @Int#@ from an @Int@.
903 -- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
904 mkIntLitInt   :: Int     -> Expr b
905
906 mkIntLit    n = Lit (mkMachInt n)
907 mkIntLitInt n = Lit (mkMachInt (toInteger n))
908
909 -- | Create a machine word literal expression of type  @Word#@ from an @Integer@.
910 -- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
911 mkWordLit     :: Integer -> Expr b
912 -- | Create a machine word literal expression of type  @Word#@ from a @Word@.
913 -- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
914 mkWordLitWord :: Word -> Expr b
915
916 mkWordLit     w = Lit (mkMachWord w)
917 mkWordLitWord w = Lit (mkMachWord (toInteger w))
918
919 -- | Create a machine character literal expression of type @Char#@.
920 -- If you want an expression of type @Char@ use 'MkCore.mkCharExpr'
921 mkCharLit :: Char -> Expr b
922 -- | Create a machine string literal expression of type @Addr#@.
923 -- If you want an expression of type @String@ use 'MkCore.mkStringExpr'
924 mkStringLit :: String -> Expr b
925
926 mkCharLit   c = Lit (mkMachChar c)
927 mkStringLit s = Lit (mkMachString s)
928
929 -- | Create a machine single precision literal expression of type @Float#@ from a @Rational@.
930 -- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
931 mkFloatLit :: Rational -> Expr b
932 -- | Create a machine single precision literal expression of type @Float#@ from a @Float@.
933 -- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
934 mkFloatLitFloat :: Float -> Expr b
935
936 mkFloatLit      f = Lit (mkMachFloat f)
937 mkFloatLitFloat f = Lit (mkMachFloat (toRational f))
938
939 -- | Create a machine double precision literal expression of type @Double#@ from a @Rational@.
940 -- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
941 mkDoubleLit :: Rational -> Expr b
942 -- | Create a machine double precision literal expression of type @Double#@ from a @Double@.
943 -- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
944 mkDoubleLitDouble :: Double -> Expr b
945
946 mkDoubleLit       d = Lit (mkMachDouble d)
947 mkDoubleLitDouble d = Lit (mkMachDouble (toRational d))
948
949 -- | Bind all supplied binding groups over an expression in a nested let expression. Prefer to
950 -- use 'CoreUtils.mkCoreLets' if possible
951 mkLets        :: [Bind b] -> Expr b -> Expr b
952 -- | Bind all supplied binders over an expression in a nested lambda expression. Prefer to
953 -- use 'CoreUtils.mkCoreLams' if possible
954 mkLams        :: [b] -> Expr b -> Expr b
955
956 mkLams binders body = foldr Lam body binders
957 mkLets binds body   = foldr Let body binds
958
959
960 -- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let",
961 -- this can only be used to bind something in a non-recursive @let@ expression
962 mkTyBind :: TyVar -> Type -> CoreBind
963 mkTyBind tv ty      = NonRec tv (Type ty)
964
965 -- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let",
966 -- this can only be used to bind something in a non-recursive @let@ expression
967 mkCoBind :: CoVar -> Coercion -> CoreBind
968 mkCoBind cv co      = NonRec cv (Coercion co)
969
970 -- | Convert a binder into either a 'Var' or 'Type' 'Expr' appropriately
971 varToCoreExpr :: CoreBndr -> Expr b
972 varToCoreExpr v | isTyVar v = Type (mkTyVarTy v)
973                 | isCoVar v = Coercion (mkCoVarCo v)
974                 | otherwise = ASSERT( isId v ) Var v
975
976 varsToCoreExprs :: [CoreBndr] -> [Expr b]
977 varsToCoreExprs vs = map varToCoreExpr vs
978 \end{code}
979
980
981 %************************************************************************
982 %*                                                                      *
983 \subsection{Simple access functions}
984 %*                                                                      *
985 %************************************************************************
986
987 \begin{code}
988 -- | Extract every variable by this group
989 bindersOf  :: Bind b -> [b]
990 bindersOf (NonRec binder _) = [binder]
991 bindersOf (Rec pairs)       = [binder | (binder, _) <- pairs]
992
993 -- | 'bindersOf' applied to a list of binding groups
994 bindersOfBinds :: [Bind b] -> [b]
995 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
996
997 rhssOfBind :: Bind b -> [Expr b]
998 rhssOfBind (NonRec _ rhs) = [rhs]
999 rhssOfBind (Rec pairs)    = [rhs | (_,rhs) <- pairs]
1000
1001 rhssOfAlts :: [Alt b] -> [Expr b]
1002 rhssOfAlts alts = [e | (_,_,e) <- alts]
1003
1004 -- | Collapse all the bindings in the supplied groups into a single
1005 -- list of lhs\/rhs pairs suitable for binding in a 'Rec' binding group
1006 flattenBinds :: [Bind b] -> [(b, Expr b)]
1007 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
1008 flattenBinds (Rec prs1   : binds) = prs1 ++ flattenBinds binds
1009 flattenBinds []                   = []
1010 \end{code}
1011
1012 \begin{code}
1013 -- | We often want to strip off leading lambdas before getting down to
1014 -- business. This function is your friend.
1015 collectBinders               :: Expr b -> ([b],         Expr b)
1016 -- | Collect as many type bindings as possible from the front of a nested lambda
1017 collectTyBinders             :: CoreExpr -> ([TyVar],     CoreExpr)
1018 -- | Collect as many value bindings as possible from the front of a nested lambda
1019 collectValBinders            :: CoreExpr -> ([Id],        CoreExpr)
1020 -- | Collect type binders from the front of the lambda first, 
1021 -- then follow up by collecting as many value bindings as possible
1022 -- from the resulting stripped expression
1023 collectTyAndValBinders       :: CoreExpr -> ([TyVar], [Id], CoreExpr)
1024
1025 collectBinders expr
1026   = go [] expr
1027   where
1028     go bs (Lam b e) = go (b:bs) e
1029     go bs e          = (reverse bs, e)
1030
1031 collectTyAndValBinders expr
1032   = (tvs, ids, body)
1033   where
1034     (tvs, body1) = collectTyBinders expr
1035     (ids, body)  = collectValBinders body1
1036
1037 collectTyBinders expr
1038   = go [] expr
1039   where
1040     go tvs (Lam b e) | isTyVar b = go (b:tvs) e
1041     go tvs e                     = (reverse tvs, e)
1042
1043 collectValBinders expr
1044   = go [] expr
1045   where
1046     go ids (Lam b e) | isId b = go (b:ids) e
1047     go ids body               = (reverse ids, body)
1048 \end{code}
1049
1050 \begin{code}
1051 -- | Takes a nested application expression and returns the the function
1052 -- being applied and the arguments to which it is applied
1053 collectArgs :: Expr b -> (Expr b, [Arg b])
1054 collectArgs expr
1055   = go expr []
1056   where
1057     go (App f a) as = go f (a:as)
1058     go e         as = (e, as)
1059 \end{code}
1060
1061 \begin{code}
1062 -- | Gets the cost centre enclosing an expression, if any.
1063 -- It looks inside lambdas because @(scc \"foo\" \\x.e) = \\x. scc \"foo\" e@
1064 coreExprCc :: Expr b -> CostCentre
1065 coreExprCc (Note (SCC cc) _)   = cc
1066 coreExprCc (Note _ e)          = coreExprCc e
1067 coreExprCc (Lam _ e)           = coreExprCc e
1068 coreExprCc _                   = noCostCentre
1069 \end{code}
1070
1071 %************************************************************************
1072 %*                                                                      *
1073 \subsection{Predicates}
1074 %*                                                                      *
1075 %************************************************************************
1076
1077 At one time we optionally carried type arguments through to runtime.
1078 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
1079 i.e. if type applications are actual lambdas because types are kept around
1080 at runtime.  Similarly isRuntimeArg.  
1081
1082 \begin{code}
1083 -- | Will this variable exist at runtime?
1084 isRuntimeVar :: Var -> Bool
1085 isRuntimeVar = isId 
1086
1087 -- | Will this argument expression exist at runtime?
1088 isRuntimeArg :: CoreExpr -> Bool
1089 isRuntimeArg = isValArg
1090
1091 -- | Returns @False@ iff the expression is a 'Type' or 'Coercion'
1092 -- expression at its top level
1093 isValArg :: Expr b -> Bool
1094 isValArg e = not (isTypeArg e)
1095
1096 -- | Returns @True@ iff the expression is a 'Type' or 'Coercion'
1097 -- expression at its top level
1098 isTyCoArg :: Expr b -> Bool
1099 isTyCoArg (Type {})     = True
1100 isTyCoArg (Coercion {}) = True
1101 isTyCoArg _             = False
1102
1103 -- | Returns @True@ iff the expression is a 'Type' expression at its
1104 -- top level.  Note this does NOT include 'Coercion's.
1105 isTypeArg :: Expr b -> Bool
1106 isTypeArg (Type {}) = True
1107 isTypeArg _         = False
1108
1109 -- | The number of binders that bind values rather than types
1110 valBndrCount :: [CoreBndr] -> Int
1111 valBndrCount = count isId
1112
1113 -- | The number of argument expressions that are values rather than types at their top level
1114 valArgCount :: [Arg b] -> Int
1115 valArgCount = count isValArg
1116
1117 notSccNote :: Note -> Bool
1118 notSccNote (SCC {}) = False
1119 notSccNote _        = True
1120 \end{code}
1121
1122
1123 %************************************************************************
1124 %*                                                                      *
1125 \subsection{Seq stuff}
1126 %*                                                                      *
1127 %************************************************************************
1128
1129 \begin{code}
1130 seqExpr :: CoreExpr -> ()
1131 seqExpr (Var v)         = v `seq` ()
1132 seqExpr (Lit lit)       = lit `seq` ()
1133 seqExpr (App f a)       = seqExpr f `seq` seqExpr a
1134 seqExpr (Lam b e)       = seqBndr b `seq` seqExpr e
1135 seqExpr (Let b e)       = seqBind b `seq` seqExpr e
1136 seqExpr (Case e b t as) = seqExpr e `seq` seqBndr b `seq` seqType t `seq` seqAlts as
1137 seqExpr (Cast e co)     = seqExpr e `seq` seqCo co
1138 seqExpr (Note n e)      = seqNote n `seq` seqExpr e
1139 seqExpr (Type t)       = seqType t
1140 seqExpr (Coercion co)   = seqCo co
1141
1142 seqExprs :: [CoreExpr] -> ()
1143 seqExprs [] = ()
1144 seqExprs (e:es) = seqExpr e `seq` seqExprs es
1145
1146 seqNote :: Note -> ()
1147 seqNote (CoreNote s)   = s `seq` ()
1148 seqNote _              = ()
1149
1150 seqBndr :: CoreBndr -> ()
1151 seqBndr b = b `seq` ()
1152
1153 seqBndrs :: [CoreBndr] -> ()
1154 seqBndrs [] = ()
1155 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
1156
1157 seqBind :: Bind CoreBndr -> ()
1158 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
1159 seqBind (Rec prs)    = seqPairs prs
1160
1161 seqPairs :: [(CoreBndr, CoreExpr)] -> ()
1162 seqPairs [] = ()
1163 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
1164
1165 seqAlts :: [CoreAlt] -> ()
1166 seqAlts [] = ()
1167 seqAlts ((c,bs,e):alts) = c `seq` seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
1168
1169 seqRules :: [CoreRule] -> ()
1170 seqRules [] = ()
1171 seqRules (Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs } : rules) 
1172   = seqBndrs bndrs `seq` seqExprs (rhs:args) `seq` seqRules rules
1173 seqRules (BuiltinRule {} : rules) = seqRules rules
1174 \end{code}
1175
1176 %************************************************************************
1177 %*                                                                      *
1178 \subsection{Annotated core}
1179 %*                                                                      *
1180 %************************************************************************
1181
1182 \begin{code}
1183 -- | Annotated core: allows annotation at every node in the tree
1184 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
1185
1186 -- | A clone of the 'Expr' type but allowing annotation at every tree node
1187 data AnnExpr' bndr annot
1188   = AnnVar      Id
1189   | AnnLit      Literal
1190   | AnnLam      bndr (AnnExpr bndr annot)
1191   | AnnApp      (AnnExpr bndr annot) (AnnExpr bndr annot)
1192   | AnnCase     (AnnExpr bndr annot) bndr Type [AnnAlt bndr annot]
1193   | AnnLet      (AnnBind bndr annot) (AnnExpr bndr annot)
1194   | AnnCast     (AnnExpr bndr annot) (annot, Coercion)
1195                    -- Put an annotation on the (root of) the coercion
1196   | AnnNote     Note (AnnExpr bndr annot)
1197   | AnnType     Type
1198   | AnnCoercion Coercion
1199
1200 -- | A clone of the 'Alt' type but allowing annotation at every tree node
1201 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
1202
1203 -- | A clone of the 'Bind' type but allowing annotation at every tree node
1204 data AnnBind bndr annot
1205   = AnnNonRec bndr (AnnExpr bndr annot)
1206   | AnnRec    [(bndr, AnnExpr bndr annot)]
1207 \end{code}
1208
1209 \begin{code}
1210 -- | Takes a nested application expression and returns the the function
1211 -- being applied and the arguments to which it is applied
1212 collectAnnArgs :: AnnExpr b a -> (AnnExpr b a, [AnnExpr b a])
1213 collectAnnArgs expr
1214   = go expr []
1215   where
1216     go (_, AnnApp f a) as = go f (a:as)
1217     go e               as = (e, as)
1218 \end{code}
1219
1220 \begin{code}
1221 deAnnotate :: AnnExpr bndr annot -> Expr bndr
1222 deAnnotate (_, e) = deAnnotate' e
1223
1224 deAnnotate' :: AnnExpr' bndr annot -> Expr bndr
1225 deAnnotate' (AnnType t)          = Type t
1226 deAnnotate' (AnnCoercion co)      = Coercion co
1227 deAnnotate' (AnnVar  v)           = Var v
1228 deAnnotate' (AnnLit  lit)         = Lit lit
1229 deAnnotate' (AnnLam  binder body) = Lam binder (deAnnotate body)
1230 deAnnotate' (AnnApp  fun arg)     = App (deAnnotate fun) (deAnnotate arg)
1231 deAnnotate' (AnnCast e (_,co))    = Cast (deAnnotate e) co
1232 deAnnotate' (AnnNote note body)   = Note note (deAnnotate body)
1233
1234 deAnnotate' (AnnLet bind body)
1235   = Let (deAnnBind bind) (deAnnotate body)
1236   where
1237     deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
1238     deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
1239
1240 deAnnotate' (AnnCase scrut v t alts)
1241   = Case (deAnnotate scrut) v t (map deAnnAlt alts)
1242
1243 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
1244 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
1245 \end{code}
1246
1247 \begin{code}
1248 -- | As 'collectBinders' but for 'AnnExpr' rather than 'Expr'
1249 collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
1250 collectAnnBndrs e
1251   = collect [] e
1252   where
1253     collect bs (_, AnnLam b body) = collect (b:bs) body
1254     collect bs body               = (reverse bs, body)
1255 \end{code}