[project @ 1996-07-25 20:43:49 by partain]
[ghc-hetmet.git] / ghc / compiler / simplCore / SimplUtils.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1996
3 %
4 \section[SimplUtils]{The simplifier utilities}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module SimplUtils (
10
11         floatExposesHNF,
12
13         mkTyLamTryingEta, mkValLamTryingEta,
14
15         etaExpandCount,
16
17         mkIdentityAlts,
18
19         simplIdWantsToBeINLINEd,
20
21         type_ok_for_let_to_case
22     ) where
23
24 IMP_Ubiq(){-uitous-}
25 IMPORT_DELOOPER(SmplLoop)               -- paranoia checking
26
27 import BinderInfo
28 import CmdLineOpts      ( SimplifierSwitch(..) )
29 import CoreSyn
30 import CoreUnfold       ( SimpleUnfolding, mkFormSummary, FormSummary(..) )
31 import Id               ( idType, isBottomingId, idWantsToBeINLINEd, dataConArgTys,
32                           getIdArity, GenId{-instance Eq-}
33                         )
34 import IdInfo           ( arityMaybe )
35 import Maybes           ( maybeToBool )
36 import PrelVals         ( augmentId, buildId )
37 import PrimOp           ( primOpIsCheap )
38 import SimplEnv
39 import SimplMonad
40 import Type             ( eqTy, isPrimType, maybeAppDataTyConExpandingDicts, getTyVar_maybe )
41 import TysWiredIn       ( realWorldStateTy )
42 import TyVar            ( GenTyVar{-instance Eq-} )
43 import Util             ( isIn, panic )
44
45 \end{code}
46
47
48 Floating
49 ~~~~~~~~
50 The function @floatExposesHNF@ tells whether let/case floating will
51 expose a head normal form.  It is passed booleans indicating the
52 desired strategy.
53
54 \begin{code}
55 floatExposesHNF
56         :: Bool                 -- Float let(rec)s out of rhs
57         -> Bool                 -- Float cheap primops out of rhs
58         -> Bool                 -- OK to duplicate code
59         -> GenCoreExpr bdr Id tyvar uvar
60         -> Bool
61
62 floatExposesHNF float_lets float_primops ok_to_dup rhs
63   = try rhs
64   where
65     try (Case (Prim _ _) (PrimAlts alts deflt) )
66       | float_primops && (null alts || ok_to_dup)
67       = or (try_deflt deflt : map try_alt alts)
68
69     try (Let bind body) | float_lets = try body
70
71     --    `build g'
72     -- is like a HNF,
73     -- because it *will* become one.
74     -- likewise for `augment g h'
75     --
76     try (App (App (Var bld) _) _)         | bld == buildId   = True
77     try (App (App (App (Var aug) _) _) _) | aug == augmentId = True
78
79     try other = case mkFormSummary other of
80                         VarForm   -> True
81                         ValueForm -> True
82                         other     -> False
83         {- but *not* necessarily "BottomForm"...
84
85            We may want to float a let out of a let to expose WHNFs,
86             but to do that to expose a "bottom" is a Bad Idea:
87             let x = let y = ...
88                     in ...error ...y... --  manifestly bottom using y
89             in ...
90             =/=>
91             let y = ...
92             in let x = ...error ...y...
93                in ...
94
95             as y is only used in case of an error, we do not want
96             to allocate it eagerly as that's a waste.
97         -}
98
99     try_alt (lit,rhs) = try rhs
100
101     try_deflt NoDefault           = False
102     try_deflt (BindDefault _ rhs) = try rhs
103 \end{code}
104
105
106 Eta reduction on ordinary lambdas
107 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
108 We have a go at doing
109
110         \ x y -> f x y  ===>  f
111
112 But we only do this if it gets rid of a whole lambda, not part.
113 The idea is that lambdas are often quite helpful: they indicate
114 head normal forms, so we don't want to chuck them away lightly.
115 But if they expose a simple variable then we definitely win.  Even
116 if they expose a type application we win.  So we check for this special
117 case.
118
119 It does arise:
120
121         f xs = [y | (y,_) <- xs]
122
123 gives rise to a recursive function for the list comprehension, and
124 f turns out to be just a single call to this recursive function.
125
126 \begin{code}
127 mkValLamTryingEta :: [Id]               -- Args to the lambda
128                -> CoreExpr              -- Lambda body
129                -> CoreExpr
130
131 mkValLamTryingEta [] body = body
132
133 mkValLamTryingEta orig_ids body
134   = reduce_it (reverse orig_ids) body
135   where
136     bale_out = mkValLam orig_ids body
137
138     reduce_it [] residual
139       | residual_ok residual = residual
140       | otherwise            = bale_out
141
142     reduce_it (id:ids) (App fun (VarArg arg))
143       | id == arg
144       && not (idType id `eqTy` realWorldStateTy)
145          -- *never* eta-reduce away a PrimIO state token! (WDP 94/11)
146       = reduce_it ids fun
147
148     reduce_it ids other = bale_out
149
150     is_elem = isIn "mkValLamTryingEta"
151
152     -----------
153     residual_ok :: CoreExpr -> Bool     -- Checks for type application
154                                         -- and function not one of the
155                                         -- bound vars
156
157     residual_ok (Var v) = not (v `is_elem` orig_ids)
158                           -- Fun mustn't be one of the bound ids
159     residual_ok (App fun arg)
160       | notValArg arg   = residual_ok fun
161     residual_ok other   = False
162 \end{code}
163
164 Eta expansion
165 ~~~~~~~~~~~~~
166 @etaExpandCount@ takes an expression, E, and returns an integer n,
167 such that
168
169         E  ===>   (\x1::t1 x1::t2 ... xn::tn -> E x1 x2 ... xn)
170
171 is a safe transformation.  In particular, the transformation should
172 not cause work to be duplicated, unless it is ``cheap'' (see
173 @manifestlyCheap@ below).
174
175 @etaExpandCount@ errs on the conservative side.  It is always safe to
176 return 0.
177
178 An application of @error@ is special, because it can absorb as many
179 arguments as you care to give it.  For this special case we return
180 100, to represent "infinity", which is a bit of a hack.
181
182 \begin{code}
183 etaExpandCount :: GenCoreExpr bdr Id tyvar uvar
184                -> Int   -- Number of extra args you can safely abstract
185
186 etaExpandCount (Lam (ValBinder _) body)
187   = 1 + etaExpandCount body
188
189 etaExpandCount (Let bind body)
190   | all manifestlyCheap (rhssOfBind bind)
191   = etaExpandCount body
192
193 etaExpandCount (Case scrut alts)
194   | manifestlyCheap scrut
195   = minimum [etaExpandCount rhs | rhs <- rhssOfAlts alts]
196
197 etaExpandCount fun@(Var _)     = eta_fun fun
198 etaExpandCount (App fun arg)
199   | notValArg arg = eta_fun fun
200   | otherwise     = case etaExpandCount fun of
201                       0 -> 0
202                       n -> n-1  -- Knock off one
203
204 etaExpandCount other = 0    -- Give up
205         -- Lit, Con, Prim,
206         -- non-val Lam,
207         -- Scc (pessimistic; ToDo),
208         -- Let with non-whnf rhs(s),
209         -- Case with non-whnf scrutinee
210
211 -----------------------------
212 eta_fun :: GenCoreExpr bdr Id tv uv -- The function
213         -> Int                      -- How many args it can safely be applied to
214
215 eta_fun (App fun arg) | notValArg arg = eta_fun fun
216
217 eta_fun expr@(Var v)
218   | isBottomingId v             -- Bottoming ids have "infinite arity"
219   = 10000                       -- Blargh.  Infinite enough!
220
221 eta_fun expr@(Var v)
222   | maybeToBool arity_maybe     -- We know the arity
223   = arity
224   where
225     arity_maybe = arityMaybe (getIdArity v)
226     arity       = case arity_maybe of { Just arity -> arity }
227
228 eta_fun other = 0               -- Give up
229 \end{code}
230
231 @manifestlyCheap@ looks at a Core expression and returns \tr{True} if
232 it is obviously in weak head normal form, or is cheap to get to WHNF.
233 By ``cheap'' we mean a computation we're willing to duplicate in order
234 to bring a couple of lambdas together.  The main examples of things
235 which aren't WHNF but are ``cheap'' are:
236
237   *     case e of
238           pi -> ei
239
240         where e, and all the ei are cheap; and
241
242   *     let x = e
243         in b
244
245         where e and b are cheap; and
246
247   *     op x1 ... xn
248
249         where op is a cheap primitive operator
250
251 \begin{code}
252 manifestlyCheap :: GenCoreExpr bndr Id tv uv -> Bool
253
254 manifestlyCheap (Var _)        = True
255 manifestlyCheap (Lit _)        = True
256 manifestlyCheap (Con _ _)      = True
257 manifestlyCheap (SCC _ e)      = manifestlyCheap e
258 manifestlyCheap (Coerce _ _ e) = manifestlyCheap e
259 manifestlyCheap (Lam x e)      = if isValBinder x then True else manifestlyCheap e
260 manifestlyCheap (Prim op _)    = primOpIsCheap op
261
262 manifestlyCheap (Let bind body)
263   = manifestlyCheap body && all manifestlyCheap (rhssOfBind bind)
264
265 manifestlyCheap (Case scrut alts)
266   = manifestlyCheap scrut && all manifestlyCheap (rhssOfAlts alts)
267
268 manifestlyCheap other_expr   -- look for manifest partial application
269   = case (collectArgs other_expr) of { (fun, _, _, vargs) ->
270     case fun of
271
272       Var f | isBottomingId f -> True   -- Application of a function which
273                                         -- always gives bottom; we treat this as
274                                         -- a WHNF, because it certainly doesn't
275                                         -- need to be shared!
276
277       Var f -> let
278                     num_val_args = length vargs
279                in
280                num_val_args == 0 ||     -- Just a type application of
281                                         -- a variable (f t1 t2 t3)
282                                         -- counts as WHNF
283                case (arityMaybe (getIdArity f)) of
284                  Nothing     -> False
285                  Just arity  -> num_val_args < arity
286
287       _ -> False
288     }
289 \end{code}
290
291 Eta reduction on type lambdas
292 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
293 We have a go at doing
294
295         /\a -> <expr> a    ===>     <expr>
296
297 where <expr> doesn't mention a.
298 This is sometimes quite useful, because we can get the sequence:
299
300         f ab d = let d1 = ...d... in
301                  letrec f' b x = ...d...(f' b)... in
302                  f' b
303 specialise ==>
304
305         f.Int b = letrec f' b x = ...dInt...(f' b)... in
306                   f' b
307
308 float ==>
309
310         f' b x = ...dInt...(f' b)...
311         f.Int b = f' b
312
313 Now we really want to simplify to
314
315         f.Int = f'
316
317 and then replace all the f's with f.Ints.
318
319 N.B. We are careful not to partially eta-reduce a sequence of type
320 applications since this breaks the specialiser:
321
322         /\ a -> f Char# a       =NO=> f Char#
323
324 \begin{code}
325 mkTyLamTryingEta :: [TyVar] -> CoreExpr -> CoreExpr
326
327 mkTyLamTryingEta tyvars tylam_body
328   = if
329         tyvars == tyvar_args && -- Same args in same order
330         check_fun fun           -- Function left is ok
331     then
332         -- Eta reduction worked
333         fun
334     else
335         -- The vastly common case
336         mkTyLam tyvars tylam_body
337   where
338     (tyvar_args, fun) = strip_tyvar_args [] tylam_body
339
340     strip_tyvar_args args_so_far tyapp@(App fun (TyArg ty))
341       = case getTyVar_maybe ty of
342           Just tyvar_arg -> strip_tyvar_args (tyvar_arg:args_so_far) fun
343           Nothing        -> (args_so_far, tyapp)
344
345     strip_tyvar_args args_so_far (App _ (UsageArg _))
346       = panic "SimplUtils.mkTyLamTryingEta: strip_tyvar_args UsageArg"
347
348     strip_tyvar_args args_so_far fun
349       = (args_so_far, fun)
350
351     check_fun (Var f) = True     -- Claim: tyvars not mentioned by type of f
352     check_fun other     = False
353 \end{code}
354
355 Let to case
356 ~~~~~~~~~~~
357
358 Given a type generate the case alternatives
359
360         C a b -> C a b
361
362 if there's one constructor, or
363
364         x -> x
365
366 if there's many, or if it's a primitive type.
367
368
369 \begin{code}
370 mkIdentityAlts
371         :: Type         -- type of RHS
372         -> SmplM InAlts         -- result
373
374 mkIdentityAlts rhs_ty
375   | isPrimType rhs_ty
376   = newId rhs_ty        `thenSmpl` \ binder ->
377     returnSmpl (PrimAlts [] (BindDefault (binder, bad_occ_info) (Var binder)))
378
379   | otherwise
380   = case (maybeAppDataTyConExpandingDicts rhs_ty) of
381         Just (tycon, ty_args, [data_con]) ->  -- algebraic type suitable for unpacking
382             let
383                 inst_con_arg_tys = dataConArgTys data_con ty_args
384             in
385             newIds inst_con_arg_tys     `thenSmpl` \ new_bindees ->
386             let
387                 new_binders = [ (b, bad_occ_info) | b <- new_bindees ]
388             in
389             returnSmpl (
390               AlgAlts
391                 [(data_con, new_binders, mkCon data_con [] ty_args (map VarArg new_bindees))]
392                 NoDefault
393             )
394
395         _ -> -- Multi-constructor or abstract algebraic type
396              newId rhs_ty       `thenSmpl` \ binder ->
397              returnSmpl (AlgAlts [] (BindDefault (binder,bad_occ_info) (Var binder)))
398   where
399     bad_occ_info = ManyOcc 0    -- Non-committal!
400 \end{code}
401
402 \begin{code}
403 simplIdWantsToBeINLINEd :: Id -> SimplEnv -> Bool
404
405 simplIdWantsToBeINLINEd id env
406   = if switchIsSet env IgnoreINLINEPragma
407     then False
408     else idWantsToBeINLINEd id
409
410 type_ok_for_let_to_case :: Type -> Bool
411
412 type_ok_for_let_to_case ty
413   = case (maybeAppDataTyConExpandingDicts ty) of
414       Nothing                                   -> False
415       Just (tycon, ty_args, [])                 -> False
416       Just (tycon, ty_args, non_null_data_cons) -> True
417       -- Null data cons => type is abstract
418 \end{code}