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