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