2 % (c) The AQUA Project, Glasgow University, 1993-1996
4 \section[SimplUtils]{The simplifier utilities}
7 #include "HsVersions.h"
13 etaCoreExpr, mkRhsTyLam,
19 simplIdWantsToBeINLINEd,
21 singleConstructorType, typeOkForCase
25 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,
42 maybeAppDataTyConExpandingDicts, SYN_IE(Type)
44 import TysWiredIn ( realWorldStateTy )
45 import TyVar ( elementOfTyVarSet,
46 GenTyVar{-instance Eq-} )
47 import Util ( isIn, panic )
54 The function @floatExposesHNF@ tells whether let/case floating will
55 expose a head normal form. It is passed booleans indicating the
60 :: Bool -- Float let(rec)s out of rhs
61 -> Bool -- Float cheap primops out of rhs
62 -> Bool -- OK to duplicate code
63 -> GenCoreExpr bdr Id tyvar uvar
66 floatExposesHNF float_lets float_primops ok_to_dup rhs
69 try (Case (Prim _ _) (PrimAlts alts deflt) )
70 | float_primops && (null alts || ok_to_dup)
71 = or (try_deflt deflt : map try_alt alts)
73 try (Let bind body) | float_lets = try body
77 -- because it *will* become one.
78 -- likewise for `augment g h'
80 try (App (App (Var bld) _) _) | bld == buildId = True
81 try (App (App (App (Var aug) _) _) _) | aug == augmentId = True
83 try other = case mkFormSummary other of
87 {- but *not* necessarily "BottomForm"...
89 We may want to float a let out of a let to expose WHNFs,
90 but to do that to expose a "bottom" is a Bad Idea:
92 in ...error ...y... -- manifestly bottom using y
96 in let x = ...error ...y...
99 as y is only used in case of an error, we do not want
100 to allocate it eagerly as that's a waste.
103 try_alt (lit,rhs) = try rhs
105 try_deflt NoDefault = False
106 try_deflt (BindDefault _ rhs) = try rhs
112 mkRhsTyLam tries this transformation, when the big lambda appears as
113 the RHS of a let(rec) binding:
115 /\abc -> let(rec) x = e in b
117 let(rec) x' = /\abc -> let x = x' a b c in e
119 /\abc -> let x = x' a b c in b
121 This is good because it can turn things like:
123 let f = /\a -> letrec g = ... g ... in g
125 letrec g' = /\a -> ... g' a ...
129 which is better. In effect, it means that big lambdas don't impede
132 This optimisation is CRUCIAL in eliminating the junk introduced by
133 desugaring mutually recursive definitions. Don't eliminate it lightly!
135 So far as the implemtation is concerned:
137 Invariant: go F e = /\tvs -> F e
141 = Let x' = /\tvs -> F e
145 G = F . Let x = x' tvs
147 go F (Letrec xi=ei in b)
148 = Letrec {xi' = /\tvs -> G ei}
152 G = F . Let {xi = xi' tvs}
155 mkRhsTyLam [] body = returnSmpl body
157 mkRhsTyLam tyvars body
160 tyvar_tys = mkTyVarTys tyvars
162 go fn (Let bind@(NonRec var rhs) body) | exprIsTrivial rhs
163 = go (fn . Let bind) body
165 go fn (Let bind@(NonRec var rhs) body)
166 = mk_poly var `thenSmpl` \ (var', rhs') ->
167 go (fn . Let (mk_silly_bind var rhs')) body `thenSmpl` \ body' ->
168 returnSmpl (Let (NonRec var' (mkTyLam tyvars (fn rhs))) body')
170 go fn (Let (Rec prs) body)
171 = mapAndUnzipSmpl mk_poly vars `thenSmpl` \ (vars', rhss') ->
173 gn body = fn $ foldr Let body (zipWith mk_silly_bind vars rhss')
175 go gn body `thenSmpl` \ body' ->
176 returnSmpl (Let (Rec (vars' `zip` [mkTyLam tyvars (gn rhs) | rhs <- rhss])) body')
178 (vars,rhss) = unzip prs
180 go fn body = returnSmpl (mkTyLam tyvars (fn body))
183 = newId (mkForAllTys tyvars (idType var)) `thenSmpl` \ poly_id ->
184 returnSmpl (poly_id, mkTyApp (Var poly_id) tyvar_tys)
186 mk_silly_bind var rhs = NonRec (addInlinePragma var) rhs
187 -- The addInlinePragma is really important! If we don't say
188 -- INLINE on these silly little bindings then look what happens!
189 -- Suppose we start with:
191 -- x = let g = /\a -> \x -> f x x
193 -- /\ b -> let g* = g b in E
195 -- Then: * the binding for g gets floated out
196 -- * but then it gets inlined into the rhs of g*
197 -- * then the binding for g* is floated out of the /\b
198 -- * so we're back to square one
199 -- The silly binding for g* must be INLINE, so that no inlining
200 -- will happen in its RHS.
205 @etaCoreExpr@ trys an eta reduction at the top level of a Core Expr.
207 e.g. \ x y -> f x y ===> f
210 a) Before constructing an Unfolding, to
211 try to make the unfolding smaller;
212 b) In tidyCoreExpr, which is done just before converting to STG.
214 But we only do this if it gets rid of a whole lambda, not part.
215 The idea is that lambdas are often quite helpful: they indicate
216 head normal forms, so we don't want to chuck them away lightly.
217 But if they expose a simple variable then we definitely win. Even
218 if they expose a type application we win. So we check for this special
223 f xs = [y | (y,_) <- xs]
225 gives rise to a recursive function for the list comprehension, and
226 f turns out to be just a single call to this recursive function.
228 Doing eta on type lambdas is useful too:
230 /\a -> <expr> a ===> <expr>
232 where <expr> doesn't mention a.
233 This is sometimes quite useful, because we can get the sequence:
235 f ab d = let d1 = ...d... in
236 letrec f' b x = ...d...(f' b)... in
240 f.Int b = letrec f' b x = ...dInt...(f' b)... in
245 f' b x = ...dInt...(f' b)...
248 Now we really want to simplify to
252 and then replace all the f's with f.Ints.
254 N.B. We are careful not to partially eta-reduce a sequence of type
255 applications since this breaks the specialiser:
257 /\ a -> f Char# a =NO=> f Char#
260 etaCoreExpr :: CoreExpr -> CoreExpr
263 etaCoreExpr expr@(Lam bndr body)
265 = case etaCoreExpr body of
266 App fun arg | eta_match bndr arg &&
269 other -> expr -- Can't eliminate it, so do nothing at all
271 eta_match (ValBinder v) (VarArg v') = v == v'
272 eta_match (TyBinder tv) (TyArg ty) = tv `elementOfTyVarSet` tyVarsOfType ty
273 eta_match bndr arg = False
275 residual_ok :: CoreExpr -> Bool -- Checks for type application
276 -- and function not one of the
280 = not (eta_match bndr (VarArg v))
281 residual_ok (App fun arg)
282 | eta_match bndr arg = False
283 | otherwise = residual_ok fun
284 residual_ok (Coerce coercion ty body)
285 | eta_match bndr (TyArg ty) = False
286 | otherwise = residual_ok body
288 residual_ok other = False -- Safe answer
289 -- This last clause may seem conservative, but consider:
290 -- primops, constructors, and literals, are impossible here
291 -- let and case are unlikely (the argument would have been floated inside)
292 -- SCCs we probably want to be conservative about (not sure, but it's safe to be)
294 etaCoreExpr expr = expr -- The common case
300 @etaExpandCount@ takes an expression, E, and returns an integer n,
303 E ===> (\x1::t1 x1::t2 ... xn::tn -> E x1 x2 ... xn)
305 is a safe transformation. In particular, the transformation should
306 not cause work to be duplicated, unless it is ``cheap'' (see
307 @manifestlyCheap@ below).
309 @etaExpandCount@ errs on the conservative side. It is always safe to
312 An application of @error@ is special, because it can absorb as many
313 arguments as you care to give it. For this special case we return
314 100, to represent "infinity", which is a bit of a hack.
317 etaExpandCount :: GenCoreExpr bdr Id tyvar uvar
318 -> Int -- Number of extra args you can safely abstract
320 etaExpandCount (Lam (ValBinder _) body)
321 = 1 + etaExpandCount body
323 etaExpandCount (Let bind body)
324 | all manifestlyCheap (rhssOfBind bind)
325 = etaExpandCount body
327 etaExpandCount (Case scrut alts)
328 | manifestlyCheap scrut
329 = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
331 etaExpandCount fun@(Var _) = eta_fun fun
332 etaExpandCount (App fun arg)
333 | notValArg arg = eta_fun fun
334 | otherwise = case etaExpandCount fun of
336 n -> n-1 -- Knock off one
338 etaExpandCount other = 0 -- Give up
341 -- Scc (pessimistic; ToDo),
342 -- Let with non-whnf rhs(s),
343 -- Case with non-whnf scrutinee
345 -----------------------------
346 eta_fun :: GenCoreExpr bdr Id tv uv -- The function
347 -> Int -- How many args it can safely be applied to
349 eta_fun (App fun arg) | notValArg arg = eta_fun fun
352 | isBottomingId v -- Bottoming ids have "infinite arity"
353 = 10000 -- Blargh. Infinite enough!
355 eta_fun expr@(Var v) = idMinArity v
357 eta_fun other = 0 -- Give up
360 @manifestlyCheap@ looks at a Core expression and returns \tr{True} if
361 it is obviously in weak head normal form, or is cheap to get to WHNF.
362 By ``cheap'' we mean a computation we're willing to duplicate in order
363 to bring a couple of lambdas together. The main examples of things
364 which aren't WHNF but are ``cheap'' are:
369 where e, and all the ei are cheap; and
374 where e and b are cheap; and
378 where op is a cheap primitive operator
381 manifestlyCheap :: GenCoreExpr bndr Id tv uv -> Bool
383 manifestlyCheap (Var _) = True
384 manifestlyCheap (Lit _) = True
385 manifestlyCheap (Con _ _) = True
386 manifestlyCheap (SCC _ e) = manifestlyCheap e
387 manifestlyCheap (Coerce _ _ e) = manifestlyCheap e
388 manifestlyCheap (Lam x e) = if isValBinder x then True else manifestlyCheap e
389 manifestlyCheap (Prim op _) = primOpIsCheap op
391 manifestlyCheap (Let bind body)
392 = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
394 manifestlyCheap (Case scrut alts)
395 = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
397 manifestlyCheap other_expr -- look for manifest partial application
398 = case (collectArgs other_expr) of { (fun, _, _, vargs) ->
401 Var f | isBottomingId f -> True -- Application of a function which
402 -- always gives bottom; we treat this as
403 -- a WHNF, because it certainly doesn't
404 -- need to be shared!
407 num_val_args = length vargs
409 num_val_args == 0 || -- Just a type application of
410 -- a variable (f t1 t2 t3)
412 num_val_args < idMinArity f
423 Given a type generate the case alternatives
427 if there's one constructor, or
431 if there's many, or if it's a primitive type.
436 :: Type -- type of RHS
437 -> DemandInfo -- Appropriate demand info
438 -> SmplM InAlts -- result
440 mkIdentityAlts rhs_ty demand_info
441 = case (maybeAppDataTyConExpandingDicts rhs_ty) of
442 Just (tycon, ty_args, [data_con]) -> -- algebraic type suitable for unpacking
444 inst_con_arg_tys = dataConArgTys data_con ty_args
446 newIds inst_con_arg_tys `thenSmpl` \ new_bindees ->
448 new_binders = [ (b, bad_occ_info) | b <- new_bindees ]
452 [(data_con, new_binders, mkCon data_con [] ty_args (map VarArg new_bindees))]
456 _ -> panic "mkIdentityAlts" -- Should never happen; only called for single-constructor types
458 bad_occ_info = ManyOcc 0 -- Non-committal!
461 {- SHOULD NEVER HAPPEN
463 = newId rhs_ty `thenSmpl` \ binder ->
465 binder_w_info = binder `addIdDemandInfo` demand_info
466 -- It's occasionally really worth adding the right demand info. Consider
468 -- where x is sure to be demanded in B
469 -- We will transform to:
471 -- Now suppose that E simplifies to just y; we get
473 -- Because x is sure to be demanded, we can eliminate the case
474 -- even if pedantic-bottoms is on; but we need to have the right
475 -- demand-info on the default branch of the case. That's what
476 -- we are doing here.
478 returnSmpl (PrimAlts [] (BindDefault (binder, bad_occ_info) (Var binder)))
483 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
485 simplIdWantsToBeINLINEd id env
486 = {- We used to arrange that in the final simplification pass we'd switch
487 off all INLINE pragmas, so that we'd inline workers back into the
488 body of their wrapper if the wrapper hadn't itself been inlined by then.
489 This occurred especially for methods in dictionaries.
491 We no longer do this:
492 a) there's a good chance that the exported wrapper will get
493 inlined in some importing scope, in which case we don't
494 want to lose the w/w idea.
496 b) The occurrence analyser must agree about what has an
497 INLINE pragma. Not hard, but delicate.
499 c) if the worker gets inlined we have to tell the wrapepr
500 that it's no longer a wrapper, else the interface file stuff
501 asks for a worker that no longer exists.
503 if switchIsSet env IgnoreINLINEPragma
508 idWantsToBeINLINEd id
510 idMinArity id = case getIdArity id of
515 singleConstructorType :: Type -> Bool
516 singleConstructorType ty
517 = case (maybeAppDataTyConExpandingDicts ty) of
518 Just (tycon, ty_args, [con]) -> True
521 typeOkForCase :: Type -> Bool
523 = case (maybeAppDataTyConExpandingDicts ty) of
525 Just (tycon, ty_args, []) -> False
526 Just (tycon, ty_args, non_null_data_cons) -> True
527 -- Null data cons => type is abstract, which code gen can't
528 -- currently handle. (ToDo: when return-in-heap is universal we
529 -- don't need to worry about this.)