752dcf08f618c4baaa96f269d09b1eb5094aca42
[ghc-hetmet.git] / compiler / coreSyn / CoreFVs.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 Taken quite directly from the Peyton Jones/Lester paper.
6
7 \begin{code}
8 {-# OPTIONS -w #-}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 --     http://hackage.haskell.org/trac/ghc/wiki/CodingStyle#Warnings
13 -- for details
14
15 module CoreFVs (
16         exprFreeVars,   -- CoreExpr   -> VarSet -- Find all locally-defined free Ids or tyvars
17         exprsFreeVars,  -- [CoreExpr] -> VarSet
18         bindFreeVars,   -- CoreBind   -> VarSet
19
20         exprSomeFreeVars, exprsSomeFreeVars,
21         exprFreeNames, exprsFreeNames,
22
23         idRuleVars, idFreeVars, varTypeTyVars, 
24         ruleRhsFreeVars, rulesFreeVars,
25         ruleLhsFreeNames, ruleLhsFreeIds, 
26
27         CoreExprWithFVs,        -- = AnnExpr Id VarSet
28         CoreBindWithFVs,        -- = AnnBind Id VarSet
29         freeVars,               -- CoreExpr -> CoreExprWithFVs
30         freeVarsOf              -- CoreExprWithFVs -> IdSet
31     ) where
32
33 #include "HsVersions.h"
34
35 import CoreSyn
36 import Id
37 import IdInfo
38 import NameSet
39 import UniqFM
40 import Name
41 import VarSet
42 import Var
43 import TcType
44 import Util
45 import Outputable
46 \end{code}
47
48
49 %************************************************************************
50 %*                                                                      *
51 \section{Finding the free variables of an expression}
52 %*                                                                      *
53 %************************************************************************
54
55 This function simply finds the free variables of an expression.
56 So far as type variables are concerned, it only finds tyvars that are
57
58         * free in type arguments, 
59         * free in the type of a binder,
60
61 but not those that are free in the type of variable occurrence.
62
63 \begin{code}
64 exprFreeVars :: CoreExpr -> VarSet      -- Find all locally-defined free Ids or tyvars
65 exprFreeVars = exprSomeFreeVars isLocalVar
66
67 exprsFreeVars :: [CoreExpr] -> VarSet
68 exprsFreeVars = foldr (unionVarSet . exprFreeVars) emptyVarSet
69
70 bindFreeVars :: CoreBind -> VarSet
71 bindFreeVars (NonRec b r) = exprFreeVars r
72 bindFreeVars (Rec prs)    = addBndrs (map fst prs) 
73                                      (foldr (union . rhs_fvs) noVars prs)
74                                      isLocalVar emptyVarSet
75
76 exprSomeFreeVars :: InterestingVarFun   -- Says which Vars are interesting
77                  -> CoreExpr
78                  -> VarSet
79 exprSomeFreeVars fv_cand e = expr_fvs e fv_cand emptyVarSet
80
81 exprsSomeFreeVars :: InterestingVarFun  -- Says which Vars are interesting
82                   -> [CoreExpr]
83                   -> VarSet
84 exprsSomeFreeVars fv_cand = foldr (unionVarSet . exprSomeFreeVars fv_cand) emptyVarSet
85
86 type InterestingVarFun = Var -> Bool    -- True <=> interesting
87 \end{code}
88
89
90 \begin{code}
91 type FV = InterestingVarFun 
92         -> VarSet               -- In scope
93         -> VarSet               -- Free vars
94
95 union :: FV -> FV -> FV
96 union fv1 fv2 fv_cand in_scope = fv1 fv_cand in_scope `unionVarSet` fv2 fv_cand in_scope
97
98 noVars :: FV
99 noVars fv_cand in_scope = emptyVarSet
100
101 --      Comment about obselete code
102 -- We used to gather the free variables the RULES at a variable occurrence
103 -- with the following cryptic comment:
104 --     "At a variable occurrence, add in any free variables of its rule rhss
105 --     Curiously, we gather the Id's free *type* variables from its binding
106 --     site, but its free *rule-rhs* variables from its usage sites.  This
107 --     is a little weird.  The reason is that the former is more efficient,
108 --     but the latter is more fine grained, and a makes a difference when
109 --     a variable mentions itself one of its own rule RHSs"
110 -- Not only is this "weird", but it's also pretty bad because it can make
111 -- a function seem more recursive than it is.  Suppose
112 --      f  = ...g...
113 --      g  = ...
114 --         RULE g x = ...f...
115 -- Then f is not mentioned in its own RHS, and needn't be a loop breaker
116 -- (though g may be).  But if we collect the rule fvs from g's occurrence,
117 -- it looks as if f mentions itself.  (This bites in the eftInt/eftIntFB
118 -- code in GHC.Enum.)
119 -- 
120 -- Anyway, it seems plain wrong.  The RULE is like an extra RHS for the
121 -- function, so its free variables belong at the definition site.
122 --
123 -- Deleted code looked like
124 --     foldVarSet add_rule_var var_itself_set (idRuleVars var)
125 --     add_rule_var var set | keep_it fv_cand in_scope var = extendVarSet set var
126 --                          | otherwise                    = set
127 --      SLPJ Feb06
128
129 oneVar :: Id -> FV
130 oneVar var fv_cand in_scope
131   = ASSERT( isId var ) 
132     if keep_it fv_cand in_scope var 
133     then unitVarSet var
134     else emptyVarSet
135
136 someVars :: VarSet -> FV
137 someVars vars fv_cand in_scope
138   = filterVarSet (keep_it fv_cand in_scope) vars
139
140 keep_it fv_cand in_scope var
141   | var `elemVarSet` in_scope = False
142   | fv_cand var               = True
143   | otherwise                 = False
144
145
146 addBndr :: CoreBndr -> FV -> FV
147 addBndr bndr fv fv_cand in_scope
148   = someVars (varTypeTyVars bndr) fv_cand in_scope
149         -- Include type varibles in the binder's type
150         --      (not just Ids; coercion variables too!)
151     `unionVarSet`  fv fv_cand (in_scope `extendVarSet` bndr) 
152
153 addBndrs :: [CoreBndr] -> FV -> FV
154 addBndrs bndrs fv = foldr addBndr fv bndrs
155 \end{code}
156
157
158 \begin{code}
159 expr_fvs :: CoreExpr -> FV
160
161 expr_fvs (Type ty)       = someVars (tyVarsOfType ty)
162 expr_fvs (Var var)       = oneVar var
163 expr_fvs (Lit lit)       = noVars
164 expr_fvs (Note _ expr)   = expr_fvs expr
165 expr_fvs (App fun arg)   = expr_fvs fun `union` expr_fvs arg
166 expr_fvs (Lam bndr body) = addBndr bndr (expr_fvs body)
167 expr_fvs (Cast expr co)  = expr_fvs expr `union` someVars (tyVarsOfType co)
168
169 expr_fvs (Case scrut bndr ty alts)
170   = expr_fvs scrut `union` someVars (tyVarsOfType ty) `union` addBndr bndr  
171       (foldr (union . alt_fvs) noVars alts)
172   where
173     alt_fvs (con, bndrs, rhs) = addBndrs bndrs (expr_fvs rhs)
174
175 expr_fvs (Let (NonRec bndr rhs) body)
176   = rhs_fvs (bndr, rhs) `union` addBndr bndr (expr_fvs body)
177
178 expr_fvs (Let (Rec pairs) body)
179   = addBndrs (map fst pairs) 
180              (foldr (union . rhs_fvs) (expr_fvs body) pairs)
181
182 ---------
183 rhs_fvs (bndr, rhs) = expr_fvs rhs `union` someVars (idRuleVars bndr)
184         -- Treat any RULES as extra RHSs of the binding
185
186 ---------
187 exprs_fvs exprs = foldr (union . expr_fvs) noVars exprs
188 \end{code}
189
190
191 %************************************************************************
192 %*                                                                      *
193 \section{Free names}
194 %*                                                                      *
195 %************************************************************************
196
197 exprFreeNames finds the free *external* *names* of an expression, notably
198 including the names of type constructors (which of course do not show
199 up in exprFreeVars).  Similarly ruleLhsFreeNames.  The latter is used
200 when deciding whether a rule is an orphan.  In particular, suppose that
201 T is defined in this module; we want to avoid declaring that a rule like
202         fromIntegral T = fromIntegral_T
203 is an orphan.  Of course it isn't, an declaring it an orphan would
204 make the whole module an orphan module, which is bad.
205
206 There's no need to delete local binders, because they will all
207 be *internal* names.
208
209 \begin{code}
210 ruleLhsFreeNames :: CoreRule -> NameSet
211 ruleLhsFreeNames (BuiltinRule { ru_fn = fn }) = unitNameSet fn
212 ruleLhsFreeNames (Rule { ru_fn = fn, ru_bndrs = tpl_vars, ru_args = tpl_args })
213   = addOneToNameSet (exprsFreeNames tpl_args) fn
214
215 exprFreeNames :: CoreExpr -> NameSet
216 -- Find the free *external* names of an expression
217 exprFreeNames e
218   = go e
219   where
220     go (Var v) 
221       | isExternalName n    = unitNameSet n
222       | otherwise           = emptyNameSet
223       where n = idName v
224     go (Lit _)              = emptyNameSet
225     go (Type ty)            = tyClsNamesOfType ty       -- Don't need free tyvars
226     go (App e1 e2)          = go e1 `unionNameSets` go e2
227     go (Lam v e)            = go e `delFromNameSet` idName v
228     go (Note n e)           = go e  
229     go (Cast e co)          = go e `unionNameSets` tyClsNamesOfType co
230     go (Let (NonRec b r) e) = go e `unionNameSets` go r
231     go (Let (Rec prs) e)    = exprsFreeNames (map snd prs) `unionNameSets` go e
232     go (Case e b ty as)     = go e `unionNameSets` tyClsNamesOfType ty 
233                               `unionNameSets` unionManyNameSets (map go_alt as)
234
235     go_alt (_,_,r) = go r
236
237 exprsFreeNames es = foldr (unionNameSets . exprFreeNames) emptyNameSet es
238 \end{code}
239
240 %************************************************************************
241 %*                                                                      *
242 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
243 %*                                                                      *
244 %************************************************************************
245
246
247 \begin{code}
248 ruleRhsFreeVars :: CoreRule -> VarSet
249 ruleRhsFreeVars (BuiltinRule {}) = noFVs
250 ruleRhsFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs })
251   = delFromUFM fvs fn    -- Note [Rule free var hack]
252   where
253     fvs = addBndrs bndrs (expr_fvs rhs) isLocalVar emptyVarSet
254
255 ruleFreeVars :: CoreRule -> VarSet      -- All free variables, both left and right
256 ruleFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs, ru_args = args })
257   = delFromUFM fvs fn   -- Note [Rule free var hack]
258   where
259     fvs = addBndrs bndrs (exprs_fvs (rhs:args)) isLocalVar emptyVarSet
260
261 rulesFreeVars :: [CoreRule] -> VarSet
262 rulesFreeVars rules = foldr (unionVarSet . ruleFreeVars) emptyVarSet rules
263
264 ruleLhsFreeIds :: CoreRule -> VarSet
265 -- This finds all locally-defined free Ids on the LHS of the rule
266 ruleLhsFreeIds (BuiltinRule {}) = noFVs
267 ruleLhsFreeIds (Rule { ru_bndrs = bndrs, ru_args = args })
268   = addBndrs bndrs (exprs_fvs args) isLocalId emptyVarSet
269 \end{code}
270
271 Note [Rule free var hack]
272 ~~~~~~~~~~~~~~~~~~~~~~~~~
273 Don't include the Id in its own rhs free-var set.
274 Otherwise the occurrence analyser makes bindings recursive
275 that shoudn't be.  E.g.
276         RULE:  f (f x y) z  ==>  f x (f y z)
277
278 Also since rule_fn is a Name, not a Var, we have to use the grungy delUFM.
279
280 %************************************************************************
281 %*                                                                      *
282 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
283 %*                                                                      *
284 %************************************************************************
285
286 The free variable pass annotates every node in the expression with its
287 NON-GLOBAL free variables and type variables.
288
289 \begin{code}
290 type CoreBindWithFVs = AnnBind Id VarSet
291 type CoreExprWithFVs = AnnExpr Id VarSet
292         -- Every node annotated with its free variables,
293         -- both Ids and TyVars
294
295 freeVarsOf :: CoreExprWithFVs -> IdSet
296 freeVarsOf (free_vars, _) = free_vars
297
298 noFVs    = emptyVarSet
299 aFreeVar = unitVarSet
300 unionFVs = unionVarSet
301
302 delBindersFV :: [Var] -> VarSet -> VarSet
303 delBindersFV bs fvs = foldr delBinderFV fvs bs
304
305 delBinderFV :: Var -> VarSet -> VarSet
306 -- This way round, so we can do it multiple times using foldr
307
308 -- (b `delBinderFV` s) removes the binder b from the free variable set s,
309 -- but *adds* to s
310 --      (a) the free variables of b's type
311 --      (b) the idSpecVars of b
312 --
313 -- This is really important for some lambdas:
314 --      In (\x::a -> x) the only mention of "a" is in the binder.
315 --
316 -- Also in
317 --      let x::a = b in ...
318 -- we should really note that "a" is free in this expression.
319 -- It'll be pinned inside the /\a by the binding for b, but
320 -- it seems cleaner to make sure that a is in the free-var set 
321 -- when it is mentioned.
322 --
323 -- This also shows up in recursive bindings.  Consider:
324 --      /\a -> letrec x::a = x in E
325 -- Now, there are no explicit free type variables in the RHS of x,
326 -- but nevertheless "a" is free in its definition.  So we add in
327 -- the free tyvars of the types of the binders, and include these in the
328 -- free vars of the group, attached to the top level of each RHS.
329 --
330 -- This actually happened in the defn of errorIO in IOBase.lhs:
331 --      errorIO (ST io) = case (errorIO# io) of
332 --                          _ -> bottom
333 --                        where
334 --                          bottom = bottom -- Never evaluated
335
336 delBinderFV b s = (s `delVarSet` b) `unionFVs` varTypeTyVars b
337         -- Include coercion variables too!
338
339 varTypeTyVars :: Var -> TyVarSet
340 -- Find the type variables free in the type of the variable
341 -- Remember, coercion variables can mention type variables...
342 varTypeTyVars var
343   | isLocalId var || isCoVar var = tyVarsOfType (idType var)
344   | otherwise = emptyVarSet     -- Global Ids and non-coercion TyVars
345
346 idFreeVars :: Id -> VarSet
347 idFreeVars id = ASSERT( isId id) idRuleVars id `unionVarSet` varTypeTyVars id
348
349 idRuleVars ::Id -> VarSet
350 idRuleVars id = ASSERT( isId id) specInfoFreeVars (idSpecialisation id)
351 \end{code}
352
353
354 %************************************************************************
355 %*                                                                      *
356 \subsection{Free variables (and types)}
357 %*                                                                      *
358 %************************************************************************
359
360 \begin{code}
361 freeVars :: CoreExpr -> CoreExprWithFVs
362
363 freeVars (Var v)
364   = (fvs, AnnVar v)
365   where
366         -- ToDo: insert motivating example for why we *need*
367         -- to include the idSpecVars in the FV list.
368         --      Actually [June 98] I don't think it's necessary
369         -- fvs = fvs_v `unionVarSet` idSpecVars v
370
371     fvs | isLocalVar v = aFreeVar v
372         | otherwise    = noFVs
373
374 freeVars (Lit lit) = (noFVs, AnnLit lit)
375 freeVars (Lam b body)
376   = (b `delBinderFV` freeVarsOf body', AnnLam b body')
377   where
378     body' = freeVars body
379
380 freeVars (App fun arg)
381   = (freeVarsOf fun2 `unionFVs` freeVarsOf arg2, AnnApp fun2 arg2)
382   where
383     fun2 = freeVars fun
384     arg2 = freeVars arg
385
386 freeVars (Case scrut bndr ty alts)
387   = ((bndr `delBinderFV` alts_fvs) `unionFVs` freeVarsOf scrut2 `unionFVs` tyVarsOfType ty,
388      AnnCase scrut2 bndr ty alts2)
389   where
390     scrut2 = freeVars scrut
391
392     (alts_fvs_s, alts2) = mapAndUnzip fv_alt alts
393     alts_fvs            = foldr1 unionFVs alts_fvs_s
394
395     fv_alt (con,args,rhs) = (delBindersFV args (freeVarsOf rhs2),
396                              (con, args, rhs2))
397                           where
398                              rhs2 = freeVars rhs
399
400 freeVars (Let (NonRec binder rhs) body)
401   = (freeVarsOf rhs2 `unionFVs` body_fvs `unionFVs` idRuleVars binder,
402                 -- Remember any rules; cf rhs_fvs above
403      AnnLet (AnnNonRec binder rhs2) body2)
404   where
405     rhs2     = freeVars rhs
406     body2    = freeVars body
407     body_fvs = binder `delBinderFV` freeVarsOf body2
408
409 freeVars (Let (Rec binds) body)
410   = (delBindersFV binders all_fvs,
411      AnnLet (AnnRec (binders `zip` rhss2)) body2)
412   where
413     (binders, rhss) = unzip binds
414
415     rhss2     = map freeVars rhss
416     rhs_body_fvs = foldr (unionFVs . freeVarsOf) body_fvs rhss2
417     all_fvs      = foldr (unionFVs . idRuleVars) rhs_body_fvs binders
418         -- The "delBinderFV" happens after adding the idSpecVars,
419         -- since the latter may add some of the binders as fvs
420
421     body2     = freeVars body
422     body_fvs  = freeVarsOf body2
423
424
425 freeVars (Cast expr co)
426   = (freeVarsOf expr2 `unionFVs` cfvs, AnnCast expr2 co)
427   where
428     expr2 = freeVars expr
429     cfvs  = tyVarsOfType co
430
431 freeVars (Note other_note expr)
432   = (freeVarsOf expr2, AnnNote other_note expr2)
433   where
434     expr2 = freeVars expr
435
436 freeVars (Type ty) = (tyVarsOfType ty, AnnType ty)
437 \end{code}
438