[project @ 2001-02-26 15:06:57 by simonmar]
[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, 
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 CoreUtils        ( exprArity )
18 import CoreFVs          ( ruleSomeFreeVars, exprSomeFreeVars )
19 import CoreLint         ( showPass, endPass )
20 import VarEnv
21 import VarSet
22 import Var              ( Id, Var )
23 import Id               ( idType, idInfo, idName, isExportedId,
24                           idCafInfo, mkId, isLocalId, isImplicitId,
25                           idFlavour, modifyIdInfo, idArity
26                         ) 
27 import IdInfo           {- loads of stuff -}
28 import Name             ( getOccName, nameOccName, globaliseName, setNameOcc, 
29                           localiseName, mkLocalName, isGlobalName, isDllName
30                         )
31 import OccName          ( TidyOccEnv, initTidyOccEnv, tidyOccName )
32 import Type             ( tidyTopType, tidyType, tidyTyVar )
33 import Module           ( Module, moduleName )
34 import PrimOp           ( PrimOp(..), setCCallUnique )
35 import HscTypes         ( PersistentCompilerState( pcs_PRS ), 
36                           PersistentRenamerState( prsOrig ),
37                           NameSupply( nsNames ), OrigNameCache
38                         )
39 import UniqSupply
40 import DataCon          ( DataCon, dataConName )
41 import Literal          ( isLitLitLit )
42 import FiniteMap        ( lookupFM, addToFM )
43 import Maybes           ( maybeToBool, orElse )
44 import ErrUtils         ( showPass )
45 import PprCore          ( pprIdCoreRule )
46 import SrcLoc           ( noSrcLoc )
47 import UniqFM           ( mapUFM )
48 import Outputable
49 import FastTypes
50 import List             ( partition )
51 import Util             ( mapAccumL )
52 \end{code}
53
54
55
56 %************************************************************************
57 %*                                                                      *
58 \subsection{What goes on}
59 %*                                                                      * 
60 %************************************************************************
61
62 [SLPJ: 19 Nov 00]
63
64 The plan is this.  
65
66 Step 1: Figure out external Ids
67 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68 First we figure out which Ids are "external" Ids.  An
69 "external" Id is one that is visible from outside the compilation
70 unit.  These are
71         a) the user exported ones
72         b) ones mentioned in the unfoldings, workers, 
73            or rules of externally-visible ones 
74 This exercise takes a sweep of the bindings bottom to top.  Actually,
75 in Step 2 we're also going to need to know which Ids should be
76 exported with their unfoldings, so we produce not an IdSet but an
77 IdEnv Bool
78
79
80 Step 2: Tidy the program
81 ~~~~~~~~~~~~~~~~~~~~~~~~
82 Next we traverse the bindings top to bottom.  For each top-level
83 binder
84
85   - Make all external Ids have Global names and vice versa
86     This is used by the code generator to decide whether
87     to make the label externally visible
88
89   - Give external ids a "tidy" occurrence name.  This means
90     we can print them in interface files without confusing 
91     "x" (unique 5) with "x" (unique 10).
92   
93   - Give external Ids the same Unique as they had before
94     if the name is in the renamer's name cache
95   
96   - Clone all local Ids.  This means that Tidy Core has the property
97     that all Ids are unique, rather than the weaker guarantee of
98     no clashes which the simplifier provides.
99
100   - Give each dynamic CCall occurrence a fresh unique; this is
101     rather like the cloning step above.
102
103   - Give the Id its UTTERLY FINAL IdInfo; in ptic, 
104         * Its flavour becomes ConstantId, reflecting the fact that
105           from now on we regard it as a constant, not local, Id
106
107         * its unfolding, if it should have one
108         
109         * its arity, computed from the number of visible lambdas
110
111         * its CAF info, computed from what is free in its RHS
112
113                 
114 Finally, substitute these new top-level binders consistently
115 throughout, including in unfoldings.  We also tidy binders in
116 RHSs, so that they print nicely in interfaces.
117
118 \begin{code}
119 tidyCorePgm :: DynFlags -> Module
120             -> PersistentCompilerState
121             -> [CoreBind] -> [IdCoreRule]
122             -> IO (PersistentCompilerState, [CoreBind], [IdCoreRule])
123 tidyCorePgm dflags mod pcs binds_in orphans_in
124   = do  { showPass dflags "Tidy Core"
125
126         ; let ext_ids = findExternalSet binds_in orphans_in
127
128         ; us <- mkSplitUniqSupply 't' -- for "tidy"
129
130         ; let ((us1, orig_env', occ_env, subst_env), binds_out) 
131                         = mapAccumL (tidyTopBind mod ext_ids) 
132                                     (init_tidy_env us) binds_in
133
134         ; let (orphans_out, _) 
135                    = initUs us1 (tidyIdRules (occ_env,subst_env) orphans_in)
136
137         ; let prs' = prs { prsOrig = orig { nsNames = orig_env' } }
138               pcs' = pcs { pcs_PRS = prs' }
139
140         ; endPass dflags "Tidy Core" Opt_D_dump_simpl binds_out
141
142         ; return (pcs', binds_out, orphans_out)
143         }
144   where
145         -- We also make sure to avoid any exported binders.  Consider
146         --      f{-u1-} = 1     -- Local decl
147         --      ...
148         --      f{-u2-} = 2     -- Exported decl
149         --
150         -- The second exported decl must 'get' the name 'f', so we
151         -- have to put 'f' in the avoids list before we get to the first
152         -- decl.  tidyTopId then does a no-op on exported binders.
153     prs              = pcs_PRS pcs
154     orig             = prsOrig prs
155     orig_env         = nsNames orig
156
157     init_tidy_env us = (us, orig_env, initTidyOccEnv avoids, emptyVarEnv)
158     avoids           = [getOccName bndr | bndr <- bindersOfBinds binds_in,
159                                        isGlobalName (idName bndr)]
160 \end{code}
161
162
163 %************************************************************************
164 %*                                                                      *
165 \subsection{Step 1: finding externals}
166 %*                                                                      * 
167 %************************************************************************
168
169 \begin{code}
170 findExternalSet :: [CoreBind] -> [IdCoreRule]
171                 -> IdEnv Bool   -- True <=> show unfolding
172         -- Step 1 from the notes above
173 findExternalSet binds orphan_rules
174   = foldr find init_needed binds
175   where
176     orphan_rule_ids :: IdSet
177     orphan_rule_ids = unionVarSets [ ruleSomeFreeVars isIdAndLocal rule 
178                                    | (_, rule) <- orphan_rules]
179     init_needed :: IdEnv Bool
180     init_needed = mapUFM (\_ -> False) orphan_rule_ids
181         -- The mapUFM is a bit cheesy.  It is a cheap way
182         -- to turn the set of orphan_rule_ids, which we use to initialise
183         -- the sweep, into a mapping saying 'don't expose unfolding'    
184         -- (When we come to the binding site we may change our mind, of course.)
185
186     find (NonRec id rhs) needed
187         | need_id needed id = addExternal (id,rhs) needed
188         | otherwise         = needed
189     find (Rec prs) needed   = find_prs prs needed
190
191         -- For a recursive group we have to look for a fixed point
192     find_prs prs needed 
193         | null needed_prs = needed
194         | otherwise       = find_prs other_prs new_needed
195         where
196           (needed_prs, other_prs) = partition (need_pr needed) prs
197           new_needed = foldr addExternal needed needed_prs
198
199         -- The 'needed' set contains the Ids that are needed by earlier
200         -- interface file emissions.  If the Id isn't in this set, and isn't
201         -- exported, there's no need to emit anything
202     need_id needed_set id       = id `elemVarEnv` needed_set || isExportedId id 
203     need_pr needed_set (id,rhs) = need_id needed_set id
204
205 isIdAndLocal id = isId id && isLocalId id
206
207 addExternal :: (Id,CoreExpr) -> IdEnv Bool -> IdEnv Bool
208 -- The Id is needed; extend the needed set
209 -- with it and its dependents (free vars etc)
210 addExternal (id,rhs) needed
211   = extendVarEnv (foldVarSet add_occ needed new_needed_ids)
212                  id show_unfold
213   where
214     add_occ id needed = extendVarEnv needed id False
215         -- "False" because we don't know we need the Id's unfolding
216         -- We'll override it later when we find the binding site
217
218     new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
219                    | otherwise                = worker_ids      `unionVarSet`
220                                                 unfold_ids      `unionVarSet`
221                                                 spec_ids
222
223     idinfo         = idInfo id
224     dont_inline    = isNeverInlinePrag (inlinePragInfo idinfo)
225     loop_breaker   = isLoopBreaker (occInfo idinfo)
226     bottoming_fn   = isBottomingStrictness (strictnessInfo idinfo)
227     spec_ids       = rulesRhsFreeVars (specInfo idinfo)
228     worker_info    = workerInfo idinfo
229
230         -- Stuff to do with the Id's unfolding
231         -- The simplifier has put an up-to-date unfolding
232         -- in the IdInfo, but the RHS will do just as well
233     unfolding    = unfoldingInfo idinfo
234     rhs_is_small = not (neverUnfold unfolding)
235
236         -- We leave the unfolding there even if there is a worker
237         -- In GHCI the unfolding is used by importers
238         -- When writing an interface file, we omit the unfolding 
239         -- if there is a worker
240     show_unfold = not bottoming_fn       &&     -- Not necessary
241                   not dont_inline        &&
242                   not loop_breaker       &&
243                   rhs_is_small           &&     -- Small enough
244                   okToUnfoldInHiFile rhs        -- No casms etc
245
246     unfold_ids | show_unfold = exprSomeFreeVars isIdAndLocal rhs
247                | otherwise   = emptyVarSet
248
249     worker_ids = case worker_info of
250                    HasWorker work_id _ -> unitVarSet work_id
251                    otherwise           -> emptyVarSet
252 \end{code}
253
254
255 %************************************************************************
256 %*                                                                      *
257 \subsection{Step 2: top-level tidying}
258 %*                                                                      *
259 %************************************************************************
260
261
262 \begin{code}
263 type TopTidyEnv = (UniqSupply, OrigNameCache, TidyOccEnv, VarEnv Var)
264
265 -- TopTidyEnv: when tidying we need to know
266 --   * orig_env: Any pre-ordained Names.  These may have arisen because the
267 --        renamer read in an interface file mentioning M.$wf, say,
268 --        and assigned it unique r77.  If, on this compilation, we've
269 --        invented an Id whose name is $wf (but with a different unique)
270 --        we want to rename it to have unique r77, so that we can do easy
271 --        comparisons with stuff from the interface file
272 --
273 --   * occ_env: The TidyOccEnv, which tells us which local occurrences 
274 --     are 'used'
275 --
276 --   * subst_env: A Var->Var mapping that substitutes the new Var for the old
277 --
278 --   * uniqsuppy: so we can clone any Ids with non-preordained names.
279 --
280 \end{code}
281
282
283 \begin{code}
284 tidyTopBind :: Module
285             -> IdEnv Bool       -- Domain = Ids that should be external
286                                 -- True <=> their unfolding is external too
287             -> TopTidyEnv -> CoreBind
288             -> (TopTidyEnv, CoreBind)
289
290 tidyTopBind mod ext_ids env (NonRec bndr rhs)
291   = ((us2,orig,occ,subst) , NonRec bndr' rhs')
292   where
293     ((us1,orig,occ,subst), bndr')
294          = tidyTopBinder mod ext_ids tidy_env rhs' caf_info env bndr
295     tidy_env    = (occ,subst)
296     caf_info    = hasCafRefs (const True) rhs'
297     (rhs',us2)  = initUs us1 (tidyExpr tidy_env rhs)
298
299 tidyTopBind mod ext_ids env (Rec prs)
300   = (final_env, Rec prs')
301   where
302     (final_env@(_,_,occ,subst), prs') = mapAccumL do_one env prs
303     final_tidy_env = (occ,subst)
304
305     do_one env (bndr,rhs) 
306         = ((us',orig,occ,subst), (bndr',rhs'))
307         where
308         ((us,orig,occ,subst), bndr')
309            = tidyTopBinder mod ext_ids final_tidy_env rhs' caf_info env bndr
310         (rhs', us')   = initUs us (tidyExpr final_tidy_env rhs)
311
312         -- the CafInfo for a recursive group says whether *any* rhs in
313         -- the group may refer indirectly to a CAF (because then, they all do).
314     (bndrs, rhss) = unzip prs'
315     caf_info = hasCafRefss pred rhss
316     pred v = v `notElem` bndrs
317
318
319 tidyTopBinder :: Module -> IdEnv Bool
320               -> TidyEnv -> CoreExpr -> CafInfo
321                         -- The TidyEnv is used to tidy the IdInfo
322                         -- The expr is the already-tided RHS
323                         -- Both are knot-tied: don't look at them!
324               -> TopTidyEnv -> Id -> (TopTidyEnv, Id)
325
326 tidyTopBinder mod ext_ids tidy_env rhs caf_info
327               env@(us, orig_env2, occ_env2, subst_env2) id
328
329   | isImplicitId id     -- Don't mess with constructors, 
330   = (env, id)           -- record selectors, and the like
331
332   | otherwise
333         -- This function is the heart of Step 2
334         -- The second env is the one to use for the IdInfo
335         -- It's necessary because when we are dealing with a recursive
336         -- group, a variable late in the group might be mentioned
337         -- in the IdInfo of one early in the group
338
339         -- The rhs is already tidied
340         
341   = ((us_r, orig_env', occ_env', subst_env'), id')
342   where
343     (us_l, us_r)    = splitUniqSupply us
344
345     (orig_env', occ_env', name') = tidyTopName mod orig_env2 occ_env2
346                                                is_external
347                                                (idName id)
348     ty'             = tidyTopType (idType id)
349     idinfo'         = tidyIdInfo us_l tidy_env
350                          is_external unfold_info arity_info caf_info id
351
352     id'        = mkId name' ty' idinfo'
353     subst_env' = extendVarEnv subst_env2 id id'
354
355     maybe_external = lookupVarEnv ext_ids id
356     is_external    = maybeToBool maybe_external
357
358     -- Expose an unfolding if ext_ids tells us to
359     show_unfold = maybe_external `orElse` False
360     unfold_info | show_unfold = mkTopUnfolding rhs
361                 | otherwise   = noUnfolding
362
363     arity_info = exprArity rhs
364
365
366 tidyIdInfo us tidy_env is_external unfold_info arity_info caf_info id
367   | opt_OmitInterfacePragmas || not is_external
368         -- No IdInfo if the Id isn't external, or if we don't have -O
369   = mkIdInfo new_flavour caf_info
370         `setStrictnessInfo` strictnessInfo core_idinfo
371         `setArityInfo`      ArityExactly arity_info
372         -- Keep strictness, arity and CAF info; it's used by the code generator
373
374   | otherwise
375   =  let (rules', _) = initUs us (tidyRules tidy_env (specInfo core_idinfo))
376      in
377      mkIdInfo new_flavour caf_info
378         `setCprInfo`        cprInfo core_idinfo
379         `setStrictnessInfo` strictnessInfo core_idinfo
380         `setInlinePragInfo` inlinePragInfo core_idinfo
381         `setUnfoldingInfo`  unfold_info
382         `setWorkerInfo`     tidyWorker tidy_env arity_info (workerInfo core_idinfo)
383         `setSpecInfo`       rules'
384         `setArityInfo`      ArityExactly arity_info
385                 -- this is the final IdInfo, it must agree with the
386                 -- code finally generated (i.e. NO more transformations
387                 -- after this!).
388   where
389     core_idinfo = idInfo id
390     new_flavour = makeConstantFlavour (flavourInfo core_idinfo)
391         -- A DFunId must stay a DFunId, so that we can gather the
392         -- DFunIds up later.  Other local things become ConstantIds.
393
394
395 -- This is where we set names to local/global based on whether they really are 
396 -- externally visible (see comment at the top of this module).  If the name
397 -- was previously local, we have to give it a unique occurrence name if
398 -- we intend to globalise it.
399 tidyTopName mod orig_env occ_env external name
400   | global && internal = (orig_env, occ_env, localiseName name)
401
402   | local  && internal = (orig_env, occ_env', setNameOcc name occ')
403         -- Even local, internal names must get a unique occurrence, because
404         -- if we do -split-objs we globalise the name later, n the code generator
405
406   | global && external = (orig_env, occ_env, name)
407         -- Global names are assumed to have been allocated by the renamer,
408         -- so they already have the "right" unique
409
410   | local  && external = case lookupFM orig_env key of
411                            Just orig -> (orig_env,                         occ_env', orig)
412                            Nothing   -> (addToFM orig_env key global_name, occ_env', global_name)
413         -- If we want to globalise a currently-local name, check
414         -- whether we have already assigned a unique for it.
415         -- If so, use it; if not, extend the table
416
417   where
418     (occ_env', occ') = tidyOccName occ_env (nameOccName name)
419     key              = (moduleName mod, occ')
420     global_name      = globaliseName (setNameOcc name occ') mod
421     global           = isGlobalName name
422     local            = not global
423     internal         = not external
424
425 ------------  Worker  --------------
426 -- We only treat a function as having a worker if
427 -- the exported arity (which is now the number of visible lambdas)
428 -- is the same as the arity at the moment of the w/w split
429 -- If so, we can safely omit the unfolding inside the wrapper, and
430 -- instead re-generate it from the type/arity/strictness info
431 -- But if the arity has changed, we just take the simple path and
432 -- put the unfolding into the interface file, forgetting the fact
433 -- that it's a wrapper.  
434 --
435 -- How can this happen?  Sometimes we get
436 --      f = coerce t (\x y -> $wf x y)
437 -- at the moment of w/w split; but the eta reducer turns it into
438 --      f = coerce t $wf
439 -- which is perfectly fine except that the exposed arity so far as
440 -- the code generator is concerned (zero) differs from the arity
441 -- when we did the split (2).  
442 --
443 -- All this arises because we use 'arity' to mean "exactly how many
444 -- top level lambdas are there" in interface files; but during the
445 -- compilation of this module it means "how many things can I apply
446 -- this to".
447 tidyWorker tidy_env real_arity (HasWorker work_id wrap_arity) 
448   | real_arity == wrap_arity
449   = HasWorker (tidyVarOcc tidy_env work_id) wrap_arity
450 tidyWorker tidy_env real_arity other
451   = NoWorker
452
453 ------------  Rules  --------------
454 tidyIdRules :: TidyEnv -> [IdCoreRule] -> UniqSM [IdCoreRule]
455 tidyIdRules env [] = returnUs []
456 tidyIdRules env ((fn,rule) : rules)
457   = tidyRule env rule           `thenUs` \ rule ->
458     tidyIdRules env rules       `thenUs` \ rules ->
459     returnUs ((tidyVarOcc env fn, rule) : rules)
460
461 tidyRules :: TidyEnv -> CoreRules -> UniqSM CoreRules
462 tidyRules env (Rules rules fvs) 
463   = mapUs (tidyRule env) rules          `thenUs` \ rules ->
464     returnUs (Rules rules (foldVarSet tidy_set_elem emptyVarSet fvs))
465   where
466     tidy_set_elem var new_set = extendVarSet new_set (tidyVarOcc env var)
467
468 tidyRule :: TidyEnv -> CoreRule -> UniqSM CoreRule
469 tidyRule env rule@(BuiltinRule _) = returnUs rule
470 tidyRule env (Rule name vars tpl_args rhs)
471   = tidyBndrs env vars                  `thenUs` \ (env', vars) ->
472     mapUs (tidyExpr env') tpl_args      `thenUs` \ tpl_args ->
473     tidyExpr env' rhs                   `thenUs` \ rhs ->
474     returnUs (Rule name vars tpl_args rhs)
475 \end{code}
476
477 %************************************************************************
478 %*                                                                      *
479 \subsection{Step 2: inner tidying
480 %*                                                                      *
481 %************************************************************************
482
483 \begin{code}
484 tidyBind :: TidyEnv
485          -> CoreBind
486          -> UniqSM (TidyEnv, CoreBind)
487 tidyBind env (NonRec bndr rhs)
488   = tidyBndrWithRhs env (bndr,rhs) `thenUs` \ (env', bndr') ->
489     tidyExpr env' rhs              `thenUs` \ rhs' ->
490     returnUs (env', NonRec bndr' rhs')
491
492 tidyBind env (Rec prs)
493   = mapAccumLUs tidyBndrWithRhs env prs         `thenUs` \ (env', bndrs') ->
494     mapUs (tidyExpr env') (map snd prs)         `thenUs` \ rhss' ->
495     returnUs (env', Rec (zip bndrs' rhss'))
496
497 tidyExpr env (Var v)   
498   = fiddleCCall v  `thenUs` \ v ->
499     returnUs (Var (tidyVarOcc env v))
500
501 tidyExpr env (Type ty) = returnUs (Type (tidyType env ty))
502 tidyExpr env (Lit lit) = returnUs (Lit lit)
503
504 tidyExpr env (App f a)
505   = tidyExpr env f              `thenUs` \ f ->
506     tidyExpr env a              `thenUs` \ a ->
507     returnUs (App f a)
508
509 tidyExpr env (Note n e)
510   = tidyExpr env e              `thenUs` \ e ->
511     returnUs (Note (tidyNote env n) e)
512
513 tidyExpr env (Let b e) 
514   = tidyBind env b              `thenUs` \ (env', b') ->
515     tidyExpr env' e             `thenUs` \ e ->
516     returnUs (Let b' e)
517
518 tidyExpr env (Case e b alts)
519   = tidyExpr env e              `thenUs` \ e ->
520     tidyBndr env b              `thenUs` \ (env', b) ->
521     mapUs (tidyAlt env') alts   `thenUs` \ alts ->
522     returnUs (Case e b alts)
523
524 tidyExpr env (Lam b e)
525   = tidyBndr env b              `thenUs` \ (env', b) ->
526     tidyExpr env' e             `thenUs` \ e ->
527     returnUs (Lam b e)
528
529
530 tidyAlt env (con, vs, rhs)
531   = tidyBndrs env vs            `thenUs` \ (env', vs) ->
532     tidyExpr env' rhs           `thenUs` \ rhs ->
533     returnUs (con, vs, rhs)
534
535 tidyNote env (Coerce t1 t2)  = Coerce (tidyType env t1) (tidyType env t2)
536 tidyNote env note            = note
537 \end{code}
538
539
540 %************************************************************************
541 %*                                                                      *
542 \subsection{Tidying up non-top-level binders}
543 %*                                                                      *
544 %************************************************************************
545
546 \begin{code}
547 tidyVarOcc (_, var_env) v = case lookupVarEnv var_env v of
548                                   Just v' -> v'
549                                   Nothing -> v
550
551 -- tidyBndr is used for lambda and case binders
552 tidyBndr :: TidyEnv -> Var -> UniqSM (TidyEnv, Var)
553 tidyBndr env var
554   | isTyVar var = returnUs (tidyTyVar env var)
555   | otherwise   = tidyId env var vanillaIdInfo
556
557 tidyBndrs :: TidyEnv -> [Var] -> UniqSM (TidyEnv, [Var])
558 tidyBndrs env vars = mapAccumLUs tidyBndr env vars
559
560 -- tidyBndrWithRhs is used for let binders
561 tidyBndrWithRhs :: TidyEnv -> (Var, CoreExpr) -> UniqSM (TidyEnv, Var)
562 tidyBndrWithRhs env (id,rhs)
563    = tidyId env id idinfo
564    where
565         idinfo = vanillaIdInfo `setArityInfo` ArityExactly (exprArity rhs)
566                         -- NB: This throws away the IdInfo of the Id, which we
567                         -- no longer need.  That means we don't need to
568                         -- run over it with env, nor renumber it.
569
570 tidyId :: TidyEnv -> Id -> IdInfo -> UniqSM (TidyEnv, Id)
571 tidyId env@(tidy_env, var_env) id idinfo
572   =     -- Non-top-level variables
573     getUniqueUs   `thenUs` \ uniq ->
574     let 
575         -- Give the Id a fresh print-name, *and* rename its type
576         -- The SrcLoc isn't important now, 
577         -- though we could extract it from the Id
578         name'             = mkLocalName uniq occ' noSrcLoc
579         (tidy_env', occ') = tidyOccName tidy_env (getOccName id)
580         ty'               = tidyType (tidy_env,var_env) (idType id)
581         id'               = mkId name' ty' idinfo
582         var_env'          = extendVarEnv var_env id id'
583     in
584     returnUs ((tidy_env', var_env'), id')
585
586
587 fiddleCCall id 
588   = case idFlavour id of
589          PrimOpId (CCallOp ccall) ->
590             -- Make a guaranteed unique name for a dynamic ccall.
591             getUniqueUs         `thenUs` \ uniq ->
592             returnUs (modifyIdInfo (`setFlavourInfo` 
593                             PrimOpId (CCallOp (setCCallUnique ccall uniq))) id)
594          other_flavour ->
595              returnUs id
596 \end{code}
597
598 %************************************************************************
599 %*                                                                      *
600 \subsection{Figuring out CafInfo for an expression}
601 %*                                                                      *
602 %************************************************************************
603
604 hasCafRefs decides whether a top-level closure can point into the dynamic heap.
605 We mark such things as `MayHaveCafRefs' because this information is
606 used to decide whether a particular closure needs to be referenced
607 in an SRT or not.
608
609 There are two reasons for setting MayHaveCafRefs:
610         a) The RHS is a CAF: a top-level updatable thunk.
611         b) The RHS refers to something that MayHaveCafRefs
612
613 Possible improvement: In an effort to keep the number of CAFs (and 
614 hence the size of the SRTs) down, we could also look at the expression and 
615 decide whether it requires a small bounded amount of heap, so we can ignore 
616 it as a CAF.  In these cases however, we would need to use an additional
617 CAF list to keep track of non-collectable CAFs.  
618
619 \begin{code}
620 hasCafRefs  :: (Id -> Bool) -> CoreExpr -> CafInfo
621 -- Only called for the RHS of top-level lets
622 hasCafRefss :: (Id -> Bool) -> [CoreExpr] -> CafInfo
623         -- predicate returns True for a given Id if we look at this Id when
624         -- calculating the result.  Used to *avoid* looking at the CafInfo
625         -- field for an Id that is part of the current recursive group.
626
627 hasCafRefs p expr = if isCAF expr || isFastTrue (cafRefs p expr)
628                         then MayHaveCafRefs
629                         else NoCafRefs
630
631         -- used for recursive groups.  The whole group is set to
632         -- "MayHaveCafRefs" if at least one of the group is a CAF or
633         -- refers to any CAFs.
634 hasCafRefss p exprs = if any isCAF exprs || isFastTrue (cafRefss p exprs)
635                         then MayHaveCafRefs
636                         else NoCafRefs
637
638 cafRefs p (Var id)
639  | p id
640  = case idCafInfo id of 
641         NoCafRefs      -> fastBool False
642         MayHaveCafRefs -> fastBool True
643  | otherwise
644  = fastBool False
645
646 cafRefs p (Lit l)            = fastBool False
647 cafRefs p (App f a)          = cafRefs p f `fastOr` cafRefs p a
648 cafRefs p (Lam x e)          = cafRefs p e
649 cafRefs p (Let b e)          = cafRefss p (rhssOfBind b) `fastOr` cafRefs p e
650 cafRefs p (Case e bndr alts) = cafRefs p e `fastOr` cafRefss p (rhssOfAlts alts)
651 cafRefs p (Note n e)         = cafRefs p e
652 cafRefs p (Type t)           = fastBool False
653
654 cafRefss p []     = fastBool False
655 cafRefss p (e:es) = cafRefs p e `fastOr` cafRefss p es
656
657
658 isCAF :: CoreExpr -> Bool
659 -- Only called for the RHS of top-level lets
660 isCAF e = not (rhsIsNonUpd e)
661   {- ToDo: check type for onceness, i.e. non-updatable thunks? -}
662
663 rhsIsNonUpd :: CoreExpr -> Bool
664   -- True => Value-lambda, constructor, PAP
665   -- This is a bit like CoreUtils.exprIsValue, with the following differences:
666   --    a) scc "foo" (\x -> ...) is updatable (so we catch the right SCC)
667   --
668   --    b) (C x xs), where C is a contructors is updatable if the application is
669   --       dynamic: see isDynConApp
670   -- 
671   --    c) don't look through unfolding of f in (f x).  I'm suspicious of this one
672
673 rhsIsNonUpd (Lam b e)          = isId b || rhsIsNonUpd e
674 rhsIsNonUpd (Note (SCC _) e)   = False
675 rhsIsNonUpd (Note _ e)         = rhsIsNonUpd e
676 rhsIsNonUpd other_expr
677   = go other_expr 0 []
678   where
679     go (Var f) n_args args = idAppIsNonUpd f n_args args
680         
681     go (App f a) n_args args
682         | isTypeArg a = go f n_args args
683         | otherwise   = go f (n_args + 1) (a:args)
684
685     go (Note (SCC _) f) n_args args = False
686     go (Note _ f) n_args args       = go f n_args args
687
688     go other n_args args = False
689
690 idAppIsNonUpd :: Id -> Int -> [CoreExpr] -> Bool
691 idAppIsNonUpd id n_val_args args
692   = case idFlavour id of
693         DataConId con | not (isDynConApp con args) -> True
694         other -> n_val_args < idArity id
695
696 isDynConApp :: DataCon -> [CoreExpr] -> Bool
697 isDynConApp con args = isDllName (dataConName con) || any isDynArg args
698 -- Top-level constructor applications can usually be allocated 
699 -- statically, but they can't if 
700 --      a) the constructor, or any of the arguments, come from another DLL
701 --      b) any of the arguments are LitLits
702 -- (because we can't refer to static labels in other DLLs).
703 -- If this happens we simply make the RHS into an updatable thunk, 
704 -- and 'exectute' it rather than allocating it statically.
705 -- All this should match the decision in (see CoreToStg.coreToStgRhs)
706
707
708 isDynArg :: CoreExpr -> Bool
709 isDynArg (Var v)    = isDllName (idName v)
710 isDynArg (Note _ e) = isDynArg e
711 isDynArg (Lit lit)  = isLitLitLit lit
712 isDynArg (App e _)  = isDynArg e        -- must be a type app
713 isDynArg (Lam _ e)  = isDynArg e        -- must be a type lam
714 \end{code}