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
28 import CoreUtils ( manifestlyWHNF )
29 import Id ( idType, isBottomingId, getIdArity )
30 import IdInfo ( arityMaybe )
31 import Maybes ( maybeToBool )
32 import PrelInfo ( augmentId, buildId, realWorldStateTy )
35 import Type ( isPrimType, maybeAppDataTyCon, getTyVar_maybe )
36 import Util ( isIn, panic )
38 primOpIsCheap = panic "SimplUtils. (ToDo)"
44 The function @floatExposesHNF@ tells whether let/case floating will
45 expose a head normal form. It is passed booleans indicating the
50 :: Bool -- Float let(rec)s out of rhs
51 -> Bool -- Float cheap primops out of rhs
52 -> Bool -- OK to duplicate code
56 floatExposesHNF float_lets float_primops ok_to_dup rhs
59 try (Case (Prim _ _ _) (PrimAlts alts deflt) )
60 | float_primops && (null alts || ok_to_dup)
61 = or (try_deflt deflt : map try_alt alts)
63 try (Let bind body) | float_lets = try body
67 -- because it *will* become one.
68 -- likewise for `augment g h'
70 try (App (App (Var bld) _) _) | bld == buildId = True
71 try (App (App (App (Var aug) _) _) _) | aug == augmentId = True
73 try other = manifestlyWHNF other
74 {- but *not* necessarily "manifestlyBottom other"...
76 We may want to float a let out of a let to expose WHNFs,
77 but to do that to expose a "bottom" is a Bad Idea:
79 in ...error ...y... -- manifestly bottom using y
83 in let x = ...error ...y...
86 as y is only used in case of an error, we do not want
87 to allocate it eagerly as that's a waste.
90 try_alt (lit,rhs) = try rhs
92 try_deflt NoDefault = False
93 try_deflt (BindDefault _ rhs) = try rhs
97 Eta reduction on ordinary lambdas
98 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
101 \ x y -> f x y ===> f
103 But we only do this if it gets rid of a whole lambda, not part.
104 The idea is that lambdas are often quite helpful: they indicate
105 head normal forms, so we don't want to chuck them away lightly.
106 But if they expose a simple variable then we definitely win. Even
107 if they expose a type application we win. So we check for this special
112 f xs = [y | (y,_) <- xs]
114 gives rise to a recursive function for the list comprehension, and
115 f turns out to be just a single call to this recursive function.
118 mkValLamTryingEta :: [Id] -- Args to the lambda
119 -> CoreExpr -- Lambda body
122 mkValLamTryingEta [] body = body
124 mkValLamTryingEta orig_ids body
125 = reduce_it (reverse orig_ids) body
127 bale_out = mkValLam orig_ids body
129 reduce_it [] residual
130 | residual_ok residual = residual
131 | otherwise = bale_out
133 reduce_it (id:ids) (App fun (VarArg arg))
135 && idType id /= realWorldStateTy
136 -- *never* eta-reduce away a PrimIO state token! (WDP 94/11)
139 reduce_it ids other = bale_out
141 is_elem = isIn "mkValLamTryingEta"
144 residual_ok :: CoreExpr -> Bool -- Checks for type application
145 -- and function not one of the
148 residual_ok (Var v) = not (v `is_elem` orig_ids)
149 -- Fun mustn't be one of the bound ids
150 residual_ok (App fun arg)
151 | notValArg arg = residual_ok fun
152 residual_ok other = False
157 @etaExpandCount@ takes an expression, E, and returns an integer n,
160 E ===> (\x1::t1 x1::t2 ... xn::tn -> E x1 x2 ... xn)
162 is a safe transformation. In particular, the transformation should
163 not cause work to be duplicated, unless it is ``cheap'' (see
164 @manifestlyCheap@ below).
166 @etaExpandCount@ errs on the conservative side. It is always safe to
169 An application of @error@ is special, because it can absorb as many
170 arguments as you care to give it. For this special case we return
171 100, to represent "infinity", which is a bit of a hack.
174 etaExpandCount :: GenCoreExpr bdr Id
175 -> Int -- Number of extra args you can safely abstract
177 etaExpandCount (Lam (ValBinder _) body)
178 = 1 + etaExpandCount body
180 etaExpandCount (Let bind body)
181 | all manifestlyCheap (rhssOfBind bind)
182 = etaExpandCount body
184 etaExpandCount (Case scrut alts)
185 | manifestlyCheap scrut
186 = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
188 etaExpandCount fun@(Var _) = eta_fun fun
189 etaExpandCount (App fun arg)
190 | notValArg arg = eta_fun fun
191 | otherwise = case etaExpandCount fun of
193 n -> n-1 -- Knock off one
195 etaExpandCount other = 0 -- Give up
198 -- Scc (pessimistic; ToDo),
199 -- Let with non-whnf rhs(s),
200 -- Case with non-whnf scrutinee
202 -----------------------------
203 eta_fun :: GenCoreExpr bdr Id -- The function
204 -> Int -- How many args it can safely be applied to
206 eta_fun (App fun arg) | notValArg arg = eta_fun fun
209 | isBottomingId v -- Bottoming ids have "infinite arity"
210 = 10000 -- Blargh. Infinite enough!
213 | maybeToBool arity_maybe -- We know the arity
216 arity_maybe = arityMaybe (getIdArity v)
217 arity = case arity_maybe of { Just arity -> arity }
219 eta_fun other = 0 -- Give up
222 @manifestlyCheap@ looks at a Core expression and returns \tr{True} if
223 it is obviously in weak head normal form, or is cheap to get to WHNF.
224 By ``cheap'' we mean a computation we're willing to duplicate in order
225 to bring a couple of lambdas together. The main examples of things
226 which aren't WHNF but are ``cheap'' are:
231 where e, and all the ei are cheap; and
236 where e and b are cheap; and
240 where op is a cheap primitive operator
243 manifestlyCheap :: GenCoreExpr bndr Id -> Bool
245 manifestlyCheap (Var _) = True
246 manifestlyCheap (Lit _) = True
247 manifestlyCheap (Con _ _ _) = True
248 manifestlyCheap (SCC _ e) = manifestlyCheap e
250 manifestlyCheap (Lam (ValBinder _) _) = True
251 manifestlyCheap (Lam other_binder e) = manifestlyCheap e
253 manifestlyCheap (Prim op _ _) = primOpIsCheap op
255 manifestlyCheap (Let bind body)
256 = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
258 manifestlyCheap (Case scrut alts)
259 = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
261 manifestlyCheap other_expr -- look for manifest partial application
262 = case (collectArgs other_expr) of { (fun, args) ->
265 Var f | isBottomingId f -> True -- Application of a function which
266 -- always gives bottom; we treat this as
267 -- a WHNF, because it certainly doesn't
268 -- need to be shared!
271 num_val_args = numValArgs args
273 num_val_args == 0 || -- Just a type application of
274 -- a variable (f t1 t2 t3)
276 case (arityMaybe (getIdArity f)) of
278 Just arity -> num_val_args < arity
284 Eta reduction on type lambdas
285 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
286 We have a go at doing
288 /\a -> <expr> a ===> <expr>
290 where <expr> doesn't mention a.
291 This is sometimes quite useful, because we can get the sequence:
293 f ab d = let d1 = ...d... in
294 letrec f' b x = ...d...(f' b)... in
298 f.Int b = letrec f' b x = ...dInt...(f' b)... in
303 f' b x = ...dInt...(f' b)...
306 Now we really want to simplify to
310 and then replace all the f's with f.Ints.
312 N.B. We are careful not to partially eta-reduce a sequence of type
313 applications since this breaks the specialiser:
315 /\ a -> f Char# a =NO=> f Char#
318 mkTyLamTryingEta :: [TyVar] -> CoreExpr -> CoreExpr
320 mkTyLamTryingEta tyvars tylam_body
322 tyvars == tyvar_args && -- Same args in same order
323 check_fun fun -- Function left is ok
325 -- Eta reduction worked
328 -- The vastly common case
329 mkTyLam tyvars tylam_body
331 (tyvar_args, fun) = strip_tyvar_args [] tylam_body
333 strip_tyvar_args args_so_far tyapp@(App fun (TyArg ty))
334 = case getTyVar_maybe ty of
335 Just tyvar_arg -> strip_tyvar_args (tyvar_arg:args_so_far) fun
336 Nothing -> (args_so_far, tyapp)
338 strip_tyvar_args args_so_far (App _ (UsageArg _))
339 = panic "SimplUtils.mkTyLamTryingEta: strip_tyvar_args UsageArg"
341 strip_tyvar_args args_so_far fun
344 check_fun (Var f) = True -- Claim: tyvars not mentioned by type of f
345 check_fun other = False
351 Given a type generate the case alternatives
355 if there's one constructor, or
359 if there's many, or if it's a primitive type.
364 :: Type -- type of RHS
365 -> SmplM InAlts -- result
367 mkIdentityAlts rhs_ty
369 = newId rhs_ty `thenSmpl` \ binder ->
370 returnSmpl (PrimAlts [] (BindDefault (binder, bad_occ_info) (Var binder)))
373 = case (maybeAppDataTyCon rhs_ty) of
374 Just (tycon, ty_args, [data_con]) -> -- algebraic type suitable for unpacking
376 (_,inst_con_arg_tys,_) = getInstantiatedDataConSig data_con ty_args
378 newIds inst_con_arg_tys `thenSmpl` \ new_bindees ->
380 new_binders = [ (b, bad_occ_info) | b <- new_bindees ]
384 [(data_con, new_binders, Con data_con ty_args (map VarArg new_bindees))]
388 _ -> -- Multi-constructor or abstract algebraic type
389 newId rhs_ty `thenSmpl` \ binder ->
390 returnSmpl (AlgAlts [] (BindDefault (binder,bad_occ_info) (Var binder)))
392 bad_occ_info = ManyOcc 0 -- Non-committal!
396 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
398 simplIdWantsToBeINLINEd id env
399 = if switchIsSet env IgnoreINLINEPragma
401 else idWantsToBeINLINEd id
403 type_ok_for_let_to_case :: Type -> Bool
405 type_ok_for_let_to_case ty
406 = case (maybeAppDataTyCon ty) of
408 Just (tycon, ty_args, []) -> False
409 Just (tycon, ty_args, non_null_data_cons) -> True
410 -- Null data cons => type is abstract