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