2 % (c) The AQUA Project, Glasgow University, 1993-1996
4 \section[SimplUtils]{The simplifier utilities}
7 #include "HsVersions.h"
13 etaCoreExpr, mkRhsTyLam,
17 simplIdWantsToBeINLINEd,
19 singleConstructorType, typeOkForCase
23 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 201
24 IMPORT_DELOOPER(SmplLoop) -- paranoia checking
28 import CmdLineOpts ( opt_DoEtaReduction, SimplifierSwitch(..) )
30 import CoreUnfold ( SimpleUnfolding, mkFormSummary, exprIsTrivial, FormSummary(..) )
31 import Id ( idType, isBottomingId, addInlinePragma, addIdDemandInfo,
32 idWantsToBeINLINEd, dataConArgTys, SYN_IE(Id),
33 getIdArity, GenId{-instance Eq-}
35 import IdInfo ( ArityInfo(..), DemandInfo )
36 import Maybes ( maybeToBool )
37 import PrelVals ( augmentId, buildId )
38 import PrimOp ( primOpIsCheap )
41 import Type ( tyVarsOfType, mkForAllTys, mkTyVarTys, isPrimType, getTyVar_maybe,
42 maybeAppDataTyConExpandingDicts, SYN_IE(Type)
44 import TyCon ( isDataTyCon )
45 import TysWiredIn ( realWorldStateTy )
46 import TyVar ( elementOfTyVarSet,
47 GenTyVar{-instance Eq-} )
48 import Util ( isIn, panic, assertPanic )
55 The function @floatExposesHNF@ tells whether let/case floating will
56 expose a head normal form. It is passed booleans indicating the
61 :: Bool -- Float let(rec)s out of rhs
62 -> Bool -- Float cheap primops out of rhs
63 -> Bool -- OK to duplicate code
64 -> GenCoreExpr bdr Id tyvar uvar
67 floatExposesHNF float_lets float_primops ok_to_dup rhs
70 try (Case (Prim _ _) (PrimAlts alts deflt) )
71 | float_primops && (null alts || ok_to_dup)
72 = or (try_deflt deflt : map try_alt alts)
74 try (Let bind body) | float_lets = try body
78 -- because it *will* become one.
79 -- likewise for `augment g h'
81 try (App (App (Var bld) _) _) | bld == buildId = True
82 try (App (App (App (Var aug) _) _) _) | aug == augmentId = True
84 try other = case mkFormSummary other of
88 {- but *not* necessarily "BottomForm"...
90 We may want to float a let out of a let to expose WHNFs,
91 but to do that to expose a "bottom" is a Bad Idea:
93 in ...error ...y... -- manifestly bottom using y
97 in let x = ...error ...y...
100 as y is only used in case of an error, we do not want
101 to allocate it eagerly as that's a waste.
104 try_alt (lit,rhs) = try rhs
106 try_deflt NoDefault = False
107 try_deflt (BindDefault _ rhs) = try rhs
113 mkRhsTyLam tries this transformation, when the big lambda appears as
114 the RHS of a let(rec) binding:
116 /\abc -> let(rec) x = e in b
118 let(rec) x' = /\abc -> let x = x' a b c in e
120 /\abc -> let x = x' a b c in b
122 This is good because it can turn things like:
124 let f = /\a -> letrec g = ... g ... in g
126 letrec g' = /\a -> ... g' a ...
130 which is better. In effect, it means that big lambdas don't impede
133 This optimisation is CRUCIAL in eliminating the junk introduced by
134 desugaring mutually recursive definitions. Don't eliminate it lightly!
136 So far as the implemtation is concerned:
138 Invariant: go F e = /\tvs -> F e
142 = Let x' = /\tvs -> F e
146 G = F . Let x = x' tvs
148 go F (Letrec xi=ei in b)
149 = Letrec {xi' = /\tvs -> G ei}
153 G = F . Let {xi = xi' tvs}
156 mkRhsTyLam [] body = returnSmpl body
158 mkRhsTyLam tyvars body
161 tyvar_tys = mkTyVarTys tyvars
163 go fn (Let bind@(NonRec var rhs) body) | exprIsTrivial rhs
164 = go (fn . Let bind) body
166 go fn (Let bind@(NonRec var rhs) body)
167 = mk_poly var `thenSmpl` \ (var', rhs') ->
168 go (fn . Let (mk_silly_bind var rhs')) body `thenSmpl` \ body' ->
169 returnSmpl (Let (NonRec var' (mkTyLam tyvars (fn rhs))) body')
171 go fn (Let (Rec prs) body)
172 = mapAndUnzipSmpl mk_poly vars `thenSmpl` \ (vars', rhss') ->
174 gn body = fn $ foldr Let body (zipWith mk_silly_bind vars rhss')
176 go gn body `thenSmpl` \ body' ->
177 returnSmpl (Let (Rec (vars' `zip` [mkTyLam tyvars (gn rhs) | rhs <- rhss])) body')
179 (vars,rhss) = unzip prs
181 go fn body = returnSmpl (mkTyLam tyvars (fn body))
184 = newId (mkForAllTys tyvars (idType var)) `thenSmpl` \ poly_id ->
185 returnSmpl (poly_id, mkTyApp (Var poly_id) tyvar_tys)
187 mk_silly_bind var rhs = NonRec (addInlinePragma var) rhs
188 -- The addInlinePragma is really important! If we don't say
189 -- INLINE on these silly little bindings then look what happens!
190 -- Suppose we start with:
192 -- x = let g = /\a -> \x -> f x x
194 -- /\ b -> let g* = g b in E
196 -- Then: * the binding for g gets floated out
197 -- * but then it gets inlined into the rhs of g*
198 -- * then the binding for g* is floated out of the /\b
199 -- * so we're back to square one
200 -- The silly binding for g* must be INLINE, so that no inlining
201 -- will happen in its RHS.
206 @etaCoreExpr@ trys an eta reduction at the top level of a Core Expr.
208 e.g. \ x y -> f x y ===> f
211 a) Before constructing an Unfolding, to
212 try to make the unfolding smaller;
213 b) In tidyCoreExpr, which is done just before converting to STG.
215 But we only do this if it gets rid of a whole lambda, not part.
216 The idea is that lambdas are often quite helpful: they indicate
217 head normal forms, so we don't want to chuck them away lightly.
218 But if they expose a simple variable then we definitely win. Even
219 if they expose a type application we win. So we check for this special
224 f xs = [y | (y,_) <- xs]
226 gives rise to a recursive function for the list comprehension, and
227 f turns out to be just a single call to this recursive function.
229 Doing eta on type lambdas is useful too:
231 /\a -> <expr> a ===> <expr>
233 where <expr> doesn't mention a.
234 This is sometimes quite useful, because we can get the sequence:
236 f ab d = let d1 = ...d... in
237 letrec f' b x = ...d...(f' b)... in
241 f.Int b = letrec f' b x = ...dInt...(f' b)... in
246 f' b x = ...dInt...(f' b)...
249 Now we really want to simplify to
253 and then replace all the f's with f.Ints.
255 N.B. We are careful not to partially eta-reduce a sequence of type
256 applications since this breaks the specialiser:
258 /\ a -> f Char# a =NO=> f Char#
261 etaCoreExpr :: CoreExpr -> CoreExpr
264 etaCoreExpr expr@(Lam bndr body)
266 = case etaCoreExpr body of
267 App fun arg | eta_match bndr arg &&
270 other -> expr -- Can't eliminate it, so do nothing at all
272 eta_match (ValBinder v) (VarArg v') = v == v'
273 eta_match (TyBinder tv) (TyArg ty) = case getTyVar_maybe ty of
275 Just tv' -> tv == tv'
276 eta_match bndr arg = False
278 residual_ok :: CoreExpr -> Bool -- Checks for type application
279 -- and function not one of the
282 (VarArg v) `mentions` (ValBinder v') = v == v'
283 (TyArg ty) `mentions` (TyBinder tv) = tv `elementOfTyVarSet` tyVarsOfType ty
284 bndr `mentions` arg = False
287 = not (VarArg v `mentions` bndr)
288 residual_ok (App fun arg)
289 | arg `mentions` bndr = False
290 | otherwise = residual_ok fun
291 residual_ok (Coerce coercion ty body)
292 | TyArg ty `mentions` bndr = False
293 | otherwise = residual_ok body
295 residual_ok other = False -- Safe answer
296 -- This last clause may seem conservative, but consider:
297 -- primops, constructors, and literals, are impossible here
298 -- let and case are unlikely (the argument would have been floated inside)
299 -- SCCs we probably want to be conservative about (not sure, but it's safe to be)
301 etaCoreExpr expr = expr -- The common case
307 @etaExpandCount@ takes an expression, E, and returns an integer n,
310 E ===> (\x1::t1 x1::t2 ... xn::tn -> E x1 x2 ... xn)
312 is a safe transformation. In particular, the transformation should
313 not cause work to be duplicated, unless it is ``cheap'' (see
314 @manifestlyCheap@ below).
316 @etaExpandCount@ errs on the conservative side. It is always safe to
319 An application of @error@ is special, because it can absorb as many
320 arguments as you care to give it. For this special case we return
321 100, to represent "infinity", which is a bit of a hack.
324 etaExpandCount :: GenCoreExpr bdr Id tyvar uvar
325 -> Int -- Number of extra args you can safely abstract
327 etaExpandCount (Lam (ValBinder _) body)
328 = 1 + etaExpandCount body
330 etaExpandCount (Let bind body)
331 | all manifestlyCheap (rhssOfBind bind)
332 = etaExpandCount body
334 etaExpandCount (Case scrut alts)
335 | manifestlyCheap scrut
336 = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
338 etaExpandCount fun@(Var _) = eta_fun fun
339 etaExpandCount (App fun arg)
340 | notValArg arg = eta_fun fun
341 | otherwise = case etaExpandCount fun of
343 n -> n-1 -- Knock off one
345 etaExpandCount other = 0 -- Give up
348 -- Scc (pessimistic; ToDo),
349 -- Let with non-whnf rhs(s),
350 -- Case with non-whnf scrutinee
352 -----------------------------
353 eta_fun :: GenCoreExpr bdr Id tv uv -- The function
354 -> Int -- How many args it can safely be applied to
356 eta_fun (App fun arg) | notValArg arg = eta_fun fun
359 | isBottomingId v -- Bottoming ids have "infinite arity"
360 = 10000 -- Blargh. Infinite enough!
362 eta_fun expr@(Var v) = idMinArity v
364 eta_fun other = 0 -- Give up
367 @manifestlyCheap@ looks at a Core expression and returns \tr{True} if
368 it is obviously in weak head normal form, or is cheap to get to WHNF.
369 By ``cheap'' we mean a computation we're willing to duplicate in order
370 to bring a couple of lambdas together. The main examples of things
371 which aren't WHNF but are ``cheap'' are:
376 where e, and all the ei are cheap; and
381 where e and b are cheap; and
385 where op is a cheap primitive operator
388 manifestlyCheap :: GenCoreExpr bndr Id tv uv -> Bool
390 manifestlyCheap (Var _) = True
391 manifestlyCheap (Lit _) = True
392 manifestlyCheap (Con _ _) = True
393 manifestlyCheap (SCC _ e) = manifestlyCheap e
394 manifestlyCheap (Coerce _ _ e) = manifestlyCheap e
395 manifestlyCheap (Lam x e) = if isValBinder x then True else manifestlyCheap e
396 manifestlyCheap (Prim op _) = primOpIsCheap op
398 manifestlyCheap (Let bind body)
399 = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
401 manifestlyCheap (Case scrut alts)
402 = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
404 manifestlyCheap other_expr -- look for manifest partial application
405 = case (collectArgs other_expr) of { (fun, _, _, vargs) ->
408 Var f | isBottomingId f -> True -- Application of a function which
409 -- always gives bottom; we treat this as
410 -- a WHNF, because it certainly doesn't
411 -- need to be shared!
414 num_val_args = length vargs
416 num_val_args == 0 || -- Just a type application of
417 -- a variable (f t1 t2 t3)
419 num_val_args < idMinArity f
428 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
430 simplIdWantsToBeINLINEd id env
431 = {- We used to arrange that in the final simplification pass we'd switch
432 off all INLINE pragmas, so that we'd inline workers back into the
433 body of their wrapper if the wrapper hadn't itself been inlined by then.
434 This occurred especially for methods in dictionaries.
436 We no longer do this:
437 a) there's a good chance that the exported wrapper will get
438 inlined in some importing scope, in which case we don't
439 want to lose the w/w idea.
441 b) The occurrence analyser must agree about what has an
442 INLINE pragma. Not hard, but delicate.
444 c) if the worker gets inlined we have to tell the wrapepr
445 that it's no longer a wrapper, else the interface file stuff
446 asks for a worker that no longer exists.
448 if switchIsSet env IgnoreINLINEPragma
453 idWantsToBeINLINEd id
455 idMinArity id = case getIdArity id of
460 singleConstructorType :: Type -> Bool
461 singleConstructorType ty
462 = case (maybeAppDataTyConExpandingDicts ty) of
463 Just (tycon, ty_args, [con]) | isDataTyCon tycon -> True
466 typeOkForCase :: Type -> Bool
468 = case (maybeAppDataTyConExpandingDicts ty) of
469 Just (tycon, ty_args, []) -> False
470 Just (tycon, ty_args, non_null_data_cons) | isDataTyCon tycon -> True
472 -- Null data cons => type is abstract, which code gen can't
473 -- currently handle. (ToDo: when return-in-heap is universal we
474 -- don't need to worry about this.)