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