2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Tidying up Core}
7 module TidyPgm( mkBootModDetailsDs, mkBootModDetailsTc, tidyProgram ) where
9 #include "HsVersions.h"
23 import Var hiding( mkGlobalId )
43 import FastBool hiding ( fastOr )
45 import Data.List ( partition )
46 import Data.Maybe ( isJust )
47 import Data.IORef ( IORef, readIORef, writeIORef )
51 Constructing the TypeEnv, Instances, Rules from which the ModIface is
52 constructed, and which goes on to subsequent modules in --make mode.
54 Most of the interface file is obtained simply by serialising the
55 TypeEnv. One important consequence is that if the *interface file*
56 has pragma info if and only if the final TypeEnv does. This is not so
57 important for *this* module, but it's essential for ghc --make:
58 subsequent compilations must not see (e.g.) the arity if the interface
59 file does not contain arity If they do, they'll exploit the arity;
60 then the arity might change, but the iface file doesn't change =>
61 recompilation does not happen => disaster.
63 For data types, the final TypeEnv will have a TyThing for the TyCon,
64 plus one for each DataCon; the interface file will contain just one
65 data type declaration, but it is de-serialised back into a collection
68 %************************************************************************
72 %************************************************************************
75 Plan A: mkBootModDetails: omit pragmas, make interfaces small
76 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
79 * Drop all WiredIn things from the TypeEnv
80 (we never want them in interface files)
82 * Retain all TyCons and Classes in the TypeEnv, to avoid
83 having to find which ones are mentioned in the
86 * Trim off the constructors of non-exported TyCons, both
87 from the TyCon and from the TypeEnv
89 * Drop non-exported Ids from the TypeEnv
91 * Tidy the types of the DFunIds of Instances,
92 make them into GlobalIds, (they already have External Names)
93 and add them to the TypeEnv
95 * Tidy the types of the (exported) Ids in the TypeEnv,
96 make them into GlobalIds (they already have External Names)
98 * Drop rules altogether
100 * Tidy the bindings, to ensure that the Caf and Arity
101 information is correct for each top-level binder; the
102 code generator needs it. And to ensure that local names have
103 distinct OccNames in case of object-file splitting
106 -- This is Plan A: make a small type env when typechecking only,
107 -- or when compiling a hs-boot file, or simply when not using -O
109 -- We don't look at the bindings at all -- there aren't any
112 mkBootModDetailsTc :: HscEnv -> TcGblEnv -> IO ModDetails
113 mkBootModDetailsTc hsc_env
114 TcGblEnv{ tcg_exports = exports,
115 tcg_type_env = type_env,
117 tcg_fam_insts = fam_insts
119 = mkBootModDetails hsc_env exports type_env insts fam_insts
121 mkBootModDetailsDs :: HscEnv -> ModGuts -> IO ModDetails
122 mkBootModDetailsDs hsc_env
123 ModGuts{ mg_exports = exports,
126 mg_fam_insts = fam_insts
128 = mkBootModDetails hsc_env exports type_env insts fam_insts
130 mkBootModDetails :: HscEnv -> [AvailInfo] -> NameEnv TyThing
131 -> [Instance] -> [FamInstEnv.FamInst] -> IO ModDetails
132 mkBootModDetails hsc_env exports type_env insts fam_insts
133 = do { let dflags = hsc_dflags hsc_env
134 ; showPass dflags "Tidy [hoot] type env"
136 ; let { insts' = tidyInstances tidyExternalId insts
137 ; dfun_ids = map instanceDFunId insts'
138 ; type_env1 = tidyBootTypeEnv (availsToNameSet exports) type_env
139 ; type_env' = extendTypeEnvWithIds type_env1 dfun_ids
141 ; return (ModDetails { md_types = type_env'
143 , md_fam_insts = fam_insts
145 , md_exports = exports
146 , md_vect_info = noVectInfo
151 tidyBootTypeEnv :: NameSet -> TypeEnv -> TypeEnv
152 tidyBootTypeEnv exports type_env
153 = tidyTypeEnv True False exports type_env final_ids
155 -- Find the LocalIds in the type env that are exported
156 -- Make them into GlobalIds, and tidy their types
158 -- It's very important to remove the non-exported ones
159 -- because we don't tidy the OccNames, and if we don't remove
160 -- the non-exported ones we'll get many things with the
161 -- same name in the interface file, giving chaos.
162 final_ids = [ tidyExternalId id
163 | id <- typeEnvIds type_env
167 -- default methods have their export flag set, but everything
168 -- else doesn't (yet), because this is pre-desugaring, so we
170 keep_it id = isExportedId id || idName id `elemNameSet` exports
173 tidyExternalId :: Id -> Id
174 -- Takes an LocalId with an External Name,
175 -- makes it into a GlobalId with VanillaIdInfo, and tidies its type
176 -- (NB: vanillaIdInfo makes a conservative assumption about Caf-hood.)
178 = ASSERT2( isLocalId id && isExternalName (idName id), ppr id )
179 mkVanillaGlobal (idName id) (tidyTopType (idType id)) vanillaIdInfo
183 %************************************************************************
185 Plan B: tidy bindings, make TypeEnv full of IdInfo
187 %************************************************************************
189 Plan B: include pragmas, make interfaces
190 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
191 * Figure out which Ids are externally visible
193 * Tidy the bindings, externalising appropriate Ids
195 * Drop all Ids from the TypeEnv, and add all the External Ids from
196 the bindings. (This adds their IdInfo to the TypeEnv; and adds
197 floated-out Ids that weren't even in the TypeEnv before.)
199 Step 1: Figure out external Ids
200 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
201 First we figure out which Ids are "external" Ids. An
202 "external" Id is one that is visible from outside the compilation
204 a) the user exported ones
205 b) ones mentioned in the unfoldings, workers,
206 or rules of externally-visible ones
207 This exercise takes a sweep of the bindings bottom to top. Actually,
208 in Step 2 we're also going to need to know which Ids should be
209 exported with their unfoldings, so we produce not an IdSet but an
213 Step 2: Tidy the program
214 ~~~~~~~~~~~~~~~~~~~~~~~~
215 Next we traverse the bindings top to bottom. For each *top-level*
218 1. Make it into a GlobalId; its IdDetails becomes VanillaGlobal,
219 reflecting the fact that from now on we regard it as a global,
222 2. Give it a system-wide Unique.
223 [Even non-exported things need system-wide Uniques because the
224 byte-code generator builds a single Name->BCO symbol table.]
226 We use the NameCache kept in the HscEnv as the
227 source of such system-wide uniques.
229 For external Ids, use the original-name cache in the NameCache
230 to ensure that the unique assigned is the same as the Id had
231 in any previous compilation run.
233 3. If it's an external Id, make it have a External Name, otherwise
234 make it have an Internal Name.
235 This is used by the code generator to decide whether
236 to make the label externally visible
238 4. Give external Ids a "tidy" OccName. This means
239 we can print them in interface files without confusing
240 "x" (unique 5) with "x" (unique 10).
242 5. Give it its UTTERLY FINAL IdInfo; in ptic,
243 * its unfolding, if it should have one
245 * its arity, computed from the number of visible lambdas
247 * its CAF info, computed from what is free in its RHS
250 Finally, substitute these new top-level binders consistently
251 throughout, including in unfoldings. We also tidy binders in
252 RHSs, so that they print nicely in interfaces.
255 tidyProgram :: HscEnv -> ModGuts -> IO (CgGuts, ModDetails)
256 tidyProgram hsc_env (ModGuts { mg_module = mod, mg_exports = exports,
258 mg_insts = insts, mg_fam_insts = fam_insts,
260 mg_rules = imp_rules,
261 mg_vect_info = vect_info,
262 mg_dir_imps = dir_imps,
264 mg_foreign = foreign_stubs,
265 mg_hpc_info = hpc_info,
266 mg_modBreaks = modBreaks })
268 = do { let dflags = hsc_dflags hsc_env
269 ; showPass dflags "Tidy Core"
271 ; let { omit_prags = dopt Opt_OmitInterfacePragmas dflags
272 ; th = dopt Opt_TemplateHaskell dflags
273 ; ext_ids = findExternalIds omit_prags binds
276 | otherwise = findExternalRules binds imp_rules ext_ids
277 -- findExternalRules filters imp_rules to avoid binders that
278 -- aren't externally visible; but the externally-visible binders
279 -- are computed (by findExternalIds) assuming that all orphan
280 -- rules are exported (they get their Exported flag set in the desugarer)
281 -- So in fact we may export more than we need.
282 -- (It's a sort of mutual recursion.)
285 ; (tidy_env, tidy_binds) <- tidyTopBinds hsc_env mod type_env ext_ids
288 ; let { export_set = availsToNameSet exports
289 ; final_ids = [ id | id <- bindersOfBinds tidy_binds,
290 isExternalName (idName id)]
291 ; tidy_type_env = tidyTypeEnv omit_prags th export_set
293 ; tidy_insts = tidyInstances (lookup_dfun tidy_type_env) insts
294 -- A DFunId will have a binding in tidy_binds, and so
295 -- will now be in final_env, replete with IdInfo
296 -- Its name will be unchanged since it was born, but
297 -- we want Global, IdInfo-rich (or not) DFunId in the
300 ; tidy_rules = tidyRules tidy_env ext_rules
301 -- You might worry that the tidy_env contains IdInfo-rich stuff
302 -- and indeed it does, but if omit_prags is on, ext_rules is
305 ; alg_tycons = filter isAlgTyCon (typeEnvTyCons type_env)
308 ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
309 ; dumpIfSet_core dflags Opt_D_dump_simpl
311 (pprRules tidy_rules)
313 ; let dir_imp_mods = moduleEnvKeys dir_imps
315 ; return (CgGuts { cg_module = mod,
316 cg_tycons = alg_tycons,
317 cg_binds = tidy_binds,
318 cg_dir_imps = dir_imp_mods,
319 cg_foreign = foreign_stubs,
320 cg_dep_pkgs = dep_pkgs deps,
321 cg_hpc_info = hpc_info,
322 cg_modBreaks = modBreaks },
324 ModDetails { md_types = tidy_type_env,
325 md_rules = tidy_rules,
326 md_insts = tidy_insts,
327 md_fam_insts = fam_insts,
328 md_exports = exports,
329 md_vect_info = vect_info -- is already tidy
333 lookup_dfun :: TypeEnv -> Var -> Id
334 lookup_dfun type_env dfun_id
335 = case lookupTypeEnv type_env (idName dfun_id) of
336 Just (AnId dfun_id') -> dfun_id'
337 _other -> pprPanic "lookup_dfun" (ppr dfun_id)
339 --------------------------
340 tidyTypeEnv :: Bool -- Compiling without -O, so omit prags
341 -> Bool -- Template Haskell is on
342 -> NameSet -> TypeEnv -> [Id] -> TypeEnv
344 -- The competed type environment is gotten from
345 -- Dropping any wired-in things, and then
346 -- a) keeping the types and classes
347 -- b) removing all Ids,
348 -- c) adding Ids with correct IdInfo, including unfoldings,
349 -- gotten from the bindings
350 -- From (c) we keep only those Ids with External names;
351 -- the CoreTidy pass makes sure these are all and only
352 -- the externally-accessible ones
353 -- This truncates the type environment to include only the
354 -- exported Ids and things needed from them, which saves space
356 tidyTypeEnv th omit_prags exports type_env final_ids
357 = let type_env1 = filterNameEnv keep_it type_env
358 type_env2 = extendTypeEnvWithIds type_env1 final_ids
359 type_env3 | omit_prags = mapNameEnv (trimThing th exports) type_env2
360 | otherwise = type_env2
364 -- We keep GlobalIds, because they won't appear
365 -- in the bindings from which final_ids are derived!
366 -- (The bindings bind LocalIds.)
367 keep_it thing | isWiredInThing thing = False
368 keep_it (AnId id) = isGlobalId id -- Keep GlobalIds (e.g. class ops)
369 keep_it _other = True -- Keep all TyCons, DataCons, and Classes
371 --------------------------
372 isWiredInThing :: TyThing -> Bool
373 isWiredInThing thing = isWiredInName (getName thing)
375 --------------------------
376 trimThing :: Bool -> NameSet -> TyThing -> TyThing
377 -- Trim off inessentials, for boot files and no -O
378 trimThing th exports (ATyCon tc)
379 | not th && not (mustExposeTyCon exports tc)
380 = ATyCon (makeTyConAbstract tc) -- Note [Trimming and Template Haskell]
382 trimThing _th _exports (AnId id)
383 | not (isImplicitId id)
384 = AnId (id `setIdInfo` vanillaIdInfo)
386 trimThing _th _exports other_thing
390 {- Note [Trimming and Template Haskell]
391 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
392 Consider (Trac #2386) this
393 module M(T, makeOne) where
395 makeOne = [| Yay "Yep" |]
396 Notice that T is exported abstractly, but makeOne effectively exports it too!
397 A module that splices in $(makeOne) will then look for a declartion of Yay,
398 so it'd better be there. Hence, brutally but simply, we switch off type
399 constructor trimming if TH is enabled in this module. -}
402 mustExposeTyCon :: NameSet -- Exports
403 -> TyCon -- The tycon
404 -> Bool -- Can its rep be hidden?
405 -- We are compiling without -O, and thus trying to write as little as
406 -- possible into the interface file. But we must expose the details of
407 -- any data types whose constructors or fields are exported
408 mustExposeTyCon exports tc
409 | not (isAlgTyCon tc) -- Synonyms
411 | isEnumerationTyCon tc -- For an enumeration, exposing the constructors
412 = True -- won't lead to the need for further exposure
413 -- (This includes data types with no constructors.)
414 | isOpenTyCon tc -- Open type family
417 | otherwise -- Newtype, datatype
418 = any exported_con (tyConDataCons tc)
419 -- Expose rep if any datacon or field is exported
421 || (isNewTyCon tc && isFFITy (snd (newTyConRhs tc)))
422 -- Expose the rep for newtypes if the rep is an FFI type.
423 -- For a very annoying reason. 'Foreign import' is meant to
424 -- be able to look through newtypes transparently, but it
425 -- can only do that if it can "see" the newtype representation
427 exported_con con = any (`elemNameSet` exports)
428 (dataConName con : dataConFieldLabels con)
430 tidyInstances :: (DFunId -> DFunId) -> [Instance] -> [Instance]
431 tidyInstances tidy_dfun ispecs
434 tidy ispec = setInstanceDFunId ispec $
435 tidy_dfun (instanceDFunId ispec)
439 %************************************************************************
441 \subsection{Step 1: finding externals}
443 %************************************************************************
446 findExternalIds :: Bool
448 -> IdEnv Bool -- In domain => external
449 -- Range = True <=> show unfolding
450 -- Step 1 from the notes above
451 findExternalIds omit_prags binds
453 = mkVarEnv [ (id,False) | id <- bindersOfBinds binds, isExportedId id ]
456 = foldr find emptyVarEnv binds
458 find (NonRec id rhs) needed
459 | need_id needed id = addExternal (id,rhs) needed
461 find (Rec prs) needed = find_prs prs needed
463 -- For a recursive group we have to look for a fixed point
465 | null needed_prs = needed
466 | otherwise = find_prs other_prs new_needed
468 (needed_prs, other_prs) = partition (need_pr needed) prs
469 new_needed = foldr addExternal needed needed_prs
471 -- The 'needed' set contains the Ids that are needed by earlier
472 -- interface file emissions. If the Id isn't in this set, and isn't
473 -- exported, there's no need to emit anything
474 need_id needed_set id = id `elemVarEnv` needed_set || isExportedId id
475 need_pr needed_set (id,_) = need_id needed_set id
477 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
478 -- The Id is needed; extend the needed set
479 -- with it and its dependents (free vars etc)
480 addExternal (id,rhs) needed
481 = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
484 add_occ id needed | id `elemVarEnv` needed = needed
485 | otherwise = extendVarEnv needed id False
486 -- "False" because we don't know we need the Id's unfolding
487 -- Don't override existing bindings; we might have already set it to True
489 new_needed_ids = worker_ids `unionVarSet`
490 unfold_ids `unionVarSet`
494 dont_inline = isNeverActive (inlinePragInfo idinfo)
495 loop_breaker = isNonRuleLoopBreaker (occInfo idinfo)
496 bottoming_fn = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
497 spec_ids = specInfoFreeVars (specInfo idinfo)
498 worker_info = workerInfo idinfo
500 -- Stuff to do with the Id's unfolding
501 -- The simplifier has put an up-to-date unfolding
502 -- in the IdInfo, but the RHS will do just as well
503 unfolding = unfoldingInfo idinfo
504 rhs_is_small = not (neverUnfold unfolding)
506 -- We leave the unfolding there even if there is a worker
507 -- In GHCI the unfolding is used by importers
508 -- When writing an interface file, we omit the unfolding
509 -- if there is a worker
510 show_unfold = not bottoming_fn && -- Not necessary
513 rhs_is_small -- Small enough
515 unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
516 | otherwise = emptyVarSet
518 worker_ids = case worker_info of
519 HasWorker work_id _ -> unitVarSet work_id
520 _otherwise -> emptyVarSet
525 findExternalRules :: [CoreBind]
526 -> [CoreRule] -- Non-local rules (i.e. ones for imported fns)
527 -> IdEnv a -- Ids that are exported, so we need their rules
529 -- The complete rules are gotten by combining
530 -- a) the non-local rules
531 -- b) rules embedded in the top-level Ids
532 findExternalRules binds non_local_rules ext_ids
533 = filter (not . internal_rule) (non_local_rules ++ local_rules)
536 | id <- bindersOfBinds binds,
537 id `elemVarEnv` ext_ids,
538 rule <- idCoreRules id
542 = any internal_id (varSetElems (ruleLhsFreeIds rule))
543 -- Don't export a rule whose LHS mentions a locally-defined
544 -- Id that is completely internal (i.e. not visible to an
547 internal_id id = not (id `elemVarEnv` ext_ids)
552 %************************************************************************
554 \subsection{Step 2: top-level tidying}
556 %************************************************************************
560 -- TopTidyEnv: when tidying we need to know
561 -- * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.
562 -- These may have arisen because the
563 -- renamer read in an interface file mentioning M.$wf, say,
564 -- and assigned it unique r77. If, on this compilation, we've
565 -- invented an Id whose name is $wf (but with a different unique)
566 -- we want to rename it to have unique r77, so that we can do easy
567 -- comparisons with stuff from the interface file
569 -- * occ_env: The TidyOccEnv, which tells us which local occurrences
572 -- * subst_env: A Var->Var mapping that substitutes the new Var for the old
574 tidyTopBinds :: HscEnv
577 -> IdEnv Bool -- Domain = Ids that should be external
578 -- True <=> their unfolding is external too
580 -> IO (TidyEnv, [CoreBind])
582 tidyTopBinds hsc_env mod type_env ext_ids binds
583 = tidy init_env binds
585 nc_var = hsc_NC hsc_env
587 -- We also make sure to avoid any exported binders. Consider
588 -- f{-u1-} = 1 -- Local decl
590 -- f{-u2-} = 2 -- Exported decl
592 -- The second exported decl must 'get' the name 'f', so we
593 -- have to put 'f' in the avoids list before we get to the first
594 -- decl. tidyTopId then does a no-op on exported binders.
595 init_env = (initTidyOccEnv avoids, emptyVarEnv)
596 avoids = [getOccName name | bndr <- typeEnvIds type_env,
597 let name = idName bndr,
599 -- In computing our "avoids" list, we must include
601 -- all things with global names (assigned once and for
602 -- all by the renamer)
603 -- since their names are "taken".
604 -- The type environment is a convenient source of such things.
606 this_pkg = thisPackage (hsc_dflags hsc_env)
608 tidy env [] = return (env, [])
609 tidy env (b:bs) = do { (env1, b') <- tidyTopBind this_pkg mod nc_var ext_ids env b
610 ; (env2, bs') <- tidy env1 bs
611 ; return (env2, b':bs') }
613 ------------------------
614 tidyTopBind :: PackageId
616 -> IORef NameCache -- For allocating new unique names
617 -> IdEnv Bool -- Domain = Ids that should be external
618 -- True <=> their unfolding is external too
619 -> TidyEnv -> CoreBind
620 -> IO (TidyEnv, CoreBind)
622 tidyTopBind this_pkg mod nc_var ext_ids (occ_env1,subst1) (NonRec bndr rhs)
623 = do { (occ_env2, name') <- tidyTopName mod nc_var ext_ids occ_env1 bndr
624 ; let { (bndr', rhs') = tidyTopPair ext_ids tidy_env2 caf_info name' (bndr, rhs)
625 ; subst2 = extendVarEnv subst1 bndr bndr'
626 ; tidy_env2 = (occ_env2, subst2) }
627 ; return (tidy_env2, NonRec bndr' rhs') }
629 caf_info = hasCafRefs this_pkg subst1 (idArity bndr) rhs
631 tidyTopBind this_pkg mod nc_var ext_ids (occ_env1,subst1) (Rec prs)
632 = do { (occ_env2, names') <- tidyTopNames mod nc_var ext_ids occ_env1 bndrs
633 ; let { prs' = zipWith (tidyTopPair ext_ids tidy_env2 caf_info)
635 ; subst2 = extendVarEnvList subst1 (bndrs `zip` map fst prs')
636 ; tidy_env2 = (occ_env2, subst2) }
637 ; return (tidy_env2, Rec prs') }
641 -- the CafInfo for a recursive group says whether *any* rhs in
642 -- the group may refer indirectly to a CAF (because then, they all do).
644 | or [ mayHaveCafRefs (hasCafRefs this_pkg subst1 (idArity bndr) rhs)
645 | (bndr,rhs) <- prs ] = MayHaveCafRefs
646 | otherwise = NoCafRefs
648 --------------------------------------------------------------------
650 -- This is where we set names to local/global based on whether they really are
651 -- externally visible (see comment at the top of this module). If the name
652 -- was previously local, we have to give it a unique occurrence name if
653 -- we intend to externalise it.
654 tidyTopNames :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
655 -> [Id] -> IO (TidyOccEnv, [Name])
656 tidyTopNames _mod _nc_var _ext_ids occ_env [] = return (occ_env, [])
657 tidyTopNames mod nc_var ext_ids occ_env (id:ids)
658 = do { (occ_env1, name) <- tidyTopName mod nc_var ext_ids occ_env id
659 ; (occ_env2, names) <- tidyTopNames mod nc_var ext_ids occ_env1 ids
660 ; return (occ_env2, name:names) }
662 tidyTopName :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
663 -> Id -> IO (TidyOccEnv, Name)
664 tidyTopName mod nc_var ext_ids occ_env id
665 | global && internal = return (occ_env, localiseName name)
667 | global && external = return (occ_env, name)
668 -- Global names are assumed to have been allocated by the renamer,
669 -- so they already have the "right" unique
670 -- And it's a system-wide unique too
672 -- Now we get to the real reason that all this is in the IO Monad:
673 -- we have to update the name cache in a nice atomic fashion
675 | local && internal = do { nc <- readIORef nc_var
676 ; let (nc', new_local_name) = mk_new_local nc
677 ; writeIORef nc_var nc'
678 ; return (occ_env', new_local_name) }
679 -- Even local, internal names must get a unique occurrence, because
680 -- if we do -split-objs we externalise the name later, in the code generator
682 -- Similarly, we must make sure it has a system-wide Unique, because
683 -- the byte-code generator builds a system-wide Name->BCO symbol table
685 | local && external = do { nc <- readIORef nc_var
686 ; let (nc', new_external_name) = mk_new_external nc
687 ; writeIORef nc_var nc'
688 ; return (occ_env', new_external_name) }
690 | otherwise = panic "tidyTopName"
693 external = id `elemVarEnv` ext_ids
694 global = isExternalName name
696 internal = not external
697 loc = nameSrcSpan name
699 (occ_env', occ') = tidyOccName occ_env (nameOccName name)
701 mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
703 (us1, us2) = splitUniqSupply (nsUniqs nc)
704 uniq = uniqFromSupply us1
706 mk_new_external nc = allocateGlobalBinder nc mod occ' loc
707 -- If we want to externalise a currently-local name, check
708 -- whether we have already assigned a unique for it.
709 -- If so, use it; if not, extend the table.
710 -- All this is done by allcoateGlobalBinder.
711 -- This is needed when *re*-compiling a module in GHCi; we must
712 -- use the same name for externally-visible things as we did before.
715 -----------------------------------------------------------
716 tidyTopPair :: VarEnv Bool
717 -> TidyEnv -- The TidyEnv is used to tidy the IdInfo
718 -- It is knot-tied: don't look at it!
721 -> (Id, CoreExpr) -- Binder and RHS before tidying
723 -- This function is the heart of Step 2
724 -- The rec_tidy_env is the one to use for the IdInfo
725 -- It's necessary because when we are dealing with a recursive
726 -- group, a variable late in the group might be mentioned
727 -- in the IdInfo of one early in the group
729 tidyTopPair ext_ids rhs_tidy_env caf_info name' (bndr, rhs)
732 bndr' = mkGlobalId details name' ty' idinfo'
733 -- Preserve the GlobalIdDetails of existing global-ids
734 details = case globalIdDetails bndr of
735 NotGlobalId -> VanillaGlobal
736 old_details -> old_details
737 ty' = tidyTopType (idType bndr)
738 rhs' = tidyExpr rhs_tidy_env rhs
740 idinfo' = tidyTopIdInfo (isJust maybe_external)
741 idinfo unfold_info worker_info
744 -- Expose an unfolding if ext_ids tells us to
745 -- Remember that ext_ids maps an Id to a Bool:
746 -- True to show the unfolding, False to hide it
747 maybe_external = lookupVarEnv ext_ids bndr
748 show_unfold = maybe_external `orElse` False
749 unfold_info | show_unfold = mkTopUnfolding rhs'
750 | otherwise = noUnfolding
751 worker_info = tidyWorker rhs_tidy_env show_unfold (workerInfo idinfo)
753 -- Usually the Id will have an accurate arity on it, because
754 -- the simplifier has just run, but not always.
755 -- One case I found was when the last thing the simplifier
756 -- did was to let-bind a non-atomic argument and then float
757 -- it to the top level. So it seems more robust just to
759 arity = exprArity rhs
762 -- tidyTopIdInfo creates the final IdInfo for top-level
763 -- binders. There are two delicate pieces:
765 -- * Arity. After CoreTidy, this arity must not change any more.
766 -- Indeed, CorePrep must eta expand where necessary to make
767 -- the manifest arity equal to the claimed arity.
769 -- * CAF info. This must also remain valid through to code generation.
770 -- We add the info here so that it propagates to all
771 -- occurrences of the binders in RHSs, and hence to occurrences in
772 -- unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
773 -- CoreToStg makes use of this when constructing SRTs.
774 tidyTopIdInfo :: Bool -> IdInfo -> Unfolding
775 -> WorkerInfo -> ArityInfo -> CafInfo
777 tidyTopIdInfo is_external idinfo unfold_info worker_info arity caf_info
778 | not is_external -- For internal Ids (not externally visible)
779 = vanillaIdInfo -- we only need enough info for code generation
780 -- Arity and strictness info are enough;
781 -- c.f. CoreTidy.tidyLetBndr
782 `setCafInfo` caf_info
784 `setAllStrictnessInfo` newStrictnessInfo idinfo
786 | otherwise -- Externally-visible Ids get the whole lot
788 `setCafInfo` caf_info
790 `setAllStrictnessInfo` newStrictnessInfo idinfo
791 `setInlinePragInfo` inlinePragInfo idinfo
792 `setUnfoldingInfo` unfold_info
793 `setWorkerInfo` worker_info
794 -- NB: we throw away the Rules
795 -- They have already been extracted by findExternalRules
799 ------------ Worker --------------
800 tidyWorker :: TidyEnv -> Bool -> WorkerInfo -> WorkerInfo
801 tidyWorker _tidy_env _show_unfold NoWorker
803 tidyWorker tidy_env show_unfold (HasWorker work_id wrap_arity)
804 | show_unfold = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
805 | otherwise = NoWorker
806 -- NB: do *not* expose the worker if show_unfold is off,
807 -- because that means this thing is a loop breaker or
808 -- marked NOINLINE or something like that
809 -- This is important: if you expose the worker for a loop-breaker
810 -- then you can make the simplifier go into an infinite loop, because
811 -- in effect the unfolding is exposed. See Trac #1709
813 -- You might think that if show_unfold is False, then the thing should
814 -- not be w/w'd in the first place. But a legitimate reason is this:
815 -- the function returns bottom
816 -- In this case, show_unfold will be false (we don't expose unfoldings
817 -- for bottoming functions), but we might still have a worker/wrapper
818 -- split (see Note [Worker-wrapper for bottoming functions] in WorkWrap.lhs
821 %************************************************************************
823 \subsection{Figuring out CafInfo for an expression}
825 %************************************************************************
827 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
828 We mark such things as `MayHaveCafRefs' because this information is
829 used to decide whether a particular closure needs to be referenced
832 There are two reasons for setting MayHaveCafRefs:
833 a) The RHS is a CAF: a top-level updatable thunk.
834 b) The RHS refers to something that MayHaveCafRefs
836 Possible improvement: In an effort to keep the number of CAFs (and
837 hence the size of the SRTs) down, we could also look at the expression and
838 decide whether it requires a small bounded amount of heap, so we can ignore
839 it as a CAF. In these cases however, we would need to use an additional
840 CAF list to keep track of non-collectable CAFs.
843 hasCafRefs :: PackageId -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
844 hasCafRefs this_pkg p arity expr
845 | is_caf || mentions_cafs
847 | otherwise = NoCafRefs
849 mentions_cafs = isFastTrue (cafRefs p expr)
850 is_caf = not (arity > 0 || rhsIsStatic this_pkg expr)
852 -- NB. we pass in the arity of the expression, which is expected
853 -- to be calculated by exprArity. This is because exprArity
854 -- knows how much eta expansion is going to be done by
855 -- CorePrep later on, and we don't want to duplicate that
856 -- knowledge in rhsIsStatic below.
858 cafRefs :: VarEnv Id -> Expr a -> FastBool
860 -- imported Ids first:
861 | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
862 -- now Ids local to this module:
864 case lookupVarEnv p id of
865 Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
866 Nothing -> fastBool False
868 cafRefs _ (Lit _) = fastBool False
869 cafRefs p (App f a) = fastOr (cafRefs p f) (cafRefs p) a
870 cafRefs p (Lam _ e) = cafRefs p e
871 cafRefs p (Let b e) = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
872 cafRefs p (Case e _bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
873 cafRefs p (Note _n e) = cafRefs p e
874 cafRefs p (Cast e _co) = cafRefs p e
875 cafRefs _ (Type _) = fastBool False
877 cafRefss :: VarEnv Id -> [Expr a] -> FastBool
878 cafRefss _ [] = fastBool False
879 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
881 fastOr :: FastBool -> (a -> FastBool) -> a -> FastBool
882 -- hack for lazy-or over FastBool.
883 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))