2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 Taken quite directly from the Peyton Jones/Lester paper.
8 {-# OPTIONS -fno-warn-incomplete-patterns #-}
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/Commentary/CodingStyle#Warnings
15 -- | A module concerned with finding the free variables of an expression.
17 -- * Free variables of expressions and binding groups
18 exprFreeVars, -- CoreExpr -> VarSet -- Find all locally-defined free Ids or tyvars
19 exprFreeIds, -- CoreExpr -> IdSet -- Find all locally-defined free Ids
20 exprsFreeVars, -- [CoreExpr] -> VarSet
21 bindFreeVars, -- CoreBind -> VarSet
23 -- * Selective free variables of expressions
25 exprSomeFreeVars, exprsSomeFreeVars,
26 exprFreeNames, exprsFreeNames,
28 -- * Free variables of Rules, Vars and Ids
29 varTypeTyVars, varTypeTcTyVars,
30 idUnfoldingVars, idFreeVars, idRuleAndUnfoldingVars,
31 idRuleVars, idRuleRhsVars,
32 ruleRhsFreeVars, rulesFreeVars,
33 ruleLhsFreeNames, ruleLhsFreeIds,
35 -- * Core syntax tree annotation with free variables
36 CoreExprWithFVs, -- = AnnExpr Id VarSet
37 CoreBindWithFVs, -- = AnnBind Id VarSet
38 freeVars, -- CoreExpr -> CoreExprWithFVs
39 freeVarsOf -- CoreExprWithFVs -> IdSet
42 #include "HsVersions.h"
58 %************************************************************************
60 \section{Finding the free variables of an expression}
62 %************************************************************************
64 This function simply finds the free variables of an expression.
65 So far as type variables are concerned, it only finds tyvars that are
67 * free in type arguments,
68 * free in the type of a binder,
70 but not those that are free in the type of variable occurrence.
73 -- | Find all locally-defined free Ids or type variables in an expression
74 exprFreeVars :: CoreExpr -> VarSet
75 exprFreeVars = exprSomeFreeVars isLocalVar
77 -- | Find all locally-defined free Ids in an expression
78 exprFreeIds :: CoreExpr -> IdSet -- Find all locally-defined free Ids
79 exprFreeIds = exprSomeFreeVars isLocalId
81 -- | Find all locally-defined free Ids or type variables in several expressions
82 exprsFreeVars :: [CoreExpr] -> VarSet
83 exprsFreeVars = foldr (unionVarSet . exprFreeVars) emptyVarSet
85 -- | Find all locally defined free Ids in a binding group
86 bindFreeVars :: CoreBind -> VarSet
87 bindFreeVars (NonRec _ r) = exprFreeVars r
88 bindFreeVars (Rec prs) = addBndrs (map fst prs)
89 (foldr (union . rhs_fvs) noVars prs)
90 isLocalVar emptyVarSet
92 -- | Finds free variables in an expression selected by a predicate
93 exprSomeFreeVars :: InterestingVarFun -- ^ Says which 'Var's are interesting
96 exprSomeFreeVars fv_cand e = expr_fvs e fv_cand emptyVarSet
98 -- | Finds free variables in several expressions selected by a predicate
99 exprsSomeFreeVars :: InterestingVarFun -- Says which 'Var's are interesting
102 exprsSomeFreeVars fv_cand = foldr (unionVarSet . exprSomeFreeVars fv_cand) emptyVarSet
104 -- | Predicate on possible free variables: returns @True@ iff the variable is interesting
105 type InterestingVarFun = Var -> Bool
110 type FV = InterestingVarFun
111 -> VarSet -- In scope
112 -> VarSet -- Free vars
114 union :: FV -> FV -> FV
115 union fv1 fv2 fv_cand in_scope = fv1 fv_cand in_scope `unionVarSet` fv2 fv_cand in_scope
118 noVars _ _ = emptyVarSet
120 -- Comment about obselete code
121 -- We used to gather the free variables the RULES at a variable occurrence
122 -- with the following cryptic comment:
123 -- "At a variable occurrence, add in any free variables of its rule rhss
124 -- Curiously, we gather the Id's free *type* variables from its binding
125 -- site, but its free *rule-rhs* variables from its usage sites. This
126 -- is a little weird. The reason is that the former is more efficient,
127 -- but the latter is more fine grained, and a makes a difference when
128 -- a variable mentions itself one of its own rule RHSs"
129 -- Not only is this "weird", but it's also pretty bad because it can make
130 -- a function seem more recursive than it is. Suppose
133 -- RULE g x = ...f...
134 -- Then f is not mentioned in its own RHS, and needn't be a loop breaker
135 -- (though g may be). But if we collect the rule fvs from g's occurrence,
136 -- it looks as if f mentions itself. (This bites in the eftInt/eftIntFB
137 -- code in GHC.Enum.)
139 -- Anyway, it seems plain wrong. The RULE is like an extra RHS for the
140 -- function, so its free variables belong at the definition site.
142 -- Deleted code looked like
143 -- foldVarSet add_rule_var var_itself_set (idRuleVars var)
144 -- add_rule_var var set | keep_it fv_cand in_scope var = extendVarSet set var
149 oneVar var fv_cand in_scope
151 if keep_it fv_cand in_scope var
155 someVars :: VarSet -> FV
156 someVars vars fv_cand in_scope
157 = filterVarSet (keep_it fv_cand in_scope) vars
159 keep_it :: InterestingVarFun -> VarSet -> Var -> Bool
160 keep_it fv_cand in_scope var
161 | var `elemVarSet` in_scope = False
166 addBndr :: CoreBndr -> FV -> FV
167 addBndr bndr fv fv_cand in_scope
168 = someVars (varTypeTyVars bndr) fv_cand in_scope
169 -- Include type varibles in the binder's type
170 -- (not just Ids; coercion variables too!)
171 `unionVarSet` fv fv_cand (in_scope `extendVarSet` bndr)
173 addBndrs :: [CoreBndr] -> FV -> FV
174 addBndrs bndrs fv = foldr addBndr fv bndrs
179 expr_fvs :: CoreExpr -> FV
181 expr_fvs (Type ty) = someVars (tyVarsOfType ty)
182 expr_fvs (Var var) = oneVar var
183 expr_fvs (Lit _) = noVars
184 expr_fvs (Note _ expr) = expr_fvs expr
185 expr_fvs (App fun arg) = expr_fvs fun `union` expr_fvs arg
186 expr_fvs (Lam bndr body) = addBndr bndr (expr_fvs body)
187 expr_fvs (Cast expr co) = expr_fvs expr `union` someVars (tyVarsOfType co)
189 expr_fvs (Case scrut bndr ty alts)
190 = expr_fvs scrut `union` someVars (tyVarsOfType ty) `union` addBndr bndr
191 (foldr (union . alt_fvs) noVars alts)
193 alt_fvs (_, bndrs, rhs) = addBndrs bndrs (expr_fvs rhs)
195 expr_fvs (Let (NonRec bndr rhs) body)
196 = rhs_fvs (bndr, rhs) `union` addBndr bndr (expr_fvs body)
198 expr_fvs (Let (Rec pairs) body)
199 = addBndrs (map fst pairs)
200 (foldr (union . rhs_fvs) (expr_fvs body) pairs)
203 rhs_fvs :: (Id,CoreExpr) -> FV
204 rhs_fvs (bndr, rhs) = expr_fvs rhs `union`
205 someVars (bndrRuleAndUnfoldingVars bndr)
206 -- Treat any RULES as extra RHSs of the binding
209 exprs_fvs :: [CoreExpr] -> FV
210 exprs_fvs exprs = foldr (union . expr_fvs) noVars exprs
214 %************************************************************************
218 %************************************************************************
221 -- | Similar to 'exprFreeNames'. However, this is used when deciding whether
222 -- a rule is an orphan. In particular, suppose that T is defined in this
223 -- module; we want to avoid declaring that a rule like:
225 -- > fromIntegral T = fromIntegral_T
227 -- is an orphan. Of course it isn't, and declaring it an orphan would
228 -- make the whole module an orphan module, which is bad.
229 ruleLhsFreeNames :: CoreRule -> NameSet
230 ruleLhsFreeNames (BuiltinRule { ru_fn = fn }) = unitNameSet fn
231 ruleLhsFreeNames (Rule { ru_fn = fn, ru_args = tpl_args })
232 = addOneToNameSet (exprsFreeNames tpl_args) fn
234 -- | Finds the free /external/ names of an expression, notably
235 -- including the names of type constructors (which of course do not show
236 -- up in 'exprFreeVars').
237 exprFreeNames :: CoreExpr -> NameSet
238 -- There's no need to delete local binders, because they will all
239 -- be /internal/ names.
244 | isExternalName n = unitNameSet n
245 | otherwise = emptyNameSet
247 go (Lit _) = emptyNameSet
248 go (Type ty) = tyClsNamesOfType ty -- Don't need free tyvars
249 go (App e1 e2) = go e1 `unionNameSets` go e2
250 go (Lam v e) = go e `delFromNameSet` idName v
252 go (Cast e co) = go e `unionNameSets` tyClsNamesOfType co
253 go (Let (NonRec _ r) e) = go e `unionNameSets` go r
254 go (Let (Rec prs) e) = exprsFreeNames (map snd prs) `unionNameSets` go e
255 go (Case e _ ty as) = go e `unionNameSets` tyClsNamesOfType ty
256 `unionNameSets` unionManyNameSets (map go_alt as)
258 go_alt (_,_,r) = go r
260 -- | Finds the free /external/ names of several expressions: see 'exprFreeNames' for details
261 exprsFreeNames :: [CoreExpr] -> NameSet
262 exprsFreeNames es = foldr (unionNameSets . exprFreeNames) emptyNameSet es
265 %************************************************************************
267 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
269 %************************************************************************
272 -- | Those variables free in the right hand side of a rule
273 ruleRhsFreeVars :: CoreRule -> VarSet
274 ruleRhsFreeVars (BuiltinRule {}) = noFVs
275 ruleRhsFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs })
276 = delFromUFM fvs fn -- Note [Rule free var hack]
278 fvs = addBndrs bndrs (expr_fvs rhs) isLocalVar emptyVarSet
280 -- | Those variables free in the both the left right hand sides of a rule
281 ruleFreeVars :: CoreRule -> VarSet
282 ruleFreeVars (BuiltinRule {}) = noFVs
283 ruleFreeVars (Rule { ru_fn = fn, ru_bndrs = bndrs, ru_rhs = rhs, ru_args = args })
284 = delFromUFM fvs fn -- Note [Rule free var hack]
286 fvs = addBndrs bndrs (exprs_fvs (rhs:args)) isLocalVar emptyVarSet
288 -- | Those variables free in the right hand side of several rules
289 rulesFreeVars :: [CoreRule] -> VarSet
290 rulesFreeVars rules = foldr (unionVarSet . ruleFreeVars) emptyVarSet rules
292 ruleLhsFreeIds :: CoreRule -> VarSet
293 -- ^ This finds all locally-defined free Ids on the left hand side of a rule
294 ruleLhsFreeIds (BuiltinRule {}) = noFVs
295 ruleLhsFreeIds (Rule { ru_bndrs = bndrs, ru_args = args })
296 = addBndrs bndrs (exprs_fvs args) isLocalId emptyVarSet
299 Note [Rule free var hack]
300 ~~~~~~~~~~~~~~~~~~~~~~~~~
301 Don't include the Id in its own rhs free-var set.
302 Otherwise the occurrence analyser makes bindings recursive
303 that shoudn't be. E.g.
304 RULE: f (f x y) z ==> f x (f y z)
306 Also since rule_fn is a Name, not a Var, we have to use the grungy delUFM.
308 %************************************************************************
310 \section[freevars-everywhere]{Attaching free variables to every sub-expression}
312 %************************************************************************
314 The free variable pass annotates every node in the expression with its
315 NON-GLOBAL free variables and type variables.
318 -- | Every node in a binding group annotated with its
319 -- (non-global) free variables, both Ids and TyVars
320 type CoreBindWithFVs = AnnBind Id VarSet
321 -- | Every node in an expression annotated with its
322 -- (non-global) free variables, both Ids and TyVars
323 type CoreExprWithFVs = AnnExpr Id VarSet
325 freeVarsOf :: CoreExprWithFVs -> IdSet
326 -- ^ Inverse function to 'freeVars'
327 freeVarsOf (free_vars, _) = free_vars
332 aFreeVar :: Var -> VarSet
333 aFreeVar = unitVarSet
335 unionFVs :: VarSet -> VarSet -> VarSet
336 unionFVs = unionVarSet
338 delBindersFV :: [Var] -> VarSet -> VarSet
339 delBindersFV bs fvs = foldr delBinderFV fvs bs
341 delBinderFV :: Var -> VarSet -> VarSet
342 -- This way round, so we can do it multiple times using foldr
344 -- (b `delBinderFV` s) removes the binder b from the free variable set s,
347 -- the free variables of b's type
349 -- This is really important for some lambdas:
350 -- In (\x::a -> x) the only mention of "a" is in the binder.
353 -- let x::a = b in ...
354 -- we should really note that "a" is free in this expression.
355 -- It'll be pinned inside the /\a by the binding for b, but
356 -- it seems cleaner to make sure that a is in the free-var set
357 -- when it is mentioned.
359 -- This also shows up in recursive bindings. Consider:
360 -- /\a -> letrec x::a = x in E
361 -- Now, there are no explicit free type variables in the RHS of x,
362 -- but nevertheless "a" is free in its definition. So we add in
363 -- the free tyvars of the types of the binders, and include these in the
364 -- free vars of the group, attached to the top level of each RHS.
366 -- This actually happened in the defn of errorIO in IOBase.lhs:
367 -- errorIO (ST io) = case (errorIO# io) of
370 -- bottom = bottom -- Never evaluated
372 delBinderFV b s = (s `delVarSet` b) `unionFVs` varTypeTyVars b
373 -- Include coercion variables too!
375 varTypeTyVars :: Var -> TyVarSet
376 -- Find the type variables free in the type of the variable
377 -- Remember, coercion variables can mention type variables...
379 | isLocalId var || isCoVar var = tyVarsOfType (idType var)
380 | otherwise = emptyVarSet -- Global Ids and non-coercion TyVars
382 varTypeTcTyVars :: Var -> TyVarSet
383 -- Find the type variables free in the type of the variable
384 -- Remember, coercion variables can mention type variables...
386 | isLocalId var || isCoVar var = tcTyVarsOfType (idType var)
387 | otherwise = emptyVarSet -- Global Ids and non-coercion TyVars
389 idFreeVars :: Id -> VarSet
390 -- Type variables, rule variables, and inline variables
391 idFreeVars id = ASSERT( isId id)
392 varTypeTyVars id `unionVarSet`
393 idRuleAndUnfoldingVars id
395 bndrRuleAndUnfoldingVars ::Var -> VarSet
396 -- A 'let' can bind a type variable, and idRuleVars assumes
397 -- it's seeing an Id. This function tests first.
398 bndrRuleAndUnfoldingVars v | isTyVar v = emptyVarSet
399 | otherwise = idRuleAndUnfoldingVars v
401 idRuleAndUnfoldingVars :: Id -> VarSet
402 idRuleAndUnfoldingVars id = ASSERT( isId id)
403 idRuleVars id `unionVarSet`
406 idRuleVars ::Id -> VarSet -- Does *not* include CoreUnfolding vars
407 idRuleVars id = ASSERT( isId id) specInfoFreeVars (idSpecialisation id)
409 idRuleRhsVars :: Id -> VarSet -- Does *not* include the CoreUnfolding vars
410 -- Just the variables free on the *rhs* of a rule
411 -- See Note [Choosing loop breakers] in Simplify.lhs
412 idRuleRhsVars id = foldr (unionVarSet . ruleRhsFreeVars)
416 idUnfoldingVars :: Id -> VarSet
417 -- Produce free vars for an unfolding, but NOT for an ordinary
418 -- (non-inline) unfolding, since it is a dup of the rhs
419 -- and we'll get exponential behaviour if we look at both unf and rhs!
420 -- But do look at the *real* unfolding, even for loop breakers, else
421 -- we might get out-of-scope variables
423 = case realIdUnfolding id of
424 CoreUnfolding { uf_tmpl = rhs, uf_src = src }
425 | isInlineRuleSource src
427 DFunUnfolding _ args -> exprsFreeVars args
432 %************************************************************************
434 \subsection{Free variables (and types)}
436 %************************************************************************
439 freeVars :: CoreExpr -> CoreExprWithFVs
440 -- ^ Annotate a 'CoreExpr' with its (non-global) free type and value variables at every tree node
444 -- ToDo: insert motivating example for why we *need*
445 -- to include the idSpecVars in the FV list.
446 -- Actually [June 98] I don't think it's necessary
447 -- fvs = fvs_v `unionVarSet` idSpecVars v
449 fvs | isLocalVar v = aFreeVar v
452 freeVars (Lit lit) = (noFVs, AnnLit lit)
453 freeVars (Lam b body)
454 = (b `delBinderFV` freeVarsOf body', AnnLam b body')
456 body' = freeVars body
458 freeVars (App fun arg)
459 = (freeVarsOf fun2 `unionFVs` freeVarsOf arg2, AnnApp fun2 arg2)
464 freeVars (Case scrut bndr ty alts)
465 = ((bndr `delBinderFV` alts_fvs) `unionFVs` freeVarsOf scrut2 `unionFVs` tyVarsOfType ty,
466 AnnCase scrut2 bndr ty alts2)
468 scrut2 = freeVars scrut
470 (alts_fvs_s, alts2) = mapAndUnzip fv_alt alts
471 alts_fvs = foldr1 unionFVs alts_fvs_s
473 fv_alt (con,args,rhs) = (delBindersFV args (freeVarsOf rhs2),
478 freeVars (Let (NonRec binder rhs) body)
481 `unionFVs` bndrRuleAndUnfoldingVars binder,
482 -- Remember any rules; cf rhs_fvs above
483 AnnLet (AnnNonRec binder rhs2) body2)
486 body2 = freeVars body
487 body_fvs = binder `delBinderFV` freeVarsOf body2
489 freeVars (Let (Rec binds) body)
490 = (delBindersFV binders all_fvs,
491 AnnLet (AnnRec (binders `zip` rhss2)) body2)
493 (binders, rhss) = unzip binds
495 rhss2 = map freeVars rhss
496 rhs_body_fvs = foldr (unionFVs . freeVarsOf) body_fvs rhss2
497 all_fvs = foldr (unionFVs . idRuleAndUnfoldingVars) rhs_body_fvs binders
498 -- The "delBinderFV" happens after adding the idSpecVars,
499 -- since the latter may add some of the binders as fvs
501 body2 = freeVars body
502 body_fvs = freeVarsOf body2
505 freeVars (Cast expr co)
506 = (freeVarsOf expr2 `unionFVs` cfvs, AnnCast expr2 co)
508 expr2 = freeVars expr
509 cfvs = tyVarsOfType co
511 freeVars (Note other_note expr)
512 = (freeVarsOf expr2, AnnNote other_note expr2)
514 expr2 = freeVars expr
516 freeVars (Type ty) = (tyVarsOfType ty, AnnType ty)