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