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_maybe <- Trans.lift $ getNormalized_maybe f
343 -- No body or not normalizeable.
344 Nothing -> return expr
345 Just norm -> if needsInline norm then do
346 -- Regenerate all uniques in the to-be-inlined expression
347 norm_uniqued <- Trans.lift $ genUniques norm
348 -- And replace the variable reference with the unique'd body.
354 -- Leave all other expressions unchanged
355 inlinetoplevel expr = return expr
356 inlinetopleveltop = everywhere ("inlinetoplevel", inlinetoplevel)
358 needsInline :: CoreExpr -> Bool
359 needsInline expr = case splitNormalized expr of
360 -- Inline any function that only has a single definition, it is probably
361 -- simple enough. This might inline some stuff that it shouldn't though it
362 -- will never inline user-defined functions (inlinetoplevel only tries
363 -- system names) and inlining should never break things.
364 (args, [bind], res) -> True
368 --------------------------------
369 -- Dictionary inlining
370 --------------------------------
371 -- Inline all top level dictionaries, so we can use them to resolve
372 -- class methods based on the dictionary passed.
373 inlinedict expr@(Var f) | Id.isDictId f = do
374 body_maybe <- Trans.lift $ getGlobalBind f
376 Nothing -> return expr
377 Just body -> change body
379 -- Leave all other expressions unchanged
380 inlinedict expr = return expr
381 inlinedicttop = everywhere ("inlinedict", inlinedict)
383 --------------------------------
384 -- Scrutinee simplification
385 --------------------------------
386 scrutsimpl,scrutsimpltop :: Transform
387 -- Don't touch scrutinees that are already simple
388 scrutsimpl expr@(Case (Var _) _ _ _) = return expr
389 -- Replace all other cases with a let that binds the scrutinee and a new
390 -- simple scrutinee, but only when the scrutinee is representable (to prevent
391 -- loops with inlinenonrep, though I don't think a non-representable scrutinee
392 -- will be supported anyway...)
393 scrutsimpl expr@(Case scrut b ty alts) = do
397 id <- Trans.lift $ mkBinderFor scrut "scrut"
398 change $ Let (NonRec id scrut) (Case (Var id) b ty alts)
401 -- Leave all other expressions unchanged
402 scrutsimpl expr = return expr
403 -- Perform this transform everywhere
404 scrutsimpltop = everywhere ("scrutsimpl", scrutsimpl)
406 --------------------------------
407 -- Scrutinee binder removal
408 --------------------------------
409 -- A case expression can have an extra binder, to which the scrutinee is bound
410 -- after bringing it to WHNF. This is used for forcing evaluation of strict
411 -- arguments. Since strictness does not matter for us (rather, everything is
412 -- sort of strict), this binder is ignored when generating VHDL, and must thus
413 -- be wild in the normal form.
414 scrutbndrremove, scrutbndrremovetop :: Transform
415 -- If the scrutinee is already simple, and the bndr is not wild yet, replace
416 -- all occurences of the binder with the scrutinee variable.
417 scrutbndrremove (Case (Var scrut) bndr ty alts) | bndr_used = do
418 alts' <- mapM subs_bndr alts
419 change $ Case (Var scrut) wild ty alts'
421 is_used (_, _, expr) = expr_uses_binders [bndr] expr
422 bndr_used = or $ map is_used alts
423 subs_bndr (con, bndrs, expr) = do
424 expr' <- substitute bndr (Var scrut) expr
425 return (con, bndrs, expr')
426 wild = MkCore.mkWildBinder (Id.idType bndr)
427 -- Leave all other expressions unchanged
428 scrutbndrremove expr = return expr
429 scrutbndrremovetop = everywhere ("scrutbndrremove", scrutbndrremove)
431 --------------------------------
432 -- Case binder wildening
433 --------------------------------
434 casesimpl, casesimpltop :: Transform
435 -- This is already a selector case (or, if x does not appear in bndrs, a very
436 -- simple case statement that will be removed by caseremove below). Just leave
438 casesimpl expr@(Case scrut b ty [(con, bndrs, Var x)]) = return expr
439 -- Make sure that all case alternatives have only wild binders and simple
441 -- This is done by creating a new let binding for each non-wild binder, which
442 -- is bound to a new simple selector case statement and for each complex
443 -- expression. We do this only for representable types, to prevent loops with
445 casesimpl expr@(Case scrut b ty alts) = do
446 (bindingss, alts') <- (Monad.liftM unzip) $ mapM doalt alts
447 let bindings = concat bindingss
448 -- Replace the case with a let with bindings and a case
449 let newlet = mkNonRecLets bindings (Case scrut b ty alts')
450 -- If there are no non-wild binders, or this case is already a simple
451 -- selector (i.e., a single alt with exactly one binding), already a simple
452 -- selector altan no bindings (i.e., no wild binders in the original case),
453 -- don't change anything, otherwise, replace the case.
454 if null bindings then return expr else change newlet
456 -- Generate a single wild binder, since they are all the same
457 wild = MkCore.mkWildBinder
458 -- Wilden the binders of one alt, producing a list of bindings as a
460 doalt :: CoreAlt -> TransformMonad ([(CoreBndr, CoreExpr)], CoreAlt)
461 doalt (con, bndrs, expr) = do
462 -- Make each binder wild, if possible
463 bndrs_res <- Monad.zipWithM dobndr bndrs [0..]
464 let (newbndrs, bindings_maybe) = unzip bndrs_res
465 -- Extract a complex expression, if possible. For this we check if any of
466 -- the new list of bndrs are used by expr. We can't use free_vars here,
467 -- since that looks at the old bndrs.
468 let uses_bndrs = not $ VarSet.isEmptyVarSet $ CoreFVs.exprSomeFreeVars (`elem` newbndrs) expr
469 (exprbinding_maybe, expr') <- doexpr expr uses_bndrs
470 -- Create a new alternative
471 let newalt = (con, newbndrs, expr')
472 let bindings = Maybe.catMaybes (bindings_maybe ++ [exprbinding_maybe])
473 return (bindings, newalt)
475 -- Make wild alternatives for each binder
476 wildbndrs = map (\bndr -> MkCore.mkWildBinder (Id.idType bndr)) bndrs
477 -- A set of all the binders that are used by the expression
478 free_vars = CoreFVs.exprSomeFreeVars (`elem` bndrs) expr
479 -- Look at the ith binder in the case alternative. Return a new binder
480 -- for it (either the same one, or a wild one) and optionally a let
481 -- binding containing a case expression.
482 dobndr :: CoreBndr -> Int -> TransformMonad (CoreBndr, Maybe (CoreBndr, CoreExpr))
485 -- Is b wild (e.g., not a free var of expr. Since b is only in scope
486 -- in expr, this means that b is unused if expr does not use it.)
487 let wild = not (VarSet.elemVarSet b free_vars)
488 -- Create a new binding for any representable binder that is not
489 -- already wild and is representable (to prevent loops with
491 if (not wild) && repr
493 -- Create on new binder that will actually capture a value in this
494 -- case statement, and return it.
495 let bty = (Id.idType b)
496 id <- Trans.lift $ mkInternalVar "sel" bty
497 let binders = take i wildbndrs ++ [id] ++ drop (i+1) wildbndrs
498 let caseexpr = Case scrut b bty [(con, binders, Var id)]
499 return (wildbndrs!!i, Just (b, caseexpr))
501 -- Just leave the original binder in place, and don't generate an
502 -- extra selector case.
504 -- Process the expression of a case alternative. Accepts an expression
505 -- and whether this expression uses any of the binders in the
506 -- alternative. Returns an optional new binding and a new expression.
507 doexpr :: CoreExpr -> Bool -> TransformMonad (Maybe (CoreBndr, CoreExpr), CoreExpr)
508 doexpr expr uses_bndrs = do
509 local_var <- Trans.lift $ is_local_var expr
511 -- Extract any expressions that do not use any binders from this
512 -- alternative, is not a local var already and is representable (to
513 -- prevent loops with inlinenonrep).
514 if (not uses_bndrs) && (not local_var) && repr
516 id <- Trans.lift $ mkBinderFor expr "caseval"
517 -- We don't flag a change here, since casevalsimpl will do that above
518 -- based on Just we return here.
519 return (Just (id, expr), Var id)
521 -- Don't simplify anything else
522 return (Nothing, expr)
523 -- Leave all other expressions unchanged
524 casesimpl expr = return expr
525 -- Perform this transform everywhere
526 casesimpltop = everywhere ("casesimpl", casesimpl)
528 --------------------------------
530 --------------------------------
531 -- Remove case statements that have only a single alternative and only wild
533 caseremove, caseremovetop :: Transform
534 -- Replace a useless case by the value of its single alternative
535 caseremove (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
536 -- Find if any of the binders are used by expr
537 where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` bndrs))) expr
538 -- Leave all other expressions unchanged
539 caseremove expr = return expr
540 -- Perform this transform everywhere
541 caseremovetop = everywhere ("caseremove", caseremove)
543 --------------------------------
544 -- Argument extraction
545 --------------------------------
546 -- Make sure that all arguments of a representable type are simple variables.
547 appsimpl, appsimpltop :: Transform
548 -- Simplify all representable arguments. Do this by introducing a new Let
549 -- that binds the argument and passing the new binder in the application.
550 appsimpl expr@(App f arg) = do
551 -- Check runtime representability
553 local_var <- Trans.lift $ is_local_var arg
554 if repr && not local_var
555 then do -- Extract representable arguments
556 id <- Trans.lift $ mkBinderFor arg "arg"
557 change $ Let (NonRec id arg) (App f (Var id))
558 else -- Leave non-representable arguments unchanged
560 -- Leave all other expressions unchanged
561 appsimpl expr = return expr
562 -- Perform this transform everywhere
563 appsimpltop = everywhere ("appsimpl", appsimpl)
565 --------------------------------
566 -- Function-typed argument propagation
567 --------------------------------
568 -- Remove all applications to function-typed arguments, by duplication the
569 -- function called with the function-typed parameter replaced by the free
570 -- variables of the argument passed in.
571 argprop, argproptop :: Transform
572 -- Transform any application of a named function (i.e., skip applications of
573 -- lambda's). Also skip applications that have arguments with free type
574 -- variables, since we can't inline those.
575 argprop expr@(App _ _) | is_var fexpr = do
576 -- Find the body of the function called
577 body_maybe <- Trans.lift $ getGlobalBind f
580 -- Process each of the arguments in turn
581 (args', changed) <- Writer.listen $ mapM doarg args
582 -- See if any of the arguments changed
583 case Monoid.getAny changed of
585 let (newargs', newparams', oldargs) = unzip3 args'
586 let newargs = concat newargs'
587 let newparams = concat newparams'
588 -- Create a new body that consists of a lambda for all new arguments and
589 -- the old body applied to some arguments.
590 let newbody = MkCore.mkCoreLams newparams (MkCore.mkCoreApps body oldargs)
591 -- Create a new function with the same name but a new body
592 newf <- Trans.lift $ mkFunction f newbody
594 Trans.lift $ MonadState.modify tsInitStates (\ismap ->
595 let init_state_maybe = Map.lookup f ismap in
596 case init_state_maybe of
598 Just init_state -> Map.insert newf init_state ismap)
599 -- Replace the original application with one of the new function to the
601 change $ MkCore.mkCoreApps (Var newf) newargs
603 -- Don't change the expression if none of the arguments changed
606 -- If we don't have a body for the function called, leave it unchanged (it
607 -- should be a primitive function then).
608 Nothing -> return expr
610 -- Find the function called and the arguments
611 (fexpr, args) = collectArgs expr
614 -- Process a single argument and return (args, bndrs, arg), where args are
615 -- the arguments to replace the given argument in the original
616 -- application, bndrs are the binders to include in the top-level lambda
617 -- in the new function body, and arg is the argument to apply to the old
619 doarg :: CoreExpr -> TransformMonad ([CoreExpr], [CoreBndr], CoreExpr)
622 bndrs <- Trans.lift getGlobalBinders
623 let interesting var = Var.isLocalVar var && (var `notElem` bndrs)
624 if not repr && not (is_var arg && interesting (exprToVar arg)) && not (has_free_tyvars arg)
626 -- Propagate all complex arguments that are not representable, but not
627 -- arguments with free type variables (since those would require types
628 -- not known yet, which will always be known eventually).
629 -- Find interesting free variables, each of which should be passed to
630 -- the new function instead of the original function argument.
632 -- Interesting vars are those that are local, but not available from the
633 -- top level scope (functions from this module are defined as local, but
634 -- they're not local to this function, so we can freely move references
635 -- to them into another function).
636 let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting arg
637 -- Mark the current expression as changed
639 -- TODO: Clone the free_vars (and update references in arg), since
640 -- this might cause conflicts if two arguments that are propagated
641 -- share a free variable. Also, we are now introducing new variables
642 -- into a function that are not fresh, which violates the binder
643 -- uniqueness invariant.
644 return (map Var free_vars, free_vars, arg)
646 -- Representable types will not be propagated, and arguments with free
647 -- type variables will be propagated later.
648 -- Note that we implicitly remove any type variables in the type of
649 -- the original argument by using the type of the actual argument
650 -- for the new formal parameter.
651 -- TODO: preserve original naming?
652 id <- Trans.lift $ mkBinderFor arg "param"
653 -- Just pass the original argument to the new function, which binds it
654 -- to a new id and just pass that new id to the old function body.
655 return ([arg], [id], mkReferenceTo id)
656 -- Leave all other expressions unchanged
657 argprop expr = return expr
658 -- Perform this transform everywhere
659 argproptop = everywhere ("argprop", argprop)
661 --------------------------------
662 -- Function-typed argument extraction
663 --------------------------------
664 -- This transform takes any function-typed argument that cannot be propagated
665 -- (because the function that is applied to it is a builtin function), and
666 -- puts it in a brand new top level binder. This allows us to for example
667 -- apply map to a lambda expression This will not conflict with inlinenonrep,
668 -- since that only inlines local let bindings, not top level bindings.
669 funextract, funextracttop :: Transform
670 funextract expr@(App _ _) | is_var fexpr = do
671 body_maybe <- Trans.lift $ getGlobalBind f
673 -- We don't have a function body for f, so we can perform this transform.
675 -- Find the new arguments
676 args' <- mapM doarg args
677 -- And update the arguments. We use return instead of changed, so the
678 -- changed flag doesn't get set if none of the args got changed.
679 return $ MkCore.mkCoreApps fexpr args'
680 -- We have a function body for f, leave this application to funprop
681 Just _ -> return expr
683 -- Find the function called and the arguments
684 (fexpr, args) = collectArgs expr
686 -- Change any arguments that have a function type, but are not simple yet
687 -- (ie, a variable or application). This means to create a new function
688 -- for map (\f -> ...) b, but not for map (foo a) b.
690 -- We could use is_applicable here instead of is_fun, but I think
691 -- arguments to functions could only have forall typing when existential
692 -- typing is enabled. Not sure, though.
693 doarg arg | not (is_simple arg) && is_fun arg = do
694 -- Create a new top level binding that binds the argument. Its body will
695 -- be extended with lambda expressions, to take any free variables used
696 -- by the argument expression.
697 let free_vars = VarSet.varSetElems $ CoreFVs.exprFreeVars arg
698 let body = MkCore.mkCoreLams free_vars arg
699 id <- Trans.lift $ mkBinderFor body "fun"
700 Trans.lift $ addGlobalBind id body
701 -- Replace the argument with a reference to the new function, applied to
703 change $ MkCore.mkCoreApps (Var id) (map Var free_vars)
704 -- Leave all other arguments untouched
705 doarg arg = return arg
707 -- Leave all other expressions unchanged
708 funextract expr = return expr
709 -- Perform this transform everywhere
710 funextracttop = everywhere ("funextract", funextract)
712 --------------------------------
713 -- Ensure that a function that just returns another function (or rather,
714 -- another top-level binder) is still properly normalized. This is a temporary
715 -- solution, we should probably integrate this pass with lambdasimpl and
717 --------------------------------
718 simplrestop expr@(Lam _ _) = return expr
719 simplrestop expr@(Let _ _) = return expr
720 simplrestop expr = do
721 local_var <- Trans.lift $ is_local_var expr
722 -- Don't extract values that are not representable, to prevent loops with
725 if local_var || not repr
729 id <- Trans.lift $ mkBinderFor expr "res"
730 change $ Let (NonRec id expr) (Var id)
731 --------------------------------
732 -- End of transformations
733 --------------------------------
738 -- What transforms to run?
739 transforms = [inlinedicttop, inlinetopleveltop, argproptop, funextracttop, etatop, betatop, castproptop, letremovesimpletop, letderectop, letremovetop, letsimpltop, letflattop, scrutsimpltop, scrutbndrremovetop, casesimpltop, caseremovetop, inlinenonreptop, appsimpltop, letremoveunusedtop, castsimpltop, lambdasimpltop, simplrestop]
741 -- | Returns the normalized version of the given function, or an error
742 -- if it is not a known global binder.
744 CoreBndr -- ^ The function to get
745 -> TranslatorSession CoreExpr -- The normalized function body
746 getNormalized bndr = do
747 norm <- getNormalized_maybe bndr
748 return $ Maybe.fromMaybe
749 (error $ "Normalize.getNormalized: Unknown or non-representable function requested: " ++ show bndr)
752 -- | Returns the normalized version of the given function, or Nothing
753 -- when the binder is not a known global binder or is not normalizeable.
754 getNormalized_maybe ::
755 CoreBndr -- ^ The function to get
756 -> TranslatorSession (Maybe CoreExpr) -- The normalized function body
758 getNormalized_maybe bndr = do
759 expr_maybe <- getGlobalBind bndr
760 normalizeable <- isNormalizeable' bndr
761 if not normalizeable || Maybe.isNothing expr_maybe
763 -- Binder not normalizeable or not found
765 else if is_poly (Var bndr)
767 -- This should really only happen at the top level... TODO: Give
768 -- a different error if this happens down in the recursion.
769 error $ "\nNormalize.normalizeBind: Function " ++ show bndr ++ " is polymorphic, can't normalize"
771 -- Binder found and is monomorphic. Normalize the expression
772 -- and cache the result.
773 normalized <- Utils.makeCached bndr tsNormalized $
774 normalizeExpr (show bndr) (Maybe.fromJust expr_maybe)
775 return (Just normalized)
777 -- | Normalize an expression
779 String -- ^ What are we normalizing? For debug output only.
780 -> CoreSyn.CoreExpr -- ^ The expression to normalize
781 -> TranslatorSession CoreSyn.CoreExpr -- ^ The normalized expression
783 normalizeExpr what expr = do
784 expr_uniqued <- genUniques expr
785 -- Normalize this expression
786 trace (what ++ " before normalization:\n\n" ++ showSDoc ( ppr expr_uniqued ) ++ "\n") $ return ()
787 expr' <- dotransforms transforms expr_uniqued
788 trace ("\n" ++ what ++ " after normalization:\n\n" ++ showSDoc ( ppr expr')) $ return ()
791 -- | Split a normalized expression into the argument binders, top level
792 -- bindings and the result binder.
794 CoreExpr -- ^ The normalized expression
795 -> ([CoreBndr], [Binding], CoreBndr)
796 splitNormalized expr = (args, binds, res)
798 (args, letexpr) = CoreSyn.collectBinders expr
799 (binds, resexpr) = flattenLets letexpr
800 res = case resexpr of
802 _ -> error $ "Normalize.splitNormalized: Not in normal form: " ++ pprString expr ++ "\n"