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