2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Tidying up Core}
7 module TidyPgm( tidyCorePgm, tidyCoreExpr ) where
9 #include "HsVersions.h"
11 import CmdLineOpts ( DynFlags, DynFlag(..), opt_OmitInterfacePragmas )
13 import CoreUnfold ( noUnfolding, mkTopUnfolding, okToUnfoldInHiFile )
14 import CoreFVs ( ruleLhsFreeIds, ruleRhsFreeVars, exprSomeFreeVars )
15 import CoreTidy ( tidyExpr, tidyVarOcc, tidyIdRules )
16 import PprCore ( pprIdRules )
17 import CoreLint ( showPass, endPass )
18 import CoreUtils ( exprArity )
21 import Var ( Id, Var )
22 import Id ( idType, idInfo, idName, idCoreRules,
23 isExportedId, mkVanillaGlobal, isLocalId,
26 import IdInfo {- loads of stuff -}
27 import NewDemand ( isBottomingSig, topSig )
28 import BasicTypes ( isNeverActive )
29 import Name ( getOccName, nameOccName, mkInternalName, mkExternalName,
30 localiseName, isExternalName, nameSrcLoc
32 import NameEnv ( filterNameEnv )
33 import OccName ( TidyOccEnv, initTidyOccEnv, tidyOccName )
34 import Type ( tidyTopType )
35 import Module ( Module, moduleName )
36 import HscTypes ( PersistentCompilerState( pcs_PRS ),
37 PersistentRenamerState( prsOrig ),
38 NameSupply( nsNames, nsUniqs ),
39 TypeEnv, extendTypeEnvList, typeEnvIds,
40 ModDetails(..), TyThing(..)
42 import FiniteMap ( lookupFM, addToFM )
43 import Maybes ( orElse )
44 import ErrUtils ( showPass, dumpIfSet_core )
45 import UniqFM ( mapUFM )
46 import UniqSupply ( splitUniqSupply, uniqFromSupply )
47 import List ( partition )
48 import Util ( mapAccumL )
49 import Maybe ( isJust )
55 %************************************************************************
57 \subsection{What goes on}
59 %************************************************************************
65 Step 1: Figure out external Ids
66 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
67 First we figure out which Ids are "external" Ids. An
68 "external" Id is one that is visible from outside the compilation
70 a) the user exported ones
71 b) ones mentioned in the unfoldings, workers,
72 or rules of externally-visible ones
73 This exercise takes a sweep of the bindings bottom to top. Actually,
74 in Step 2 we're also going to need to know which Ids should be
75 exported with their unfoldings, so we produce not an IdSet but an
79 Step 2: Tidy the program
80 ~~~~~~~~~~~~~~~~~~~~~~~~
81 Next we traverse the bindings top to bottom. For each *top-level*
84 1. Make it into a GlobalId
86 2. Give it a system-wide Unique.
87 [Even non-exported things need system-wide Uniques because the
88 byte-code generator builds a single Name->BCO symbol table.]
90 We use the NameSupply kept in the PersistentRenamerState as the
91 source of such system-wide uniques.
93 For external Ids, use the original-name cache in the NameSupply
94 to ensure that the unique assigned is the same as the Id had
95 in any previous compilation run.
97 3. If it's an external Id, make it have a global Name, otherwise
98 make it have a local Name.
99 This is used by the code generator to decide whether
100 to make the label externally visible
102 4. Give external Ids a "tidy" occurrence name. This means
103 we can print them in interface files without confusing
104 "x" (unique 5) with "x" (unique 10).
106 5. Give it its UTTERLY FINAL IdInfo; in ptic,
107 * Its IdDetails becomes VanillaGlobal, reflecting the fact that
108 from now on we regard it as a global, not local, Id
110 * its unfolding, if it should have one
112 * its arity, computed from the number of visible lambdas
114 * its CAF info, computed from what is free in its RHS
117 Finally, substitute these new top-level binders consistently
118 throughout, including in unfoldings. We also tidy binders in
119 RHSs, so that they print nicely in interfaces.
122 tidyCorePgm :: DynFlags -> Module
123 -> PersistentCompilerState
124 -> CgInfoEnv -- Information from the back end,
125 -- to be splatted into the IdInfo
127 -> IO (PersistentCompilerState, ModDetails)
129 tidyCorePgm dflags mod pcs cg_info_env
130 (ModDetails { md_types = env_tc, md_insts = insts_tc,
131 md_binds = binds_in, md_rules = orphans_in })
132 = do { showPass dflags "Tidy Core"
134 ; let ext_ids = findExternalSet binds_in orphans_in
135 ; let ext_rules = findExternalRules binds_in orphans_in ext_ids
136 -- findExternalRules filters ext_rules to avoid binders that
137 -- aren't externally visible; but the externally-visible binders
138 -- are computed (by findExternalSet) assuming that all orphan
139 -- rules are exported. So in fact we may export more than we
140 -- need. (It's a sort of mutual recursion.)
142 -- We also make sure to avoid any exported binders. Consider
143 -- f{-u1-} = 1 -- Local decl
145 -- f{-u2-} = 2 -- Exported decl
147 -- The second exported decl must 'get' the name 'f', so we
148 -- have to put 'f' in the avoids list before we get to the first
149 -- decl. tidyTopId then does a no-op on exported binders.
150 ; let prs = pcs_PRS pcs
151 orig_ns = prsOrig prs
153 init_tidy_env = (orig_ns, initTidyOccEnv avoids, emptyVarEnv)
154 avoids = [getOccName name | bndr <- typeEnvIds env_tc,
155 let name = idName bndr,
157 -- In computing our "avoids" list, we must include
159 -- all things with global names (assigned once and for
160 -- all by the renamer)
161 -- since their names are "taken".
162 -- The type environment is a convenient source of such things.
164 ; let ((orig_ns', occ_env, subst_env), tidy_binds)
165 = mapAccumL (tidyTopBind mod ext_ids cg_info_env)
166 init_tidy_env binds_in
168 ; let tidy_rules = tidyIdRules (occ_env,subst_env) ext_rules
170 ; let prs' = prs { prsOrig = orig_ns' }
171 pcs' = pcs { pcs_PRS = prs' }
173 ; let final_ids = [ id
175 , id <- bindersOf bind
176 , isExternalName (idName id)]
178 -- Dfuns are local Ids that might have
179 -- changed their unique during tidying
180 ; let lookup_dfun_id id = lookupVarEnv subst_env id `orElse`
181 pprPanic "lookup_dfun_id" (ppr id)
184 ; let tidy_type_env = mkFinalTypeEnv env_tc final_ids
185 tidy_dfun_ids = map lookup_dfun_id insts_tc
187 ; let tidy_details = ModDetails { md_types = tidy_type_env,
188 md_rules = tidy_rules,
189 md_insts = tidy_dfun_ids,
190 md_binds = tidy_binds }
192 ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
193 ; dumpIfSet_core dflags Opt_D_dump_simpl
195 (pprIdRules tidy_rules)
197 ; return (pcs', tidy_details)
200 tidyCoreExpr :: CoreExpr -> IO CoreExpr
201 tidyCoreExpr expr = return (tidyExpr emptyTidyEnv expr)
205 %************************************************************************
207 \subsection{Write a new interface file}
209 %************************************************************************
212 mkFinalTypeEnv :: TypeEnv -- From typechecker
216 mkFinalTypeEnv type_env final_ids
217 = extendTypeEnvList (filterNameEnv keep_it type_env)
220 -- The competed type environment is gotten from
221 -- a) keeping the types and classes
222 -- b) removing all Ids,
223 -- c) adding Ids with correct IdInfo, including unfoldings,
224 -- gotten from the bindings
225 -- From (c) we keep only those Ids with Global names;
226 -- the CoreTidy pass makes sure these are all and only
227 -- the externally-accessible ones
228 -- This truncates the type environment to include only the
229 -- exported Ids and things needed from them, which saves space
231 -- However, we do keep things like constructors, which should not appear
232 -- in interface files, because they are needed by importing modules when
233 -- using the compilation manager
235 -- We keep implicit Ids, because they won't appear
236 -- in the bindings from which final_ids are derived!
237 keep_it (AnId id) = isImplicitId id -- Remove all Ids except implicit ones
238 keep_it other = True -- Keep all TyCons and Classes
242 findExternalRules :: [CoreBind]
243 -> [IdCoreRule] -- Orphan rules
244 -> IdEnv a -- Ids that are exported, so we need their rules
246 -- The complete rules are gotten by combining
247 -- a) the orphan rules
248 -- b) rules embedded in the top-level Ids
249 findExternalRules binds orphan_rules ext_ids
250 | opt_OmitInterfacePragmas = []
252 = filter needed_rule (orphan_rules ++ local_rules)
255 | id <- bindersOfBinds binds,
256 id `elemVarEnv` ext_ids,
257 rule <- idCoreRules id
259 needed_rule (id, rule)
260 = not (isBuiltinRule rule)
261 -- We can't print builtin rules in interface files
262 -- Since they are built in, an importing module
263 -- will have access to them anyway
265 && not (any internal_id (varSetElems (ruleLhsFreeIds rule)))
266 -- Don't export a rule whose LHS mentions an Id that
267 -- is completely internal (i.e. not visible to an
270 internal_id id = isLocalId id && not (id `elemVarEnv` ext_ids)
273 %************************************************************************
275 \subsection{Step 1: finding externals}
277 %************************************************************************
280 findExternalSet :: [CoreBind] -> [IdCoreRule]
281 -> IdEnv Bool -- In domain => external
282 -- Range = True <=> show unfolding
283 -- Step 1 from the notes above
284 findExternalSet binds orphan_rules
285 = foldr find init_needed binds
287 orphan_rule_ids :: IdSet
288 orphan_rule_ids = unionVarSets [ ruleRhsFreeVars rule
289 | (_, rule) <- orphan_rules]
290 init_needed :: IdEnv Bool
291 init_needed = mapUFM (\_ -> False) orphan_rule_ids
292 -- The mapUFM is a bit cheesy. It is a cheap way
293 -- to turn the set of orphan_rule_ids, which we use to initialise
294 -- the sweep, into a mapping saying 'don't expose unfolding'
295 -- (When we come to the binding site we may change our mind, of course.)
297 find (NonRec id rhs) needed
298 | need_id needed id = addExternal (id,rhs) needed
300 find (Rec prs) needed = find_prs prs needed
302 -- For a recursive group we have to look for a fixed point
304 | null needed_prs = needed
305 | otherwise = find_prs other_prs new_needed
307 (needed_prs, other_prs) = partition (need_pr needed) prs
308 new_needed = foldr addExternal needed needed_prs
310 -- The 'needed' set contains the Ids that are needed by earlier
311 -- interface file emissions. If the Id isn't in this set, and isn't
312 -- exported, there's no need to emit anything
313 need_id needed_set id = id `elemVarEnv` needed_set || isExportedId id
314 need_pr needed_set (id,rhs) = need_id needed_set id
316 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
317 -- The Id is needed; extend the needed set
318 -- with it and its dependents (free vars etc)
319 addExternal (id,rhs) needed
320 = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
323 add_occ id needed = extendVarEnv needed id False
324 -- "False" because we don't know we need the Id's unfolding
325 -- We'll override it later when we find the binding site
327 new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
328 | otherwise = worker_ids `unionVarSet`
329 unfold_ids `unionVarSet`
333 dont_inline = isNeverActive (inlinePragInfo idinfo)
334 loop_breaker = isLoopBreaker (occInfo idinfo)
335 bottoming_fn = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
336 spec_ids = rulesRhsFreeVars (specInfo idinfo)
337 worker_info = workerInfo idinfo
339 -- Stuff to do with the Id's unfolding
340 -- The simplifier has put an up-to-date unfolding
341 -- in the IdInfo, but the RHS will do just as well
342 unfolding = unfoldingInfo idinfo
343 rhs_is_small = not (neverUnfold unfolding)
345 -- We leave the unfolding there even if there is a worker
346 -- In GHCI the unfolding is used by importers
347 -- When writing an interface file, we omit the unfolding
348 -- if there is a worker
349 show_unfold = not bottoming_fn && -- Not necessary
352 rhs_is_small && -- Small enough
353 okToUnfoldInHiFile rhs -- No casms etc
355 unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
356 | otherwise = emptyVarSet
358 worker_ids = case worker_info of
359 HasWorker work_id _ -> unitVarSet work_id
360 otherwise -> emptyVarSet
364 %************************************************************************
366 \subsection{Step 2: top-level tidying}
368 %************************************************************************
372 type TopTidyEnv = (NameSupply, TidyOccEnv, VarEnv Var)
374 -- TopTidyEnv: when tidying we need to know
375 -- * ns: The NameSupply, containing a unique supply and any pre-ordained Names.
376 -- These may have arisen because the
377 -- renamer read in an interface file mentioning M.$wf, say,
378 -- and assigned it unique r77. If, on this compilation, we've
379 -- invented an Id whose name is $wf (but with a different unique)
380 -- we want to rename it to have unique r77, so that we can do easy
381 -- comparisons with stuff from the interface file
383 -- * occ_env: The TidyOccEnv, which tells us which local occurrences
386 -- * subst_env: A Var->Var mapping that substitutes the new Var for the old
391 tidyTopBind :: Module
392 -> IdEnv Bool -- Domain = Ids that should be external
393 -- True <=> their unfolding is external too
395 -> TopTidyEnv -> CoreBind
396 -> (TopTidyEnv, CoreBind)
398 tidyTopBind mod ext_ids cg_info_env top_tidy_env (NonRec bndr rhs)
399 = ((orig,occ,subst) , NonRec bndr' rhs')
401 ((orig,occ,subst), bndr')
402 = tidyTopBinder mod ext_ids cg_info_env
403 rec_tidy_env rhs rhs' top_tidy_env bndr
404 rec_tidy_env = (occ,subst)
405 rhs' = tidyExpr rec_tidy_env rhs
407 tidyTopBind mod ext_ids cg_info_env top_tidy_env (Rec prs)
408 = (final_env, Rec prs')
410 (final_env@(_,occ,subst), prs') = mapAccumL do_one top_tidy_env prs
411 rec_tidy_env = (occ,subst)
413 do_one top_tidy_env (bndr,rhs)
414 = ((orig,occ,subst), (bndr',rhs'))
416 ((orig,occ,subst), bndr')
417 = tidyTopBinder mod ext_ids cg_info_env
418 rec_tidy_env rhs rhs' top_tidy_env bndr
420 rhs' = tidyExpr rec_tidy_env rhs
422 tidyTopBinder :: Module -> IdEnv Bool -> CgInfoEnv
423 -> TidyEnv -- The TidyEnv is used to tidy the IdInfo
424 -> CoreExpr -- RHS *before* tidying
425 -> CoreExpr -- RHS *after* tidying
426 -- The TidyEnv and the after-tidying RHS are
427 -- both are knot-tied: don't look at them!
428 -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
429 -- NB: tidyTopBinder doesn't affect the unique supply
431 tidyTopBinder mod ext_ids cg_info_env rec_tidy_env rhs tidy_rhs
432 env@(ns2, occ_env2, subst_env2) id
433 -- This function is the heart of Step 2
434 -- The rec_tidy_env is the one to use for the IdInfo
435 -- It's necessary because when we are dealing with a recursive
436 -- group, a variable late in the group might be mentioned
437 -- in the IdInfo of one early in the group
439 -- The rhs is already tidied
441 = ((orig_env', occ_env', subst_env'), id')
443 (orig_env', occ_env', name') = tidyTopName mod ns2 occ_env2
446 ty' = tidyTopType (idType id)
447 idinfo = tidyTopIdInfo rec_tidy_env is_external
448 (idInfo id) unfold_info arity
449 (lookupCgInfo cg_info_env name')
451 id' = mkVanillaGlobal name' ty' idinfo
453 subst_env' = extendVarEnv subst_env2 id id'
455 maybe_external = lookupVarEnv ext_ids id
456 is_external = isJust maybe_external
458 -- Expose an unfolding if ext_ids tells us to
459 -- Remember that ext_ids maps an Id to a Bool:
460 -- True to show the unfolding, False to hide it
461 show_unfold = maybe_external `orElse` False
462 unfold_info | show_unfold = mkTopUnfolding tidy_rhs
463 | otherwise = noUnfolding
465 -- Usually the Id will have an accurate arity on it, because
466 -- the simplifier has just run, but not always.
467 -- One case I found was when the last thing the simplifier
468 -- did was to let-bind a non-atomic argument and then float
469 -- it to the top level. So it seems more robust just to
471 arity = exprArity rhs
475 -- tidyTopIdInfo creates the final IdInfo for top-level
476 -- binders. There are two delicate pieces:
478 -- * Arity. After CoreTidy, this arity must not change any more.
479 -- Indeed, CorePrep must eta expand where necessary to make
480 -- the manifest arity equal to the claimed arity.
482 -- * CAF info, which comes from the CoreToStg pass via a knot.
483 -- The CAF info will not be looked at by the downstream stuff:
484 -- it *generates* it, and knot-ties it back. It will only be
485 -- looked at by (a) MkIface when generating an interface file
486 -- (b) In GHCi, importing modules
487 -- Nevertheless, we add the info here so that it propagates to all
488 -- occurrences of the binders in RHSs, and hence to occurrences in
489 -- unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
491 -- An alterative would be to do a second pass over the unfoldings
492 -- of Ids, and rules, right at the top, but that would be a pain.
494 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity cg_info
495 | opt_OmitInterfacePragmas || not is_external
496 -- Only basic info if the Id isn't external, or if we don't have -O
499 | otherwise -- Add extra optimisation info
501 `setInlinePragInfo` inlinePragInfo idinfo
502 `setUnfoldingInfo` unfold_info
503 `setWorkerInfo` tidyWorker tidy_env (workerInfo idinfo)
504 -- NB: we throw away the Rules
505 -- They have already been extracted by findExternalRules
508 -- baasic_info is attached to every top-level binder
509 basic_info = vanillaIdInfo
512 `setAllStrictnessInfo` newStrictnessInfo idinfo
514 -- This is where we set names to local/global based on whether they really are
515 -- externally visible (see comment at the top of this module). If the name
516 -- was previously local, we have to give it a unique occurrence name if
517 -- we intend to externalise it.
518 tidyTopName mod ns occ_env external name
519 | global && internal = (ns, occ_env, localiseName name)
521 | global && external = (ns, occ_env, name)
522 -- Global names are assumed to have been allocated by the renamer,
523 -- so they already have the "right" unique
524 -- And it's a system-wide unique too
526 | local && internal = (ns_w_local, occ_env', new_local_name)
527 -- Even local, internal names must get a unique occurrence, because
528 -- if we do -split-objs we externalise the name later, in the code generator
530 -- Similarly, we must make sure it has a system-wide Unique, because
531 -- the byte-code generator builds a system-wide Name->BCO symbol table
533 | local && external = case lookupFM ns_names key of
534 Just orig -> (ns, occ_env', orig)
535 Nothing -> (ns_w_global, occ_env', new_external_name)
536 -- If we want to externalise a currently-local name, check
537 -- whether we have already assigned a unique for it.
538 -- If so, use it; if not, extend the table (ns_w_global).
539 -- This is needed when *re*-compiling a module in GHCi; we want to
540 -- use the same name for externally-visible things as we did before.
543 global = isExternalName name
545 internal = not external
547 (occ_env', occ') = tidyOccName occ_env (nameOccName name)
548 key = (moduleName mod, occ')
549 ns_names = nsNames ns
550 ns_uniqs = nsUniqs ns
551 (us1, us2) = splitUniqSupply ns_uniqs
552 uniq = uniqFromSupply us1
553 loc = nameSrcLoc name
555 new_local_name = mkInternalName uniq occ' loc
556 new_external_name = mkExternalName uniq mod occ' loc
558 ns_w_local = ns { nsUniqs = us2 }
559 ns_w_global = ns { nsUniqs = us2, nsNames = addToFM ns_names key new_external_name }
562 ------------ Worker --------------
563 tidyWorker tidy_env (HasWorker work_id wrap_arity)
564 = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
565 tidyWorker tidy_env other