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