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