Haskell Program Coverage
[ghc-hetmet.git] / compiler / main / TidyPgm.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Tidying up Core}
5
6 \begin{code}
7 module TidyPgm( mkBootModDetails, tidyProgram ) where
8
9 #include "HsVersions.h"
10
11 import DynFlags         ( DynFlag(..), DynFlags(..), dopt )
12 import CoreSyn
13 import CoreUnfold       ( noUnfolding, mkTopUnfolding )
14 import CoreFVs          ( ruleLhsFreeIds, exprSomeFreeVars )
15 import CoreTidy         ( tidyExpr, tidyVarOcc, tidyRules )
16 import PprCore          ( pprRules )
17 import CoreLint         ( showPass, endPass )
18 import CoreUtils        ( exprArity, rhsIsStatic )
19 import VarEnv
20 import VarSet
21 import Var              ( Id, Var )
22 import Id               ( idType, idInfo, idName, idCoreRules, isGlobalId,
23                           isExportedId, mkVanillaGlobal, isLocalId, isNaughtyRecordSelector,
24                           idArity, idCafInfo, idUnfolding, isImplicitId, setIdInfo
25                         ) 
26 import IdInfo           {- loads of stuff -}
27 import InstEnv          ( Instance, DFunId, instanceDFunId, setInstanceDFunId )
28 import NewDemand        ( isBottomingSig, topSig )
29 import BasicTypes       ( Arity, isNeverActive, isNonRuleLoopBreaker )
30 import Name             ( Name, getOccName, nameOccName, mkInternalName,
31                           localiseName, isExternalName, nameSrcLoc,
32                           isWiredInName, getName
33                         )
34 import NameSet          ( NameSet, elemNameSet )
35 import IfaceEnv         ( allocateGlobalBinder )
36 import NameEnv          ( filterNameEnv, mapNameEnv )
37 import OccName          ( TidyOccEnv, initTidyOccEnv, tidyOccName )
38 import Type             ( tidyTopType )
39 import TcType           ( isFFITy )
40 import DataCon          ( dataConName, dataConFieldLabels, dataConWrapId_maybe )
41 import TyCon            ( TyCon, makeTyConAbstract, tyConDataCons, isNewTyCon, 
42                           newTyConRep, tyConSelIds, isAlgTyCon,
43                           isEnumerationTyCon, isOpenTyCon )
44 import Class            ( classSelIds )
45 import Module           ( Module )
46 import HscTypes
47 import Maybes           ( orElse, mapCatMaybes )
48 import ErrUtils         ( showPass, dumpIfSet_core )
49 import PackageConfig    ( PackageId )
50 import UniqSupply       ( splitUniqSupply, uniqFromSupply )
51 import Outputable
52 import FastTypes  hiding ( fastOr )
53
54 import Data.List        ( partition )
55 import Data.Maybe       ( isJust )
56 import Data.IORef       ( IORef, readIORef, writeIORef )
57 \end{code}
58
59
60 Constructing the TypeEnv, Instances, Rules from which the ModIface is
61 constructed, and which goes on to subsequent modules in --make mode.
62
63 Most of the interface file is obtained simply by serialising the
64 TypeEnv.  One important consequence is that if the *interface file*
65 has pragma info if and only if the final TypeEnv does. This is not so
66 important for *this* module, but it's essential for ghc --make:
67 subsequent compilations must not see (e.g.) the arity if the interface
68 file does not contain arity If they do, they'll exploit the arity;
69 then the arity might change, but the iface file doesn't change =>
70 recompilation does not happen => disaster. 
71
72 For data types, the final TypeEnv will have a TyThing for the TyCon,
73 plus one for each DataCon; the interface file will contain just one
74 data type declaration, but it is de-serialised back into a collection
75 of TyThings.
76
77 %************************************************************************
78 %*                                                                      *
79                 Plan A: simpleTidyPgm
80 %*                                                                      * 
81 %************************************************************************
82
83
84 Plan A: mkBootModDetails: omit pragmas, make interfaces small
85 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
86 * Ignore the bindings
87
88 * Drop all WiredIn things from the TypeEnv 
89         (we never want them in interface files)
90
91 * Retain all TyCons and Classes in the TypeEnv, to avoid
92         having to find which ones are mentioned in the
93         types of exported Ids
94
95 * Trim off the constructors of non-exported TyCons, both
96         from the TyCon and from the TypeEnv
97
98 * Drop non-exported Ids from the TypeEnv
99
100 * Tidy the types of the DFunIds of Instances, 
101   make them into GlobalIds, (they already have External Names)
102   and add them to the TypeEnv
103
104 * Tidy the types of the (exported) Ids in the TypeEnv,
105   make them into GlobalIds (they already have External Names)
106
107 * Drop rules altogether
108
109 * Tidy the bindings, to ensure that the Caf and Arity
110   information is correct for each top-level binder; the 
111   code generator needs it. And to ensure that local names have
112   distinct OccNames in case of object-file splitting
113
114 \begin{code}
115 mkBootModDetails :: HscEnv -> ModGuts -> IO ModDetails
116 -- This is Plan A: make a small type env when typechecking only,
117 -- or when compiling a hs-boot file, or simply when not using -O
118 --
119 -- We don't look at the bindings at all -- there aren't any
120 -- for hs-boot files
121
122 mkBootModDetails hsc_env (ModGuts { mg_module    = mod
123                                   , mg_exports   = exports
124                                   , mg_types     = type_env
125                                   , mg_insts     = insts
126                                   , mg_fam_insts = fam_insts })
127   = do  { let dflags = hsc_dflags hsc_env 
128         ; showPass dflags "Tidy [hoot] type env"
129
130         ; let { insts'     = tidyInstances tidyExternalId insts
131               ; type_env1  = filterNameEnv (not . isWiredInThing) type_env
132               ; type_env2  = mapNameEnv tidyBootThing type_env1
133               ; type_env'  = extendTypeEnvWithIds type_env2
134                                 (map instanceDFunId insts')
135               }
136         ; return (ModDetails { md_types     = type_env'
137                              , md_insts     = insts'
138                              , md_fam_insts = fam_insts
139                              , md_rules     = []
140                              , md_exports   = exports })
141         }
142   where
143
144 isWiredInThing :: TyThing -> Bool
145 isWiredInThing thing = isWiredInName (getName thing)
146
147 tidyBootThing :: TyThing -> TyThing
148 -- Just externalise the Ids; keep everything
149 tidyBootThing (AnId id) | isLocalId id = AnId (tidyExternalId id)
150 tidyBootThing thing                    = thing
151
152 tidyExternalId :: Id -> Id
153 -- Takes an LocalId with an External Name, 
154 -- makes it into a GlobalId with VanillaIdInfo, and tidies its type
155 -- (NB: vanillaIdInfo makes a conservative assumption about Caf-hood.)
156 tidyExternalId id 
157   = ASSERT2( isLocalId id && isExternalName (idName id), ppr id )
158     mkVanillaGlobal (idName id) (tidyTopType (idType id)) vanillaIdInfo
159 \end{code}
160
161
162 %************************************************************************
163 %*                                                                      *
164         Plan B: tidy bindings, make TypeEnv full of IdInfo
165 %*                                                                      * 
166 %************************************************************************
167
168 Plan B: include pragmas, make interfaces 
169 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
170 * Figure out which Ids are externally visible
171
172 * Tidy the bindings, externalising appropriate Ids
173
174 * Drop all Ids from the TypeEnv, and add all the External Ids from 
175   the bindings.  (This adds their IdInfo to the TypeEnv; and adds
176   floated-out Ids that weren't even in the TypeEnv before.)
177
178 Step 1: Figure out external Ids
179 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
180 First we figure out which Ids are "external" Ids.  An
181 "external" Id is one that is visible from outside the compilation
182 unit.  These are
183         a) the user exported ones
184         b) ones mentioned in the unfoldings, workers, 
185            or rules of externally-visible ones 
186 This exercise takes a sweep of the bindings bottom to top.  Actually,
187 in Step 2 we're also going to need to know which Ids should be
188 exported with their unfoldings, so we produce not an IdSet but an
189 IdEnv Bool
190
191
192 Step 2: Tidy the program
193 ~~~~~~~~~~~~~~~~~~~~~~~~
194 Next we traverse the bindings top to bottom.  For each *top-level*
195 binder
196
197  1. Make it into a GlobalId; its IdDetails becomes VanillaGlobal, 
198     reflecting the fact that from now on we regard it as a global, 
199     not local, Id
200
201  2. Give it a system-wide Unique.
202     [Even non-exported things need system-wide Uniques because the
203     byte-code generator builds a single Name->BCO symbol table.]
204
205     We use the NameCache kept in the HscEnv as the
206     source of such system-wide uniques.
207
208     For external Ids, use the original-name cache in the NameCache
209     to ensure that the unique assigned is the same as the Id had 
210     in any previous compilation run.
211   
212  3. If it's an external Id, make it have a External Name, otherwise
213     make it have an Internal Name.
214     This is used by the code generator to decide whether
215     to make the label externally visible
216
217  4. Give external Ids a "tidy" OccName.  This means
218     we can print them in interface files without confusing 
219     "x" (unique 5) with "x" (unique 10).
220   
221  5. Give it its UTTERLY FINAL IdInfo; in ptic, 
222         * its unfolding, if it should have one
223         
224         * its arity, computed from the number of visible lambdas
225
226         * its CAF info, computed from what is free in its RHS
227
228                 
229 Finally, substitute these new top-level binders consistently
230 throughout, including in unfoldings.  We also tidy binders in
231 RHSs, so that they print nicely in interfaces.
232
233 \begin{code}
234 tidyProgram :: HscEnv -> ModGuts -> IO (CgGuts, ModDetails)
235 tidyProgram hsc_env
236             mod_impl@(ModGuts { mg_module = mod, mg_exports = exports, 
237                                 mg_types = type_env, 
238                                 mg_insts = insts, mg_fam_insts = fam_insts,
239                                 mg_binds = binds, 
240                                 mg_rules = imp_rules,
241                                 mg_dir_imps = dir_imps, mg_deps = deps, 
242                                 mg_foreign = foreign_stubs,
243                                 mg_hpc_info = hpc_info })
244
245   = do  { let dflags = hsc_dflags hsc_env
246         ; showPass dflags "Tidy Core"
247
248         ; let { omit_prags = dopt Opt_OmitInterfacePragmas dflags
249               ; ext_ids = findExternalIds omit_prags binds
250               ; ext_rules 
251                    | omit_prags = []
252                    | otherwise  = findExternalRules binds imp_rules ext_ids
253                 -- findExternalRules filters imp_rules to avoid binders that 
254                 -- aren't externally visible; but the externally-visible binders 
255                 -- are computed (by findExternalIds) assuming that all orphan
256                 -- rules are exported (they get their Exported flag set in the desugarer)
257                 -- So in fact we may export more than we need. 
258                 -- (It's a sort of mutual recursion.)
259         }
260
261         ; (tidy_env, tidy_binds) <- tidyTopBinds hsc_env mod type_env ext_ids 
262                                                  binds
263
264         ; let { export_set = availsToNameSet exports
265               ; tidy_type_env = tidyTypeEnv omit_prags export_set type_env 
266                                             tidy_binds
267               ; tidy_insts    = tidyInstances (lookup_dfun tidy_type_env) insts
268                 -- A DFunId will have a binding in tidy_binds, and so
269                 -- will now be in final_env, replete with IdInfo
270                 -- Its name will be unchanged since it was born, but
271                 -- we want Global, IdInfo-rich (or not) DFunId in the
272                 -- tidy_insts
273
274               ; tidy_rules = tidyRules tidy_env ext_rules
275                 -- You might worry that the tidy_env contains IdInfo-rich stuff
276                 -- and indeed it does, but if omit_prags is on, ext_rules is
277                 -- empty
278
279               ; implicit_binds = getImplicitBinds type_env
280               ; all_tidy_binds = implicit_binds ++ tidy_binds
281               ; alg_tycons = filter isAlgTyCon (typeEnvTyCons type_env)
282               }
283
284         ; endPass dflags "Tidy Core" Opt_D_dump_simpl all_tidy_binds
285         ; dumpIfSet_core dflags Opt_D_dump_simpl
286                 "Tidy Core Rules"
287                 (pprRules tidy_rules)
288
289         ; return (CgGuts { cg_module   = mod, 
290                            cg_tycons   = alg_tycons,
291                            cg_binds    = all_tidy_binds,
292                            cg_dir_imps = dir_imps,
293                            cg_foreign  = foreign_stubs,
294                            cg_dep_pkgs = dep_pkgs deps,
295                            cg_hpc_info = hpc_info }, 
296
297                    ModDetails { md_types     = tidy_type_env,
298                                 md_rules     = tidy_rules,
299                                 md_insts     = tidy_insts,
300                                 md_fam_insts = fam_insts,
301                                 md_exports   = exports })
302         }
303
304 lookup_dfun type_env dfun_id
305   = case lookupTypeEnv type_env (idName dfun_id) of
306         Just (AnId dfun_id') -> dfun_id'
307         other -> pprPanic "lookup_dfun" (ppr dfun_id)
308
309 tidyTypeEnv :: Bool -> NameSet -> TypeEnv -> [CoreBind] -> TypeEnv
310
311 -- The competed type environment is gotten from
312 --      Dropping any wired-in things, and then
313 --      a) keeping the types and classes
314 --      b) removing all Ids, 
315 --      c) adding Ids with correct IdInfo, including unfoldings,
316 --              gotten from the bindings
317 -- From (c) we keep only those Ids with External names;
318 --          the CoreTidy pass makes sure these are all and only
319 --          the externally-accessible ones
320 -- This truncates the type environment to include only the 
321 -- exported Ids and things needed from them, which saves space
322
323 tidyTypeEnv omit_prags exports type_env tidy_binds
324   = let type_env1 = filterNameEnv keep_it type_env
325         type_env2 = extendTypeEnvWithIds type_env1 final_ids
326         type_env3 | omit_prags = mapNameEnv trim_thing type_env2
327                   | otherwise  = type_env2
328     in 
329     type_env3
330   where
331     final_ids  = [ id | id <- bindersOfBinds tidy_binds, 
332                         isExternalName (idName id)]
333
334         -- We keep GlobalIds, because they won't appear 
335         -- in the bindings from which final_ids are derived!
336         -- (The bindings bind LocalIds.)
337     keep_it thing | isWiredInThing thing = False
338     keep_it (AnId id) = isGlobalId id   -- Keep GlobalIds (e.g. class ops)
339     keep_it other     = True            -- Keep all TyCons, DataCons, and Classes
340
341     trim_thing thing
342         = case thing of
343             ATyCon tc | mustExposeTyCon exports tc -> thing
344                       | otherwise -> ATyCon (makeTyConAbstract tc)
345
346             AnId id | isImplicitId id -> thing
347                     | otherwise       -> AnId (id `setIdInfo` vanillaIdInfo)
348
349             other -> thing
350
351 mustExposeTyCon :: NameSet      -- Exports
352                 -> TyCon        -- The tycon
353                 -> Bool         -- Can its rep be hidden?
354 -- We are compiling without -O, and thus trying to write as little as 
355 -- possible into the interface file.  But we must expose the details of
356 -- any data types whose constructors or fields are exported
357 mustExposeTyCon exports tc
358   | not (isAlgTyCon tc)         -- Synonyms
359   = True
360   | isEnumerationTyCon tc       -- For an enumeration, exposing the constructors
361   = True                        -- won't lead to the need for further exposure
362                                 -- (This includes data types with no constructors.)
363   | isOpenTyCon tc              -- open type family
364   = True
365   | otherwise                   -- Newtype, datatype
366   = any exported_con (tyConDataCons tc)
367         -- Expose rep if any datacon or field is exported
368
369   || (isNewTyCon tc && isFFITy (snd (newTyConRep tc)))
370         -- Expose the rep for newtypes if the rep is an FFI type.  
371         -- For a very annoying reason.  'Foreign import' is meant to
372         -- be able to look through newtypes transparently, but it
373         -- can only do that if it can "see" the newtype representation
374   where
375     exported_con con = any (`elemNameSet` exports) 
376                            (dataConName con : dataConFieldLabels con)
377
378 tidyInstances :: (DFunId -> DFunId) -> [Instance] -> [Instance]
379 tidyInstances tidy_dfun ispecs
380   = map tidy ispecs
381   where
382     tidy ispec = setInstanceDFunId ispec $
383                  tidy_dfun (instanceDFunId ispec)
384
385 getImplicitBinds :: TypeEnv -> [CoreBind]
386 getImplicitBinds type_env
387   = map get_defn (concatMap implicit_con_ids (typeEnvTyCons type_env)
388                   ++ concatMap other_implicit_ids (typeEnvElts type_env))
389         -- Put the constructor wrappers first, because
390         -- other implicit bindings (notably the fromT functions arising 
391         -- from generics) use the constructor wrappers.  At least that's
392         -- what External Core likes
393   where
394     implicit_con_ids tc = mapCatMaybes dataConWrapId_maybe (tyConDataCons tc)
395     
396     other_implicit_ids (ATyCon tc) = filter (not . isNaughtyRecordSelector) (tyConSelIds tc)
397         -- The "naughty" ones are not real functions at all
398         -- They are there just so we can get decent error messages
399         -- See Note  [Naughty record selectors] in MkId.lhs
400     other_implicit_ids (AClass cl) = classSelIds cl
401     other_implicit_ids other       = []
402     
403     get_defn :: Id -> CoreBind
404     get_defn id = NonRec id (tidyExpr emptyTidyEnv rhs)
405         where
406           rhs = unfoldingTemplate (idUnfolding id)
407         -- Don't forget to tidy the body !  Otherwise you get silly things like
408         --      \ tpl -> case tpl of tpl -> (tpl,tpl) -> tpl
409 \end{code}
410
411
412 %************************************************************************
413 %*                                                                      *
414 \subsection{Step 1: finding externals}
415 %*                                                                      * 
416 %************************************************************************
417
418 \begin{code}
419 findExternalIds :: Bool
420                 -> [CoreBind]
421                 -> IdEnv Bool   -- In domain => external
422                                 -- Range = True <=> show unfolding
423         -- Step 1 from the notes above
424 findExternalIds omit_prags binds
425   | omit_prags
426   = mkVarEnv [ (id,False) | id <- bindersOfBinds binds, isExportedId id ]
427
428   | otherwise
429   = foldr find emptyVarEnv binds
430   where
431     find (NonRec id rhs) needed
432         | need_id needed id = addExternal (id,rhs) needed
433         | otherwise         = needed
434     find (Rec prs) needed   = find_prs prs needed
435
436         -- For a recursive group we have to look for a fixed point
437     find_prs prs needed 
438         | null needed_prs = needed
439         | otherwise       = find_prs other_prs new_needed
440         where
441           (needed_prs, other_prs) = partition (need_pr needed) prs
442           new_needed = foldr addExternal needed needed_prs
443
444         -- The 'needed' set contains the Ids that are needed by earlier
445         -- interface file emissions.  If the Id isn't in this set, and isn't
446         -- exported, there's no need to emit anything
447     need_id needed_set id       = id `elemVarEnv` needed_set || isExportedId id 
448     need_pr needed_set (id,rhs) = need_id needed_set id
449
450 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
451 -- The Id is needed; extend the needed set
452 -- with it and its dependents (free vars etc)
453 addExternal (id,rhs) needed
454   = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
455                  id show_unfold
456   where
457     add_occ id needed | id `elemVarEnv` needed = needed
458                       | otherwise              = extendVarEnv needed id False
459         -- "False" because we don't know we need the Id's unfolding
460         -- Don't override existing bindings; we might have already set it to True
461
462     new_needed_ids = worker_ids `unionVarSet`
463                      unfold_ids `unionVarSet`
464                      spec_ids
465
466     idinfo         = idInfo id
467     dont_inline    = isNeverActive (inlinePragInfo idinfo)
468     loop_breaker   = isNonRuleLoopBreaker (occInfo idinfo)
469     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
470     spec_ids       = specInfoFreeVars (specInfo idinfo)
471     worker_info    = workerInfo idinfo
472
473         -- Stuff to do with the Id's unfolding
474         -- The simplifier has put an up-to-date unfolding
475         -- in the IdInfo, but the RHS will do just as well
476     unfolding    = unfoldingInfo idinfo
477     rhs_is_small = not (neverUnfold unfolding)
478
479         -- We leave the unfolding there even if there is a worker
480         -- In GHCI the unfolding is used by importers
481         -- When writing an interface file, we omit the unfolding 
482         -- if there is a worker
483     show_unfold = not bottoming_fn       &&     -- Not necessary
484                   not dont_inline        &&
485                   not loop_breaker       &&
486                   rhs_is_small                  -- Small enough
487
488     unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
489                | otherwise   = emptyVarSet
490
491     worker_ids = case worker_info of
492                    HasWorker work_id _ -> unitVarSet work_id
493                    otherwise           -> emptyVarSet
494 \end{code}
495
496
497 \begin{code}
498 findExternalRules :: [CoreBind]
499                   -> [CoreRule] -- Non-local rules (i.e. ones for imported fns)
500                   -> IdEnv a    -- Ids that are exported, so we need their rules
501                   -> [CoreRule]
502   -- The complete rules are gotten by combining
503   --    a) the non-local rules
504   --    b) rules embedded in the top-level Ids
505 findExternalRules binds non_local_rules ext_ids
506   = filter (not . internal_rule) (non_local_rules ++ local_rules)
507   where
508     local_rules  = [ rule
509                    | id <- bindersOfBinds binds,
510                      id `elemVarEnv` ext_ids,
511                      rule <- idCoreRules id
512                    ]
513
514     internal_rule rule
515         =  any internal_id (varSetElems (ruleLhsFreeIds rule))
516                 -- Don't export a rule whose LHS mentions a locally-defined
517                 --  Id that is completely internal (i.e. not visible to an
518                 -- importing module)
519
520     internal_id id = not (id `elemVarEnv` ext_ids)
521 \end{code}
522
523
524
525 %************************************************************************
526 %*                                                                      *
527 \subsection{Step 2: top-level tidying}
528 %*                                                                      *
529 %************************************************************************
530
531
532 \begin{code}
533 -- TopTidyEnv: when tidying we need to know
534 --   * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.  
535 --        These may have arisen because the
536 --        renamer read in an interface file mentioning M.$wf, say,
537 --        and assigned it unique r77.  If, on this compilation, we've
538 --        invented an Id whose name is $wf (but with a different unique)
539 --        we want to rename it to have unique r77, so that we can do easy
540 --        comparisons with stuff from the interface file
541 --
542 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
543 --     are 'used'
544 --
545 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
546
547 tidyTopBinds :: HscEnv
548              -> Module
549              -> TypeEnv
550              -> IdEnv Bool      -- Domain = Ids that should be external
551                                 -- True <=> their unfolding is external too
552              -> [CoreBind]
553              -> IO (TidyEnv, [CoreBind])
554
555 tidyTopBinds hsc_env mod type_env ext_ids binds
556   = tidy init_env binds
557   where
558     nc_var = hsc_NC hsc_env 
559
560         -- We also make sure to avoid any exported binders.  Consider
561         --      f{-u1-} = 1     -- Local decl
562         --      ...
563         --      f{-u2-} = 2     -- Exported decl
564         --
565         -- The second exported decl must 'get' the name 'f', so we
566         -- have to put 'f' in the avoids list before we get to the first
567         -- decl.  tidyTopId then does a no-op on exported binders.
568     init_env = (initTidyOccEnv avoids, emptyVarEnv)
569     avoids   = [getOccName name | bndr <- typeEnvIds type_env,
570                                   let name = idName bndr,
571                                   isExternalName name]
572                 -- In computing our "avoids" list, we must include
573                 --      all implicit Ids
574                 --      all things with global names (assigned once and for
575                 --                                      all by the renamer)
576                 -- since their names are "taken".
577                 -- The type environment is a convenient source of such things.
578
579     this_pkg = thisPackage (hsc_dflags hsc_env)
580
581     tidy env []     = return (env, [])
582     tidy env (b:bs) = do { (env1, b')  <- tidyTopBind this_pkg mod nc_var ext_ids env b
583                          ; (env2, bs') <- tidy env1 bs
584                          ; return (env2, b':bs') }
585
586 ------------------------
587 tidyTopBind  :: PackageId
588              -> Module
589              -> IORef NameCache -- For allocating new unique names
590              -> IdEnv Bool      -- Domain = Ids that should be external
591                                 -- True <=> their unfolding is external too
592              -> TidyEnv -> CoreBind
593              -> IO (TidyEnv, CoreBind)
594
595 tidyTopBind this_pkg mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (NonRec bndr rhs)
596   = do  { (occ_env2, name') <- tidyTopName mod nc_var ext_ids occ_env1 bndr
597         ; let   { (bndr', rhs') = tidyTopPair ext_ids tidy_env2 caf_info name' (bndr, rhs)
598                 ; subst2        = extendVarEnv subst1 bndr bndr'
599                 ; tidy_env2     = (occ_env2, subst2) }
600         ; return (tidy_env2, NonRec bndr' rhs') }
601   where
602     caf_info = hasCafRefs this_pkg subst1 (idArity bndr) rhs
603
604 tidyTopBind this_pkg mod nc_var ext_ids tidy_env1@(occ_env1,subst1) (Rec prs)
605   = do  { (occ_env2, names') <- tidyTopNames mod nc_var ext_ids occ_env1 bndrs
606         ; let   { prs'      = zipWith (tidyTopPair ext_ids tidy_env2 caf_info)
607                                       names' prs
608                 ; subst2    = extendVarEnvList subst1 (bndrs `zip` map fst prs')
609                 ; tidy_env2 = (occ_env2, subst2) }
610         ; return (tidy_env2, Rec prs') }
611   where
612     bndrs = map fst prs
613
614         -- the CafInfo for a recursive group says whether *any* rhs in
615         -- the group may refer indirectly to a CAF (because then, they all do).
616     caf_info 
617         | or [ mayHaveCafRefs (hasCafRefs this_pkg subst1 (idArity bndr) rhs)
618              | (bndr,rhs) <- prs ] = MayHaveCafRefs
619         | otherwise                = NoCafRefs
620
621 --------------------------------------------------------------------
622 --              tidyTopName
623 -- This is where we set names to local/global based on whether they really are 
624 -- externally visible (see comment at the top of this module).  If the name
625 -- was previously local, we have to give it a unique occurrence name if
626 -- we intend to externalise it.
627 tidyTopNames mod nc_var ext_ids occ_env [] = return (occ_env, [])
628 tidyTopNames mod nc_var ext_ids occ_env (id:ids)
629   = do  { (occ_env1, name)  <- tidyTopName  mod nc_var ext_ids occ_env id
630         ; (occ_env2, names) <- tidyTopNames mod nc_var ext_ids occ_env1 ids
631         ; return (occ_env2, name:names) }
632
633 tidyTopName :: Module -> IORef NameCache -> VarEnv Bool -> TidyOccEnv
634             -> Id -> IO (TidyOccEnv, Name)
635 tidyTopName mod nc_var ext_ids occ_env id
636   | global && internal = return (occ_env, localiseName name)
637
638   | global && external = return (occ_env, name)
639         -- Global names are assumed to have been allocated by the renamer,
640         -- so they already have the "right" unique
641         -- And it's a system-wide unique too
642
643   -- Now we get to the real reason that all this is in the IO Monad:
644   -- we have to update the name cache in a nice atomic fashion
645
646   | local  && internal = do { nc <- readIORef nc_var
647                             ; let (nc', new_local_name) = mk_new_local nc
648                             ; writeIORef nc_var nc'
649                             ; return (occ_env', new_local_name) }
650         -- Even local, internal names must get a unique occurrence, because
651         -- if we do -split-objs we externalise the name later, in the code generator
652         --
653         -- Similarly, we must make sure it has a system-wide Unique, because
654         -- the byte-code generator builds a system-wide Name->BCO symbol table
655
656   | local  && external = do { nc <- readIORef nc_var
657                             ; let (nc', new_external_name) = mk_new_external nc
658                             ; writeIORef nc_var nc'
659                             ; return (occ_env', new_external_name) }
660   where
661     name        = idName id
662     external    = id `elemVarEnv` ext_ids
663     global      = isExternalName name
664     local       = not global
665     internal    = not external
666     loc         = nameSrcLoc name
667
668     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
669
670     mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
671                     where
672                       (us1, us2) = splitUniqSupply (nsUniqs nc)
673                       uniq       = uniqFromSupply us1
674
675     mk_new_external nc = allocateGlobalBinder nc mod occ' loc
676         -- If we want to externalise a currently-local name, check
677         -- whether we have already assigned a unique for it.
678         -- If so, use it; if not, extend the table.
679         -- All this is done by allcoateGlobalBinder.
680         -- This is needed when *re*-compiling a module in GHCi; we must
681         -- use the same name for externally-visible things as we did before.
682
683
684 -----------------------------------------------------------
685 tidyTopPair :: VarEnv Bool
686             -> TidyEnv  -- The TidyEnv is used to tidy the IdInfo
687                         -- It is knot-tied: don't look at it!
688             -> CafInfo
689             -> Name             -- New name
690             -> (Id, CoreExpr)   -- Binder and RHS before tidying
691             -> (Id, CoreExpr)
692         -- This function is the heart of Step 2
693         -- The rec_tidy_env is the one to use for the IdInfo
694         -- It's necessary because when we are dealing with a recursive
695         -- group, a variable late in the group might be mentioned
696         -- in the IdInfo of one early in the group
697
698 tidyTopPair ext_ids rhs_tidy_env caf_info name' (bndr, rhs)
699   | isGlobalId bndr             -- Injected binding for record selector, etc
700   = (bndr, tidyExpr rhs_tidy_env rhs)
701   | otherwise
702   = (bndr', rhs')
703   where
704     bndr'   = mkVanillaGlobal name' ty' idinfo'
705     ty'     = tidyTopType (idType bndr)
706     rhs'    = tidyExpr rhs_tidy_env rhs
707     idinfo' = tidyTopIdInfo rhs_tidy_env (isJust maybe_external)
708                             (idInfo bndr) unfold_info arity
709                             caf_info
710
711     -- Expose an unfolding if ext_ids tells us to
712     -- Remember that ext_ids maps an Id to a Bool: 
713     --  True to show the unfolding, False to hide it
714     maybe_external = lookupVarEnv ext_ids bndr
715     show_unfold = maybe_external `orElse` False
716     unfold_info | show_unfold = mkTopUnfolding rhs'
717                 | otherwise   = noUnfolding
718
719     -- Usually the Id will have an accurate arity on it, because
720     -- the simplifier has just run, but not always. 
721     -- One case I found was when the last thing the simplifier
722     -- did was to let-bind a non-atomic argument and then float
723     -- it to the top level. So it seems more robust just to
724     -- fix it here.
725     arity = exprArity rhs
726
727
728 -- tidyTopIdInfo creates the final IdInfo for top-level
729 -- binders.  There are two delicate pieces:
730 --
731 --  * Arity.  After CoreTidy, this arity must not change any more.
732 --      Indeed, CorePrep must eta expand where necessary to make
733 --      the manifest arity equal to the claimed arity.
734 --
735 --  * CAF info.  This must also remain valid through to code generation.
736 --      We add the info here so that it propagates to all
737 --      occurrences of the binders in RHSs, and hence to occurrences in
738 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
739 --      CoreToStg makes use of this when constructing SRTs.
740
741 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity caf_info
742   | not is_external     -- For internal Ids (not externally visible)
743   = vanillaIdInfo       -- we only need enough info for code generation
744                         -- Arity and strictness info are enough;
745                         --      c.f. CoreTidy.tidyLetBndr
746         `setCafInfo`           caf_info
747         `setArityInfo`         arity
748         `setAllStrictnessInfo` newStrictnessInfo idinfo
749
750   | otherwise           -- Externally-visible Ids get the whole lot
751   = vanillaIdInfo
752         `setCafInfo`           caf_info
753         `setArityInfo`         arity
754         `setAllStrictnessInfo` newStrictnessInfo idinfo
755         `setInlinePragInfo`    inlinePragInfo idinfo
756         `setUnfoldingInfo`     unfold_info
757         `setWorkerInfo`        tidyWorker tidy_env (workerInfo idinfo)
758                 -- NB: we throw away the Rules
759                 -- They have already been extracted by findExternalRules
760
761
762
763 ------------  Worker  --------------
764 tidyWorker tidy_env (HasWorker work_id wrap_arity) 
765   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
766 tidyWorker tidy_env other
767   = NoWorker
768 \end{code}
769
770 %************************************************************************
771 %*                                                                      *
772 \subsection{Figuring out CafInfo for an expression}
773 %*                                                                      *
774 %************************************************************************
775
776 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
777 We mark such things as `MayHaveCafRefs' because this information is
778 used to decide whether a particular closure needs to be referenced
779 in an SRT or not.
780
781 There are two reasons for setting MayHaveCafRefs:
782         a) The RHS is a CAF: a top-level updatable thunk.
783         b) The RHS refers to something that MayHaveCafRefs
784
785 Possible improvement: In an effort to keep the number of CAFs (and 
786 hence the size of the SRTs) down, we could also look at the expression and 
787 decide whether it requires a small bounded amount of heap, so we can ignore 
788 it as a CAF.  In these cases however, we would need to use an additional
789 CAF list to keep track of non-collectable CAFs.  
790
791 \begin{code}
792 hasCafRefs  :: PackageId -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
793 hasCafRefs this_pkg p arity expr 
794   | is_caf || mentions_cafs || is_tick
795                             = MayHaveCafRefs
796   | otherwise               = NoCafRefs
797  where
798   mentions_cafs = isFastTrue (cafRefs p expr)
799   is_caf = not (arity > 0 || rhsIsStatic this_pkg expr)
800   is_tick = case expr of
801               Note (TickBox {}) _       -> True
802               Note (BinaryTickBox {}) _ -> True
803               _                         -> False
804         
805   -- NB. we pass in the arity of the expression, which is expected
806   -- to be calculated by exprArity.  This is because exprArity
807   -- knows how much eta expansion is going to be done by 
808   -- CorePrep later on, and we don't want to duplicate that
809   -- knowledge in rhsIsStatic below.
810
811 cafRefs p (Var id)
812         -- imported Ids first:
813   | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
814         -- now Ids local to this module:
815   | otherwise =
816      case lookupVarEnv p id of
817         Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
818         Nothing  -> fastBool False
819
820 cafRefs p (Lit l)              = fastBool False
821 cafRefs p (App f a)            = fastOr (cafRefs p f) (cafRefs p) a
822 cafRefs p (Lam x e)            = cafRefs p e
823 cafRefs p (Let b e)            = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
824 cafRefs p (Case e bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
825 cafRefs p (Note n e)           = cafRefs p e
826 cafRefs p (Cast e co)          = cafRefs p e
827 cafRefs p (Type t)             = fastBool False
828
829 cafRefss p []     = fastBool False
830 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
831
832 -- hack for lazy-or over FastBool.
833 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))
834 \end{code}