2 % (c) The AQUA Project, Glasgow University, 1993-1996
4 \section[SimplUtils]{The simplifier utilities}
7 #include "HsVersions.h"
19 simplIdWantsToBeINLINEd,
21 type_ok_for_let_to_case
25 IMPORT_DELOOPER(SmplLoop) -- paranoia checking
28 import CmdLineOpts ( opt_DoEtaReduction, SimplifierSwitch(..) )
30 import CoreUnfold ( SimpleUnfolding, mkFormSummary, FormSummary(..) )
31 import Id ( idType, isBottomingId, idWantsToBeINLINEd, dataConArgTys,
32 getIdArity, GenId{-instance Eq-}
34 import IdInfo ( ArityInfo(..) )
35 import Maybes ( maybeToBool )
36 import PrelVals ( augmentId, buildId )
37 import PrimOp ( primOpIsCheap )
40 import Type ( tyVarsOfType, isPrimType, maybeAppDataTyConExpandingDicts )
41 import TysWiredIn ( realWorldStateTy )
42 import TyVar ( elementOfTyVarSet,
43 GenTyVar{-instance Eq-} )
44 import Util ( isIn, panic )
51 The function @floatExposesHNF@ tells whether let/case floating will
52 expose a head normal form. It is passed booleans indicating the
57 :: Bool -- Float let(rec)s out of rhs
58 -> Bool -- Float cheap primops out of rhs
59 -> Bool -- OK to duplicate code
60 -> GenCoreExpr bdr Id tyvar uvar
63 floatExposesHNF float_lets float_primops ok_to_dup rhs
66 try (Case (Prim _ _) (PrimAlts alts deflt) )
67 | float_primops && (null alts || ok_to_dup)
68 = or (try_deflt deflt : map try_alt alts)
70 try (Let bind body) | float_lets = try body
74 -- because it *will* become one.
75 -- likewise for `augment g h'
77 try (App (App (Var bld) _) _) | bld == buildId = True
78 try (App (App (App (Var aug) _) _) _) | aug == augmentId = True
80 try other = case mkFormSummary other of
84 {- but *not* necessarily "BottomForm"...
86 We may want to float a let out of a let to expose WHNFs,
87 but to do that to expose a "bottom" is a Bad Idea:
89 in ...error ...y... -- manifestly bottom using y
93 in let x = ...error ...y...
96 as y is only used in case of an error, we do not want
97 to allocate it eagerly as that's a waste.
100 try_alt (lit,rhs) = try rhs
102 try_deflt NoDefault = False
103 try_deflt (BindDefault _ rhs) = try rhs
108 @etaCoreExpr@ trys an eta reduction at the top level of a Core Expr.
110 e.g. \ x y -> f x y ===> f
113 a) Before constructing an Unfolding, to
114 try to make the unfolding smaller;
115 b) In tidyCoreExpr, which is done just before converting to STG.
117 But we only do this if it gets rid of a whole lambda, not part.
118 The idea is that lambdas are often quite helpful: they indicate
119 head normal forms, so we don't want to chuck them away lightly.
120 But if they expose a simple variable then we definitely win. Even
121 if they expose a type application we win. So we check for this special
126 f xs = [y | (y,_) <- xs]
128 gives rise to a recursive function for the list comprehension, and
129 f turns out to be just a single call to this recursive function.
131 Doing eta on type lambdas is useful too:
133 /\a -> <expr> a ===> <expr>
135 where <expr> doesn't mention a.
136 This is sometimes quite useful, because we can get the sequence:
138 f ab d = let d1 = ...d... in
139 letrec f' b x = ...d...(f' b)... in
143 f.Int b = letrec f' b x = ...dInt...(f' b)... in
148 f' b x = ...dInt...(f' b)...
151 Now we really want to simplify to
155 and then replace all the f's with f.Ints.
157 N.B. We are careful not to partially eta-reduce a sequence of type
158 applications since this breaks the specialiser:
160 /\ a -> f Char# a =NO=> f Char#
163 etaCoreExpr :: CoreExpr -> CoreExpr
166 etaCoreExpr expr@(Lam bndr body)
168 = case etaCoreExpr body of
169 App fun arg | eta_match bndr arg &&
172 other -> expr -- Can't eliminate it, so do nothing at all
174 eta_match (ValBinder v) (VarArg v') = v == v'
175 eta_match (TyBinder tv) (TyArg ty) = tv `elementOfTyVarSet` tyVarsOfType ty
176 eta_match bndr arg = False
178 residual_ok :: CoreExpr -> Bool -- Checks for type application
179 -- and function not one of the
183 = not (eta_match bndr (VarArg v))
184 residual_ok (App fun arg)
185 | eta_match bndr arg = False
186 | otherwise = residual_ok fun
187 residual_ok (Coerce coercion ty body)
188 | eta_match bndr (TyArg ty) = False
189 | otherwise = residual_ok body
191 residual_ok other = False -- Safe answer
192 -- This last clause may seem conservative, but consider:
193 -- primops, constructors, and literals, are impossible here
194 -- let and case are unlikely (the argument would have been floated inside)
195 -- SCCs we probably want to be conservative about (not sure, but it's safe to be)
197 etaCoreExpr expr = expr -- The common case
203 @etaExpandCount@ takes an expression, E, and returns an integer n,
206 E ===> (\x1::t1 x1::t2 ... xn::tn -> E x1 x2 ... xn)
208 is a safe transformation. In particular, the transformation should
209 not cause work to be duplicated, unless it is ``cheap'' (see
210 @manifestlyCheap@ below).
212 @etaExpandCount@ errs on the conservative side. It is always safe to
215 An application of @error@ is special, because it can absorb as many
216 arguments as you care to give it. For this special case we return
217 100, to represent "infinity", which is a bit of a hack.
220 etaExpandCount :: GenCoreExpr bdr Id tyvar uvar
221 -> Int -- Number of extra args you can safely abstract
223 etaExpandCount (Lam (ValBinder _) body)
224 = 1 + etaExpandCount body
226 etaExpandCount (Let bind body)
227 | all manifestlyCheap (rhssOfBind bind)
228 = etaExpandCount body
230 etaExpandCount (Case scrut alts)
231 | manifestlyCheap scrut
232 = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
234 etaExpandCount fun@(Var _) = eta_fun fun
235 etaExpandCount (App fun arg)
236 | notValArg arg = eta_fun fun
237 | otherwise = case etaExpandCount fun of
239 n -> n-1 -- Knock off one
241 etaExpandCount other = 0 -- Give up
244 -- Scc (pessimistic; ToDo),
245 -- Let with non-whnf rhs(s),
246 -- Case with non-whnf scrutinee
248 -----------------------------
249 eta_fun :: GenCoreExpr bdr Id tv uv -- The function
250 -> Int -- How many args it can safely be applied to
252 eta_fun (App fun arg) | notValArg arg = eta_fun fun
255 | isBottomingId v -- Bottoming ids have "infinite arity"
256 = 10000 -- Blargh. Infinite enough!
258 eta_fun expr@(Var v) = idMinArity v
260 eta_fun other = 0 -- Give up
263 @manifestlyCheap@ looks at a Core expression and returns \tr{True} if
264 it is obviously in weak head normal form, or is cheap to get to WHNF.
265 By ``cheap'' we mean a computation we're willing to duplicate in order
266 to bring a couple of lambdas together. The main examples of things
267 which aren't WHNF but are ``cheap'' are:
272 where e, and all the ei are cheap; and
277 where e and b are cheap; and
281 where op is a cheap primitive operator
284 manifestlyCheap :: GenCoreExpr bndr Id tv uv -> Bool
286 manifestlyCheap (Var _) = True
287 manifestlyCheap (Lit _) = True
288 manifestlyCheap (Con _ _) = True
289 manifestlyCheap (SCC _ e) = manifestlyCheap e
290 manifestlyCheap (Coerce _ _ e) = manifestlyCheap e
291 manifestlyCheap (Lam x e) = if isValBinder x then True else manifestlyCheap e
292 manifestlyCheap (Prim op _) = primOpIsCheap op
294 manifestlyCheap (Let bind body)
295 = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
297 manifestlyCheap (Case scrut alts)
298 = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
300 manifestlyCheap other_expr -- look for manifest partial application
301 = case (collectArgs other_expr) of { (fun, _, _, vargs) ->
304 Var f | isBottomingId f -> True -- Application of a function which
305 -- always gives bottom; we treat this as
306 -- a WHNF, because it certainly doesn't
307 -- need to be shared!
310 num_val_args = length vargs
312 num_val_args == 0 || -- Just a type application of
313 -- a variable (f t1 t2 t3)
315 num_val_args < idMinArity f
326 Given a type generate the case alternatives
330 if there's one constructor, or
334 if there's many, or if it's a primitive type.
339 :: Type -- type of RHS
340 -> SmplM InAlts -- result
342 mkIdentityAlts rhs_ty
344 = newId rhs_ty `thenSmpl` \ binder ->
345 returnSmpl (PrimAlts [] (BindDefault (binder, bad_occ_info) (Var binder)))
348 = case (maybeAppDataTyConExpandingDicts rhs_ty) of
349 Just (tycon, ty_args, [data_con]) -> -- algebraic type suitable for unpacking
351 inst_con_arg_tys = dataConArgTys data_con ty_args
353 newIds inst_con_arg_tys `thenSmpl` \ new_bindees ->
355 new_binders = [ (b, bad_occ_info) | b <- new_bindees ]
359 [(data_con, new_binders, mkCon data_con [] ty_args (map VarArg new_bindees))]
363 _ -> -- Multi-constructor or abstract algebraic type
364 newId rhs_ty `thenSmpl` \ binder ->
365 returnSmpl (AlgAlts [] (BindDefault (binder,bad_occ_info) (Var binder)))
367 bad_occ_info = ManyOcc 0 -- Non-committal!
371 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
373 simplIdWantsToBeINLINEd id env
374 = if switchIsSet env IgnoreINLINEPragma
376 else idWantsToBeINLINEd id
378 idMinArity id = case getIdArity id of
383 type_ok_for_let_to_case :: Type -> Bool
385 type_ok_for_let_to_case ty
386 = case (maybeAppDataTyConExpandingDicts ty) of
388 Just (tycon, ty_args, []) -> False
389 Just (tycon, ty_args, non_null_data_cons) -> True
390 -- Null data cons => type is abstract