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