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