db34553c79907bbcbf61ac16a36d7d31dd1cfe2a
[ghc-hetmet.git] / ghc / compiler / simplCore / SimplUtils.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1996
3 %
4 \section[SimplUtils]{The simplifier utilities}
5
6 \begin{code}
7 module SimplUtils (
8
9         newId, newIds,
10
11         floatExposesHNF,
12
13         etaCoreExpr, mkRhsTyLam,
14
15         etaExpandCount,
16
17         simplIdWantsToBeINLINEd,
18
19         singleConstructorType, typeOkForCase,
20
21         substSpecEnvRhs
22     ) where
23
24 #include "HsVersions.h"
25
26 import BinderInfo
27 import CmdLineOpts      ( opt_DoEtaReduction, SimplifierSwitch(..) )
28 import CoreSyn
29 import CoreUnfold       ( mkFormSummary, exprIsTrivial, FormSummary(..) )
30 import MkId             ( mkSysLocal )
31 import Id               ( idType, isBottomingId, getIdArity,
32                           addInlinePragma, addIdDemandInfo,
33                           idWantsToBeINLINEd, dataConArgTys, Id,
34                           lookupIdEnv, delOneFromIdEnv
35                         )
36 import IdInfo           ( ArityInfo(..), DemandInfo )
37 import Maybes           ( maybeToBool )
38 import PrelVals         ( augmentId, buildId )
39 import PrimOp           ( primOpIsCheap )
40 import SimplEnv
41 import SimplMonad
42 import Type             ( tyVarsOfType, tyVarsOfTypes, mkForAllTys, mkTyVarTys, getTyVar_maybe,
43                           splitAlgTyConApp_maybe, instantiateTy, Type
44                         )
45 import TyCon            ( isDataTyCon )
46 import TyVar            ( mkTyVarSet, intersectTyVarSets, elementOfTyVarSet, tyVarSetToList,
47                           delFromTyVarEnv
48                         )
49 import SrcLoc           ( noSrcLoc )
50 import Util             ( isIn, zipWithEqual, panic, assertPanic )
51
52 \end{code}
53
54
55 %************************************************************************
56 %*                                                                      *
57 \subsection{New ids}
58 %*                                                                      *
59 %************************************************************************
60
61 \begin{code}
62 newId :: Type -> SmplM Id
63 newId ty
64   = getUniqueSmpl     `thenSmpl`  \ uniq ->
65     returnSmpl (mkSysLocal SLIT("s") uniq ty noSrcLoc)
66
67 newIds :: [Type] -> SmplM [Id]
68 newIds tys
69   = getUniquesSmpl (length tys)    `thenSmpl`  \ uniqs ->
70     returnSmpl (zipWithEqual "newIds" mk_id tys uniqs)
71   where
72     mk_id ty uniq = mkSysLocal SLIT("s") uniq ty noSrcLoc
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78 \subsection{Floating}
79 %*                                                                      *
80 %************************************************************************
81
82 The function @floatExposesHNF@ tells whether let/case floating will
83 expose a head normal form.  It is passed booleans indicating the
84 desired strategy.
85
86 \begin{code}
87 floatExposesHNF
88         :: Bool                 -- Float let(rec)s out of rhs
89         -> Bool                 -- Float cheap primops out of rhs
90         -> GenCoreExpr bdr Id flexi
91         -> Bool
92
93 floatExposesHNF float_lets float_primops rhs
94   = try rhs
95   where
96     try (Case (Prim _ _) (PrimAlts alts deflt) )
97       | float_primops && null alts
98       = or (try_deflt deflt : map try_alt alts)
99
100     try (Let bind body) | float_lets = try body
101
102     --    `build g'
103     -- is like a HNF,
104     -- because it *will* become one.
105     -- likewise for `augment g h'
106     --
107     try (App (App (Var bld) _) _)         | bld == buildId   = True
108     try (App (App (App (Var aug) _) _) _) | aug == augmentId = True
109
110     try other = case mkFormSummary other of
111                         VarForm   -> True
112                         ValueForm -> True
113                         other     -> False
114         {- but *not* necessarily "BottomForm"...
115
116            We may want to float a let out of a let to expose WHNFs,
117             but to do that to expose a "bottom" is a Bad Idea:
118             let x = let y = ...
119                     in ...error ...y... --  manifestly bottom using y
120             in ...
121             =/=>
122             let y = ...
123             in let x = ...error ...y...
124                in ...
125
126             as y is only used in case of an error, we do not want
127             to allocate it eagerly as that's a waste.
128         -}
129
130     try_alt (lit,rhs) = try rhs
131
132     try_deflt NoDefault           = False
133     try_deflt (BindDefault _ rhs) = try rhs
134 \end{code}
135
136
137 Local tyvar-lifting
138 ~~~~~~~~~~~~~~~~~~~
139 mkRhsTyLam tries this transformation, when the big lambda appears as
140 the RHS of a let(rec) binding:
141
142         /\abc -> let(rec) x = e in b
143    ==>
144         let(rec) x' = /\abc -> let x = x' a b c in e
145         in 
146         /\abc -> let x = x' a b c in b
147
148 This is good because it can turn things like:
149
150         let f = /\a -> letrec g = ... g ... in g
151 into
152         letrec g' = /\a -> ... g' a ...
153         in
154         let f = /\ a -> f a
155
156 which is better.  In effect, it means that big lambdas don't impede
157 let-floating.
158
159 This optimisation is CRUCIAL in eliminating the junk introduced by
160 desugaring mutually recursive definitions.  Don't eliminate it lightly!
161
162 So far as the implemtation is concerned:
163
164         Invariant: go F e = /\tvs -> F e
165         
166         Equalities:
167                 go F (Let x=e in b)
168                 = Let x' = /\tvs -> F e 
169                   in 
170                   go G b
171                 where
172                     G = F . Let x = x' tvs
173         
174                 go F (Letrec xi=ei in b)
175                 = Letrec {xi' = /\tvs -> G ei} 
176                   in
177                   go G b
178                 where
179                   G = F . Let {xi = xi' tvs}
180
181 \begin{code}
182 mkRhsTyLam [] body = returnSmpl body
183
184 mkRhsTyLam tyvars body
185   = go (\x -> x) body
186   where
187     main_tyvar_set = mkTyVarSet tyvars
188
189     go fn (Let bind@(NonRec var rhs) body) | exprIsTrivial rhs
190       = go (fn . Let bind) body
191
192     go fn (Let bind@(NonRec var rhs) body)
193       = mk_poly tyvars_here var_ty                      `thenSmpl` \ (var', rhs') ->
194         go (fn . Let (mk_silly_bind var rhs')) body     `thenSmpl` \ body' ->
195         returnSmpl (Let (NonRec var' (mkTyLam tyvars_here (fn rhs))) body')
196       where
197         var_ty = idType var
198         tyvars_here = tyvars
199                 -- tyVarSetToList (main_tyvar_set `intersectTyVarSets` tyVarsOfTypes var_ty)
200                 -- tyvars_here was an attempt to reduce the number of tyvars
201                 -- wrt which the new binding is abstracted.  But the naive
202                 -- approach of abstract wrt the tyvars free in the Id's type
203                 -- fails. Consider:
204                 --      /\ a b -> let t :: (a,b) = (e1, e2)
205                 --                    x :: a     = fst t
206                 --                in ...
207                 -- Here, b isn't free in a's type, but we must nevertheless
208                 -- abstract wrt b as well, because t's type mentions b.
209                 -- Since t is floated too, we'd end up with the bogus:
210                 --      poly_t = /\ a b -> (e1, e2)
211                 --      poly_x = /\ a   -> fst (poly_t a *b*)
212                 -- So for now we adopt the even more naive approach of
213                 -- abstracting wrt *all* the tyvars.  We'll see if that
214                 -- gives rise to problems.   SLPJ June 98
215
216     go fn (Let (Rec prs) body)
217        = mapAndUnzipSmpl (mk_poly tyvars_here) var_tys  `thenSmpl` \ (vars', rhss') ->
218          let
219             gn body = fn $ foldr Let body (zipWith mk_silly_bind vars rhss')
220          in
221          go gn body                             `thenSmpl` \ body' ->
222          returnSmpl (Let (Rec (vars' `zip` [mkTyLam tyvars_here (gn rhs) | rhs <- rhss])) body')
223        where
224          (vars,rhss) = unzip prs
225          var_tys     = map idType vars
226          tyvars_here = tyvars   -- See notes on tyvars_here above
227
228     go fn body = returnSmpl (mkTyLam tyvars (fn body))
229
230     mk_poly tyvars_here var_ty
231       = newId (mkForAllTys tyvars_here var_ty)  `thenSmpl` \ poly_id ->
232         returnSmpl (poly_id, mkTyApp (Var poly_id) (mkTyVarTys tyvars_here))
233
234     mk_silly_bind var rhs = NonRec (addInlinePragma var) rhs
235                 -- The addInlinePragma is really important!  If we don't say 
236                 -- INLINE on these silly little bindings then look what happens!
237                 -- Suppose we start with:
238                 --
239                 --      x = let g = /\a -> \x -> f x x
240                 --          in 
241                 --          /\ b -> let g* = g b in E
242                 --
243                 -- Then:        * the binding for g gets floated out
244                 --              * but then it gets inlined into the rhs of g*
245                 --              * then the binding for g* is floated out of the /\b
246                 --              * so we're back to square one
247                 -- The silly binding for g* must be INLINE, so that no inlining
248                 -- will happen in its RHS.
249 \end{code}
250
251 Eta reduction
252 ~~~~~~~~~~~~~
253 @etaCoreExpr@ trys an eta reduction at the top level of a Core Expr.
254
255 e.g.    \ x y -> f x y  ===>  f
256
257 It is used
258         a) Before constructing an Unfolding, to 
259            try to make the unfolding smaller;
260         b) In tidyCoreExpr, which is done just before converting to STG.
261
262 But we only do this if it gets rid of a whole lambda, not part.
263 The idea is that lambdas are often quite helpful: they indicate
264 head normal forms, so we don't want to chuck them away lightly.
265 But if they expose a simple variable then we definitely win.  Even
266 if they expose a type application we win.  So we check for this special
267 case.
268
269 It does arise:
270
271         f xs = [y | (y,_) <- xs]
272
273 gives rise to a recursive function for the list comprehension, and
274 f turns out to be just a single call to this recursive function.
275
276 Doing eta on type lambdas is useful too:
277
278         /\a -> <expr> a    ===>     <expr>
279
280 where <expr> doesn't mention a.
281 This is sometimes quite useful, because we can get the sequence:
282
283         f ab d = let d1 = ...d... in
284                  letrec f' b x = ...d...(f' b)... in
285                  f' b
286 specialise ==>
287
288         f.Int b = letrec f' b x = ...dInt...(f' b)... in
289                   f' b
290
291 float ==>
292
293         f' b x = ...dInt...(f' b)...
294         f.Int b = f' b
295
296 Now we really want to simplify to
297
298         f.Int = f'
299
300 and then replace all the f's with f.Ints.
301
302 N.B. We are careful not to partially eta-reduce a sequence of type
303 applications since this breaks the specialiser:
304
305         /\ a -> f Char# a       =NO=> f Char#
306
307 \begin{code}
308 etaCoreExpr :: CoreExpr -> CoreExpr
309
310
311 etaCoreExpr expr@(Lam bndr body)
312   | opt_DoEtaReduction
313   = case etaCoreExpr body of
314         App fun arg | eta_match bndr arg &&
315                       residual_ok fun
316                     -> fun                      -- Eta
317         other       -> expr                     -- Can't eliminate it, so do nothing at all
318   where
319     eta_match (ValBinder v) (VarArg v') = v == v'
320     eta_match (TyBinder tv) (TyArg  ty) = case getTyVar_maybe ty of
321                                                 Nothing  -> False
322                                                 Just tv' -> tv == tv'
323     eta_match bndr          arg         = False
324
325     residual_ok :: CoreExpr -> Bool     -- Checks for type application
326                                         -- and function not one of the
327                                         -- bound vars
328
329     (VarArg v) `mentions` (ValBinder v') = v == v'
330     (TyArg ty) `mentions` (TyBinder tv)  = tv `elementOfTyVarSet` tyVarsOfType ty
331     bndr       `mentions` arg            = False
332
333     residual_ok (Var v)
334         = not (VarArg v `mentions` bndr)
335     residual_ok (App fun arg)
336         | arg `mentions` bndr = False
337         | otherwise           = residual_ok fun
338     residual_ok (Note (Coerce to_ty from_ty) body)
339         |  TyArg to_ty   `mentions` bndr 
340         || TyArg from_ty `mentions` bndr = False
341         | otherwise                      = residual_ok body
342
343     residual_ok other        = False            -- Safe answer
344         -- This last clause may seem conservative, but consider:
345         --      primops, constructors, and literals, are impossible here
346         --      let and case are unlikely (the argument would have been floated inside)
347         --      SCCs we probably want to be conservative about (not sure, but it's safe to be)
348         
349 etaCoreExpr expr = expr         -- The common case
350 \end{code}
351         
352
353 Eta expansion
354 ~~~~~~~~~~~~~
355 @etaExpandCount@ takes an expression, E, and returns an integer n,
356 such that
357
358         E  ===>   (\x1::t1 x1::t2 ... xn::tn -> E x1 x2 ... xn)
359
360 is a safe transformation.  In particular, the transformation should
361 not cause work to be duplicated, unless it is ``cheap'' (see
362 @manifestlyCheap@ below).
363
364 @etaExpandCount@ errs on the conservative side.  It is always safe to
365 return 0.
366
367 An application of @error@ is special, because it can absorb as many
368 arguments as you care to give it.  For this special case we return
369 100, to represent "infinity", which is a bit of a hack.
370
371 \begin{code}
372 etaExpandCount :: GenCoreExpr bdr Id flexi
373                -> Int   -- Number of extra args you can safely abstract
374
375 etaExpandCount (Lam (ValBinder _) body)
376   = 1 + etaExpandCount body
377
378 etaExpandCount (Let bind body)
379   | all manifestlyCheap (rhssOfBind bind)
380   = etaExpandCount body
381
382 etaExpandCount (Case scrut alts)
383   | manifestlyCheap scrut
384   = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
385
386 etaExpandCount fun@(Var _)     = eta_fun fun
387 etaExpandCount (App fun arg)
388   | notValArg arg = eta_fun fun
389   | otherwise     = case etaExpandCount fun of
390                       0 -> 0
391                       n -> n-1  -- Knock off one
392
393 etaExpandCount other = 0    -- Give up
394         -- Lit, Con, Prim,
395         -- non-val Lam,
396         -- Scc (pessimistic; ToDo),
397         -- Let with non-whnf rhs(s),
398         -- Case with non-whnf scrutinee
399
400 -----------------------------
401 eta_fun :: GenCoreExpr bdr Id flexi -- The function
402         -> Int                      -- How many args it can safely be applied to
403
404 eta_fun (App fun arg) | notValArg arg = eta_fun fun
405
406 eta_fun expr@(Var v)
407   | isBottomingId v             -- Bottoming ids have "infinite arity"
408   = 10000                       -- Blargh.  Infinite enough!
409
410 eta_fun expr@(Var v) = idMinArity v
411
412 eta_fun other = 0               -- Give up
413 \end{code}
414
415 @manifestlyCheap@ looks at a Core expression and returns \tr{True} if
416 it is obviously in weak head normal form, or is cheap to get to WHNF.
417 By ``cheap'' we mean a computation we're willing to duplicate in order
418 to bring a couple of lambdas together.  The main examples of things
419 which aren't WHNF but are ``cheap'' are:
420
421   *     case e of
422           pi -> ei
423
424         where e, and all the ei are cheap; and
425
426   *     let x = e
427         in b
428
429         where e and b are cheap; and
430
431   *     op x1 ... xn
432
433         where op is a cheap primitive operator
434
435 \begin{code}
436 manifestlyCheap :: GenCoreExpr bndr Id flexi -> Bool
437
438 manifestlyCheap (Var _)      = True
439 manifestlyCheap (Lit _)      = True
440 manifestlyCheap (Con _ _)    = True
441 manifestlyCheap (Note _ e)   = manifestlyCheap e
442 manifestlyCheap (Lam x e)    = if isValBinder x then True else manifestlyCheap e
443 manifestlyCheap (Prim op _)  = primOpIsCheap op
444
445 manifestlyCheap (Let bind body)
446   = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
447
448 manifestlyCheap (Case scrut alts)
449   = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
450
451 manifestlyCheap other_expr   -- look for manifest partial application
452   = case (collectArgs other_expr) of { (fun, _, vargs) ->
453     case fun of
454
455       Var f | isBottomingId f -> True   -- Application of a function which
456                                         -- always gives bottom; we treat this as
457                                         -- a WHNF, because it certainly doesn't
458                                         -- need to be shared!
459
460       Var f -> let
461                     num_val_args = length vargs
462                in
463                num_val_args == 0 ||     -- Just a type application of
464                                         -- a variable (f t1 t2 t3)
465                                         -- counts as WHNF
466                num_val_args < idMinArity f
467
468       _ -> False
469     }
470
471 \end{code}
472
473
474 \begin{code}
475 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
476
477 simplIdWantsToBeINLINEd id env
478   = {-  We used to arrange that in the final simplification pass we'd switch
479         off all INLINE pragmas, so that we'd inline workers back into the
480         body of their wrapper if the wrapper hadn't itself been inlined by then.
481         This occurred especially for methods in dictionaries.
482
483         We no longer do this:
484                 a) there's a good chance that the exported wrapper will get
485                 inlined in some importing scope, in which case we don't 
486                 want to lose the w/w idea.
487
488                 b) The occurrence analyser must agree about what has an
489                 INLINE pragma.  Not hard, but delicate.
490         
491                 c) if the worker gets inlined we have to tell the wrapepr
492                 that it's no longer a wrapper, else the interface file stuff
493                 asks for a worker that no longer exists.
494                   
495     if switchIsSet env IgnoreINLINEPragma
496     then False
497     else 
498     -}
499
500     idWantsToBeINLINEd id
501
502 idMinArity id = case getIdArity id of
503                         UnknownArity   -> 0
504                         ArityAtLeast n -> n
505                         ArityExactly n -> n
506
507 singleConstructorType :: Type -> Bool
508 singleConstructorType ty
509   = case (splitAlgTyConApp_maybe ty) of
510       Just (tycon, ty_args, [con]) | isDataTyCon tycon -> True
511       other                                            -> False
512
513 typeOkForCase :: Type -> Bool
514 typeOkForCase ty
515   = case (splitAlgTyConApp_maybe ty) of
516       Just (tycon, ty_args, [])                                     -> False
517       Just (tycon, ty_args, non_null_data_cons) | isDataTyCon tycon -> True
518       other                                                         -> False
519       -- Null data cons => type is abstract, which code gen can't 
520       -- currently handle.  (ToDo: when return-in-heap is universal we
521       -- don't need to worry about this.)
522 \end{code}
523
524
525
526 substSpecEnvRhs applies a substitution to the RHS's of a SpecEnv
527 It exploits the known structure of a SpecEnv's RHS to have fewer
528 equations.
529
530 \begin{code}
531 substSpecEnvRhs te ve rhs
532   = go te ve rhs
533   where
534     go te ve (App f (TyArg ty)) = App (go te ve f) (TyArg (instantiateTy te ty))
535     go te ve (App f (VarArg v)) = App (go te ve f) (case lookupIdEnv ve v of
536                                                         Just (SubstVar v') -> VarArg v'
537                                                         Just (SubstLit l)  -> LitArg l
538                                                         Nothing            -> VarArg v)
539     go te ve (Var v)              = case lookupIdEnv ve v of
540                                                 Just (SubstVar v') -> Var v'
541                                                 Just (SubstLit l)  -> Lit l
542                                                 Nothing            -> Var v
543
544         -- These equations are a bit half baked, because
545         -- they don't deal properly wih capture.
546         -- But I'm sure it'll never matter... sigh.
547     go te ve (Lam b@(TyBinder tyvar) e) = Lam b (go te' ve e)
548                                         where
549                                           te' = delFromTyVarEnv te tyvar
550
551     go te ve (Lam b@(ValBinder v) e) = Lam b (go te ve' e)
552                                      where
553                                        ve' = delOneFromIdEnv ve v
554 \end{code}