refactorings
[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, 
8                 tidyProgram, globaliseAndTidyId ) where
9
10 #include "HsVersions.h"
11
12 import TcRnTypes
13 import FamInstEnv
14 import DynFlags
15 import CoreSyn
16 import CoreUnfold
17 import CoreFVs
18 import CoreTidy
19 import PprCore
20 import CoreLint
21 import CoreUtils
22 import CoreArity        ( exprArity )
23 import Class            ( classSelIds )
24 import VarEnv
25 import VarSet
26 import Var
27 import Id
28 import IdInfo
29 import InstEnv
30 import NewDemand
31 import BasicTypes
32 import Name
33 import NameSet
34 import IfaceEnv
35 import NameEnv
36 import TcType
37 import DataCon
38 import TyCon
39 import Module
40 import HscTypes
41 import Maybes
42 import ErrUtils
43 import UniqSupply
44 import Outputable
45 import FastBool hiding ( fastOr )
46 import Util
47
48 import Data.List        ( sortBy )
49 import Data.IORef       ( IORef, readIORef, writeIORef )
50 \end{code}
51
52
53 Constructing the TypeEnv, Instances, Rules from which the ModIface is
54 constructed, and which goes on to subsequent modules in --make mode.
55
56 Most of the interface file is obtained simply by serialising the
57 TypeEnv.  One important consequence is that if the *interface file*
58 has pragma info if and only if the final TypeEnv does. This is not so
59 important for *this* module, but it's essential for ghc --make:
60 subsequent compilations must not see (e.g.) the arity if the interface
61 file does not contain arity If they do, they'll exploit the arity;
62 then the arity might change, but the iface file doesn't change =>
63 recompilation does not happen => disaster. 
64
65 For data types, the final TypeEnv will have a TyThing for the TyCon,
66 plus one for each DataCon; the interface file will contain just one
67 data type declaration, but it is de-serialised back into a collection
68 of TyThings.
69
70 %************************************************************************
71 %*                                                                      *
72                 Plan A: simpleTidyPgm
73 %*                                                                      * 
74 %************************************************************************
75
76
77 Plan A: mkBootModDetails: omit pragmas, make interfaces small
78 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
79 * Ignore the bindings
80
81 * Drop all WiredIn things from the TypeEnv 
82         (we never want them in interface files)
83
84 * Retain all TyCons and Classes in the TypeEnv, to avoid
85         having to find which ones are mentioned in the
86         types of exported Ids
87
88 * Trim off the constructors of non-exported TyCons, both
89         from the TyCon and from the TypeEnv
90
91 * Drop non-exported Ids from the TypeEnv
92
93 * Tidy the types of the DFunIds of Instances, 
94   make them into GlobalIds, (they already have External Names)
95   and add them to the TypeEnv
96
97 * Tidy the types of the (exported) Ids in the TypeEnv,
98   make them into GlobalIds (they already have External Names)
99
100 * Drop rules altogether
101
102 * Tidy the bindings, to ensure that the Caf and Arity
103   information is correct for each top-level binder; the 
104   code generator needs it. And to ensure that local names have
105   distinct OccNames in case of object-file splitting
106
107 \begin{code}
108 -- This is Plan A: make a small type env when typechecking only,
109 -- or when compiling a hs-boot file, or simply when not using -O
110 --
111 -- We don't look at the bindings at all -- there aren't any
112 -- for hs-boot files
113
114 mkBootModDetailsTc :: HscEnv -> TcGblEnv -> IO ModDetails
115 mkBootModDetailsTc hsc_env 
116         TcGblEnv{ tcg_exports   = exports,
117                   tcg_type_env  = type_env,
118                   tcg_insts     = insts,
119                   tcg_fam_insts = fam_insts
120                 }
121   = mkBootModDetails hsc_env exports type_env insts fam_insts
122
123 mkBootModDetailsDs :: HscEnv -> ModGuts -> IO ModDetails
124 mkBootModDetailsDs hsc_env 
125         ModGuts{ mg_exports   = exports,
126                  mg_types     = type_env,
127                  mg_insts     = insts,
128                  mg_fam_insts = fam_insts
129                 }
130   = mkBootModDetails hsc_env exports type_env insts fam_insts
131   
132 mkBootModDetails :: HscEnv -> [AvailInfo] -> NameEnv TyThing
133                  -> [Instance] -> [FamInstEnv.FamInst] -> IO ModDetails
134 mkBootModDetails hsc_env exports type_env insts fam_insts
135   = do  { let dflags = hsc_dflags hsc_env 
136         ; showPass dflags "Tidy [hoot] type env"
137
138         ; let { insts'     = tidyInstances globaliseAndTidyId insts
139               ; dfun_ids   = map instanceDFunId insts'
140               ; type_env1  = tidyBootTypeEnv (availsToNameSet exports) type_env
141               ; type_env'  = extendTypeEnvWithIds type_env1 dfun_ids
142               }
143         ; return (ModDetails { md_types     = type_env'
144                              , md_insts     = insts'
145                              , md_fam_insts = fam_insts
146                              , md_rules     = []
147                              , md_anns      = []
148                              , md_exports   = exports
149                              , md_vect_info = noVectInfo
150                              })
151         }
152   where
153
154 tidyBootTypeEnv :: NameSet -> TypeEnv -> TypeEnv
155 tidyBootTypeEnv exports type_env 
156   = tidyTypeEnv True False exports type_env final_ids
157   where
158         -- Find the LocalIds in the type env that are exported
159         -- Make them into GlobalIds, and tidy their types
160         --
161         -- It's very important to remove the non-exported ones
162         -- because we don't tidy the OccNames, and if we don't remove
163         -- the non-exported ones we'll get many things with the
164         -- same name in the interface file, giving chaos.
165     final_ids = [ globaliseAndTidyId id
166                 | id <- typeEnvIds type_env
167                 , isLocalId id
168                 , keep_it id ]
169
170         -- default methods have their export flag set, but everything
171         -- else doesn't (yet), because this is pre-desugaring, so we
172         -- must test both.
173     keep_it id = isExportedId id || idName id `elemNameSet` exports
174
175
176
177 globaliseAndTidyId :: Id -> Id
178 -- Takes an LocalId with an External Name, 
179 -- makes it into a GlobalId 
180 --     * unchanged Name (might be Internal or External)
181 --     * unchanged details
182 --     * VanillaIdInfo (makes a conservative assumption about Caf-hood)
183 globaliseAndTidyId id   
184   = Id.setIdType (globaliseId id) tidy_type
185   where
186     tidy_type = tidyTopType (idType id)
187 \end{code}
188
189
190 %************************************************************************
191 %*                                                                      *
192         Plan B: tidy bindings, make TypeEnv full of IdInfo
193 %*                                                                      * 
194 %************************************************************************
195
196 Plan B: include pragmas, make interfaces 
197 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
198 * Figure out which Ids are externally visible
199
200 * Tidy the bindings, externalising appropriate Ids
201
202 * Drop all Ids from the TypeEnv, and add all the External Ids from 
203   the bindings.  (This adds their IdInfo to the TypeEnv; and adds
204   floated-out Ids that weren't even in the TypeEnv before.)
205
206 Step 1: Figure out external Ids
207 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
208 Note [choosing external names]
209
210 First we figure out which Ids are "external" Ids.  An
211 "external" Id is one that is visible from outside the compilation
212 unit.  These are
213         a) the user exported ones
214         b) ones mentioned in the unfoldings, workers, 
215            or rules of externally-visible ones 
216
217 While figuring out which Ids are external, we pick a "tidy" OccName
218 for each one.  That is, we make its OccName distinct from the other
219 external OccNames in this module, so that in interface files and
220 object code we can refer to it unambiguously by its OccName.  The
221 OccName for each binder is prefixed by the name of the exported Id
222 that references it; e.g. if "f" references "x" in its unfolding, then
223 "x" is renamed to "f_x".  This helps distinguish the different "x"s
224 from each other, and means that if "f" is later removed, things that
225 depend on the other "x"s will not need to be recompiled.  Of course,
226 if there are multiple "f_x"s, then we have to disambiguate somehow; we
227 use "f_x0", "f_x1" etc.
228
229 As far as possible we should assign names in a deterministic fashion.
230 Each time this module is compiled with the same options, we should end
231 up with the same set of external names with the same types.  That is,
232 the ABI hash in the interface should not change.  This turns out to be
233 quite tricky, since the order of the bindings going into the tidy
234 phase is already non-deterministic, as it is based on the ordering of
235 Uniques, which are assigned unpredictably.
236
237 To name things in a stable way, we do a depth-first-search of the
238 bindings, starting from the exports sorted by name.  This way, as long
239 as the bindings themselves are deterministic (they sometimes aren't!),
240 the order in which they are presented to the tidying phase does not
241 affect the names we assign.
242
243 Step 2: Tidy the program
244 ~~~~~~~~~~~~~~~~~~~~~~~~
245 Next we traverse the bindings top to bottom.  For each *top-level*
246 binder
247
248  1. Make it into a GlobalId; its IdDetails becomes VanillaGlobal, 
249     reflecting the fact that from now on we regard it as a global, 
250     not local, Id
251
252  2. Give it a system-wide Unique.
253     [Even non-exported things need system-wide Uniques because the
254     byte-code generator builds a single Name->BCO symbol table.]
255
256     We use the NameCache kept in the HscEnv as the
257     source of such system-wide uniques.
258
259     For external Ids, use the original-name cache in the NameCache
260     to ensure that the unique assigned is the same as the Id had 
261     in any previous compilation run.
262
263  3. Rename top-level Ids according to the names we chose in step 1.
264     If it's an external Id, make it have a External Name, otherwise
265     make it have an Internal Name.  This is used by the code generator
266     to decide whether to make the label externally visible
267
268  4. Give it its UTTERLY FINAL IdInfo; in ptic, 
269         * its unfolding, if it should have one
270         
271         * its arity, computed from the number of visible lambdas
272
273         * its CAF info, computed from what is free in its RHS
274
275                 
276 Finally, substitute these new top-level binders consistently
277 throughout, including in unfoldings.  We also tidy binders in
278 RHSs, so that they print nicely in interfaces.
279
280 \begin{code}
281 tidyProgram :: HscEnv -> ModGuts -> IO (CgGuts, ModDetails)
282 tidyProgram hsc_env  (ModGuts { mg_module = mod, mg_exports = exports, 
283                                 mg_types = type_env, 
284                                 mg_insts = insts, mg_fam_insts = fam_insts,
285                                 mg_binds = binds, 
286                                 mg_rules = imp_rules,
287                                 mg_vect_info = vect_info,
288                                 mg_dir_imps = dir_imps, 
289                                 mg_anns = anns,
290                                 mg_deps = deps, 
291                                 mg_foreign = foreign_stubs,
292                                 mg_hpc_info = hpc_info,
293                                 mg_modBreaks = modBreaks })
294
295   = do  { let dflags = hsc_dflags hsc_env
296         ; showPass dflags "Tidy Core"
297
298         ; let { omit_prags = dopt Opt_OmitInterfacePragmas dflags
299               ; th         = dopt Opt_TemplateHaskell      dflags
300               }
301
302         ; (unfold_env, tidy_occ_env)
303               <- chooseExternalIds hsc_env type_env mod omit_prags binds
304
305         ; let { ext_rules 
306                    | omit_prags = []
307                    | otherwise  = findExternalRules binds imp_rules unfold_env
308                 -- findExternalRules filters imp_rules to avoid binders that 
309                 -- aren't externally visible; but the externally-visible binders 
310                 -- are computed (by findExternalIds) assuming that all orphan
311                 -- rules are exported (they get their Exported flag set in the desugarer)
312                 -- So in fact we may export more than we need. 
313                 -- (It's a sort of mutual recursion.)
314         }
315
316         ; let { (tidy_env, tidy_binds)
317                  = tidyTopBinds hsc_env unfold_env tidy_occ_env binds }
318
319         ; let { export_set = availsToNameSet exports
320               ; final_ids  = [ id | id <- bindersOfBinds tidy_binds, 
321                                     isExternalName (idName id)]
322               ; tidy_type_env = tidyTypeEnv omit_prags th export_set
323                                             type_env final_ids
324               ; tidy_insts    = tidyInstances (lookup_dfun tidy_type_env) insts
325                 -- A DFunId will have a binding in tidy_binds, and so
326                 -- will now be in final_env, replete with IdInfo
327                 -- Its name will be unchanged since it was born, but
328                 -- we want Global, IdInfo-rich (or not) DFunId in the
329                 -- tidy_insts
330
331               ; tidy_rules = tidyRules tidy_env ext_rules
332                 -- You might worry that the tidy_env contains IdInfo-rich stuff
333                 -- and indeed it does, but if omit_prags is on, ext_rules is
334                 -- empty
335
336               -- See Note [Injecting implicit bindings]
337               ; implicit_binds = getImplicitBinds type_env
338               ; all_tidy_binds = implicit_binds ++ tidy_binds
339
340               ; alg_tycons = filter isAlgTyCon (typeEnvTyCons type_env)
341               }
342
343         ; endPass dflags "Tidy Core" Opt_D_dump_simpl all_tidy_binds
344         ; dumpIfSet_core dflags Opt_D_dump_simpl
345                 "Tidy Core Rules"
346                 (pprRules tidy_rules)
347
348         ; let dir_imp_mods = moduleEnvKeys dir_imps
349
350         ; return (CgGuts { cg_module   = mod, 
351                            cg_tycons   = alg_tycons,
352                            cg_binds    = all_tidy_binds,
353                            cg_dir_imps = dir_imp_mods,
354                            cg_foreign  = foreign_stubs,
355                            cg_dep_pkgs = dep_pkgs deps,
356                            cg_hpc_info = hpc_info,
357                            cg_modBreaks = modBreaks }, 
358
359                    ModDetails { md_types     = tidy_type_env,
360                                 md_rules     = tidy_rules,
361                                 md_insts     = tidy_insts,
362                                 md_fam_insts = fam_insts,
363                                 md_exports   = exports,
364                                 md_anns      = anns,     -- are already tidy
365                                 md_vect_info = vect_info --
366                               })
367         }
368
369 lookup_dfun :: TypeEnv -> Var -> Id
370 lookup_dfun type_env dfun_id
371   = case lookupTypeEnv type_env (idName dfun_id) of
372         Just (AnId dfun_id') -> dfun_id'
373         _other -> pprPanic "lookup_dfun" (ppr dfun_id)
374
375 --------------------------
376 tidyTypeEnv :: Bool     -- Compiling without -O, so omit prags
377             -> Bool     -- Template Haskell is on
378             -> NameSet -> TypeEnv -> [Id] -> TypeEnv
379
380 -- The competed type environment is gotten from
381 --      Dropping any wired-in things, and then
382 --      a) keeping the types and classes
383 --      b) removing all Ids, 
384 --      c) adding Ids with correct IdInfo, including unfoldings,
385 --              gotten from the bindings
386 -- From (c) we keep only those Ids with External names;
387 --          the CoreTidy pass makes sure these are all and only
388 --          the externally-accessible ones
389 -- This truncates the type environment to include only the 
390 -- exported Ids and things needed from them, which saves space
391
392 tidyTypeEnv omit_prags th exports type_env final_ids
393  = let  type_env1 = filterNameEnv keep_it type_env
394         type_env2 = extendTypeEnvWithIds type_env1 final_ids
395         type_env3 | omit_prags = mapNameEnv (trimThing th exports) type_env2
396                   | otherwise  = type_env2
397     in 
398     type_env3
399   where
400         -- We keep GlobalIds, because they won't appear 
401         -- in the bindings from which final_ids are derived!
402         -- (The bindings bind LocalIds.)
403     keep_it thing | isWiredInThing thing = False
404     keep_it (AnId id) = isGlobalId id   -- Keep GlobalIds (e.g. class ops)
405     keep_it _other    = True            -- Keep all TyCons, DataCons, and Classes
406
407 --------------------------
408 isWiredInThing :: TyThing -> Bool
409 isWiredInThing thing = isWiredInName (getName thing)
410
411 --------------------------
412 trimThing :: Bool -> NameSet -> TyThing -> TyThing
413 -- Trim off inessentials, for boot files and no -O
414 trimThing th exports (ATyCon tc)
415    | not th && not (mustExposeTyCon exports tc)
416    = ATyCon (makeTyConAbstract tc)      -- Note [Trimming and Template Haskell]
417
418 trimThing _th _exports (AnId id)
419    | not (isImplicitId id) 
420    = AnId (id `setIdInfo` vanillaIdInfo)
421
422 trimThing _th _exports other_thing 
423   = other_thing
424
425
426 {- Note [Trimming and Template Haskell]
427    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
428 Consider (Trac #2386) this
429         module M(T, makeOne) where
430           data T = Yay String
431           makeOne = [| Yay "Yep" |]
432 Notice that T is exported abstractly, but makeOne effectively exports it too!
433 A module that splices in $(makeOne) will then look for a declartion of Yay,
434 so it'd better be there.  Hence, brutally but simply, we switch off type
435 constructor trimming if TH is enabled in this module. -}
436
437
438 mustExposeTyCon :: NameSet      -- Exports
439                 -> TyCon        -- The tycon
440                 -> Bool         -- Can its rep be hidden?
441 -- We are compiling without -O, and thus trying to write as little as 
442 -- possible into the interface file.  But we must expose the details of
443 -- any data types whose constructors or fields are exported
444 mustExposeTyCon exports tc
445   | not (isAlgTyCon tc)         -- Synonyms
446   = True
447   | isEnumerationTyCon tc       -- For an enumeration, exposing the constructors
448   = True                        -- won't lead to the need for further exposure
449                                 -- (This includes data types with no constructors.)
450   | isOpenTyCon tc              -- Open type family
451   = True
452
453   | otherwise                   -- Newtype, datatype
454   = any exported_con (tyConDataCons tc)
455         -- Expose rep if any datacon or field is exported
456
457   || (isNewTyCon tc && isFFITy (snd (newTyConRhs tc)))
458         -- Expose the rep for newtypes if the rep is an FFI type.  
459         -- For a very annoying reason.  'Foreign import' is meant to
460         -- be able to look through newtypes transparently, but it
461         -- can only do that if it can "see" the newtype representation
462   where
463     exported_con con = any (`elemNameSet` exports) 
464                            (dataConName con : dataConFieldLabels con)
465
466 tidyInstances :: (DFunId -> DFunId) -> [Instance] -> [Instance]
467 tidyInstances tidy_dfun ispecs
468   = map tidy ispecs
469   where
470     tidy ispec = setInstanceDFunId ispec $
471                  tidy_dfun (instanceDFunId ispec)
472 \end{code}
473
474
475 %************************************************************************
476 %*                                                                      *
477         Implicit bindings
478 %*                                                                      *
479 %************************************************************************
480
481 Note [Injecting implicit bindings]
482 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
483 We inject the implict bindings right at the end, in CoreTidy.
484 Some of these bindings, notably record selectors, are not
485 constructed in an optimised form.  E.g. record selector for
486         data T = MkT { x :: {-# UNPACK #-} !Int }
487 Then the unfolding looks like
488         x = \t. case t of MkT x1 -> let x = I# x1 in x
489 This generates bad code unless it's first simplified a bit.  That is
490 why CoreUnfold.mkImplicitUnfolding uses simleExprOpt to do a bit of
491 optimisation first.  (Only matters when the selector is used curried;
492 eg map x ys.)  See Trac #2070.
493
494 At one time I tried injecting the implicit bindings *early*, at the
495 beginning of SimplCore.  But that gave rise to real difficulty,
496 becuase GlobalIds are supposed to have *fixed* IdInfo, but the
497 simplifier and other core-to-core passes mess with IdInfo all the
498 time.  The straw that broke the camels back was when a class selector
499 got the wrong arity -- ie the simplifier gave it arity 2, whereas
500 importing modules were expecting it to have arity 1 (Trac #2844).
501 It's much safer just to inject them right at the end, after tidying.
502
503 Oh: two other reasons for injecting them late:
504   - If implicit Ids are already in the bindings when we start TidyPgm,
505     we'd have to be careful not to treat them as external Ids (in
506     the sense of findExternalIds); else the Ids mentioned in *their*
507     RHSs will be treated as external and you get an interface file 
508     saying      a18 = <blah>
509     but nothing refererring to a18 (because the implicit Id is the 
510     one that does).
511
512   - More seriously, the tidied type-envt will include the implicit
513     Id replete with a18 in its unfolding; but we won't take account
514     of a18 when computing a fingerprint for the class; result chaos.
515     
516
517 \begin{code}
518 getImplicitBinds :: TypeEnv -> [CoreBind]
519 getImplicitBinds type_env
520   = map get_defn (concatMap implicit_ids (typeEnvElts type_env))
521   where
522     implicit_ids (ATyCon tc)  = mapCatMaybes dataConWrapId_maybe (tyConDataCons tc)
523     implicit_ids (AClass cls) = classSelIds cls
524     implicit_ids _            = []
525     
526     get_defn :: Id -> CoreBind
527     get_defn id = NonRec id (unfoldingTemplate (idUnfolding id))
528 \end{code}
529
530
531 %************************************************************************
532 %*                                                                      *
533 \subsection{Step 1: finding externals}
534 %*                                                                      * 
535 %************************************************************************
536
537 Sete Note [choosing external names].
538
539 \begin{code}
540 type UnfoldEnv  = IdEnv (Name{-new name-}, Bool {-show unfolding-})
541   -- maps each top-level Id to its new Name (the Id is tidied in step 2)
542   -- The Unique is unchanged.  If the new Id is external, it will be
543   -- visible in the interface file.  
544   --
545   -- Bool => expose unfolding or not.
546
547 chooseExternalIds :: HscEnv
548                   -> TypeEnv
549                   -> Module
550                   -> Bool
551                   -> [CoreBind]
552                   -> IO (UnfoldEnv, TidyOccEnv)
553         -- Step 1 from the notes above
554
555 chooseExternalIds hsc_env type_env mod omit_prags binds 
556   = do
557     (unfold_env1,occ_env1) 
558         <- search (zip sorted_exports sorted_exports) emptyVarEnv init_occ_env
559     let internal_ids = filter (not . (`elemVarEnv` unfold_env1)) binders
560     tidy_internal internal_ids unfold_env1 occ_env1
561  where
562   nc_var = hsc_NC hsc_env 
563
564   -- the exports, sorted by OccName.  This is a deterministic list of
565   -- Ids (i.e. it's the same list every time this module is compiled),
566   -- in contrast to the bindings, which are ordered
567   -- non-deterministically.
568   --
569   -- This list will serve as a starting point for finding a
570   -- deterministic, tidy, renaming for all external Ids in this
571   -- module.
572   sorted_exports = sortBy (compare `on` getOccName) $
573                      filter isExportedId binders
574
575   binders = bindersOfBinds binds
576
577   bind_env :: IdEnv CoreExpr
578   bind_env = mkVarEnv (flattenBinds binds)
579
580   avoids   = [getOccName name | bndr <- typeEnvIds type_env,
581                                 let name = idName bndr,
582                                 isExternalName name]
583                 -- In computing our "avoids" list, we must include
584                 --      all implicit Ids
585                 --      all things with global names (assigned once and for
586                 --                                      all by the renamer)
587                 -- since their names are "taken".
588                 -- The type environment is a convenient source of such things.
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_occ_env = initTidyOccEnv avoids
599
600
601   search :: [(Id,Id)]    -- (external id, referrring id)
602          -> UnfoldEnv    -- id -> (new Name, show_unfold)
603          -> TidyOccEnv   -- occ env for choosing new Names
604          -> IO (UnfoldEnv, TidyOccEnv)
605
606   search [] unfold_env occ_env = return (unfold_env, occ_env)
607
608   search ((id,referrer) : rest) unfold_env occ_env
609     | id `elemVarEnv` unfold_env = search rest unfold_env occ_env
610     | otherwise = do
611       (occ_env', name') <- tidyTopName mod nc_var (Just referrer) occ_env id
612       let 
613           rhs = expectJust "chooseExternalIds" $ lookupVarEnv bind_env id
614           (new_ids, show_unfold)
615                 | omit_prags = ([], False)
616                 | otherwise  = addExternal id rhs
617           unfold_env' = extendVarEnv unfold_env id (name',show_unfold)
618           referrer' | isExportedId id = id
619                     | otherwise       = referrer
620       --
621       search (zip new_ids (repeat referrer') ++ rest) unfold_env' occ_env'
622
623   tidy_internal :: [Id] -> UnfoldEnv -> TidyOccEnv
624                 -> IO (UnfoldEnv, TidyOccEnv)
625   tidy_internal []       unfold_env occ_env = return (unfold_env,occ_env)
626   tidy_internal (id:ids) unfold_env occ_env = do
627       (occ_env', name') <- tidyTopName mod nc_var Nothing occ_env id
628       let unfold_env' = extendVarEnv unfold_env id (name',False)
629       tidy_internal ids unfold_env' occ_env'
630
631 addExternal :: Id -> CoreExpr -> ([Id],Bool)
632 addExternal id rhs = (new_needed_ids, show_unfold)
633   where
634     new_needed_ids = unfold_ids ++
635                      filter (not . (`elemVarSet` unfold_set)) 
636                        (varSetElems worker_ids ++ 
637                         varSetElems spec_ids) -- XXX non-det ordering
638
639     idinfo         = idInfo id
640     dont_inline    = isNeverActive (inlinePragmaActivation (inlinePragInfo idinfo))
641     loop_breaker   = isNonRuleLoopBreaker (occInfo idinfo)
642     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
643     spec_ids       = specInfoFreeVars (specInfo idinfo)
644     worker_info    = workerInfo idinfo
645
646         -- Stuff to do with the Id's unfolding
647         -- The simplifier has put an up-to-date unfolding
648         -- in the IdInfo, but the RHS will do just as well
649     unfolding    = unfoldingInfo idinfo
650     rhs_is_small = not (neverUnfold unfolding)
651
652         -- We leave the unfolding there even if there is a worker
653         -- In GHCI the unfolding is used by importers
654         -- When writing an interface file, we omit the unfolding 
655         -- if there is a worker
656     show_unfold = not bottoming_fn       &&     -- Not necessary
657                   not dont_inline        &&
658                   not loop_breaker       &&
659                   rhs_is_small                  -- Small enough
660
661     (unfold_set, unfold_ids)
662                | show_unfold = freeVarsInDepthFirstOrder rhs
663                | otherwise   = (emptyVarSet, [])
664
665     worker_ids = case worker_info of
666                    HasWorker work_id _ -> unitVarSet work_id
667                    _otherwise          -> emptyVarSet
668
669
670 -- We want a deterministic free-variable list.  exprFreeVars gives us
671 -- a VarSet, which is in a non-deterministic order when converted to a
672 -- list.  Hence, here we define a free-variable finder that returns
673 -- the free variables in the order that they are encountered.
674 --
675 -- Note [choosing external names]
676
677 freeVarsInDepthFirstOrder :: CoreExpr -> (VarSet, [Id])
678 freeVarsInDepthFirstOrder e = 
679   case dffvExpr e of
680     DFFV m -> case m emptyVarSet [] of
681                 (set,ids,_) -> (set,ids)
682
683 newtype DFFV a = DFFV (VarSet -> [Var] -> (VarSet,[Var],a))
684
685 instance Monad DFFV where
686   return a = DFFV $ \set ids -> (set, ids, a)
687   (DFFV m) >>= k = DFFV $ \set ids ->
688     case m set ids of
689        (set',ids',a) -> case k a of
690                           DFFV f -> f set' ids' 
691
692 insert :: Var -> DFFV ()
693 insert v = DFFV $ \ set ids  -> case () of 
694  _ | v `elemVarSet` set -> (set,ids,())
695    | otherwise          -> (extendVarSet set v, v:ids, ())
696
697 dffvExpr :: CoreExpr -> DFFV ()
698 dffvExpr e = go emptyVarSet e
699   where
700     go scope e = case e of
701       Var v | isLocalId v && not (v `elemVarSet` scope) -> insert v
702       App e1 e2          -> do go scope e1; go scope e2
703       Lam v e            -> go (extendVarSet scope v) e
704       Note _ e           -> go scope e
705       Cast e _           -> go scope e
706       Let (NonRec x r) e -> do go scope r; go (extendVarSet scope x) e
707       Let (Rec prs) e    -> do let scope' = extendVarSetList scope (map fst prs)
708                                mapM_ (go scope') (map snd prs)
709                                go scope' e
710       Case e b _ as      -> do go scope e
711                                mapM_ (go_alt (extendVarSet scope b)) as
712       _other             -> return ()
713
714     go_alt scope (_,xs,r) = go (extendVarSetList scope xs) r
715 \end{code}
716
717
718 --------------------------------------------------------------------
719 --              tidyTopName
720 -- This is where we set names to local/global based on whether they really are 
721 -- externally visible (see comment at the top of this module).  If the name
722 -- was previously local, we have to give it a unique occurrence name if
723 -- we intend to externalise it.
724
725 \begin{code}
726 tidyTopName :: Module -> IORef NameCache -> Maybe Id -> TidyOccEnv
727             -> Id -> IO (TidyOccEnv, Name)
728 tidyTopName mod nc_var maybe_ref occ_env id
729   | global && internal = return (occ_env, localiseName name)
730
731   | global && external = return (occ_env, name)
732         -- Global names are assumed to have been allocated by the renamer,
733         -- so they already have the "right" unique
734         -- And it's a system-wide unique too
735
736   -- Now we get to the real reason that all this is in the IO Monad:
737   -- we have to update the name cache in a nice atomic fashion
738
739   | local  && internal = do { nc <- readIORef nc_var
740                             ; let (nc', new_local_name) = mk_new_local nc
741                             ; writeIORef nc_var nc'
742                             ; return (occ_env', new_local_name) }
743         -- Even local, internal names must get a unique occurrence, because
744         -- if we do -split-objs we externalise the name later, in the code generator
745         --
746         -- Similarly, we must make sure it has a system-wide Unique, because
747         -- the byte-code generator builds a system-wide Name->BCO symbol table
748
749   | local  && external = do { nc <- readIORef nc_var
750                             ; let (nc', new_external_name) = mk_new_external nc
751                             ; writeIORef nc_var nc'
752                             ; return (occ_env', new_external_name) }
753
754   | otherwise = panic "tidyTopName"
755   where
756     name        = idName id
757     external    = isJust maybe_ref
758     global      = isExternalName name
759     local       = not global
760     internal    = not external
761     loc         = nameSrcSpan name
762
763     old_occ     = nameOccName name
764     new_occ
765       | Just ref <- maybe_ref, ref /= id = 
766           mkOccName (occNameSpace old_occ) $
767              occNameString (getOccName ref) ++ '_' : occNameString old_occ
768       | otherwise = old_occ
769
770     (occ_env', occ') = tidyOccName occ_env new_occ
771
772     mk_new_local nc = (nc { nsUniqs = us2 }, mkInternalName uniq occ' loc)
773                     where
774                       (us1, us2) = splitUniqSupply (nsUniqs nc)
775                       uniq       = uniqFromSupply us1
776
777     mk_new_external nc = allocateGlobalBinder nc mod occ' loc
778         -- If we want to externalise a currently-local name, check
779         -- whether we have already assigned a unique for it.
780         -- If so, use it; if not, extend the table.
781         -- All this is done by allcoateGlobalBinder.
782         -- This is needed when *re*-compiling a module in GHCi; we must
783         -- use the same name for externally-visible things as we did before.
784 \end{code}
785
786 \begin{code}
787 findExternalRules :: [CoreBind]
788                   -> [CoreRule] -- Non-local rules (i.e. ones for imported fns)
789                   -> UnfoldEnv  -- Ids that are exported, so we need their rules
790                   -> [CoreRule]
791   -- The complete rules are gotten by combining
792   --    a) the non-local rules
793   --    b) rules embedded in the top-level Ids
794 findExternalRules binds non_local_rules unfold_env
795   = filter (not . internal_rule) (non_local_rules ++ local_rules)
796   where
797     local_rules  = [ rule
798                    | id <- bindersOfBinds binds,
799                      external_id id,
800                      rule <- idCoreRules id
801                    ]
802
803     internal_rule rule
804         =  any (not . external_id) (varSetElems (ruleLhsFreeIds rule))
805                 -- Don't export a rule whose LHS mentions a locally-defined
806                 --  Id that is completely internal (i.e. not visible to an
807                 -- importing module)
808
809     external_id id
810       | Just (name,_) <- lookupVarEnv unfold_env id = isExternalName name
811       | otherwise = False
812 \end{code}
813
814
815
816 %************************************************************************
817 %*                                                                      *
818 \subsection{Step 2: top-level tidying}
819 %*                                                                      *
820 %************************************************************************
821
822
823 \begin{code}
824 -- TopTidyEnv: when tidying we need to know
825 --   * nc_var: The NameCache, containing a unique supply and any pre-ordained Names.  
826 --        These may have arisen because the
827 --        renamer read in an interface file mentioning M.$wf, say,
828 --        and assigned it unique r77.  If, on this compilation, we've
829 --        invented an Id whose name is $wf (but with a different unique)
830 --        we want to rename it to have unique r77, so that we can do easy
831 --        comparisons with stuff from the interface file
832 --
833 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
834 --     are 'used'
835 --
836 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
837
838 tidyTopBinds :: HscEnv
839              -> UnfoldEnv
840              -> TidyOccEnv
841              -> [CoreBind]
842              -> (TidyEnv, [CoreBind])
843
844 tidyTopBinds hsc_env unfold_env init_occ_env binds
845   = tidy init_env binds
846   where
847     init_env = (init_occ_env, emptyVarEnv)
848
849     this_pkg = thisPackage (hsc_dflags hsc_env)
850
851     tidy env []     = (env, [])
852     tidy env (b:bs) = let (env1, b')  = tidyTopBind this_pkg unfold_env env b
853                           (env2, bs') = tidy env1 bs
854                       in
855                           (env2, b':bs')
856
857 ------------------------
858 tidyTopBind  :: PackageId
859              -> UnfoldEnv
860              -> TidyEnv
861              -> CoreBind
862              -> (TidyEnv, CoreBind)
863
864 tidyTopBind this_pkg unfold_env (occ_env,subst1) (NonRec bndr rhs)
865   = (tidy_env2,  NonRec bndr' rhs')
866   where
867     Just (name',show_unfold) = lookupVarEnv unfold_env bndr
868     caf_info      = hasCafRefs this_pkg subst1 (idArity bndr) rhs
869     (bndr', rhs') = tidyTopPair show_unfold tidy_env2 caf_info name' (bndr, rhs)
870     subst2        = extendVarEnv subst1 bndr bndr'
871     tidy_env2     = (occ_env, subst2)
872
873 tidyTopBind this_pkg unfold_env (occ_env,subst1) (Rec prs)
874   = (tidy_env2, Rec prs')
875   where
876     prs' = [ tidyTopPair show_unfold tidy_env2 caf_info name' (id,rhs)
877            | (id,rhs) <- prs,
878              let (name',show_unfold) = 
879                     expectJust "tidyTopBind" $ lookupVarEnv unfold_env id
880            ]
881
882     subst2    = extendVarEnvList subst1 (bndrs `zip` map fst prs')
883     tidy_env2 = (occ_env, subst2)
884
885     bndrs = map fst prs
886
887         -- the CafInfo for a recursive group says whether *any* rhs in
888         -- the group may refer indirectly to a CAF (because then, they all do).
889     caf_info 
890         | or [ mayHaveCafRefs (hasCafRefs this_pkg subst1 (idArity bndr) rhs)
891              | (bndr,rhs) <- prs ] = MayHaveCafRefs
892         | otherwise                = NoCafRefs
893
894 -----------------------------------------------------------
895 tidyTopPair :: Bool  -- show unfolding
896             -> TidyEnv  -- The TidyEnv is used to tidy the IdInfo
897                         -- It is knot-tied: don't look at it!
898             -> CafInfo
899             -> Name             -- New name
900             -> (Id, CoreExpr)   -- Binder and RHS before tidying
901             -> (Id, CoreExpr)
902         -- This function is the heart of Step 2
903         -- The rec_tidy_env is the one to use for the IdInfo
904         -- It's necessary because when we are dealing with a recursive
905         -- group, a variable late in the group might be mentioned
906         -- in the IdInfo of one early in the group
907
908 tidyTopPair show_unfold rhs_tidy_env caf_info name' (bndr, rhs)
909   = (bndr', rhs')
910   where
911     bndr' = mkGlobalId details name' ty' idinfo'
912     details = idDetails bndr    -- Preserve the IdDetails
913     ty'     = tidyTopType (idType bndr)
914     rhs'    = tidyExpr rhs_tidy_env rhs
915     idinfo  = idInfo bndr
916     idinfo' = tidyTopIdInfo (isExternalName name')
917                             idinfo unfold_info worker_info
918                             arity caf_info
919
920     unfold_info | show_unfold = mkTopUnfolding rhs'
921                 | otherwise   = noUnfolding
922     worker_info = tidyWorker rhs_tidy_env show_unfold (workerInfo idinfo)
923
924     -- Usually the Id will have an accurate arity on it, because
925     -- the simplifier has just run, but not always. 
926     -- One case I found was when the last thing the simplifier
927     -- did was to let-bind a non-atomic argument and then float
928     -- it to the top level. So it seems more robust just to
929     -- fix it here.
930     arity = exprArity rhs
931
932
933 -- tidyTopIdInfo creates the final IdInfo for top-level
934 -- binders.  There are two delicate pieces:
935 --
936 --  * Arity.  After CoreTidy, this arity must not change any more.
937 --      Indeed, CorePrep must eta expand where necessary to make
938 --      the manifest arity equal to the claimed arity.
939 --
940 --  * CAF info.  This must also remain valid through to code generation.
941 --      We add the info here so that it propagates to all
942 --      occurrences of the binders in RHSs, and hence to occurrences in
943 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
944 --      CoreToStg makes use of this when constructing SRTs.
945 tidyTopIdInfo :: Bool -> IdInfo -> Unfolding
946               -> WorkerInfo -> ArityInfo -> CafInfo
947               -> IdInfo
948 tidyTopIdInfo is_external idinfo unfold_info worker_info arity caf_info
949   | not is_external     -- For internal Ids (not externally visible)
950   = vanillaIdInfo       -- we only need enough info for code generation
951                         -- Arity and strictness info are enough;
952                         --      c.f. CoreTidy.tidyLetBndr
953         `setCafInfo`           caf_info
954         `setArityInfo`         arity
955         `setAllStrictnessInfo` newStrictnessInfo idinfo
956
957   | otherwise           -- Externally-visible Ids get the whole lot
958   = vanillaIdInfo
959         `setCafInfo`           caf_info
960         `setArityInfo`         arity
961         `setAllStrictnessInfo` newStrictnessInfo idinfo
962         `setInlinePragInfo`    inlinePragInfo idinfo
963         `setUnfoldingInfo`     unfold_info
964         `setWorkerInfo`        worker_info
965                 -- NB: we throw away the Rules
966                 -- They have already been extracted by findExternalRules
967
968
969
970 ------------  Worker  --------------
971 tidyWorker :: TidyEnv -> Bool -> WorkerInfo -> WorkerInfo
972 tidyWorker _tidy_env _show_unfold NoWorker
973   = NoWorker
974 tidyWorker tidy_env show_unfold (HasWorker work_id wrap_arity) 
975   | show_unfold = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
976   | otherwise   = NoWorker
977     -- NB: do *not* expose the worker if show_unfold is off,
978     --     because that means this thing is a loop breaker or
979     --     marked NOINLINE or something like that
980     -- This is important: if you expose the worker for a loop-breaker
981     -- then you can make the simplifier go into an infinite loop, because
982     -- in effect the unfolding is exposed.  See Trac #1709
983     -- 
984     -- You might think that if show_unfold is False, then the thing should
985     -- not be w/w'd in the first place.  But a legitimate reason is this:
986     --    the function returns bottom
987     -- In this case, show_unfold will be false (we don't expose unfoldings
988     -- for bottoming functions), but we might still have a worker/wrapper
989     -- split (see Note [Worker-wrapper for bottoming functions] in WorkWrap.lhs
990 \end{code}
991
992 %************************************************************************
993 %*                                                                      *
994 \subsection{Figuring out CafInfo for an expression}
995 %*                                                                      *
996 %************************************************************************
997
998 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
999 We mark such things as `MayHaveCafRefs' because this information is
1000 used to decide whether a particular closure needs to be referenced
1001 in an SRT or not.
1002
1003 There are two reasons for setting MayHaveCafRefs:
1004         a) The RHS is a CAF: a top-level updatable thunk.
1005         b) The RHS refers to something that MayHaveCafRefs
1006
1007 Possible improvement: In an effort to keep the number of CAFs (and 
1008 hence the size of the SRTs) down, we could also look at the expression and 
1009 decide whether it requires a small bounded amount of heap, so we can ignore 
1010 it as a CAF.  In these cases however, we would need to use an additional
1011 CAF list to keep track of non-collectable CAFs.  
1012
1013 \begin{code}
1014 hasCafRefs  :: PackageId -> VarEnv Var -> Arity -> CoreExpr -> CafInfo
1015 hasCafRefs this_pkg p arity expr 
1016   | is_caf || mentions_cafs 
1017                             = MayHaveCafRefs
1018   | otherwise               = NoCafRefs
1019  where
1020   mentions_cafs = isFastTrue (cafRefs p expr)
1021   is_caf = not (arity > 0 || rhsIsStatic this_pkg expr)
1022
1023   -- NB. we pass in the arity of the expression, which is expected
1024   -- to be calculated by exprArity.  This is because exprArity
1025   -- knows how much eta expansion is going to be done by 
1026   -- CorePrep later on, and we don't want to duplicate that
1027   -- knowledge in rhsIsStatic below.
1028
1029 cafRefs :: VarEnv Id -> Expr a -> FastBool
1030 cafRefs p (Var id)
1031         -- imported Ids first:
1032   | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
1033         -- now Ids local to this module:
1034   | otherwise =
1035      case lookupVarEnv p id of
1036         Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
1037         Nothing  -> fastBool False
1038
1039 cafRefs _ (Lit _)              = fastBool False
1040 cafRefs p (App f a)            = fastOr (cafRefs p f) (cafRefs p) a
1041 cafRefs p (Lam _ e)            = cafRefs p e
1042 cafRefs p (Let b e)            = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
1043 cafRefs p (Case e _bndr _ alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
1044 cafRefs p (Note _n e)          = cafRefs p e
1045 cafRefs p (Cast e _co)         = cafRefs p e
1046 cafRefs _ (Type _)             = fastBool False
1047
1048 cafRefss :: VarEnv Id -> [Expr a] -> FastBool
1049 cafRefss _ []     = fastBool False
1050 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
1051
1052 fastOr :: FastBool -> (a -> FastBool) -> a -> FastBool
1053 -- hack for lazy-or over FastBool.
1054 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))
1055 \end{code}