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, hasCafRefs )
21 import Var ( Id, Var )
22 import Id ( idType, idInfo, idName, idCoreRules,
23 isExportedId, mkVanillaGlobal, isLocalId,
24 isImplicitId, idArity, setIdInfo
26 import IdInfo {- loads of stuff -}
27 import NewDemand ( isBottomingSig, topSig )
28 import BasicTypes ( isNeverActive )
29 import Name ( getOccName, nameOccName, mkInternalName,
30 localiseName, isExternalName, nameSrcLoc
32 import RnEnv ( lookupOrigNameCache, newExternalName )
33 import NameEnv ( lookupNameEnv, filterNameEnv )
34 import OccName ( TidyOccEnv, initTidyOccEnv, tidyOccName )
35 import Type ( tidyTopType )
36 import Module ( Module )
37 import HscTypes ( PersistentCompilerState( pcs_nc ),
38 NameCache( nsNames, nsUniqs ),
39 TypeEnv, extendTypeEnvList, typeEnvIds,
40 ModGuts(..), ModGuts, TyThing(..)
42 import Maybes ( orElse )
43 import ErrUtils ( showPass, dumpIfSet_core )
44 import UniqFM ( mapUFM )
45 import UniqSupply ( splitUniqSupply, uniqFromSupply )
46 import List ( partition )
47 import Util ( mapAccumL )
48 import Maybe ( isJust )
53 %************************************************************************
55 \subsection{What goes on}
57 %************************************************************************
63 Step 1: Figure out external Ids
64 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
65 First we figure out which Ids are "external" Ids. An
66 "external" Id is one that is visible from outside the compilation
68 a) the user exported ones
69 b) ones mentioned in the unfoldings, workers,
70 or rules of externally-visible ones
71 This exercise takes a sweep of the bindings bottom to top. Actually,
72 in Step 2 we're also going to need to know which Ids should be
73 exported with their unfoldings, so we produce not an IdSet but an
77 Step 2: Tidy the program
78 ~~~~~~~~~~~~~~~~~~~~~~~~
79 Next we traverse the bindings top to bottom. For each *top-level*
82 1. Make it into a GlobalId
84 2. Give it a system-wide Unique.
85 [Even non-exported things need system-wide Uniques because the
86 byte-code generator builds a single Name->BCO symbol table.]
88 We use the NameCache kept in the PersistentCompilerState as the
89 source of such system-wide uniques.
91 For external Ids, use the original-name cache in the NameCache
92 to ensure that the unique assigned is the same as the Id had
93 in any previous compilation run.
95 3. If it's an external Id, make it have a global Name, otherwise
96 make it have a local Name.
97 This is used by the code generator to decide whether
98 to make the label externally visible
100 4. Give external Ids a "tidy" occurrence name. This means
101 we can print them in interface files without confusing
102 "x" (unique 5) with "x" (unique 10).
104 5. Give it its UTTERLY FINAL IdInfo; in ptic,
105 * Its IdDetails becomes VanillaGlobal, reflecting the fact that
106 from now on we regard it as a global, not local, Id
108 * its unfolding, if it should have one
110 * its arity, computed from the number of visible lambdas
112 * its CAF info, computed from what is free in its RHS
115 Finally, substitute these new top-level binders consistently
116 throughout, including in unfoldings. We also tidy binders in
117 RHSs, so that they print nicely in interfaces.
120 tidyCorePgm :: DynFlags
121 -> PersistentCompilerState
123 -> IO (PersistentCompilerState, ModGuts)
125 tidyCorePgm dflags pcs
126 mod_impl@(ModGuts { mg_module = mod,
127 mg_types = env_tc, mg_insts = insts_tc,
128 mg_binds = binds_in, mg_rules = orphans_in })
129 = do { showPass dflags "Tidy Core"
131 ; let ext_ids = findExternalSet binds_in orphans_in
132 ; let ext_rules = findExternalRules binds_in orphans_in ext_ids
133 -- findExternalRules filters ext_rules to avoid binders that
134 -- aren't externally visible; but the externally-visible binders
135 -- are computed (by findExternalSet) assuming that all orphan
136 -- rules are exported. So in fact we may export more than we
137 -- need. (It's a sort of mutual recursion.)
139 -- We also make sure to avoid any exported binders. Consider
140 -- f{-u1-} = 1 -- Local decl
142 -- f{-u2-} = 2 -- Exported decl
144 -- The second exported decl must 'get' the name 'f', so we
145 -- have to put 'f' in the avoids list before we get to the first
146 -- decl. tidyTopId then does a no-op on exported binders.
147 ; let orig_ns = pcs_nc pcs
148 init_tidy_env = (orig_ns, initTidyOccEnv avoids, emptyVarEnv)
149 avoids = [getOccName name | bndr <- typeEnvIds env_tc,
150 let name = idName bndr,
152 -- In computing our "avoids" list, we must include
154 -- all things with global names (assigned once and for
155 -- all by the renamer)
156 -- since their names are "taken".
157 -- The type environment is a convenient source of such things.
159 ; let ((orig_ns', occ_env, subst_env), tidy_binds)
160 = mapAccumL (tidyTopBind mod ext_ids)
161 init_tidy_env binds_in
163 ; let tidy_rules = tidyIdRules (occ_env,subst_env) ext_rules
165 ; let pcs' = pcs { pcs_nc = orig_ns' }
167 ; let tidy_type_env = mkFinalTypeEnv env_tc tidy_binds
169 -- Dfuns are local Ids that might have
170 -- changed their unique during tidying. Remember
171 -- to lookup the id in the TypeEnv too, because
172 -- those Ids have had their IdInfo stripped if
174 ; let lookup_dfun_id id =
175 case lookupVarEnv subst_env id of
176 Nothing -> dfun_panic
178 case lookupNameEnv tidy_type_env (idName id) of
182 dfun_panic = pprPanic "lookup_dfun_id" (ppr id)
184 tidy_dfun_ids = map lookup_dfun_id insts_tc
186 ; let tidy_result = mod_impl { mg_types = tidy_type_env,
187 mg_rules = tidy_rules,
188 mg_insts = tidy_dfun_ids,
189 mg_binds = tidy_binds }
191 ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
192 ; dumpIfSet_core dflags Opt_D_dump_simpl
194 (pprIdRules tidy_rules)
196 ; return (pcs', tidy_result)
199 tidyCoreExpr :: CoreExpr -> IO CoreExpr
200 tidyCoreExpr expr = return (tidyExpr emptyTidyEnv expr)
204 %************************************************************************
206 \subsection{Write a new interface file}
208 %************************************************************************
211 mkFinalTypeEnv :: TypeEnv -- From typechecker
212 -> [CoreBind] -- Final Ids
215 -- The competed type environment is gotten from
216 -- a) keeping the types and classes
217 -- b) removing all Ids,
218 -- c) adding Ids with correct IdInfo, including unfoldings,
219 -- gotten from the bindings
220 -- From (c) we keep only those Ids with Global names;
221 -- the CoreTidy pass makes sure these are all and only
222 -- the externally-accessible ones
223 -- This truncates the type environment to include only the
224 -- exported Ids and things needed from them, which saves space
226 -- However, we do keep things like constructors, which should not appear
227 -- in interface files, because they are needed by importing modules when
228 -- using the compilation manager
230 mkFinalTypeEnv type_env tidy_binds
231 = extendTypeEnvList (filterNameEnv keep_it type_env) final_ids
233 final_ids = [ AnId (strip_id_info id)
234 | bind <- tidy_binds,
235 id <- bindersOf bind,
236 isExternalName (idName id)]
239 | opt_OmitInterfacePragmas = id `setIdInfo` vanillaIdInfo
241 -- If the interface file has no pragma info then discard all
244 -- This is not so important for *this* module, but it's
245 -- vital for ghc --make:
246 -- subsequent compilations must not see (e.g.) the arity if
247 -- the interface file does not contain arity
248 -- If they do, they'll exploit the arity; then the arity might
249 -- change, but the iface file doesn't change => recompilation
250 -- does not happen => disaster
252 -- This IdInfo will live long-term in the Id => vanillaIdInfo makes
253 -- a conservative assumption about Caf-hood
255 -- We're not worried about occurrences of these Ids in unfoldings,
256 -- because in OmitInterfacePragmas mode we're stripping all the
257 -- unfoldings anyway.
259 -- We keep implicit Ids, because they won't appear
260 -- in the bindings from which final_ids are derived!
261 keep_it (AnId id) = isImplicitId id -- Remove all Ids except implicit ones
262 keep_it other = True -- Keep all TyCons and Classes
266 findExternalRules :: [CoreBind]
267 -> [IdCoreRule] -- Orphan rules
268 -> IdEnv a -- Ids that are exported, so we need their rules
270 -- The complete rules are gotten by combining
271 -- a) the orphan rules
272 -- b) rules embedded in the top-level Ids
273 findExternalRules binds orphan_rules ext_ids
274 | opt_OmitInterfacePragmas = []
276 = filter needed_rule (orphan_rules ++ local_rules)
279 | id <- bindersOfBinds binds,
280 id `elemVarEnv` ext_ids,
281 rule <- idCoreRules id
283 needed_rule (id, rule)
284 = not (isBuiltinRule rule)
285 -- We can't print builtin rules in interface files
286 -- Since they are built in, an importing module
287 -- will have access to them anyway
289 && not (any internal_id (varSetElems (ruleLhsFreeIds rule)))
290 -- Don't export a rule whose LHS mentions an Id that
291 -- is completely internal (i.e. not visible to an
294 internal_id id = isLocalId id && not (id `elemVarEnv` ext_ids)
297 %************************************************************************
299 \subsection{Step 1: finding externals}
301 %************************************************************************
304 findExternalSet :: [CoreBind] -> [IdCoreRule]
305 -> IdEnv Bool -- In domain => external
306 -- Range = True <=> show unfolding
307 -- Step 1 from the notes above
308 findExternalSet binds orphan_rules
309 = foldr find init_needed binds
311 orphan_rule_ids :: IdSet
312 orphan_rule_ids = unionVarSets [ ruleRhsFreeVars rule
313 | (_, rule) <- orphan_rules]
314 init_needed :: IdEnv Bool
315 init_needed = mapUFM (\_ -> False) orphan_rule_ids
316 -- The mapUFM is a bit cheesy. It is a cheap way
317 -- to turn the set of orphan_rule_ids, which we use to initialise
318 -- the sweep, into a mapping saying 'don't expose unfolding'
319 -- (When we come to the binding site we may change our mind, of course.)
321 find (NonRec id rhs) needed
322 | need_id needed id = addExternal (id,rhs) needed
324 find (Rec prs) needed = find_prs prs needed
326 -- For a recursive group we have to look for a fixed point
328 | null needed_prs = needed
329 | otherwise = find_prs other_prs new_needed
331 (needed_prs, other_prs) = partition (need_pr needed) prs
332 new_needed = foldr addExternal needed needed_prs
334 -- The 'needed' set contains the Ids that are needed by earlier
335 -- interface file emissions. If the Id isn't in this set, and isn't
336 -- exported, there's no need to emit anything
337 need_id needed_set id = id `elemVarEnv` needed_set || isExportedId id
338 need_pr needed_set (id,rhs) = need_id needed_set id
340 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
341 -- The Id is needed; extend the needed set
342 -- with it and its dependents (free vars etc)
343 addExternal (id,rhs) needed
344 = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
347 add_occ id needed = extendVarEnv needed id False
348 -- "False" because we don't know we need the Id's unfolding
349 -- We'll override it later when we find the binding site
351 new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
352 | otherwise = worker_ids `unionVarSet`
353 unfold_ids `unionVarSet`
357 dont_inline = isNeverActive (inlinePragInfo idinfo)
358 loop_breaker = isLoopBreaker (occInfo idinfo)
359 bottoming_fn = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
360 spec_ids = rulesRhsFreeVars (specInfo idinfo)
361 worker_info = workerInfo idinfo
363 -- Stuff to do with the Id's unfolding
364 -- The simplifier has put an up-to-date unfolding
365 -- in the IdInfo, but the RHS will do just as well
366 unfolding = unfoldingInfo idinfo
367 rhs_is_small = not (neverUnfold unfolding)
369 -- We leave the unfolding there even if there is a worker
370 -- In GHCI the unfolding is used by importers
371 -- When writing an interface file, we omit the unfolding
372 -- if there is a worker
373 show_unfold = not bottoming_fn && -- Not necessary
376 rhs_is_small && -- Small enough
377 okToUnfoldInHiFile rhs -- No casms etc
379 unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
380 | otherwise = emptyVarSet
382 worker_ids = case worker_info of
383 HasWorker work_id _ -> unitVarSet work_id
384 otherwise -> emptyVarSet
388 %************************************************************************
390 \subsection{Step 2: top-level tidying}
392 %************************************************************************
396 type TopTidyEnv = (NameCache, TidyOccEnv, VarEnv Var)
398 -- TopTidyEnv: when tidying we need to know
399 -- * ns: The NameCache, containing a unique supply and any pre-ordained Names.
400 -- These may have arisen because the
401 -- renamer read in an interface file mentioning M.$wf, say,
402 -- and assigned it unique r77. If, on this compilation, we've
403 -- invented an Id whose name is $wf (but with a different unique)
404 -- we want to rename it to have unique r77, so that we can do easy
405 -- comparisons with stuff from the interface file
407 -- * occ_env: The TidyOccEnv, which tells us which local occurrences
410 -- * subst_env: A Var->Var mapping that substitutes the new Var for the old
415 tidyTopBind :: Module
416 -> IdEnv Bool -- Domain = Ids that should be external
417 -- True <=> their unfolding is external too
418 -> TopTidyEnv -> CoreBind
419 -> (TopTidyEnv, CoreBind)
421 tidyTopBind mod ext_ids top_tidy_env (NonRec bndr rhs)
422 = ((orig,occ,subst) , NonRec bndr' rhs')
424 ((orig,occ,subst), bndr')
425 = tidyTopBinder mod ext_ids caf_info
426 rec_tidy_env rhs rhs' top_tidy_env bndr
427 rec_tidy_env = (occ,subst)
428 rhs' = tidyExpr rec_tidy_env rhs
429 caf_info = hasCafRefs (const True) (idArity bndr') rhs'
431 tidyTopBind mod ext_ids top_tidy_env (Rec prs)
432 = (final_env, Rec prs')
434 (final_env@(_,occ,subst), prs') = mapAccumL do_one top_tidy_env prs
435 rec_tidy_env = (occ,subst)
437 do_one top_tidy_env (bndr,rhs)
438 = ((orig,occ,subst), (bndr',rhs'))
440 ((orig,occ,subst), bndr')
441 = tidyTopBinder mod ext_ids caf_info
442 rec_tidy_env rhs rhs' top_tidy_env bndr
444 rhs' = tidyExpr rec_tidy_env rhs
446 -- the CafInfo for a recursive group says whether *any* rhs in
447 -- the group may refer indirectly to a CAF (because then, they all do).
448 pred v = v `notElem` map fst prs'
450 | or [ mayHaveCafRefs (hasCafRefs pred (idArity bndr) rhs)
451 | (bndr,rhs) <- prs' ] = MayHaveCafRefs
452 | otherwise = NoCafRefs
454 tidyTopBinder :: Module -> IdEnv Bool -> CafInfo
455 -> TidyEnv -- The TidyEnv is used to tidy the IdInfo
456 -> CoreExpr -- RHS *before* tidying
457 -> CoreExpr -- RHS *after* tidying
458 -- The TidyEnv and the after-tidying RHS are
459 -- both are knot-tied: don't look at them!
460 -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
461 -- NB: tidyTopBinder doesn't affect the unique supply
463 tidyTopBinder mod ext_ids caf_info rec_tidy_env rhs tidy_rhs
464 env@(ns2, occ_env2, subst_env2) id
465 -- This function is the heart of Step 2
466 -- The rec_tidy_env is the one to use for the IdInfo
467 -- It's necessary because when we are dealing with a recursive
468 -- group, a variable late in the group might be mentioned
469 -- in the IdInfo of one early in the group
471 -- The rhs is already tidied
473 = ((orig_env', occ_env', subst_env'), id')
475 (orig_env', occ_env', name') = tidyTopName mod ns2 occ_env2
478 ty' = tidyTopType (idType id)
479 idinfo = tidyTopIdInfo rec_tidy_env is_external
480 (idInfo id) unfold_info arity
483 id' = mkVanillaGlobal name' ty' idinfo
485 subst_env' = extendVarEnv subst_env2 id id'
487 maybe_external = lookupVarEnv ext_ids id
488 is_external = isJust maybe_external
490 -- Expose an unfolding if ext_ids tells us to
491 -- Remember that ext_ids maps an Id to a Bool:
492 -- True to show the unfolding, False to hide it
493 show_unfold = maybe_external `orElse` False
494 unfold_info | show_unfold = mkTopUnfolding tidy_rhs
495 | otherwise = noUnfolding
497 -- Usually the Id will have an accurate arity on it, because
498 -- the simplifier has just run, but not always.
499 -- One case I found was when the last thing the simplifier
500 -- did was to let-bind a non-atomic argument and then float
501 -- it to the top level. So it seems more robust just to
503 arity = exprArity rhs
506 -- tidyTopIdInfo creates the final IdInfo for top-level
507 -- binders. There are two delicate pieces:
509 -- * Arity. After CoreTidy, this arity must not change any more.
510 -- Indeed, CorePrep must eta expand where necessary to make
511 -- the manifest arity equal to the claimed arity.
513 -- * CAF info. This must also remain valid through to code generation.
514 -- We add the info here so that it propagates to all
515 -- occurrences of the binders in RHSs, and hence to occurrences in
516 -- unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
517 -- CoreToStg makes use of this when constructing SRTs.
519 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity caf_info
520 | not is_external -- For internal Ids (not externally visible)
521 = vanillaIdInfo -- we only need enough info for code generation
522 -- Arity and strictness info are enough;
523 -- c.f. CoreTidy.tidyLetBndr
524 `setCafInfo` caf_info
526 `setAllStrictnessInfo` newStrictnessInfo idinfo
528 | otherwise -- Externally-visible Ids get the whole lot
530 `setCafInfo` caf_info
532 `setAllStrictnessInfo` newStrictnessInfo idinfo
533 `setInlinePragInfo` inlinePragInfo idinfo
534 `setUnfoldingInfo` unfold_info
535 `setWorkerInfo` tidyWorker tidy_env (workerInfo idinfo)
536 -- NB: we throw away the Rules
537 -- They have already been extracted by findExternalRules
540 -- This is where we set names to local/global based on whether they really are
541 -- externally visible (see comment at the top of this module). If the name
542 -- was previously local, we have to give it a unique occurrence name if
543 -- we intend to externalise it.
544 tidyTopName mod ns occ_env external name
545 | global && internal = (ns, occ_env, localiseName name)
547 | global && external = (ns, occ_env, name)
548 -- Global names are assumed to have been allocated by the renamer,
549 -- so they already have the "right" unique
550 -- And it's a system-wide unique too
552 | local && internal = (ns_w_local, occ_env', new_local_name)
553 -- Even local, internal names must get a unique occurrence, because
554 -- if we do -split-objs we externalise the name later, in the code generator
556 -- Similarly, we must make sure it has a system-wide Unique, because
557 -- the byte-code generator builds a system-wide Name->BCO symbol table
559 | local && external = case lookupOrigNameCache ns_names mod occ' of
560 Just orig -> (ns, occ_env', orig)
561 Nothing -> (ns_w_global, occ_env', new_external_name)
562 -- If we want to externalise a currently-local name, check
563 -- whether we have already assigned a unique for it.
564 -- If so, use it; if not, extend the table (ns_w_global).
565 -- This is needed when *re*-compiling a module in GHCi; we want to
566 -- use the same name for externally-visible things as we did before.
569 global = isExternalName name
571 internal = not external
572 loc = nameSrcLoc name
574 (occ_env', occ') = tidyOccName occ_env (nameOccName name)
576 ns_names = nsNames ns
577 (us1, us2) = splitUniqSupply (nsUniqs ns)
578 uniq = uniqFromSupply us1
579 new_local_name = mkInternalName uniq occ' loc
580 ns_w_local = ns { nsUniqs = us2 }
582 (ns_w_global, new_external_name) = newExternalName ns mod occ' loc
585 ------------ Worker --------------
586 tidyWorker tidy_env (HasWorker work_id wrap_arity)
587 = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
588 tidyWorker tidy_env other