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