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