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