[project @ 2001-10-19 11:47:18 by simonpj]
[ghc-hetmet.git] / ghc / compiler / coreSyn / CoreTidy.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section{Tidying up Core}
5
6 \begin{code}
7 module CoreTidy (
8         tidyCorePgm, tidyExpr, tidyCoreExpr,
9         tidyBndr, tidyBndrs
10     ) where
11
12 #include "HsVersions.h"
13
14 import CmdLineOpts      ( DynFlags, DynFlag(..), opt_OmitInterfacePragmas )
15 import CoreSyn
16 import CoreUnfold       ( noUnfolding, mkTopUnfolding, okToUnfoldInHiFile )
17 import CoreFVs          ( ruleSomeFreeVars, exprSomeFreeVars )
18 import PprCore          ( pprIdCoreRule )
19 import CoreLint         ( showPass, endPass )
20 import VarEnv
21 import VarSet
22 import Var              ( Id, Var )
23 import Id               ( idType, idInfo, idName, isExportedId, 
24                           idSpecialisation, idUnique, 
25                           mkVanillaGlobal, isLocalId, 
26                           isImplicitId, mkUserLocal, setIdInfo
27                         ) 
28 import IdInfo           {- loads of stuff -}
29 import NewDemand        ( isBottomingSig, topSig )
30 import BasicTypes       ( isNeverActive )
31 import Name             ( getOccName, nameOccName, mkLocalName, mkGlobalName, 
32                           localiseName, isGlobalName, nameSrcLoc
33                         )
34 import NameEnv          ( filterNameEnv )
35 import OccName          ( TidyOccEnv, initTidyOccEnv, tidyOccName )
36 import Type             ( tidyTopType, tidyType, tidyTyVarBndr )
37 import Module           ( Module, moduleName )
38 import HscTypes         ( PersistentCompilerState( pcs_PRS ), 
39                           PersistentRenamerState( prsOrig ),
40                           NameSupply( nsNames, nsUniqs ),
41                           TypeEnv, extendTypeEnvList, typeEnvIds,
42                           ModDetails(..), TyThing(..)
43                         )
44 import FiniteMap        ( lookupFM, addToFM )
45 import Maybes           ( orElse )
46 import ErrUtils         ( showPass, dumpIfSet_core )
47 import SrcLoc           ( noSrcLoc )
48 import UniqFM           ( mapUFM )
49 import UniqSupply       ( splitUniqSupply, uniqFromSupply )
50 import List             ( partition )
51 import Util             ( mapAccumL )
52 import Maybe            ( isJust )
53 import Outputable
54 \end{code}
55
56
57
58 %************************************************************************
59 %*                                                                      *
60 \subsection{What goes on}
61 %*                                                                      * 
62 %************************************************************************
63
64 [SLPJ: 19 Nov 00]
65
66 The plan is this.  
67
68 Step 1: Figure out external Ids
69 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70 First we figure out which Ids are "external" Ids.  An
71 "external" Id is one that is visible from outside the compilation
72 unit.  These are
73         a) the user exported ones
74         b) ones mentioned in the unfoldings, workers, 
75            or rules of externally-visible ones 
76 This exercise takes a sweep of the bindings bottom to top.  Actually,
77 in Step 2 we're also going to need to know which Ids should be
78 exported with their unfoldings, so we produce not an IdSet but an
79 IdEnv Bool
80
81
82 Step 2: Tidy the program
83 ~~~~~~~~~~~~~~~~~~~~~~~~
84 Next we traverse the bindings top to bottom.  For each *top-level*
85 binder
86
87  1. Make it into a GlobalId
88
89  2. Give it a system-wide Unique.
90     [Even non-exported things need system-wide Uniques because the
91     byte-code generator builds a single Name->BCO symbol table.]
92
93     We use the NameSupply kept in the PersistentRenamerState as the
94     source of such system-wide uniques.
95
96     For external Ids, use the original-name cache in the NameSupply 
97     to ensure that the unique assigned is the same as the Id had 
98     in any previous compilation run.
99   
100  3. If it's an external Id, make it have a global Name, otherwise
101     make it have a local Name.
102     This is used by the code generator to decide whether
103     to make the label externally visible
104
105  4. Give external Ids a "tidy" occurrence name.  This means
106     we can print them in interface files without confusing 
107     "x" (unique 5) with "x" (unique 10).
108   
109  5. Give it its UTTERLY FINAL IdInfo; in ptic, 
110         * Its IdDetails becomes VanillaGlobal, reflecting the fact that
111           from now on we regard it as a global, not local, Id
112
113         * its unfolding, if it should have one
114         
115         * its arity, computed from the number of visible lambdas
116
117         * its CAF info, computed from what is free in its RHS
118
119                 
120 Finally, substitute these new top-level binders consistently
121 throughout, including in unfoldings.  We also tidy binders in
122 RHSs, so that they print nicely in interfaces.
123
124 \begin{code}
125 tidyCorePgm :: DynFlags -> Module
126             -> PersistentCompilerState
127             -> CgInfoEnv                -- Information from the back end,
128                                         -- to be splatted into the IdInfo
129             -> ModDetails
130             -> IO (PersistentCompilerState, ModDetails)
131
132 tidyCorePgm dflags mod pcs cg_info_env
133             (ModDetails { md_types = env_tc, md_insts = insts_tc, 
134                           md_binds = binds_in, md_rules = orphans_in })
135   = do  { showPass dflags "Tidy Core"
136
137         ; let ext_ids   = findExternalSet   binds_in orphans_in
138         ; let ext_rules = findExternalRules binds_in orphans_in ext_ids
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   prs           = pcs_PRS pcs
149                 orig_ns       = prsOrig prs
150
151                 init_tidy_env = (orig_ns, initTidyOccEnv avoids, emptyVarEnv)
152                 avoids        = [getOccName name | bndr <- typeEnvIds env_tc,
153                                                    let name = idName bndr,
154                                                    isGlobalName name]
155                 -- In computing our "avoids" list, we must include
156                 --      all implicit Ids
157                 --      all things with global names (assigned once and for
158                 --                                      all by the renamer)
159                 -- since their names are "taken".
160                 -- The type environment is a convenient source of such things.
161
162         ; let ((orig_ns', occ_env, subst_env), tidy_binds) 
163                         = mapAccumL (tidyTopBind mod ext_ids cg_info_env) 
164                                     init_tidy_env binds_in
165
166         ; let tidy_rules = tidyIdRules (occ_env,subst_env) ext_rules
167
168         ; let prs' = prs { prsOrig = orig_ns' }
169               pcs' = pcs { pcs_PRS = prs' }
170
171         ; let final_ids  = [ id 
172                            | bind <- tidy_binds
173                            , id <- bindersOf bind
174                            , isGlobalName (idName id)]
175
176                 -- Dfuns are local Ids that might have
177                 -- changed their unique during tidying
178         ; let lookup_dfun_id id = lookupVarEnv subst_env id `orElse` 
179                                   pprPanic "lookup_dfun_id" (ppr id)
180
181
182         ; let tidy_type_env = mkFinalTypeEnv env_tc final_ids
183               tidy_dfun_ids = map lookup_dfun_id insts_tc
184
185         ; let tidy_details = ModDetails { md_types = tidy_type_env,
186                                           md_rules = tidy_rules,
187                                           md_insts = tidy_dfun_ids,
188                                           md_binds = tidy_binds }
189
190         ; endPass dflags "Tidy Core" Opt_D_dump_simpl tidy_binds
191         ; dumpIfSet_core dflags Opt_D_dump_simpl
192                 "Tidy Core Rules"
193                 (vcat (map pprIdCoreRule tidy_rules))
194
195         ; return (pcs', tidy_details)
196         }
197
198 tidyCoreExpr :: CoreExpr -> IO CoreExpr
199 tidyCoreExpr expr = return (tidyExpr emptyTidyEnv expr)
200 \end{code}
201
202
203 %************************************************************************
204 %*                                                                      *
205 \subsection{Write a new interface file}
206 %*                                                                      *
207 %************************************************************************
208
209 \begin{code}
210 mkFinalTypeEnv :: TypeEnv       -- From typechecker
211                -> [Id]          -- Final Ids
212                -> TypeEnv
213
214 mkFinalTypeEnv type_env final_ids
215   = extendTypeEnvList (filterNameEnv keep_it type_env)
216                       (map AnId final_ids)
217   where
218         -- The competed type environment is gotten from
219         --      a) keeping the types and classes
220         --      b) removing all Ids, 
221         --      c) adding Ids with correct IdInfo, including unfoldings,
222         --              gotten from the bindings
223         -- From (c) we keep only those Ids with Global names;
224         --          the CoreTidy pass makes sure these are all and only
225         --          the externally-accessible ones
226         -- This truncates the type environment to include only the 
227         -- exported Ids and things needed from them, which saves space
228         --
229         -- However, we do keep things like constructors, which should not appear 
230         -- in interface files, because they are needed by importing modules when
231         -- using the compilation manager
232
233         -- We keep implicit Ids, because they won't appear 
234         -- in the bindings from which final_ids are derived!
235     keep_it (AnId id) = isImplicitId id -- Remove all Ids except implicit ones
236     keep_it other     = True            -- Keep all TyCons and Classes
237 \end{code}
238
239 \begin{code}
240 findExternalRules :: [CoreBind]
241                   -> [IdCoreRule] -- Orphan rules
242                   -> IdEnv a      -- Ids that are exported, so we need their rules
243                   -> [IdCoreRule]
244   -- The complete rules are gotten by combining
245   --    a) the orphan rules
246   --    b) rules embedded in the top-level Ids
247 findExternalRules binds orphan_rules ext_ids
248   | opt_OmitInterfacePragmas = []
249   | otherwise
250   = orphan_rules ++ local_rules
251   where
252     local_rules  = [ (id, rule)
253                    | id <- bindersOfBinds binds,
254                      id `elemVarEnv` ext_ids,
255                      rule <- rulesRules (idSpecialisation id),
256                      not (isBuiltinRule rule)
257                         -- We can't print builtin rules in interface files
258                         -- Since they are built in, an importing module
259                         -- will have access to them anyway
260                  ]
261 \end{code}
262
263 %************************************************************************
264 %*                                                                      *
265 \subsection{Step 1: finding externals}
266 %*                                                                      * 
267 %************************************************************************
268
269 \begin{code}
270 findExternalSet :: [CoreBind] -> [IdCoreRule]
271                 -> IdEnv Bool   -- In domain => external
272                                 -- Range = True <=> show unfolding
273         -- Step 1 from the notes above
274 findExternalSet binds orphan_rules
275   = foldr find init_needed binds
276   where
277     orphan_rule_ids :: IdSet
278     orphan_rule_ids = unionVarSets [ ruleSomeFreeVars isLocalId rule 
279                                    | (_, rule) <- orphan_rules]
280     init_needed :: IdEnv Bool
281     init_needed = mapUFM (\_ -> False) orphan_rule_ids
282         -- The mapUFM is a bit cheesy.  It is a cheap way
283         -- to turn the set of orphan_rule_ids, which we use to initialise
284         -- the sweep, into a mapping saying 'don't expose unfolding'    
285         -- (When we come to the binding site we may change our mind, of course.)
286
287     find (NonRec id rhs) needed
288         | need_id needed id = addExternal (id,rhs) needed
289         | otherwise         = needed
290     find (Rec prs) needed   = find_prs prs needed
291
292         -- For a recursive group we have to look for a fixed point
293     find_prs prs needed 
294         | null needed_prs = needed
295         | otherwise       = find_prs other_prs new_needed
296         where
297           (needed_prs, other_prs) = partition (need_pr needed) prs
298           new_needed = foldr addExternal needed needed_prs
299
300         -- The 'needed' set contains the Ids that are needed by earlier
301         -- interface file emissions.  If the Id isn't in this set, and isn't
302         -- exported, there's no need to emit anything
303     need_id needed_set id       = id `elemVarEnv` needed_set || isExportedId id 
304     need_pr needed_set (id,rhs) = need_id needed_set id
305
306 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
307 -- The Id is needed; extend the needed set
308 -- with it and its dependents (free vars etc)
309 addExternal (id,rhs) needed
310   = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
311                  id show_unfold
312   where
313     add_occ id needed = extendVarEnv needed id False
314         -- "False" because we don't know we need the Id's unfolding
315         -- We'll override it later when we find the binding site
316
317     new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
318                    | otherwise                = worker_ids      `unionVarSet`
319                                                 unfold_ids      `unionVarSet`
320                                                 spec_ids
321
322     idinfo         = idInfo id
323     dont_inline    = isNeverActive (inlinePragInfo idinfo)
324     loop_breaker   = isLoopBreaker (occInfo idinfo)
325     bottoming_fn   = isBottomingSig (newStrictnessInfo idinfo `orElse` topSig)
326     spec_ids       = rulesRhsFreeVars (specInfo idinfo)
327     worker_info    = workerInfo idinfo
328
329         -- Stuff to do with the Id's unfolding
330         -- The simplifier has put an up-to-date unfolding
331         -- in the IdInfo, but the RHS will do just as well
332     unfolding    = unfoldingInfo idinfo
333     rhs_is_small = not (neverUnfold unfolding)
334
335         -- We leave the unfolding there even if there is a worker
336         -- In GHCI the unfolding is used by importers
337         -- When writing an interface file, we omit the unfolding 
338         -- if there is a worker
339     show_unfold = not bottoming_fn       &&     -- Not necessary
340                   not dont_inline        &&
341                   not loop_breaker       &&
342                   rhs_is_small           &&     -- Small enough
343                   okToUnfoldInHiFile rhs        -- No casms etc
344
345     unfold_ids | show_unfold = exprSomeFreeVars isLocalId rhs
346                | otherwise   = emptyVarSet
347
348     worker_ids = case worker_info of
349                    HasWorker work_id _ -> unitVarSet work_id
350                    otherwise           -> emptyVarSet
351 \end{code}
352
353
354 %************************************************************************
355 %*                                                                      *
356 \subsection{Step 2: top-level tidying}
357 %*                                                                      *
358 %************************************************************************
359
360
361 \begin{code}
362 type TopTidyEnv = (NameSupply, TidyOccEnv, VarEnv Var)
363
364 -- TopTidyEnv: when tidying we need to know
365 --   * ns: The NameSupply, containing a unique supply and any pre-ordained Names.  
366 --        These may have arisen because the
367 --        renamer read in an interface file mentioning M.$wf, say,
368 --        and assigned it unique r77.  If, on this compilation, we've
369 --        invented an Id whose name is $wf (but with a different unique)
370 --        we want to rename it to have unique r77, so that we can do easy
371 --        comparisons with stuff from the interface file
372 --
373 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
374 --     are 'used'
375 --
376 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
377 \end{code}
378
379
380 \begin{code}
381 tidyTopBind :: Module
382             -> IdEnv Bool       -- Domain = Ids that should be external
383                                 -- True <=> their unfolding is external too
384             -> CgInfoEnv
385             -> TopTidyEnv -> CoreBind
386             -> (TopTidyEnv, CoreBind)
387
388 tidyTopBind mod ext_ids cg_info_env top_tidy_env (NonRec bndr rhs)
389   = ((orig,occ,subst) , NonRec bndr' rhs')
390   where
391     ((orig,occ,subst), bndr')
392          = tidyTopBinder mod ext_ids cg_info_env 
393                          rec_tidy_env rhs' top_tidy_env bndr
394     rec_tidy_env = (occ,subst)
395     rhs' = tidyExpr rec_tidy_env rhs
396
397 tidyTopBind mod ext_ids cg_info_env top_tidy_env (Rec prs)
398   = (final_env, Rec prs')
399   where
400     (final_env@(_,occ,subst), prs') = mapAccumL do_one top_tidy_env prs
401     rec_tidy_env = (occ,subst)
402
403     do_one top_tidy_env (bndr,rhs) 
404         = ((orig,occ,subst), (bndr',rhs'))
405         where
406         ((orig,occ,subst), bndr')
407            = tidyTopBinder mod ext_ids cg_info_env
408                 rec_tidy_env rhs' top_tidy_env bndr
409
410         rhs' = tidyExpr rec_tidy_env rhs
411
412 tidyTopBinder :: Module -> IdEnv Bool -> CgInfoEnv
413               -> TidyEnv -> CoreExpr
414                         -- The TidyEnv is used to tidy the IdInfo
415                         -- The expr is the already-tided RHS
416                         -- Both are knot-tied: don't look at them!
417               -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
418   -- NB: tidyTopBinder doesn't affect the unique supply
419
420 tidyTopBinder mod ext_ids cg_info_env rec_tidy_env rhs
421               env@(ns2, occ_env2, subst_env2) id
422         -- This function is the heart of Step 2
423         -- The rec_tidy_env is the one to use for the IdInfo
424         -- It's necessary because when we are dealing with a recursive
425         -- group, a variable late in the group might be mentioned
426         -- in the IdInfo of one early in the group
427
428         -- The rhs is already tidied
429         
430   = ((orig_env', occ_env', subst_env'), id')
431   where
432     (orig_env', occ_env', name') = tidyTopName mod ns2 occ_env2
433                                                is_external
434                                                (idName id)
435     ty'    = tidyTopType (idType id)
436     idinfo = tidyTopIdInfo rec_tidy_env is_external 
437                            (idInfo id) unfold_info
438                            (lookupCgInfo cg_info_env name')
439
440     id' = mkVanillaGlobal name' ty' idinfo
441
442     subst_env' = extendVarEnv subst_env2 id id'
443
444     maybe_external = lookupVarEnv ext_ids id
445     is_external    = isJust maybe_external
446
447     -- Expose an unfolding if ext_ids tells us to
448     show_unfold = maybe_external `orElse` False
449     unfold_info | show_unfold = mkTopUnfolding rhs
450                 | otherwise   = noUnfolding
451
452
453 -- tidyTopIdInfo creates the final IdInfo for top-level
454 -- binders.  There are two delicate pieces:
455 --
456 --  * Arity.  We assume that the simplifier has just run, so
457 --      that there is a reasonable arity on each binder.
458 --      After CoreTidy, this arity must not change any more.
459 --      Indeed, CorePrep must eta expand where necessary to make
460 --      the manifest arity equal to the claimed arity.
461 --
462 -- * CAF info, which comes from the CoreToStg pass via a knot.
463 --      The CAF info will not be looked at by the downstream stuff:
464 --      it *generates* it, and knot-ties it back.  It will only be
465 --      looked at by (a) MkIface when generating an interface file
466 --                   (b) In GHCi, importing modules
467 --      Nevertheless, we add the info here so that it propagates to all
468 --      occurrences of the binders in RHSs, and hence to occurrences in
469 --      unfoldings, which are inside Ids imported by GHCi. Ditto RULES.
470 --     
471 --      An alterative would be to do a second pass over the unfoldings 
472 --      of Ids, and rules, right at the top, but that would be a pain.
473
474 tidyTopIdInfo tidy_env is_external idinfo unfold_info cg_info
475   | opt_OmitInterfacePragmas || not is_external
476         -- Only basic info if the Id isn't external, or if we don't have -O
477   = basic_info
478
479   | otherwise   -- Add extra optimisation info
480   = basic_info
481         `setInlinePragInfo`    inlinePragInfo idinfo
482         `setUnfoldingInfo`     unfold_info
483         `setWorkerInfo`        tidyWorker tidy_env (workerInfo idinfo)
484                 -- NB: we throw away the Rules
485                 -- They have already been extracted by findExternalRules
486   
487   where
488         -- baasic_info is attached to every top-level binder
489     basic_info = vanillaIdInfo 
490                         `setCgInfo`            cg_info
491                         `setArityInfo`         arityInfo idinfo
492                         `setNewStrictnessInfo` newStrictnessInfo idinfo
493
494 -- This is where we set names to local/global based on whether they really are 
495 -- externally visible (see comment at the top of this module).  If the name
496 -- was previously local, we have to give it a unique occurrence name if
497 -- we intend to globalise it.
498 tidyTopName mod ns occ_env external name
499   | global && internal = (ns, occ_env, localiseName name)
500
501   | global && external = (ns, occ_env, name)
502         -- Global names are assumed to have been allocated by the renamer,
503         -- so they already have the "right" unique
504         -- And it's a system-wide unique too
505
506   | local  && internal = (ns_w_local, occ_env', new_local_name)
507         -- Even local, internal names must get a unique occurrence, because
508         -- if we do -split-objs we globalise the name later, in the code generator
509         --
510         -- Similarly, we must make sure it has a system-wide Unique, because
511         -- the byte-code generator builds a system-wide Name->BCO symbol table
512
513   | local  && external = case lookupFM ns_names key of
514                            Just orig -> (ns,          occ_env', orig)
515                            Nothing   -> (ns_w_global, occ_env', new_global_name)
516         -- If we want to globalise a currently-local name, check
517         -- whether we have already assigned a unique for it.
518         -- If so, use it; if not, extend the table (ns_w_global).
519         -- This is needed when *re*-compiling a module in GHCi; we want to
520         -- use the same name for externally-visible things as we did before.
521
522   where
523     global           = isGlobalName name
524     local            = not global
525     internal         = not external
526
527     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
528     key              = (moduleName mod, occ')
529     ns_names         = nsNames ns
530     ns_uniqs         = nsUniqs ns
531     (us1, us2)       = splitUniqSupply ns_uniqs
532     uniq             = uniqFromSupply us1
533     loc              = nameSrcLoc name
534
535     new_local_name   = mkLocalName  uniq     occ' loc
536     new_global_name  = mkGlobalName uniq mod occ' loc  
537
538     ns_w_local       = ns { nsUniqs = us2 }
539     ns_w_global      = ns { nsUniqs = us2, nsNames = addToFM ns_names key new_global_name }
540
541
542 ------------  Worker  --------------
543 tidyWorker tidy_env (HasWorker work_id wrap_arity) 
544   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
545 tidyWorker tidy_env other
546   = NoWorker
547
548 ------------  Rules  --------------
549 tidyIdRules :: TidyEnv -> [IdCoreRule] -> [IdCoreRule]
550 tidyIdRules env [] = []
551 tidyIdRules env ((fn,rule) : rules)
552   = tidyRule env rule           =: \ rule ->
553     tidyIdRules env rules       =: \ rules ->
554      ((tidyVarOcc env fn, rule) : rules)
555
556 tidyRule :: TidyEnv -> CoreRule -> CoreRule
557 tidyRule env rule@(BuiltinRule _ _) = rule
558 tidyRule env (Rule name act vars tpl_args rhs)
559   = tidyBndrs env vars                  =: \ (env', vars) ->
560     map (tidyExpr env') tpl_args        =: \ tpl_args ->
561      (Rule name act vars tpl_args (tidyExpr env' rhs))
562 \end{code}
563
564 %************************************************************************
565 %*                                                                      *
566 \subsection{Step 2: inner tidying
567 %*                                                                      *
568 %************************************************************************
569
570 \begin{code}
571 tidyBind :: TidyEnv
572          -> CoreBind
573          ->  (TidyEnv, CoreBind)
574
575 tidyBind env (NonRec bndr rhs)
576   = tidyLetBndr env (bndr,rhs)          =: \ (env', bndr') ->
577     (env', NonRec bndr' (tidyExpr env' rhs))
578
579 tidyBind env (Rec prs)
580   = mapAccumL tidyLetBndr env prs       =: \ (env', bndrs') ->
581     map (tidyExpr env') (map snd prs)   =: \ rhss' ->
582     (env', Rec (zip bndrs' rhss'))
583
584
585 tidyExpr env (Var v)    =  Var (tidyVarOcc env v)
586 tidyExpr env (Type ty)  =  Type (tidyType env ty)
587 tidyExpr env (Lit lit)  =  Lit lit
588 tidyExpr env (App f a)  =  App (tidyExpr env f) (tidyExpr env a)
589 tidyExpr env (Note n e) =  Note (tidyNote env n) (tidyExpr env e)
590
591 tidyExpr env (Let b e) 
592   = tidyBind env b      =: \ (env', b') ->
593     Let b' (tidyExpr env' e)
594
595 tidyExpr env (Case e b alts)
596   = tidyBndr env b      =: \ (env', b) ->
597     Case (tidyExpr env e) b (map (tidyAlt env') alts)
598
599 tidyExpr env (Lam b e)
600   = tidyBndr env b      =: \ (env', b) ->
601     Lam b (tidyExpr env' e)
602
603
604 tidyAlt env (con, vs, rhs)
605   = tidyBndrs env vs    =: \ (env', vs) ->
606     (con, vs, tidyExpr env' rhs)
607
608 tidyNote env (Coerce t1 t2)  = Coerce (tidyType env t1) (tidyType env t2)
609 tidyNote env note            = note
610 \end{code}
611
612
613 %************************************************************************
614 %*                                                                      *
615 \subsection{Tidying up non-top-level binders}
616 %*                                                                      *
617 %************************************************************************
618
619 \begin{code}
620 tidyVarOcc (_, var_env) v = case lookupVarEnv var_env v of
621                                   Just v' -> v'
622                                   Nothing -> v
623
624 -- tidyBndr is used for lambda and case binders
625 tidyBndr :: TidyEnv -> Var -> (TidyEnv, Var)
626 tidyBndr env var
627   | isTyVar var = tidyTyVarBndr env var
628   | otherwise   = tidyIdBndr env var
629
630 tidyBndrs :: TidyEnv -> [Var] -> (TidyEnv, [Var])
631 tidyBndrs env vars = mapAccumL tidyBndr env vars
632
633 tidyLetBndr :: TidyEnv -> (Id, CoreExpr) -> (TidyEnv, Var)
634 -- Used for local (non-top-level) let(rec)s
635 tidyLetBndr env (id,rhs) 
636   = ((tidy_env,new_var_env), final_id)
637   where
638     ((tidy_env,var_env), new_id) = tidyIdBndr env id
639
640         -- We need to keep around any interesting strictness and demand info
641         -- because later on we may need to use it when converting to A-normal form.
642         -- eg.
643         --      f (g x),  where f is strict in its argument, will be converted
644         --      into  case (g x) of z -> f z  by CorePrep, but only if f still
645         --      has its strictness info.
646         --
647         -- Similarly for the demand info - on a let binder, this tells 
648         -- CorePrep to turn the let into a case.
649         --
650         -- Similarly arity info for eta expansion in CorePrep
651     final_id = new_id `setIdInfo` new_info
652     idinfo   = idInfo id
653     new_info = vanillaIdInfo 
654                 `setArityInfo`          arityInfo idinfo
655                 `setNewStrictnessInfo`  newStrictnessInfo idinfo
656                 `setNewDemandInfo`      newDemandInfo idinfo
657
658     -- Override the env we get back from tidyId with the new IdInfo
659     -- so it gets propagated to the usage sites.
660     new_var_env = extendVarEnv var_env id final_id
661
662 tidyIdBndr :: TidyEnv -> Id -> (TidyEnv, Id)
663 tidyIdBndr env@(tidy_env, var_env) id
664   =     -- Non-top-level variables
665     let 
666         -- Give the Id a fresh print-name, *and* rename its type
667         -- The SrcLoc isn't important now, 
668         -- though we could extract it from the Id
669         -- 
670         -- All nested Ids now have the same IdInfo, namely none,
671         -- which should save some space.
672         (tidy_env', occ') = tidyOccName tidy_env (getOccName id)
673         ty'               = tidyType env (idType id)
674         id'               = mkUserLocal occ' (idUnique id) ty' noSrcLoc
675         var_env'          = extendVarEnv var_env id id'
676     in
677      ((tidy_env', var_env'), id')
678 \end{code}
679
680 \begin{code}
681 m =: k = m `seq` k m
682 \end{code}