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