2 % (c) The AQUA Project, Glasgow University, 1993-1996
4 \section[SimplUtils]{The simplifier utilities}
7 #include "HsVersions.h"
13 mkTyLamTryingEta, mkValLamTryingEta,
19 simplIdWantsToBeINLINEd,
21 type_ok_for_let_to_case
27 import CmdLineOpts ( SimplifierSwitch(..) )
29 import CoreUtils ( manifestlyWHNF )
30 import Id ( idType, isBottomingId, idWantsToBeINLINEd, dataConArgTys,
31 getIdArity, GenId{-instance Eq-}
33 import IdInfo ( arityMaybe )
34 import Maybes ( maybeToBool )
35 import PrelVals ( augmentId, buildId )
36 import PrimOp ( primOpIsCheap )
39 import Type ( eqTy, isPrimType, maybeAppDataTyConExpandingDicts, getTyVar_maybe )
40 import TysWiredIn ( realWorldStateTy )
41 import TyVar ( GenTyVar{-instance Eq-} )
42 import Util ( isIn, panic )
49 The function @floatExposesHNF@ tells whether let/case floating will
50 expose a head normal form. It is passed booleans indicating the
55 :: Bool -- Float let(rec)s out of rhs
56 -> Bool -- Float cheap primops out of rhs
57 -> Bool -- OK to duplicate code
58 -> GenCoreExpr bdr Id tyvar uvar
61 floatExposesHNF float_lets float_primops ok_to_dup rhs
64 try (Case (Prim _ _) (PrimAlts alts deflt) )
65 | float_primops && (null alts || ok_to_dup)
66 = or (try_deflt deflt : map try_alt alts)
68 try (Let bind body) | float_lets = try body
72 -- because it *will* become one.
73 -- likewise for `augment g h'
75 try (App (App (Var bld) _) _) | bld == buildId = True
76 try (App (App (App (Var aug) _) _) _) | aug == augmentId = True
78 try other = manifestlyWHNF other
79 {- but *not* necessarily "manifestlyBottom other"...
81 We may want to float a let out of a let to expose WHNFs,
82 but to do that to expose a "bottom" is a Bad Idea:
84 in ...error ...y... -- manifestly bottom using y
88 in let x = ...error ...y...
91 as y is only used in case of an error, we do not want
92 to allocate it eagerly as that's a waste.
95 try_alt (lit,rhs) = try rhs
97 try_deflt NoDefault = False
98 try_deflt (BindDefault _ rhs) = try rhs
102 Eta reduction on ordinary lambdas
103 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
104 We have a go at doing
106 \ x y -> f x y ===> f
108 But we only do this if it gets rid of a whole lambda, not part.
109 The idea is that lambdas are often quite helpful: they indicate
110 head normal forms, so we don't want to chuck them away lightly.
111 But if they expose a simple variable then we definitely win. Even
112 if they expose a type application we win. So we check for this special
117 f xs = [y | (y,_) <- xs]
119 gives rise to a recursive function for the list comprehension, and
120 f turns out to be just a single call to this recursive function.
123 mkValLamTryingEta :: [Id] -- Args to the lambda
124 -> CoreExpr -- Lambda body
127 mkValLamTryingEta [] body = body
129 mkValLamTryingEta orig_ids body
130 = reduce_it (reverse orig_ids) body
132 bale_out = mkValLam orig_ids body
134 reduce_it [] residual
135 | residual_ok residual = residual
136 | otherwise = bale_out
138 reduce_it (id:ids) (App fun (VarArg arg))
140 && not (idType id `eqTy` realWorldStateTy)
141 -- *never* eta-reduce away a PrimIO state token! (WDP 94/11)
144 reduce_it ids other = bale_out
146 is_elem = isIn "mkValLamTryingEta"
149 residual_ok :: CoreExpr -> Bool -- Checks for type application
150 -- and function not one of the
153 residual_ok (Var v) = not (v `is_elem` orig_ids)
154 -- Fun mustn't be one of the bound ids
155 residual_ok (App fun arg)
156 | notValArg arg = residual_ok fun
157 residual_ok other = False
162 @etaExpandCount@ takes an expression, E, and returns an integer n,
165 E ===> (\x1::t1 x1::t2 ... xn::tn -> E x1 x2 ... xn)
167 is a safe transformation. In particular, the transformation should
168 not cause work to be duplicated, unless it is ``cheap'' (see
169 @manifestlyCheap@ below).
171 @etaExpandCount@ errs on the conservative side. It is always safe to
174 An application of @error@ is special, because it can absorb as many
175 arguments as you care to give it. For this special case we return
176 100, to represent "infinity", which is a bit of a hack.
179 etaExpandCount :: GenCoreExpr bdr Id tyvar uvar
180 -> Int -- Number of extra args you can safely abstract
182 etaExpandCount (Lam (ValBinder _) body)
183 = 1 + etaExpandCount body
185 etaExpandCount (Let bind body)
186 | all manifestlyCheap (rhssOfBind bind)
187 = etaExpandCount body
189 etaExpandCount (Case scrut alts)
190 | manifestlyCheap scrut
191 = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
193 etaExpandCount fun@(Var _) = eta_fun fun
194 etaExpandCount (App fun arg)
195 | notValArg arg = eta_fun fun
196 | otherwise = case etaExpandCount fun of
198 n -> n-1 -- Knock off one
200 etaExpandCount other = 0 -- Give up
203 -- Scc (pessimistic; ToDo),
204 -- Let with non-whnf rhs(s),
205 -- Case with non-whnf scrutinee
207 -----------------------------
208 eta_fun :: GenCoreExpr bdr Id tv uv -- The function
209 -> Int -- How many args it can safely be applied to
211 eta_fun (App fun arg) | notValArg arg = eta_fun fun
214 | isBottomingId v -- Bottoming ids have "infinite arity"
215 = 10000 -- Blargh. Infinite enough!
218 | maybeToBool arity_maybe -- We know the arity
221 arity_maybe = arityMaybe (getIdArity v)
222 arity = case arity_maybe of { Just arity -> arity }
224 eta_fun other = 0 -- Give up
227 @manifestlyCheap@ looks at a Core expression and returns \tr{True} if
228 it is obviously in weak head normal form, or is cheap to get to WHNF.
229 By ``cheap'' we mean a computation we're willing to duplicate in order
230 to bring a couple of lambdas together. The main examples of things
231 which aren't WHNF but are ``cheap'' are:
236 where e, and all the ei are cheap; and
241 where e and b are cheap; and
245 where op is a cheap primitive operator
248 manifestlyCheap :: GenCoreExpr bndr Id tv uv -> Bool
250 manifestlyCheap (Var _) = True
251 manifestlyCheap (Lit _) = True
252 manifestlyCheap (Con _ _) = True
253 manifestlyCheap (SCC _ e) = manifestlyCheap e
254 manifestlyCheap (Coerce _ _ e) = manifestlyCheap e
255 manifestlyCheap (Lam x e) = if isValBinder x then True else manifestlyCheap e
256 manifestlyCheap (Prim op _) = primOpIsCheap op
258 manifestlyCheap (Let bind body)
259 = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
261 manifestlyCheap (Case scrut alts)
262 = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
264 manifestlyCheap other_expr -- look for manifest partial application
265 = case (collectArgs other_expr) of { (fun, _, _, vargs) ->
268 Var f | isBottomingId f -> True -- Application of a function which
269 -- always gives bottom; we treat this as
270 -- a WHNF, because it certainly doesn't
271 -- need to be shared!
274 num_val_args = length vargs
276 num_val_args == 0 || -- Just a type application of
277 -- a variable (f t1 t2 t3)
279 case (arityMaybe (getIdArity f)) of
281 Just arity -> num_val_args < arity
287 Eta reduction on type lambdas
288 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
289 We have a go at doing
291 /\a -> <expr> a ===> <expr>
293 where <expr> doesn't mention a.
294 This is sometimes quite useful, because we can get the sequence:
296 f ab d = let d1 = ...d... in
297 letrec f' b x = ...d...(f' b)... in
301 f.Int b = letrec f' b x = ...dInt...(f' b)... in
306 f' b x = ...dInt...(f' b)...
309 Now we really want to simplify to
313 and then replace all the f's with f.Ints.
315 N.B. We are careful not to partially eta-reduce a sequence of type
316 applications since this breaks the specialiser:
318 /\ a -> f Char# a =NO=> f Char#
321 mkTyLamTryingEta :: [TyVar] -> CoreExpr -> CoreExpr
323 mkTyLamTryingEta tyvars tylam_body
325 tyvars == tyvar_args && -- Same args in same order
326 check_fun fun -- Function left is ok
328 -- Eta reduction worked
331 -- The vastly common case
332 mkTyLam tyvars tylam_body
334 (tyvar_args, fun) = strip_tyvar_args [] tylam_body
336 strip_tyvar_args args_so_far tyapp@(App fun (TyArg ty))
337 = case getTyVar_maybe ty of
338 Just tyvar_arg -> strip_tyvar_args (tyvar_arg:args_so_far) fun
339 Nothing -> (args_so_far, tyapp)
341 strip_tyvar_args args_so_far (App _ (UsageArg _))
342 = panic "SimplUtils.mkTyLamTryingEta: strip_tyvar_args UsageArg"
344 strip_tyvar_args args_so_far fun
347 check_fun (Var f) = True -- Claim: tyvars not mentioned by type of f
348 check_fun other = False
354 Given a type generate the case alternatives
358 if there's one constructor, or
362 if there's many, or if it's a primitive type.
367 :: Type -- type of RHS
368 -> SmplM InAlts -- result
370 mkIdentityAlts rhs_ty
372 = newId rhs_ty `thenSmpl` \ binder ->
373 returnSmpl (PrimAlts [] (BindDefault (binder, bad_occ_info) (Var binder)))
376 = case (maybeAppDataTyConExpandingDicts rhs_ty) of
377 Just (tycon, ty_args, [data_con]) -> -- algebraic type suitable for unpacking
379 inst_con_arg_tys = dataConArgTys data_con ty_args
381 newIds inst_con_arg_tys `thenSmpl` \ new_bindees ->
383 new_binders = [ (b, bad_occ_info) | b <- new_bindees ]
387 [(data_con, new_binders, mkCon data_con [] ty_args (map VarArg new_bindees))]
391 _ -> -- Multi-constructor or abstract algebraic type
392 newId rhs_ty `thenSmpl` \ binder ->
393 returnSmpl (AlgAlts [] (BindDefault (binder,bad_occ_info) (Var binder)))
395 bad_occ_info = ManyOcc 0 -- Non-committal!
399 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
401 simplIdWantsToBeINLINEd id env
402 = if switchIsSet env IgnoreINLINEPragma
404 else idWantsToBeINLINEd id
406 type_ok_for_let_to_case :: Type -> Bool
408 type_ok_for_let_to_case ty
409 = case (maybeAppDataTyConExpandingDicts ty) of
411 Just (tycon, ty_args, []) -> False
412 Just (tycon, ty_args, non_null_data_cons) -> True
413 -- Null data cons => type is abstract