PageRenderTime 44ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/ghc-7.0.4/compiler/coreSyn/CoreFVs.lhs

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