Add comment.
[matthijs/master-project/cλash.git] / cλash / CLasH / Normalize.hs
1 {-# LANGUAGE PackageImports #-}
2 --
3 -- Functions to bring a Core expression in normal form. This module provides a
4 -- top level function "normalize", and defines the actual transformation passes that
5 -- are performed.
6 --
7 module CLasH.Normalize (getNormalized, normalizeExpr, splitNormalized) where
8
9 -- Standard modules
10 import Debug.Trace
11 import qualified Maybe
12 import qualified List
13 import qualified "transformers" Control.Monad.Trans as Trans
14 import qualified Control.Monad as Monad
15 import qualified Control.Monad.Trans.Writer as Writer
16 import qualified Data.Monoid as Monoid
17
18 -- GHC API
19 import CoreSyn
20 import qualified CoreUtils
21 import qualified Type
22 import qualified Id
23 import qualified Var
24 import qualified VarSet
25 import qualified CoreFVs
26 import qualified MkCore
27 import Outputable ( showSDoc, ppr, nest )
28
29 -- Local imports
30 import CLasH.Normalize.NormalizeTypes
31 import CLasH.Translator.TranslatorTypes
32 import CLasH.Normalize.NormalizeTools
33 import qualified CLasH.Utils as Utils
34 import CLasH.Utils.Core.CoreTools
35 import CLasH.Utils.Core.BinderTools
36 import CLasH.Utils.Pretty
37
38 --------------------------------
39 -- Start of transformations
40 --------------------------------
41
42 --------------------------------
43 -- η abstraction
44 --------------------------------
45 eta, etatop :: Transform
46 eta expr | is_fun expr && not (is_lam expr) = do
47   let arg_ty = (fst . Type.splitFunTy . CoreUtils.exprType) expr
48   id <- Trans.lift $ mkInternalVar "param" arg_ty
49   change (Lam id (App expr (Var id)))
50 -- Leave all other expressions unchanged
51 eta e = return e
52 etatop = notappargs ("eta", eta)
53
54 --------------------------------
55 -- β-reduction
56 --------------------------------
57 beta, betatop :: Transform
58 -- Substitute arg for x in expr. For value lambda's, also clone before
59 -- substitution.
60 beta (App (Lam x expr) arg) | CoreSyn.isTyVar x = setChanged >> substitute x arg expr
61                             | otherwise      = setChanged >> substitute_clone x arg expr
62 -- Propagate the application into the let
63 beta (App (Let binds expr) arg) = change $ Let binds (App expr arg)
64 -- Propagate the application into each of the alternatives
65 beta (App (Case scrut b ty alts) arg) = change $ Case scrut b ty' alts'
66   where 
67     alts' = map (\(con, bndrs, expr) -> (con, bndrs, (App expr arg))) alts
68     ty' = CoreUtils.applyTypeToArg ty arg
69 -- Leave all other expressions unchanged
70 beta expr = return expr
71 -- Perform this transform everywhere
72 betatop = everywhere ("beta", beta)
73
74 --------------------------------
75 -- Cast propagation
76 --------------------------------
77 -- Try to move casts as much downward as possible.
78 castprop, castproptop :: Transform
79 castprop (Cast (Let binds expr) ty) = change $ Let binds (Cast expr ty)
80 castprop expr@(Cast (Case scrut b _ alts) ty) = change (Case scrut b ty alts')
81   where
82     alts' = map (\(con, bndrs, expr) -> (con, bndrs, (Cast expr ty))) alts
83 -- Leave all other expressions unchanged
84 castprop expr = return expr
85 -- Perform this transform everywhere
86 castproptop = everywhere ("castprop", castprop)
87
88 --------------------------------
89 -- Cast simplification. Mostly useful for state packing and unpacking, but
90 -- perhaps for others as well.
91 --------------------------------
92 castsimpl, castsimpltop :: Transform
93 castsimpl expr@(Cast val ty) = do
94   -- Don't extract values that are already simpl
95   local_var <- Trans.lift $ is_local_var val
96   -- Don't extract values that are not representable, to prevent loops with
97   -- inlinenonrep
98   repr <- isRepr val
99   if (not local_var) && repr
100     then do
101       -- Generate a binder for the expression
102       id <- Trans.lift $ mkBinderFor val "castval"
103       -- Extract the expression
104       change $ Let (NonRec id val) (Cast (Var id) ty)
105     else
106       return expr
107 -- Leave all other expressions unchanged
108 castsimpl expr = return expr
109 -- Perform this transform everywhere
110 castsimpltop = everywhere ("castsimpl", castsimpl)
111
112
113 --------------------------------
114 -- Lambda simplication
115 --------------------------------
116 -- Ensure that a lambda always evaluates to a let expressions or a simple
117 -- variable reference.
118 lambdasimpl, lambdasimpltop :: Transform
119 -- Don't simplify a lambda that evaluates to let, since this is already
120 -- normal form (and would cause infinite loops).
121 lambdasimpl expr@(Lam _ (Let _ _)) = return expr
122 -- Put the of a lambda in its own binding, but not when the expression is
123 -- already a local variable, or not representable (to prevent loops with
124 -- inlinenonrep).
125 lambdasimpl expr@(Lam bndr res) = do
126   repr <- isRepr res
127   local_var <- Trans.lift $ is_local_var res
128   if not local_var && repr
129     then do
130       id <- Trans.lift $ mkBinderFor res "res"
131       change $ Lam bndr (Let (NonRec id res) (Var id))
132     else
133       -- If the result is already a local var or not representable, don't
134       -- extract it.
135       return expr
136
137 -- Leave all other expressions unchanged
138 lambdasimpl expr = return expr
139 -- Perform this transform everywhere
140 lambdasimpltop = everywhere ("lambdasimpl", lambdasimpl)
141
142 --------------------------------
143 -- let derecursification
144 --------------------------------
145 letderec, letderectop :: Transform
146 letderec expr@(Let (Rec binds) res) = case liftable of
147   -- Nothing is liftable, just return
148   [] -> return expr
149   -- Something can be lifted, generate a new let expression
150   _ -> change $ mkNonRecLets liftable (Let (Rec nonliftable) res)
151   where
152     -- Make a list of all the binders bound in this recursive let
153     bndrs = map fst binds
154     -- See which bindings are liftable
155     (liftable, nonliftable) = List.partition canlift binds
156     -- Any expression that does not use any of the binders in this recursive let
157     -- can be lifted into a nonrec let. It can't use its own binder either,
158     -- since that would mean the binding is self-recursive and should be in a
159     -- single bind recursive let.
160     canlift (bndr, e) = not $ expr_uses_binders bndrs e
161 -- Leave all other expressions unchanged
162 letderec expr = return expr
163 -- Perform this transform everywhere
164 letderectop = everywhere ("letderec", letderec)
165
166 --------------------------------
167 -- let simplification
168 --------------------------------
169 letsimpl, letsimpltop :: Transform
170 -- Don't simplify a let that evaluates to another let, since this is already
171 -- normal form (and would cause infinite loops with letflat below).
172 letsimpl expr@(Let _ (Let _ _)) = return expr
173 -- Put the "in ..." value of a let in its own binding, but not when the
174 -- expression is already a local variable, or not representable (to prevent loops with inlinenonrep).
175 letsimpl expr@(Let binds res) = do
176   repr <- isRepr res
177   local_var <- Trans.lift $ is_local_var res
178   if not local_var && repr
179     then do
180       -- If the result is not a local var already (to prevent loops with
181       -- ourselves), extract it.
182       id <- Trans.lift $ mkBinderFor res "foo"
183       change $ Let binds (Let (NonRec id  res) (Var id))
184     else
185       -- If the result is already a local var, don't extract it.
186       return expr
187
188 -- Leave all other expressions unchanged
189 letsimpl expr = return expr
190 -- Perform this transform everywhere
191 letsimpltop = everywhere ("letsimpl", letsimpl)
192
193 --------------------------------
194 -- let flattening
195 --------------------------------
196 -- Takes a let that binds another let, and turns that into two nested lets.
197 -- e.g., from:
198 -- let b = (let b' = expr' in res') in res
199 -- to:
200 -- let b' = expr' in (let b = res' in res)
201 letflat, letflattop :: Transform
202 -- Turn a nonrec let that binds a let into two nested lets.
203 letflat (Let (NonRec b (Let binds  res')) res) = 
204   change $ Let binds (Let (NonRec b res') res)
205 letflat (Let (Rec binds) expr) = do
206   -- Flatten each binding.
207   binds' <- Utils.concatM $ Monad.mapM flatbind binds
208   -- Return the new let. We don't use change here, since possibly nothing has
209   -- changed. If anything has changed, flatbind has already flagged that
210   -- change.
211   return $ Let (Rec binds') expr
212   where
213     -- Turns a binding of a let into a multiple bindings, or any other binding
214     -- into a list with just that binding
215     flatbind :: (CoreBndr, CoreExpr) -> TransformMonad [(CoreBndr, CoreExpr)]
216     flatbind (b, Let (Rec binds) expr) = change ((b, expr):binds)
217     flatbind (b, Let (NonRec b' expr') expr) = change [(b, expr), (b', expr')]
218     flatbind (b, expr) = return [(b, expr)]
219 -- Leave all other expressions unchanged
220 letflat expr = return expr
221 -- Perform this transform everywhere
222 letflattop = everywhere ("letflat", letflat)
223
224 --------------------------------
225 -- empty let removal
226 --------------------------------
227 -- Remove empty (recursive) lets
228 letremove, letremovetop :: Transform
229 letremove (Let (Rec []) res) = change res
230 -- Leave all other expressions unchanged
231 letremove expr = return expr
232 -- Perform this transform everywhere
233 letremovetop = everywhere ("letremove", letremove)
234
235 --------------------------------
236 -- Simple let binding removal
237 --------------------------------
238 -- Remove a = b bindings from let expressions everywhere
239 letremovesimpletop :: Transform
240 letremovesimpletop = everywhere ("letremovesimple", inlinebind (\(b, e) -> Trans.lift $ is_local_var e))
241
242 --------------------------------
243 -- Unused let binding removal
244 --------------------------------
245 letremoveunused, letremoveunusedtop :: Transform
246 letremoveunused expr@(Let (NonRec b bound) res) = do
247   let used = expr_uses_binders [b] res
248   if used
249     then return expr
250     else change res
251 letremoveunused expr@(Let (Rec binds) res) = do
252   -- Filter out all unused binds.
253   let binds' = filter dobind binds
254   -- Only set the changed flag if binds got removed
255   changeif (length binds' /= length binds) (Let (Rec binds') res)
256     where
257       bound_exprs = map snd binds
258       -- For each bind check if the bind is used by res or any of the bound
259       -- expressions
260       dobind (bndr, _) = any (expr_uses_binders [bndr]) (res:bound_exprs)
261 -- Leave all other expressions unchanged
262 letremoveunused expr = return expr
263 letremoveunusedtop = everywhere ("letremoveunused", letremoveunused)
264
265 {-
266 --------------------------------
267 -- Identical let binding merging
268 --------------------------------
269 -- Merge two bindings in a let if they are identical 
270 -- TODO: We would very much like to use GHC's CSE module for this, but that
271 -- doesn't track if something changed or not, so we can't use it properly.
272 letmerge, letmergetop :: Transform
273 letmerge expr@(Let _ _) = do
274   let (binds, res) = flattenLets expr
275   binds' <- domerge binds
276   return $ mkNonRecLets binds' res
277   where
278     domerge :: [(CoreBndr, CoreExpr)] -> TransformMonad [(CoreBndr, CoreExpr)]
279     domerge [] = return []
280     domerge (e:es) = do 
281       es' <- mapM (mergebinds e) es
282       es'' <- domerge es'
283       return (e:es'')
284
285     -- Uses the second bind to simplify the second bind, if applicable.
286     mergebinds :: (CoreBndr, CoreExpr) -> (CoreBndr, CoreExpr) -> TransformMonad (CoreBndr, CoreExpr)
287     mergebinds (b1, e1) (b2, e2)
288       -- Identical expressions? Replace the second binding with a reference to
289       -- the first binder.
290       | CoreUtils.cheapEqExpr e1 e2 = change $ (b2, Var b1)
291       -- Different expressions? Don't change
292       | otherwise = return (b2, e2)
293 -- Leave all other expressions unchanged
294 letmerge expr = return expr
295 letmergetop = everywhere ("letmerge", letmerge)
296 -}
297
298 --------------------------------
299 -- Non-representable binding inlining
300 --------------------------------
301 -- Remove a = B bindings, with B of a non-representable type, from let
302 -- expressions everywhere. This means that any value that we can't generate a
303 -- signal for, will be inlined and hopefully turned into something we can
304 -- represent.
305 --
306 -- This is a tricky function, which is prone to create loops in the
307 -- transformations. To fix this, we make sure that no transformation will
308 -- create a new let binding with a non-representable type. These other
309 -- transformations will just not work on those function-typed values at first,
310 -- but the other transformations (in particular β-reduction) should make sure
311 -- that the type of those values eventually becomes representable.
312 inlinenonreptop :: Transform
313 inlinenonreptop = everywhere ("inlinenonrep", inlinebind ((Monad.liftM not) . isRepr . snd))
314
315 --------------------------------
316 -- Top level function inlining
317 --------------------------------
318 -- This transformation inlines top level bindings that have been generated by
319 -- the compiler and are really simple. Really simple currently means that the
320 -- normalized form only contains a single binding, which catches most of the
321 -- cases where a top level function is created that simply calls a type class
322 -- method with a type and dictionary argument, e.g.
323 --   fromInteger = GHC.Num.fromInteger (SizedWord D8) $dNum
324 -- which is later called using simply
325 --   fromInteger (smallInteger 10)
326 -- By inlining such calls to simple, compiler generated functions, we prevent
327 -- huge amounts of trivial components in the VHDL output, which the user never
328 -- wanted. We never inline user-defined functions, since we want to preserve
329 -- all structure defined by the user. Currently this includes all functions
330 -- that were created by funextract, since we would get loops otherwise.
331 --
332 -- Note that "defined by the compiler" isn't completely watertight, since GHC
333 -- doesn't seem to set all those names as "system names", we apply some
334 -- guessing here.
335 inlinetoplevel, inlinetopleveltop :: Transform
336 -- Any system name is candidate for inlining. Never inline user-defined
337 -- functions, to preserve structure.
338 inlinetoplevel expr@(Var f) | not $ isUserDefined f = do
339   norm <- isNormalizeable f
340   -- See if this is a top level binding for which we have a body
341   body_maybe <- Trans.lift $ getGlobalBind f
342   if norm && Maybe.isJust body_maybe
343     then do
344       -- Get the normalized version
345       norm <- Trans.lift $ getNormalized f
346       if needsInline norm 
347         then do
348           -- Regenerate all uniques in the to-be-inlined expression
349           norm_uniqued <- Trans.lift $ genUniques norm
350           change norm_uniqued
351         else
352           return expr
353     else
354       -- No body or not normalizeable.
355       return expr
356 -- Leave all other expressions unchanged
357 inlinetoplevel expr = return expr
358 inlinetopleveltop = everywhere ("inlinetoplevel", inlinetoplevel)
359
360 needsInline :: CoreExpr -> Bool
361 needsInline expr = case splitNormalized expr of
362   -- Inline any function that only has a single definition, it is probably
363   -- simple enough. This might inline some stuff that it shouldn't though it
364   -- will never inline user-defined functions (inlinetoplevel only tries
365   -- system names) and inlining should never break things.
366   (args, [bind], res) -> True
367   _ -> False
368
369 --------------------------------
370 -- Scrutinee simplification
371 --------------------------------
372 scrutsimpl,scrutsimpltop :: Transform
373 -- Don't touch scrutinees that are already simple
374 scrutsimpl expr@(Case (Var _) _ _ _) = return expr
375 -- Replace all other cases with a let that binds the scrutinee and a new
376 -- simple scrutinee, but only when the scrutinee is representable (to prevent
377 -- loops with inlinenonrep, though I don't think a non-representable scrutinee
378 -- will be supported anyway...) 
379 scrutsimpl expr@(Case scrut b ty alts) = do
380   repr <- isRepr scrut
381   if repr
382     then do
383       id <- Trans.lift $ mkBinderFor scrut "scrut"
384       change $ Let (NonRec id scrut) (Case (Var id) b ty alts)
385     else
386       return expr
387 -- Leave all other expressions unchanged
388 scrutsimpl expr = return expr
389 -- Perform this transform everywhere
390 scrutsimpltop = everywhere ("scrutsimpl", scrutsimpl)
391
392 --------------------------------
393 -- Scrutinee binder removal
394 --------------------------------
395 -- A case expression can have an extra binder, to which the scrutinee is bound
396 -- after bringing it to WHNF. This is used for forcing evaluation of strict
397 -- arguments. Since strictness does not matter for us (rather, everything is
398 -- sort of strict), this binder is ignored when generating VHDL, and must thus
399 -- be wild in the normal form.
400 scrutbndrremove, scrutbndrremovetop :: Transform
401 -- If the scrutinee is already simple, and the bndr is not wild yet, replace
402 -- all occurences of the binder with the scrutinee variable.
403 scrutbndrremove (Case (Var scrut) bndr ty alts) | bndr_used = do
404     alts' <- mapM subs_bndr alts
405     return $ Case (Var scrut) wild ty alts'
406   where
407     is_used (_, _, expr) = expr_uses_binders [bndr] expr
408     bndr_used = or $ map is_used alts
409     subs_bndr (con, bndrs, expr) = do
410       expr' <- substitute bndr (Var scrut) expr
411       return (con, bndrs, expr')
412     wild = MkCore.mkWildBinder (Id.idType bndr)
413 -- Leave all other expressions unchanged
414 scrutbndrremove expr = return expr
415 scrutbndrremovetop = everywhere ("scrutbndrremove", scrutbndrremove)
416
417 --------------------------------
418 -- Case binder wildening
419 --------------------------------
420 casesimpl, casesimpltop :: Transform
421 -- This is already a selector case (or, if x does not appear in bndrs, a very
422 -- simple case statement that will be removed by caseremove below). Just leave
423 -- it be.
424 casesimpl expr@(Case scrut b ty [(con, bndrs, Var x)]) = return expr
425 -- Make sure that all case alternatives have only wild binders and simple
426 -- expressions.
427 -- This is done by creating a new let binding for each non-wild binder, which
428 -- is bound to a new simple selector case statement and for each complex
429 -- expression. We do this only for representable types, to prevent loops with
430 -- inlinenonrep.
431 casesimpl expr@(Case scrut b ty alts) = do
432   (bindingss, alts') <- (Monad.liftM unzip) $ mapM doalt alts
433   let bindings = concat bindingss
434   -- Replace the case with a let with bindings and a case
435   let newlet = mkNonRecLets bindings (Case scrut b ty alts')
436   -- If there are no non-wild binders, or this case is already a simple
437   -- selector (i.e., a single alt with exactly one binding), already a simple
438   -- selector altan no bindings (i.e., no wild binders in the original case),
439   -- don't change anything, otherwise, replace the case.
440   if null bindings then return expr else change newlet 
441   where
442   -- Generate a single wild binder, since they are all the same
443   wild = MkCore.mkWildBinder
444   -- Wilden the binders of one alt, producing a list of bindings as a
445   -- sideeffect.
446   doalt :: CoreAlt -> TransformMonad ([(CoreBndr, CoreExpr)], CoreAlt)
447   doalt (con, bndrs, expr) = do
448     -- Make each binder wild, if possible
449     bndrs_res <- Monad.zipWithM dobndr bndrs [0..]
450     let (newbndrs, bindings_maybe) = unzip bndrs_res
451     -- Extract a complex expression, if possible. For this we check if any of
452     -- the new list of bndrs are used by expr. We can't use free_vars here,
453     -- since that looks at the old bndrs.
454     let uses_bndrs = not $ VarSet.isEmptyVarSet $ CoreFVs.exprSomeFreeVars (`elem` newbndrs) expr
455     (exprbinding_maybe, expr') <- doexpr expr uses_bndrs
456     -- Create a new alternative
457     let newalt = (con, newbndrs, expr')
458     let bindings = Maybe.catMaybes (bindings_maybe ++ [exprbinding_maybe])
459     return (bindings, newalt)
460     where
461       -- Make wild alternatives for each binder
462       wildbndrs = map (\bndr -> MkCore.mkWildBinder (Id.idType bndr)) bndrs
463       -- A set of all the binders that are used by the expression
464       free_vars = CoreFVs.exprSomeFreeVars (`elem` bndrs) expr
465       -- Look at the ith binder in the case alternative. Return a new binder
466       -- for it (either the same one, or a wild one) and optionally a let
467       -- binding containing a case expression.
468       dobndr :: CoreBndr -> Int -> TransformMonad (CoreBndr, Maybe (CoreBndr, CoreExpr))
469       dobndr b i = do
470         repr <- isRepr b
471         -- Is b wild (e.g., not a free var of expr. Since b is only in scope
472         -- in expr, this means that b is unused if expr does not use it.)
473         let wild = not (VarSet.elemVarSet b free_vars)
474         -- Create a new binding for any representable binder that is not
475         -- already wild and is representable (to prevent loops with
476         -- inlinenonrep).
477         if (not wild) && repr
478           then do
479             -- Create on new binder that will actually capture a value in this
480             -- case statement, and return it.
481             let bty = (Id.idType b)
482             id <- Trans.lift $ mkInternalVar "sel" bty
483             let binders = take i wildbndrs ++ [id] ++ drop (i+1) wildbndrs
484             let caseexpr = Case scrut b bty [(con, binders, Var id)]
485             return (wildbndrs!!i, Just (b, caseexpr))
486           else 
487             -- Just leave the original binder in place, and don't generate an
488             -- extra selector case.
489             return (b, Nothing)
490       -- Process the expression of a case alternative. Accepts an expression
491       -- and whether this expression uses any of the binders in the
492       -- alternative. Returns an optional new binding and a new expression.
493       doexpr :: CoreExpr -> Bool -> TransformMonad (Maybe (CoreBndr, CoreExpr), CoreExpr)
494       doexpr expr uses_bndrs = do
495         local_var <- Trans.lift $ is_local_var expr
496         repr <- isRepr expr
497         -- Extract any expressions that do not use any binders from this
498         -- alternative, is not a local var already and is representable (to
499         -- prevent loops with inlinenonrep).
500         if (not uses_bndrs) && (not local_var) && repr
501           then do
502             id <- Trans.lift $ mkBinderFor expr "caseval"
503             -- We don't flag a change here, since casevalsimpl will do that above
504             -- based on Just we return here.
505             return (Just (id, expr), Var id)
506           else
507             -- Don't simplify anything else
508             return (Nothing, expr)
509 -- Leave all other expressions unchanged
510 casesimpl expr = return expr
511 -- Perform this transform everywhere
512 casesimpltop = everywhere ("casesimpl", casesimpl)
513
514 --------------------------------
515 -- Case removal
516 --------------------------------
517 -- Remove case statements that have only a single alternative and only wild
518 -- binders.
519 caseremove, caseremovetop :: Transform
520 -- Replace a useless case by the value of its single alternative
521 caseremove (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
522     -- Find if any of the binders are used by expr
523     where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` bndrs))) expr
524 -- Leave all other expressions unchanged
525 caseremove expr = return expr
526 -- Perform this transform everywhere
527 caseremovetop = everywhere ("caseremove", caseremove)
528
529 --------------------------------
530 -- Argument extraction
531 --------------------------------
532 -- Make sure that all arguments of a representable type are simple variables.
533 appsimpl, appsimpltop :: Transform
534 -- Simplify all representable arguments. Do this by introducing a new Let
535 -- that binds the argument and passing the new binder in the application.
536 appsimpl expr@(App f arg) = do
537   -- Check runtime representability
538   repr <- isRepr arg
539   local_var <- Trans.lift $ is_local_var arg
540   if repr && not local_var
541     then do -- Extract representable arguments
542       id <- Trans.lift $ mkBinderFor arg "arg"
543       change $ Let (NonRec id arg) (App f (Var id))
544     else -- Leave non-representable arguments unchanged
545       return expr
546 -- Leave all other expressions unchanged
547 appsimpl expr = return expr
548 -- Perform this transform everywhere
549 appsimpltop = everywhere ("appsimpl", appsimpl)
550
551 --------------------------------
552 -- Function-typed argument propagation
553 --------------------------------
554 -- Remove all applications to function-typed arguments, by duplication the
555 -- function called with the function-typed parameter replaced by the free
556 -- variables of the argument passed in.
557 argprop, argproptop :: Transform
558 -- Transform any application of a named function (i.e., skip applications of
559 -- lambda's). Also skip applications that have arguments with free type
560 -- variables, since we can't inline those.
561 argprop expr@(App _ _) | is_var fexpr = do
562   -- Find the body of the function called
563   body_maybe <- Trans.lift $ getGlobalBind f
564   case body_maybe of
565     Just body -> do
566       -- Process each of the arguments in turn
567       (args', changed) <- Writer.listen $ mapM doarg args
568       -- See if any of the arguments changed
569       case Monoid.getAny changed of
570         True -> do
571           let (newargs', newparams', oldargs) = unzip3 args'
572           let newargs = concat newargs'
573           let newparams = concat newparams'
574           -- Create a new body that consists of a lambda for all new arguments and
575           -- the old body applied to some arguments.
576           let newbody = MkCore.mkCoreLams newparams (MkCore.mkCoreApps body oldargs)
577           -- Create a new function with the same name but a new body
578           newf <- Trans.lift $ mkFunction f newbody
579           -- Replace the original application with one of the new function to the
580           -- new arguments.
581           change $ MkCore.mkCoreApps (Var newf) newargs
582         False ->
583           -- Don't change the expression if none of the arguments changed
584           return expr
585       
586     -- If we don't have a body for the function called, leave it unchanged (it
587     -- should be a primitive function then).
588     Nothing -> return expr
589   where
590     -- Find the function called and the arguments
591     (fexpr, args) = collectArgs expr
592     Var f = fexpr
593
594     -- Process a single argument and return (args, bndrs, arg), where args are
595     -- the arguments to replace the given argument in the original
596     -- application, bndrs are the binders to include in the top-level lambda
597     -- in the new function body, and arg is the argument to apply to the old
598     -- function body.
599     doarg :: CoreExpr -> TransformMonad ([CoreExpr], [CoreBndr], CoreExpr)
600     doarg arg = do
601       repr <- isRepr arg
602       bndrs <- Trans.lift getGlobalBinders
603       let interesting var = Var.isLocalVar var && (var `notElem` bndrs)
604       if not repr && not (is_var arg && interesting (exprToVar arg)) && not (has_free_tyvars arg) 
605         then do
606           -- Propagate all complex arguments that are not representable, but not
607           -- arguments with free type variables (since those would require types
608           -- not known yet, which will always be known eventually).
609           -- Find interesting free variables, each of which should be passed to
610           -- the new function instead of the original function argument.
611           -- 
612           -- Interesting vars are those that are local, but not available from the
613           -- top level scope (functions from this module are defined as local, but
614           -- they're not local to this function, so we can freely move references
615           -- to them into another function).
616           let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting arg
617           -- Mark the current expression as changed
618           setChanged
619           return (map Var free_vars, free_vars, arg)
620         else do
621           -- Representable types will not be propagated, and arguments with free
622           -- type variables will be propagated later.
623           -- Note that we implicitly remove any type variables in the type of
624           -- the original argument by using the type of the actual argument
625           -- for the new formal parameter.
626           -- TODO: preserve original naming?
627           id <- Trans.lift $ mkBinderFor arg "param"
628           -- Just pass the original argument to the new function, which binds it
629           -- to a new id and just pass that new id to the old function body.
630           return ([arg], [id], mkReferenceTo id) 
631 -- Leave all other expressions unchanged
632 argprop expr = return expr
633 -- Perform this transform everywhere
634 argproptop = everywhere ("argprop", argprop)
635
636 --------------------------------
637 -- Function-typed argument extraction
638 --------------------------------
639 -- This transform takes any function-typed argument that cannot be propagated
640 -- (because the function that is applied to it is a builtin function), and
641 -- puts it in a brand new top level binder. This allows us to for example
642 -- apply map to a lambda expression This will not conflict with inlinenonrep,
643 -- since that only inlines local let bindings, not top level bindings.
644 funextract, funextracttop :: Transform
645 funextract expr@(App _ _) | is_var fexpr = do
646   body_maybe <- Trans.lift $ getGlobalBind f
647   case body_maybe of
648     -- We don't have a function body for f, so we can perform this transform.
649     Nothing -> do
650       -- Find the new arguments
651       args' <- mapM doarg args
652       -- And update the arguments. We use return instead of changed, so the
653       -- changed flag doesn't get set if none of the args got changed.
654       return $ MkCore.mkCoreApps fexpr args'
655     -- We have a function body for f, leave this application to funprop
656     Just _ -> return expr
657   where
658     -- Find the function called and the arguments
659     (fexpr, args) = collectArgs expr
660     Var f = fexpr
661     -- Change any arguments that have a function type, but are not simple yet
662     -- (ie, a variable or application). This means to create a new function
663     -- for map (\f -> ...) b, but not for map (foo a) b.
664     --
665     -- We could use is_applicable here instead of is_fun, but I think
666     -- arguments to functions could only have forall typing when existential
667     -- typing is enabled. Not sure, though.
668     doarg arg | not (is_simple arg) && is_fun arg = do
669       -- Create a new top level binding that binds the argument. Its body will
670       -- be extended with lambda expressions, to take any free variables used
671       -- by the argument expression.
672       let free_vars = VarSet.varSetElems $ CoreFVs.exprFreeVars arg
673       let body = MkCore.mkCoreLams free_vars arg
674       id <- Trans.lift $ mkBinderFor body "fun"
675       Trans.lift $ addGlobalBind id body
676       -- Replace the argument with a reference to the new function, applied to
677       -- all vars it uses.
678       change $ MkCore.mkCoreApps (Var id) (map Var free_vars)
679     -- Leave all other arguments untouched
680     doarg arg = return arg
681
682 -- Leave all other expressions unchanged
683 funextract expr = return expr
684 -- Perform this transform everywhere
685 funextracttop = everywhere ("funextract", funextract)
686
687 --------------------------------
688 -- Ensure that a function that just returns another function (or rather,
689 -- another top-level binder) is still properly normalized. This is a temporary
690 -- solution, we should probably integrate this pass with lambdasimpl and
691 -- letsimpl instead.
692 --------------------------------
693 simplrestop expr@(Lam _ _) = return expr
694 simplrestop expr@(Let _ _) = return expr
695 simplrestop expr = do
696   local_var <- Trans.lift $ is_local_var expr
697   -- Don't extract values that are not representable, to prevent loops with
698   -- inlinenonrep
699   repr <- isRepr expr
700   if local_var || not repr
701     then
702       return expr
703     else do
704       id <- Trans.lift $ mkBinderFor expr "res" 
705       change $ Let (NonRec id expr) (Var id)
706 --------------------------------
707 -- End of transformations
708 --------------------------------
709
710
711
712
713 -- What transforms to run?
714 transforms = [inlinetopleveltop, argproptop, funextracttop, etatop, betatop, castproptop, letremovesimpletop, letderectop, letremovetop, letsimpltop, letflattop, scrutsimpltop, scrutbndrremovetop, casesimpltop, caseremovetop, inlinenonreptop, appsimpltop, letremoveunusedtop, castsimpltop, lambdasimpltop, simplrestop]
715
716 -- | Returns the normalized version of the given function.
717 getNormalized ::
718   CoreBndr -- ^ The function to get
719   -> TranslatorSession CoreExpr -- The normalized function body
720
721 getNormalized bndr = Utils.makeCached bndr tsNormalized $
722   if is_poly (Var bndr)
723     then
724       -- This should really only happen at the top level... TODO: Give
725       -- a different error if this happens down in the recursion.
726       error $ "\nNormalize.normalizeBind: Function " ++ show bndr ++ " is polymorphic, can't normalize"
727     else do
728       expr <- getBinding bndr
729       normalizeExpr (show bndr) expr
730
731 -- | Normalize an expression
732 normalizeExpr ::
733   String -- ^ What are we normalizing? For debug output only.
734   -> CoreSyn.CoreExpr -- ^ The expression to normalize 
735   -> TranslatorSession CoreSyn.CoreExpr -- ^ The normalized expression
736
737 normalizeExpr what expr = do
738       expr_uniqued <- genUniques expr
739       -- Normalize this expression
740       trace (what ++ " before normalization:\n\n" ++ showSDoc ( ppr expr_uniqued ) ++ "\n") $ return ()
741       expr' <- dotransforms transforms expr_uniqued
742       trace ("\n" ++ what ++ " after normalization:\n\n" ++ showSDoc ( ppr expr')) $ return ()
743       return expr'
744
745 -- | Get the value that is bound to the given binder at top level. Fails when
746 --   there is no such binding.
747 getBinding ::
748   CoreBndr -- ^ The binder to get the expression for
749   -> TranslatorSession CoreExpr -- ^ The value bound to the binder
750
751 getBinding bndr = Utils.makeCached bndr tsBindings $
752   -- If the binding isn't in the "cache" (bindings map), then we can't create
753   -- it out of thin air, so return an error.
754   error $ "Normalize.getBinding: Unknown function requested: " ++ show bndr
755
756 -- | Split a normalized expression into the argument binders, top level
757 --   bindings and the result binder.
758 splitNormalized ::
759   CoreExpr -- ^ The normalized expression
760   -> ([CoreBndr], [Binding], CoreBndr)
761 splitNormalized expr = (args, binds, res)
762   where
763     (args, letexpr) = CoreSyn.collectBinders expr
764     (binds, resexpr) = flattenLets letexpr
765     res = case resexpr of 
766       (Var x) -> x
767       _ -> error $ "Normalize.splitNormalized: Not in normal form: " ++ pprString expr ++ "\n"