2 % (c) The AQUA Project, Glasgow University, 1993-1996
4 \section[SimplUtils]{The simplifier utilities}
13 etaCoreExpr, mkRhsTyLam,
17 simplIdWantsToBeINLINEd,
19 singleConstructorType, typeOkForCase,
24 #include "HsVersions.h"
27 import CmdLineOpts ( opt_DoEtaReduction, SimplifierSwitch(..) )
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
36 import IdInfo ( ArityInfo(..), DemandInfo )
37 import Maybes ( maybeToBool )
38 import PrelVals ( augmentId, buildId )
39 import PrimOp ( primOpIsCheap )
42 import Type ( tyVarsOfType, tyVarsOfTypes, mkForAllTys, mkTyVarTys, getTyVar_maybe,
43 splitAlgTyConApp_maybe, instantiateTy, Type
45 import TyCon ( isDataTyCon )
46 import TyVar ( mkTyVarSet, intersectTyVarSets, elementOfTyVarSet, tyVarSetToList,
49 import SrcLoc ( noSrcLoc )
50 import Util ( isIn, zipWithEqual, panic, assertPanic )
55 %************************************************************************
59 %************************************************************************
62 newId :: Type -> SmplM Id
64 = getUniqueSmpl `thenSmpl` \ uniq ->
65 returnSmpl (mkSysLocal SLIT("s") uniq ty noSrcLoc)
67 newIds :: [Type] -> SmplM [Id]
69 = getUniquesSmpl (length tys) `thenSmpl` \ uniqs ->
70 returnSmpl (zipWithEqual "newIds" mk_id tys uniqs)
72 mk_id ty uniq = mkSysLocal SLIT("s") uniq ty noSrcLoc
76 %************************************************************************
80 %************************************************************************
82 The function @floatExposesHNF@ tells whether let/case floating will
83 expose a head normal form. It is passed booleans indicating the
88 :: Bool -- Float let(rec)s out of rhs
89 -> Bool -- Float cheap primops out of rhs
90 -> GenCoreExpr bdr Id flexi
93 floatExposesHNF float_lets float_primops rhs
96 try (Case (Prim _ _) (PrimAlts alts deflt) )
97 | float_primops && null alts
98 = or (try_deflt deflt : map try_alt alts)
100 try (Let bind body) | float_lets = try body
104 -- because it *will* become one.
105 -- likewise for `augment g h'
107 try (App (App (Var bld) _) _) | bld == buildId = True
108 try (App (App (App (Var aug) _) _) _) | aug == augmentId = True
110 try other = case mkFormSummary other of
114 {- but *not* necessarily "BottomForm"...
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:
119 in ...error ...y... -- manifestly bottom using y
123 in let x = ...error ...y...
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.
130 try_alt (lit,rhs) = try rhs
132 try_deflt NoDefault = False
133 try_deflt (BindDefault _ rhs) = try rhs
139 mkRhsTyLam tries this transformation, when the big lambda appears as
140 the RHS of a let(rec) binding:
142 /\abc -> let(rec) x = e in b
144 let(rec) x' = /\abc -> let x = x' a b c in e
146 /\abc -> let x = x' a b c in b
148 This is good because it can turn things like:
150 let f = /\a -> letrec g = ... g ... in g
152 letrec g' = /\a -> ... g' a ...
156 which is better. In effect, it means that big lambdas don't impede
159 This optimisation is CRUCIAL in eliminating the junk introduced by
160 desugaring mutually recursive definitions. Don't eliminate it lightly!
162 So far as the implemtation is concerned:
164 Invariant: go F e = /\tvs -> F e
168 = Let x' = /\tvs -> F e
172 G = F . Let x = x' tvs
174 go F (Letrec xi=ei in b)
175 = Letrec {xi' = /\tvs -> G ei}
179 G = F . Let {xi = xi' tvs}
182 mkRhsTyLam [] body = returnSmpl body
184 mkRhsTyLam tyvars body
187 main_tyvar_set = mkTyVarSet tyvars
189 go fn (Let bind@(NonRec var rhs) body) | exprIsTrivial rhs
190 = go (fn . Let bind) body
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')
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
204 -- /\ a b -> let t :: (a,b) = (e1, e2)
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
216 go fn (Let (Rec prs) body)
217 = mapAndUnzipSmpl (mk_poly tyvars_here) var_tys `thenSmpl` \ (vars', rhss') ->
219 gn body = fn $ foldr Let body (zipWith mk_silly_bind vars rhss')
221 go gn body `thenSmpl` \ body' ->
222 returnSmpl (Let (Rec (vars' `zip` [mkTyLam tyvars_here (gn rhs) | rhs <- rhss])) body')
224 (vars,rhss) = unzip prs
225 var_tys = map idType vars
226 tyvars_here = tyvars -- See notes on tyvars_here above
228 go fn body = returnSmpl (mkTyLam tyvars (fn body))
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))
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:
239 -- x = let g = /\a -> \x -> f x x
241 -- /\ b -> let g* = g b in E
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.
253 @etaCoreExpr@ trys an eta reduction at the top level of a Core Expr.
255 e.g. \ x y -> f x y ===> f
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.
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
271 f xs = [y | (y,_) <- xs]
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.
276 Doing eta on type lambdas is useful too:
278 /\a -> <expr> a ===> <expr>
280 where <expr> doesn't mention a.
281 This is sometimes quite useful, because we can get the sequence:
283 f ab d = let d1 = ...d... in
284 letrec f' b x = ...d...(f' b)... in
288 f.Int b = letrec f' b x = ...dInt...(f' b)... in
293 f' b x = ...dInt...(f' b)...
296 Now we really want to simplify to
300 and then replace all the f's with f.Ints.
302 N.B. We are careful not to partially eta-reduce a sequence of type
303 applications since this breaks the specialiser:
305 /\ a -> f Char# a =NO=> f Char#
308 etaCoreExpr :: CoreExpr -> CoreExpr
311 etaCoreExpr expr@(Lam bndr body)
313 = case etaCoreExpr body of
314 App fun arg | eta_match bndr arg &&
317 other -> expr -- Can't eliminate it, so do nothing at all
319 eta_match (ValBinder v) (VarArg v') = v == v'
320 eta_match (TyBinder tv) (TyArg ty) = case getTyVar_maybe ty of
322 Just tv' -> tv == tv'
323 eta_match bndr arg = False
325 residual_ok :: CoreExpr -> Bool -- Checks for type application
326 -- and function not one of the
329 (VarArg v) `mentions` (ValBinder v') = v == v'
330 (TyArg ty) `mentions` (TyBinder tv) = tv `elementOfTyVarSet` tyVarsOfType ty
331 bndr `mentions` arg = False
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
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)
349 etaCoreExpr expr = expr -- The common case
355 @etaExpandCount@ takes an expression, E, and returns an integer n,
358 E ===> (\x1::t1 x1::t2 ... xn::tn -> E x1 x2 ... xn)
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).
364 @etaExpandCount@ errs on the conservative side. It is always safe to
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.
372 etaExpandCount :: GenCoreExpr bdr Id flexi
373 -> Int -- Number of extra args you can safely abstract
375 etaExpandCount (Lam (ValBinder _) body)
376 = 1 + etaExpandCount body
378 etaExpandCount (Let bind body)
379 | all manifestlyCheap (rhssOfBind bind)
380 = etaExpandCount body
382 etaExpandCount (Case scrut alts)
383 | manifestlyCheap scrut
384 = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
386 etaExpandCount fun@(Var _) = eta_fun fun
387 etaExpandCount (App fun arg)
388 | notValArg arg = eta_fun fun
389 | otherwise = case etaExpandCount fun of
391 n -> n-1 -- Knock off one
393 etaExpandCount other = 0 -- Give up
396 -- Scc (pessimistic; ToDo),
397 -- Let with non-whnf rhs(s),
398 -- Case with non-whnf scrutinee
400 -----------------------------
401 eta_fun :: GenCoreExpr bdr Id flexi -- The function
402 -> Int -- How many args it can safely be applied to
404 eta_fun (App fun arg) | notValArg arg = eta_fun fun
407 | isBottomingId v -- Bottoming ids have "infinite arity"
408 = 10000 -- Blargh. Infinite enough!
410 eta_fun expr@(Var v) = idMinArity v
412 eta_fun other = 0 -- Give up
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:
424 where e, and all the ei are cheap; and
429 where e and b are cheap; and
433 where op is a cheap primitive operator
436 manifestlyCheap :: GenCoreExpr bndr Id flexi -> Bool
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
445 manifestlyCheap (Let bind body)
446 = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
448 manifestlyCheap (Case scrut alts)
449 = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
451 manifestlyCheap other_expr -- look for manifest partial application
452 = case (collectArgs other_expr) of { (fun, _, vargs) ->
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!
461 num_val_args = length vargs
463 num_val_args == 0 || -- Just a type application of
464 -- a variable (f t1 t2 t3)
466 num_val_args < idMinArity f
475 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
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.
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.
488 b) The occurrence analyser must agree about what has an
489 INLINE pragma. Not hard, but delicate.
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.
495 if switchIsSet env IgnoreINLINEPragma
500 idWantsToBeINLINEd id
502 idMinArity id = case getIdArity id of
507 singleConstructorType :: Type -> Bool
508 singleConstructorType ty
509 = case (splitAlgTyConApp_maybe ty) of
510 Just (tycon, ty_args, [con]) | isDataTyCon tycon -> True
513 typeOkForCase :: Type -> Bool
515 = case (splitAlgTyConApp_maybe ty) of
516 Just (tycon, ty_args, []) -> False
517 Just (tycon, ty_args, non_null_data_cons) | isDataTyCon tycon -> True
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.)
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
531 substSpecEnvRhs te ve rhs
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
539 go te ve (Var v) = case lookupIdEnv ve v of
540 Just (SubstVar v') -> Var v'
541 Just (SubstLit l) -> Lit l
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)
549 te' = delFromTyVarEnv te tyvar
551 go te ve (Lam b@(ValBinder v) e) = Lam b (go te ve' e)
553 ve' = delOneFromIdEnv ve v