[project @ 2003-06-09 15:37:37 by simonpj]
[ghc-hetmet.git] / ghc / 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( tidyCorePgm, tidyCoreExpr ) where
8
9 #include "HsVersions.h"
10
11 import CmdLineOpts      ( DynFlags, DynFlag(..), opt_OmitInterfacePragmas )
12 import CoreSyn
13 import CoreUnfold       ( noUnfolding, mkTopUnfolding, okToUnfoldInHiFile )
14 import CoreFVs          ( ruleLhsFreeIds, ruleRhsFreeVars, exprSomeFreeVars )
15 import CoreTidy         ( tidyExpr, tidyVarOcc, tidyIdRules )
16 import PprCore          ( pprIdRules )
17 import CoreLint         ( showPass, endPass )
18 import CoreUtils        ( exprArity, hasNoRedexes )
19 import VarEnv
20 import VarSet
21 import Var              ( Id, Var )
22 import Id               ( idType, idInfo, idName, idCoreRules, 
23                           isExportedId, mkVanillaGlobal, isLocalId, 
24                           isImplicitId, idArity, setIdInfo, idCafInfo
25                         ) 
26 import IdInfo           {- loads of stuff -}
27 import NewDemand        ( isBottomingSig, topSig )
28 import BasicTypes       ( Arity, isNeverActive )
29 import Name             ( getOccName, nameOccName, mkInternalName,
30                           localiseName, isExternalName, nameSrcLoc
31                         )
32 import RnEnv            ( lookupOrigNameCache, newExternalName )
33 import NameEnv          ( lookupNameEnv, filterNameEnv )
34 import OccName          ( TidyOccEnv, initTidyOccEnv, tidyOccName )
35 import Type             ( tidyTopType )
36 import Module           ( Module )
37 import HscTypes         ( PersistentCompilerState( pcs_nc ), 
38                           NameCache( nsNames, nsUniqs ),
39                           TypeEnv, extendTypeEnvList, typeEnvIds,
40                           ModGuts(..), ModGuts, TyThing(..)
41                         )
42 import Maybes           ( orElse )
43 import ErrUtils         ( showPass, dumpIfSet_core )
44 import UniqFM           ( mapUFM )
45 import UniqSupply       ( splitUniqSupply, uniqFromSupply )
46 import List             ( partition )
47 import Util             ( mapAccumL )
48 import Maybe            ( isJust )
49 import Outputable
50 import FastTypes  hiding ( fastOr )
51 \end{code}
52
53
54 %************************************************************************
55 %*                                                                      *
56 \subsection{What goes on}
57 %*                                                                      * 
58 %************************************************************************
59
60 [SLPJ: 19 Nov 00]
61
62 The plan is this.  
63
64 Step 1: Figure out external Ids
65 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
66 First we figure out which Ids are "external" Ids.  An
67 "external" Id is one that is visible from outside the compilation
68 unit.  These are
69         a) the user exported ones
70         b) ones mentioned in the unfoldings, workers, 
71            or rules of externally-visible ones 
72 This exercise takes a sweep of the bindings bottom to top.  Actually,
73 in Step 2 we're also going to need to know which Ids should be
74 exported with their unfoldings, so we produce not an IdSet but an
75 IdEnv Bool
76
77
78 Step 2: Tidy the program
79 ~~~~~~~~~~~~~~~~~~~~~~~~
80 Next we traverse the bindings top to bottom.  For each *top-level*
81 binder
82
83  1. Make it into a GlobalId
84
85  2. Give it a system-wide Unique.
86     [Even non-exported things need system-wide Uniques because the
87     byte-code generator builds a single Name->BCO symbol table.]
88
89     We use the NameCache kept in the PersistentCompilerState as the
90     source of such system-wide uniques.
91
92     For external Ids, use the original-name cache in the NameCache
93     to ensure that the unique assigned is the same as the Id had 
94     in any previous compilation run.
95   
96  3. If it's an external Id, make it have a global Name, otherwise
97     make it have a local Name.
98     This is used by the code generator to decide whether
99     to make the label externally visible
100
101  4. Give external Ids a "tidy" occurrence name.  This means
102     we can print them in interface files without confusing 
103     "x" (unique 5) with "x" (unique 10).
104   
105  5. Give it its UTTERLY FINAL IdInfo; in ptic, 
106         * Its IdDetails becomes VanillaGlobal, reflecting the fact that
107           from now on we regard it as a global, not local, Id
108
109         * its unfolding, if it should have one
110         
111         * its arity, computed from the number of visible lambdas
112
113         * its CAF info, computed from what is free in its RHS
114
115                 
116 Finally, substitute these new top-level binders consistently
117 throughout, including in unfoldings.  We also tidy binders in
118 RHSs, so that they print nicely in interfaces.
119
120 \begin{code}
121 tidyCorePgm :: DynFlags
122             -> PersistentCompilerState
123             -> ModGuts
124             -> IO (PersistentCompilerState, ModGuts)
125
126 tidyCorePgm dflags pcs
127             mod_impl@(ModGuts { mg_module = mod, 
128                                 mg_types = env_tc, mg_insts = insts_tc, 
129                                 mg_binds = binds_in, mg_rules = orphans_in })
130   = do  { showPass dflags "Tidy Core"
131
132         ; let ext_ids   = findExternalSet   binds_in orphans_in
133         ; let ext_rules = findExternalRules binds_in orphans_in ext_ids
134                 -- findExternalRules filters ext_rules to avoid binders that 
135                 -- aren't externally visible; but the externally-visible binders 
136                 -- are computed (by findExternalSet) assuming that all orphan
137                 -- rules are exported.  So in fact we may export more than we
138                 -- need.  (It's a sort of mutual recursion.)
139
140         -- We also make sure to avoid any exported binders.  Consider
141         --      f{-u1-} = 1     -- Local decl
142         --      ...
143         --      f{-u2-} = 2     -- Exported decl
144         --
145         -- The second exported decl must 'get' the name 'f', so we
146         -- have to put 'f' in the avoids list before we get to the first
147         -- decl.  tidyTopId then does a no-op on exported binders.
148         ; let   orig_ns       = pcs_nc pcs
149                 init_tidy_env = (orig_ns, initTidyOccEnv avoids, emptyVarEnv)
150                 avoids        = [getOccName name | bndr <- typeEnvIds env_tc,
151                                                    let name = idName bndr,
152                                                    isExternalName name]
153                 -- In computing our "avoids" list, we must include
154                 --      all implicit Ids
155                 --      all things with global names (assigned once and for
156                 --                                      all by the renamer)
157                 -- since their names are "taken".
158                 -- The type environment is a convenient source of such things.
159
160         ; let ((orig_ns', occ_env, subst_env), tidy_binds) 
161                         = mapAccumL (tidyTopBind mod ext_ids) 
162                                     init_tidy_env binds_in
163
164         ; let tidy_rules = tidyIdRules (occ_env,subst_env) ext_rules
165
166         ; let pcs' = pcs { pcs_nc = orig_ns' }
167
168         ; let tidy_type_env = mkFinalTypeEnv env_tc tidy_binds
169
170                 -- Dfuns are local Ids that might have
171                 -- changed their unique during tidying.  Remember
172                 -- to lookup the id in the TypeEnv too, because
173                 -- those Ids have had their IdInfo stripped if
174                 -- necessary.
175         ; let lookup_dfun_id id = 
176                  case lookupVarEnv subst_env id of
177                    Nothing -> dfun_panic
178                    Just id -> 
179                       case lookupNameEnv tidy_type_env (idName id) of
180                         Just (AnId id) -> id
181                         _other -> dfun_panic
182                 where 
183                    dfun_panic = pprPanic "lookup_dfun_id" (ppr id)
184
185               tidy_dfun_ids = map lookup_dfun_id insts_tc
186
187         ; let tidy_result = mod_impl { mg_types = tidy_type_env,
188                                        mg_rules = tidy_rules,
189                                        mg_insts = tidy_dfun_ids,
190                                        mg_binds = tidy_binds }
191
192         ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
193         ; dumpIfSet_core dflags Opt_D_dump_simpl
194                 "Tidy Core Rules"
195                 (pprIdRules tidy_rules)
196
197         ; return (pcs', tidy_result)
198         }
199
200 tidyCoreExpr :: CoreExpr -> IO CoreExpr
201 tidyCoreExpr expr = return (tidyExpr emptyTidyEnv expr)
202 \end{code}
203
204
205 %************************************************************************
206 %*                                                                      *
207 \subsection{Write a new interface file}
208 %*                                                                      *
209 %************************************************************************
210
211 \begin{code}
212 mkFinalTypeEnv :: TypeEnv       -- From typechecker
213                -> [CoreBind]    -- Final Ids
214                -> TypeEnv
215
216 -- The competed type environment is gotten from
217 --      a) keeping the types and classes
218 --      b) removing all Ids, 
219 --      c) adding Ids with correct IdInfo, including unfoldings,
220 --              gotten from the bindings
221 -- From (c) we keep only those Ids with Global names;
222 --          the CoreTidy pass makes sure these are all and only
223 --          the externally-accessible ones
224 -- This truncates the type environment to include only the 
225 -- exported Ids and things needed from them, which saves space
226 --
227 -- However, we do keep things like constructors, which should not appear 
228 -- in interface files, because they are needed by importing modules when
229 -- using the compilation manager
230
231 mkFinalTypeEnv type_env tidy_binds
232   = extendTypeEnvList (filterNameEnv keep_it type_env) final_ids
233   where
234     final_ids  = [ AnId (strip_id_info id)
235                  | bind <- tidy_binds,
236                    id <- bindersOf bind,
237                    isExternalName (idName id)]
238
239     strip_id_info id
240           | opt_OmitInterfacePragmas = id `setIdInfo` vanillaIdInfo
241           | otherwise                = id
242         -- If the interface file has no pragma info then discard all
243         -- info right here.
244         --
245         -- This is not so important for *this* module, but it's
246         -- vital for ghc --make:
247         --   subsequent compilations must not see (e.g.) the arity if
248         --   the interface file does not contain arity
249         -- If they do, they'll exploit the arity; then the arity might
250         -- change, but the iface file doesn't change => recompilation
251         -- does not happen => disaster
252         --
253         -- This IdInfo will live long-term in the Id => vanillaIdInfo makes
254         -- a conservative assumption about Caf-hood
255         -- 
256         -- We're not worried about occurrences of these Ids in unfoldings,
257         -- because in OmitInterfacePragmas mode we're stripping all the
258         -- unfoldings anyway.
259
260         -- We keep implicit Ids, because they won't appear 
261         -- in the bindings from which final_ids are derived!
262     keep_it (AnId id) = isImplicitId id -- Remove all Ids except implicit ones
263     keep_it other     = True            -- Keep all TyCons and Classes
264 \end{code}
265
266 \begin{code}
267 findExternalRules :: [CoreBind]
268                   -> [IdCoreRule] -- Orphan rules
269                   -> IdEnv a      -- Ids that are exported, so we need their rules
270                   -> [IdCoreRule]
271   -- The complete rules are gotten by combining
272   --    a) the orphan rules
273   --    b) rules embedded in the top-level Ids
274 findExternalRules binds orphan_rules ext_ids
275   | opt_OmitInterfacePragmas = []
276   | otherwise
277   = filter needed_rule (orphan_rules ++ local_rules)
278   where
279     local_rules  = [ rule
280                    | id <- bindersOfBinds binds,
281                      id `elemVarEnv` ext_ids,
282                      rule <- idCoreRules id
283                    ]
284     needed_rule (id, rule)
285         =  not (isBuiltinRule rule)
286                 -- We can't print builtin rules in interface files
287                 -- Since they are built in, an importing module
288                 -- will have access to them anyway
289
290         && not (any internal_id (varSetElems (ruleLhsFreeIds rule)))
291                 -- Don't export a rule whose LHS mentions an Id that
292                 -- is completely internal (i.e. not visible to an
293                 -- importing module)
294
295     internal_id id = isLocalId id && not (id `elemVarEnv` ext_ids)
296 \end{code}
297
298 %************************************************************************
299 %*                                                                      *
300 \subsection{Step 1: finding externals}
301 %*                                                                      * 
302 %************************************************************************
303
304 \begin{code}
305 findExternalSet :: [CoreBind] -> [IdCoreRule]
306                 -> IdEnv Bool   -- In domain => external
307                                 -- Range = True <=> show unfolding
308         -- Step 1 from the notes above
309 findExternalSet binds orphan_rules
310   = foldr find init_needed binds
311   where
312     orphan_rule_ids :: IdSet
313     orphan_rule_ids = unionVarSets [ ruleRhsFreeVars rule 
314                                    | (_, rule) <- orphan_rules]
315     init_needed :: IdEnv Bool
316     init_needed = mapUFM (\_ -> False) orphan_rule_ids
317         -- The mapUFM is a bit cheesy.  It is a cheap way
318         -- to turn the set of orphan_rule_ids, which we use to initialise
319         -- the sweep, into a mapping saying 'don't expose unfolding'    
320         -- (When we come to the binding site we may change our mind, of course.)
321
322     find (NonRec id rhs) needed
323         | need_id needed id = addExternal (id,rhs) needed
324         | otherwise         = needed
325     find (Rec prs) needed   = find_prs prs needed
326
327         -- For a recursive group we have to look for a fixed point
328     find_prs prs needed 
329         | null needed_prs = needed
330         | otherwise       = find_prs other_prs new_needed
331         where
332           (needed_prs, other_prs) = partition (need_pr needed) prs
333           new_needed = foldr addExternal needed needed_prs
334
335         -- The 'needed' set contains the Ids that are needed by earlier
336         -- interface file emissions.  If the Id isn't in this set, and isn't
337         -- exported, there's no need to emit anything
338     need_id needed_set id       = id `elemVarEnv` needed_set || isExportedId id 
339     need_pr needed_set (id,rhs) = need_id needed_set id
340
341 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
342 -- The Id is needed; extend the needed set
343 -- with it and its dependents (free vars etc)
344 addExternal (id,rhs) needed
345   = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
346                  id show_unfold
347   where
348     add_occ id needed = extendVarEnv needed id False
349         -- "False" because we don't know we need the Id's unfolding
350         -- We'll override it later when we find the binding site
351
352     new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
353                    | otherwise                = worker_ids      `unionVarSet`
354                                                 unfold_ids      `unionVarSet`
355                                                 spec_ids
356
357     idinfo         = idInfo id
358     dont_inline    = isNeverActive (inlinePragInfo idinfo)
359     loop_breaker   = isLoopBreaker (occInfo idinfo)
360     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
361     spec_ids       = rulesRhsFreeVars (specInfo idinfo)
362     worker_info    = workerInfo idinfo
363
364         -- Stuff to do with the Id's unfolding
365         -- The simplifier has put an up-to-date unfolding
366         -- in the IdInfo, but the RHS will do just as well
367     unfolding    = unfoldingInfo idinfo
368     rhs_is_small = not (neverUnfold unfolding)
369
370         -- We leave the unfolding there even if there is a worker
371         -- In GHCI the unfolding is used by importers
372         -- When writing an interface file, we omit the unfolding 
373         -- if there is a worker
374     show_unfold = not bottoming_fn       &&     -- Not necessary
375                   not dont_inline        &&
376                   not loop_breaker       &&
377                   rhs_is_small           &&     -- Small enough
378                   okToUnfoldInHiFile rhs        -- No casms etc
379
380     unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
381                | otherwise   = emptyVarSet
382
383     worker_ids = case worker_info of
384                    HasWorker work_id _ -> unitVarSet work_id
385                    otherwise           -> emptyVarSet
386 \end{code}
387
388
389 %************************************************************************
390 %*                                                                      *
391 \subsection{Step 2: top-level tidying}
392 %*                                                                      *
393 %************************************************************************
394
395
396 \begin{code}
397 type TopTidyEnv = (NameCache, TidyOccEnv, VarEnv Var)
398
399 -- TopTidyEnv: when tidying we need to know
400 --   * ns: The NameCache, containing a unique supply and any pre-ordained Names.  
401 --        These may have arisen because the
402 --        renamer read in an interface file mentioning M.$wf, say,
403 --        and assigned it unique r77.  If, on this compilation, we've
404 --        invented an Id whose name is $wf (but with a different unique)
405 --        we want to rename it to have unique r77, so that we can do easy
406 --        comparisons with stuff from the interface file
407 --
408 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
409 --     are 'used'
410 --
411 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
412 \end{code}
413
414
415 \begin{code}
416 tidyTopBind :: Module
417             -> IdEnv Bool       -- Domain = Ids that should be external
418                                 -- True <=> their unfolding is external too
419             -> TopTidyEnv -> CoreBind
420             -> (TopTidyEnv, CoreBind)
421
422 tidyTopBind mod ext_ids top_tidy_env@(_,_,subst1) (NonRec bndr rhs)
423   = ((orig,occ,subst) , NonRec bndr' rhs')
424   where
425     ((orig,occ,subst), bndr')
426          = tidyTopBinder mod ext_ids caf_info
427                          rec_tidy_env rhs rhs' top_tidy_env bndr
428     rec_tidy_env = (occ,subst)
429     rhs' = tidyExpr rec_tidy_env rhs
430     caf_info = hasCafRefs subst1 (idArity bndr') rhs'
431
432 tidyTopBind mod ext_ids top_tidy_env@(_,_,subst1) (Rec prs)
433   = (final_env, Rec prs')
434   where
435     (final_env@(_,occ,subst), prs') = mapAccumL do_one top_tidy_env prs
436     rec_tidy_env = (occ,subst)
437
438     do_one top_tidy_env (bndr,rhs) 
439         = ((orig,occ,subst), (bndr',rhs'))
440         where
441         ((orig,occ,subst), bndr')
442            = tidyTopBinder mod ext_ids caf_info
443                 rec_tidy_env rhs rhs' top_tidy_env bndr
444
445         rhs' = tidyExpr rec_tidy_env rhs
446
447         -- the CafInfo for a recursive group says whether *any* rhs in
448         -- the group may refer indirectly to a CAF (because then, they all do).
449     caf_info 
450         | or [ mayHaveCafRefs (hasCafRefs subst1 (idArity bndr) rhs)
451              | (bndr,rhs) <- prs ] = MayHaveCafRefs
452         | otherwise = NoCafRefs
453
454 tidyTopBinder :: Module -> IdEnv Bool -> CafInfo
455               -> TidyEnv        -- The TidyEnv is used to tidy the IdInfo
456               -> CoreExpr       -- RHS *before* tidying
457               -> CoreExpr       -- RHS *after* tidying
458                         -- The TidyEnv and the after-tidying RHS are
459                         -- both are knot-tied: don't look at them!
460               -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
461   -- NB: tidyTopBinder doesn't affect the unique supply
462
463 tidyTopBinder mod ext_ids caf_info rec_tidy_env rhs tidy_rhs
464               env@(ns2, occ_env2, subst_env2) id
465         -- This function is the heart of Step 2
466         -- The rec_tidy_env is the one to use for the IdInfo
467         -- It's necessary because when we are dealing with a recursive
468         -- group, a variable late in the group might be mentioned
469         -- in the IdInfo of one early in the group
470
471         -- The rhs is already tidied
472
473   = ASSERT(isLocalId id)  -- "all Ids defined in this module are local
474                           -- until the CoreTidy phase"  --GHC comentary
475     ((orig_env', occ_env', subst_env'), id')
476   where
477     (orig_env', occ_env', name') = tidyTopName mod ns2 occ_env2
478                                                is_external
479                                                (idName id)
480     ty'    = tidyTopType (idType id)
481     idinfo = tidyTopIdInfo rec_tidy_env is_external 
482                            (idInfo id) unfold_info arity
483                            caf_info
484
485     id' = mkVanillaGlobal name' ty' idinfo
486
487     subst_env' = extendVarEnv subst_env2 id id'
488
489     maybe_external = lookupVarEnv ext_ids id
490     is_external    = isJust maybe_external
491
492     -- Expose an unfolding if ext_ids tells us to
493     -- Remember that ext_ids maps an Id to a Bool: 
494     --  True to show the unfolding, False to hide it
495     show_unfold = maybe_external `orElse` False
496     unfold_info | show_unfold = mkTopUnfolding tidy_rhs
497                 | otherwise   = noUnfolding
498
499     -- Usually the Id will have an accurate arity on it, because
500     -- the simplifier has just run, but not always. 
501     -- One case I found was when the last thing the simplifier
502     -- did was to let-bind a non-atomic argument and then float
503     -- it to the top level. So it seems more robust just to
504     -- fix it here.
505     arity = exprArity rhs
506
507
508 -- tidyTopIdInfo creates the final IdInfo for top-level
509 -- binders.  There are two delicate pieces:
510 --
511 --  * Arity.  After CoreTidy, this arity must not change any more.
512 --      Indeed, CorePrep must eta expand where necessary to make
513 --      the manifest arity equal to the claimed arity.
514 --
515 --  * CAF info.  This must also remain valid through to code generation.
516 --      We add the info here so that it propagates to all
517 --      occurrences of the binders in RHSs, and hence to occurrences in
518 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
519 --      CoreToStg makes use of this when constructing SRTs.
520
521 tidyTopIdInfo tidy_env is_external idinfo unfold_info arity caf_info
522   | not is_external     -- For internal Ids (not externally visible)
523   = vanillaIdInfo       -- we only need enough info for code generation
524                         -- Arity and strictness info are enough;
525                         --      c.f. CoreTidy.tidyLetBndr
526         `setCafInfo`           caf_info
527         `setArityInfo`         arity
528         `setAllStrictnessInfo` newStrictnessInfo idinfo
529
530   | otherwise           -- Externally-visible Ids get the whole lot
531   = vanillaIdInfo
532         `setCafInfo`           caf_info
533         `setArityInfo`         arity
534         `setAllStrictnessInfo` newStrictnessInfo idinfo
535         `setInlinePragInfo`    inlinePragInfo idinfo
536         `setUnfoldingInfo`     unfold_info
537         `setWorkerInfo`        tidyWorker tidy_env (workerInfo idinfo)
538                 -- NB: we throw away the Rules
539                 -- They have already been extracted by findExternalRules
540
541
542 -- This is where we set names to local/global based on whether they really are 
543 -- externally visible (see comment at the top of this module).  If the name
544 -- was previously local, we have to give it a unique occurrence name if
545 -- we intend to externalise it.
546 tidyTopName mod ns occ_env external name
547   | global && internal = (ns, occ_env, localiseName name)
548
549   | global && external = (ns, occ_env, name)
550         -- Global names are assumed to have been allocated by the renamer,
551         -- so they already have the "right" unique
552         -- And it's a system-wide unique too
553
554   | local  && internal = (ns_w_local, occ_env', new_local_name)
555         -- Even local, internal names must get a unique occurrence, because
556         -- if we do -split-objs we externalise the name later, in the code generator
557         --
558         -- Similarly, we must make sure it has a system-wide Unique, because
559         -- the byte-code generator builds a system-wide Name->BCO symbol table
560
561   | local  && external = case lookupOrigNameCache ns_names mod occ' of
562                            Just orig -> (ns,          occ_env', orig)
563                            Nothing   -> (ns_w_global, occ_env', new_external_name)
564         -- If we want to externalise a currently-local name, check
565         -- whether we have already assigned a unique for it.
566         -- If so, use it; if not, extend the table (ns_w_global).
567         -- This is needed when *re*-compiling a module in GHCi; we want to
568         -- use the same name for externally-visible things as we did before.
569
570   where
571     global           = isExternalName name
572     local            = not global
573     internal         = not external
574     loc              = nameSrcLoc name
575
576     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
577
578     ns_names         = nsNames ns
579     (us1, us2)       = splitUniqSupply (nsUniqs ns)
580     uniq             = uniqFromSupply us1
581     new_local_name   = mkInternalName uniq occ' loc
582     ns_w_local       = ns { nsUniqs = us2 }
583
584     (ns_w_global, new_external_name) = newExternalName ns mod occ' loc
585
586
587 ------------  Worker  --------------
588 tidyWorker tidy_env (HasWorker work_id wrap_arity) 
589   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
590 tidyWorker tidy_env other
591   = NoWorker
592 \end{code}
593
594 %************************************************************************
595 %*                                                                      *
596 \subsection{Figuring out CafInfo for an expression}
597 %*                                                                      *
598 %************************************************************************
599
600 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
601 We mark such things as `MayHaveCafRefs' because this information is
602 used to decide whether a particular closure needs to be referenced
603 in an SRT or not.
604
605 There are two reasons for setting MayHaveCafRefs:
606         a) The RHS is a CAF: a top-level updatable thunk.
607         b) The RHS refers to something that MayHaveCafRefs
608
609 Possible improvement: In an effort to keep the number of CAFs (and 
610 hence the size of the SRTs) down, we could also look at the expression and 
611 decide whether it requires a small bounded amount of heap, so we can ignore 
612 it as a CAF.  In these cases however, we would need to use an additional
613 CAF list to keep track of non-collectable CAFs.  
614
615 \begin{code}
616 hasCafRefs  :: VarEnv Var -> Arity -> CoreExpr -> CafInfo
617 hasCafRefs p arity expr 
618   | is_caf || mentions_cafs = MayHaveCafRefs
619   | otherwise               = NoCafRefs
620  where
621   mentions_cafs = isFastTrue (cafRefs p expr)
622   is_caf = not (arity > 0 || hasNoRedexes expr)
623   -- NB. we pass in the arity of the expression, which is expected
624   -- to be calculated by exprArity.  This is because exprArity
625   -- knows how much eta expansion is going to be done by 
626   -- CorePrep later on, and we don't want to duplicate that
627   -- knowledge in hasNoRedexes below.
628
629 cafRefs p (Var id)
630         -- imported Ids first:
631   | not (isLocalId id) = fastBool (mayHaveCafRefs (idCafInfo id))
632         -- now Ids local to this module:
633   | otherwise =
634      case lookupVarEnv p id of
635         Just id' -> fastBool (mayHaveCafRefs (idCafInfo id'))
636         Nothing  -> fastBool False
637
638 cafRefs p (Lit l)            = fastBool False
639 cafRefs p (App f a)          = fastOr (cafRefs p f) (cafRefs p) a
640 cafRefs p (Lam x e)          = cafRefs p e
641 cafRefs p (Let b e)          = fastOr (cafRefss p (rhssOfBind b)) (cafRefs p) e
642 cafRefs p (Case e bndr alts) = fastOr (cafRefs p e) (cafRefss p) (rhssOfAlts alts)
643 cafRefs p (Note n e)         = cafRefs p e
644 cafRefs p (Type t)           = fastBool False
645
646 cafRefss p []     = fastBool False
647 cafRefss p (e:es) = fastOr (cafRefs p e) (cafRefss p) es
648
649 -- hack for lazy-or over FastBool.
650 fastOr a f x = fastBool (isFastTrue a || isFastTrue (f x))
651 \end{code}