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
27 import qualified VarSet
28 import qualified CoreFVs
29 import qualified Class
30 import qualified MkCore
31 import Outputable ( showSDoc, ppr, nest )
34 import CLasH.Normalize.NormalizeTypes
35 import CLasH.Translator.TranslatorTypes
36 import CLasH.Normalize.NormalizeTools
37 import CLasH.VHDL.Constants (builtinIds)
38 import qualified CLasH.Utils as Utils
39 import CLasH.Utils.Core.CoreTools
40 import CLasH.Utils.Core.BinderTools
41 import CLasH.Utils.Pretty
43 --------------------------------
44 -- Start of transformations
45 --------------------------------
47 --------------------------------
49 --------------------------------
50 -- Make sure all parameters to the normalized functions are named by top
51 -- level lambda expressions. For this we apply η expansion to the
52 -- function body (possibly enclosed in some lambda abstractions) while
53 -- it has a function type. Eventually this will result in a function
54 -- body consisting of a bunch of nested lambdas containing a
55 -- non-function value (e.g., a complete application).
56 eta, etatop :: Transform
57 eta c expr | is_fun expr && not (is_lam expr) && all (== LambdaBody) c = do
58 let arg_ty = (fst . Type.splitFunTy . CoreUtils.exprType) expr
59 id <- Trans.lift $ mkInternalVar "param" arg_ty
60 change (Lam id (App expr (Var id)))
61 -- Leave all other expressions unchanged
63 etatop = everywhere ("eta", eta)
65 --------------------------------
67 --------------------------------
68 beta, betatop :: Transform
69 -- Substitute arg for x in expr. For value lambda's, also clone before
71 beta c (App (Lam x expr) arg) | CoreSyn.isTyVar x = setChanged >> substitute x arg c expr
72 | otherwise = setChanged >> substitute_clone x arg c expr
73 -- Propagate the application into the let
74 beta c (App (Let binds expr) arg) = change $ Let binds (App expr arg)
75 -- Propagate the application into each of the alternatives
76 beta c (App (Case scrut b ty alts) arg) = change $ Case scrut b ty' alts'
78 alts' = map (\(con, bndrs, expr) -> (con, bndrs, (App expr arg))) alts
79 ty' = CoreUtils.applyTypeToArg ty arg
80 -- Leave all other expressions unchanged
81 beta c expr = return expr
82 -- Perform this transform everywhere
83 betatop = everywhere ("beta", beta)
85 --------------------------------
87 --------------------------------
88 -- Try to move casts as much downward as possible.
89 castprop, castproptop :: Transform
90 castprop c (Cast (Let binds expr) ty) = change $ Let binds (Cast expr ty)
91 castprop c expr@(Cast (Case scrut b _ alts) ty) = change (Case scrut b ty alts')
93 alts' = map (\(con, bndrs, expr) -> (con, bndrs, (Cast expr ty))) alts
94 -- Leave all other expressions unchanged
95 castprop c expr = return expr
96 -- Perform this transform everywhere
97 castproptop = everywhere ("castprop", castprop)
99 --------------------------------
100 -- Cast simplification. Mostly useful for state packing and unpacking, but
101 -- perhaps for others as well.
102 --------------------------------
103 castsimpl, castsimpltop :: Transform
104 castsimpl c expr@(Cast val ty) = do
105 -- Don't extract values that are already simpl
106 local_var <- Trans.lift $ is_local_var val
107 -- Don't extract values that are not representable, to prevent loops with
110 if (not local_var) && repr
112 -- Generate a binder for the expression
113 id <- Trans.lift $ mkBinderFor val "castval"
114 -- Extract the expression
115 change $ Let (NonRec id val) (Cast (Var id) ty)
118 -- Leave all other expressions unchanged
119 castsimpl c expr = return expr
120 -- Perform this transform everywhere
121 castsimpltop = everywhere ("castsimpl", castsimpl)
123 --------------------------------
124 -- Return value simplification
125 --------------------------------
126 -- Ensure the return value of a function follows proper normal form. eta
127 -- expansion ensures the body starts with lambda abstractions, this
128 -- transformation ensures that the lambda abstractions always contain a
129 -- recursive let and that, when the return value is representable, the
130 -- let contains a local variable reference in its body.
131 retvalsimpl c expr@(Let (Rec binds) body) | all (== LambdaBody) c = do
132 -- Don't extract values that are already a local variable, to prevent
133 -- loops with ourselves.
134 local_var <- Trans.lift $ is_local_var body
135 -- Don't extract values that are not representable, to prevent loops with
138 if not local_var && repr
140 id <- Trans.lift $ mkBinderFor body "res"
141 change $ Let (Rec ((id, body):binds)) (Var id)
145 retvalsimpl c expr | all (== LambdaBody) c && not (is_lam expr) && not (is_let expr) = do
146 local_var <- Trans.lift $ is_local_var expr
148 if not local_var && repr
150 id <- Trans.lift $ mkBinderFor expr "res"
151 change $ Let (Rec [(id, expr)]) (Var id)
155 -- Leave all other expressions unchanged
156 retvalsimpl c expr = return expr
157 -- Perform this transform everywhere
158 retvalsimpltop = everywhere ("retvalsimpl", retvalsimpl)
160 --------------------------------
161 -- let derecursification
162 --------------------------------
163 letrec, letrectop :: Transform
164 letrec c expr@(Let (NonRec bndr val) res) =
165 change $ Let (Rec [(bndr, val)]) res
167 -- Leave all other expressions unchanged
168 letrec c expr = return expr
169 -- Perform this transform everywhere
170 letrectop = everywhere ("letrec", letrec)
172 --------------------------------
174 --------------------------------
175 -- Takes a let that binds another let, and turns that into two nested lets.
177 -- let b = (let b' = expr' in res') in res
179 -- let b' = expr' in (let b = res' in res)
180 letflat, letflattop :: Transform
181 -- Turn a nonrec let that binds a let into two nested lets.
182 letflat c (Let (NonRec b (Let binds res')) res) =
183 change $ Let binds (Let (NonRec b res') res)
184 letflat c (Let (Rec binds) expr) = do
185 -- Flatten each binding.
186 binds' <- Utils.concatM $ Monad.mapM flatbind binds
187 -- Return the new let. We don't use change here, since possibly nothing has
188 -- changed. If anything has changed, flatbind has already flagged that
190 return $ Let (Rec binds') expr
192 -- Turns a binding of a let into a multiple bindings, or any other binding
193 -- into a list with just that binding
194 flatbind :: (CoreBndr, CoreExpr) -> TransformMonad [(CoreBndr, CoreExpr)]
195 flatbind (b, Let (Rec binds) expr) = change ((b, expr):binds)
196 flatbind (b, Let (NonRec b' expr') expr) = change [(b, expr), (b', expr')]
197 flatbind (b, expr) = return [(b, expr)]
198 -- Leave all other expressions unchanged
199 letflat c expr = return expr
200 -- Perform this transform everywhere
201 letflattop = everywhere ("letflat", letflat)
203 --------------------------------
205 --------------------------------
206 -- Remove empty (recursive) lets
207 letremove, letremovetop :: Transform
208 letremove c (Let (Rec []) res) = change res
209 -- Leave all other expressions unchanged
210 letremove c expr = return expr
211 -- Perform this transform everywhere
212 letremovetop = everywhere ("letremove", letremove)
214 --------------------------------
215 -- Simple let binding removal
216 --------------------------------
217 -- Remove a = b bindings from let expressions everywhere
218 letremovesimpletop :: Transform
219 letremovesimpletop = everywhere ("letremovesimple", inlinebind (\(b, e) -> Trans.lift $ is_local_var e))
221 --------------------------------
222 -- Unused let binding removal
223 --------------------------------
224 letremoveunused, letremoveunusedtop :: Transform
225 letremoveunused c expr@(Let (NonRec b bound) res) = do
226 let used = expr_uses_binders [b] res
230 letremoveunused c expr@(Let (Rec binds) res) = do
231 -- Filter out all unused binds.
232 let binds' = filter dobind binds
233 -- Only set the changed flag if binds got removed
234 changeif (length binds' /= length binds) (Let (Rec binds') res)
236 bound_exprs = map snd binds
237 -- For each bind check if the bind is used by res or any of the bound
239 dobind (bndr, _) = any (expr_uses_binders [bndr]) (res:bound_exprs)
240 -- Leave all other expressions unchanged
241 letremoveunused c expr = return expr
242 letremoveunusedtop = everywhere ("letremoveunused", letremoveunused)
245 --------------------------------
246 -- Identical let binding merging
247 --------------------------------
248 -- Merge two bindings in a let if they are identical
249 -- TODO: We would very much like to use GHC's CSE module for this, but that
250 -- doesn't track if something changed or not, so we can't use it properly.
251 letmerge, letmergetop :: Transform
252 letmerge c expr@(Let _ _) = do
253 let (binds, res) = flattenLets expr
254 binds' <- domerge binds
255 return $ mkNonRecLets binds' res
257 domerge :: [(CoreBndr, CoreExpr)] -> TransformMonad [(CoreBndr, CoreExpr)]
258 domerge [] = return []
260 es' <- mapM (mergebinds e) es
264 -- Uses the second bind to simplify the second bind, if applicable.
265 mergebinds :: (CoreBndr, CoreExpr) -> (CoreBndr, CoreExpr) -> TransformMonad (CoreBndr, CoreExpr)
266 mergebinds (b1, e1) (b2, e2)
267 -- Identical expressions? Replace the second binding with a reference to
269 | CoreUtils.cheapEqExpr e1 e2 = change $ (b2, Var b1)
270 -- Different expressions? Don't change
271 | otherwise = return (b2, e2)
272 -- Leave all other expressions unchanged
273 letmerge c expr = return expr
274 letmergetop = everywhere ("letmerge", letmerge)
277 --------------------------------
278 -- Non-representable binding inlining
279 --------------------------------
280 -- Remove a = B bindings, with B of a non-representable type, from let
281 -- expressions everywhere. This means that any value that we can't generate a
282 -- signal for, will be inlined and hopefully turned into something we can
285 -- This is a tricky function, which is prone to create loops in the
286 -- transformations. To fix this, we make sure that no transformation will
287 -- create a new let binding with a non-representable type. These other
288 -- transformations will just not work on those function-typed values at first,
289 -- but the other transformations (in particular β-reduction) should make sure
290 -- that the type of those values eventually becomes representable.
291 inlinenonreptop :: Transform
292 inlinenonreptop = everywhere ("inlinenonrep", inlinebind ((Monad.liftM not) . isRepr . snd))
294 --------------------------------
295 -- Top level function inlining
296 --------------------------------
297 -- This transformation inlines simple top level bindings. Simple
298 -- currently means that the body is only a single application (though
299 -- the complexity of the arguments is not currently checked) or that the
300 -- normalized form only contains a single binding. This should catch most of the
301 -- cases where a top level function is created that simply calls a type class
302 -- method with a type and dictionary argument, e.g.
303 -- fromInteger = GHC.Num.fromInteger (SizedWord D8) $dNum
304 -- which is later called using simply
305 -- fromInteger (smallInteger 10)
307 -- These useless wrappers are created by GHC automatically. If we don't
308 -- inline them, we get loads of useless components cluttering the
311 -- Note that the inlining could also inline simple functions defined by
312 -- the user, not just GHC generated functions. It turns out to be near
313 -- impossible to reliably determine what functions are generated and
314 -- what functions are user-defined. Instead of guessing (which will
315 -- inline less than we want) we will just inline all simple functions.
317 -- Only functions that are actually completely applied and bound by a
318 -- variable in a let expression are inlined. These are the expressions
319 -- that will eventually generate instantiations of trivial components.
320 -- By not inlining any other reference, we also prevent looping problems
321 -- with funextract and inlinedict.
322 inlinetoplevel, inlinetopleveltop :: Transform
323 inlinetoplevel (LetBinding:_) expr | not (is_fun expr) =
324 case collectArgs expr of
326 body_maybe <- needsInline f
329 -- Regenerate all uniques in the to-be-inlined expression
330 body_uniqued <- Trans.lift $ genUniques body
331 -- And replace the variable reference with the unique'd body.
332 change (mkApps body_uniqued args)
334 Nothing -> return expr
335 -- This is not an application of a binder, leave it unchanged.
338 -- Leave all other expressions unchanged
339 inlinetoplevel c expr = return expr
340 inlinetopleveltop = everywhere ("inlinetoplevel", inlinetoplevel)
342 -- | Does the given binder need to be inlined? If so, return the body to
343 -- be used for inlining.
344 needsInline :: CoreBndr -> TransformMonad (Maybe CoreExpr)
346 body_maybe <- Trans.lift $ getGlobalBind f
348 -- No body available?
349 Nothing -> return Nothing
350 Just body -> case CoreSyn.collectArgs body of
351 -- The body is some (top level) binder applied to 0 or more
352 -- arguments. That should be simple enough to inline.
353 (Var f, args) -> return $ Just body
354 -- Body is more complicated, try normalizing it
356 norm_maybe <- Trans.lift $ getNormalized_maybe f
358 -- Noth normalizeable
359 Nothing -> return Nothing
360 Just norm -> case splitNormalized norm of
361 -- The function has just a single binding, so that's simple
363 (args, [bind], res) -> return $ Just norm
364 -- More complicated function, don't inline
367 --------------------------------
368 -- Dictionary inlining
369 --------------------------------
370 -- Inline all top level dictionaries, that are in a position where
371 -- classopresolution can actually resolve them. This makes this
372 -- transformation look similar to classoperesolution below, but we'll
373 -- keep them separated for clarity. By not inlining other dictionaries,
374 -- we prevent expression sizes exploding when huge type level integer
375 -- dictionaries are inlined which can never be expanded (in casts, for
377 inlinedict c expr@(App (App (Var sel) ty) (Var dict)) | not is_builtin && is_classop = do
378 body_maybe <- Trans.lift $ getGlobalBind dict
380 -- No body available (no source available, or a local variable /
382 Nothing -> return expr
383 Just body -> change (App (App (Var sel) ty) body)
385 -- Is this a builtin function / method?
386 is_builtin = elem (Name.getOccString sel) builtinIds
387 -- Are we dealing with a class operation selector?
388 is_classop = Maybe.isJust (Id.isClassOpId_maybe sel)
390 -- Leave all other expressions unchanged
391 inlinedict c expr = return expr
392 inlinedicttop = everywhere ("inlinedict", inlinedict)
394 --------------------------------
395 -- ClassOp resolution
396 --------------------------------
397 -- Resolves any class operation to the actual operation whenever
398 -- possible. Class methods (as well as parent dictionary selectors) are
399 -- special "functions" that take a type and a dictionary and evaluate to
400 -- the corresponding method. A dictionary is nothing more than a
401 -- special dataconstructor applied to the type the dictionary is for,
402 -- each of the superclasses and all of the class method definitions for
403 -- that particular type. Since dictionaries all always inlined (top
404 -- levels dictionaries are inlined by inlinedict, local dictionaries are
405 -- inlined by inlinenonrep), we will eventually have something like:
408 -- @ CLasH.HardwareTypes.Bit
409 -- (D:Baz @ CLasH.HardwareTypes.Bit bitbaz)
411 -- Here, baz is the method selector for the baz method, while
412 -- D:Baz is the dictionary constructor for the Baz and bitbaz is the baz
413 -- method defined in the Baz Bit instance declaration.
415 -- To resolve this, we can look at the ClassOp IdInfo from the baz Id,
416 -- which contains the Class it is defined for. From the Class, we can
417 -- get a list of all selectors (both parent class selectors as well as
418 -- method selectors). Since the arguments to D:Baz (after the type
419 -- argument) correspond exactly to this list, we then look up baz in
420 -- that list and replace the entire expression by the corresponding
421 -- argument to D:Baz.
423 -- We don't resolve methods that have a builtin translation (such as
424 -- ==), since the actual implementation is not always (easily)
425 -- translateable. For example, when deriving ==, GHC generates code
426 -- using $con2tag functions to translate a datacon to an int and compare
427 -- that with GHC.Prim.==# . Better to avoid that for now.
428 classopresolution, classopresolutiontop :: Transform
429 classopresolution c expr@(App (App (Var sel) ty) dict) | not is_builtin =
430 case Id.isClassOpId_maybe sel of
431 -- Not a class op selector
432 Nothing -> return expr
433 Just cls -> case collectArgs dict of
434 (_, []) -> return expr -- Dict is not an application (e.g., not inlined yet)
435 (Var dictdc, (ty':selectors)) | not (Maybe.isJust (Id.isDataConId_maybe dictdc)) -> return expr -- Dictionary is not a datacon yet (but e.g., a top level binder)
436 | tyargs_neq ty ty' -> error $ "Normalize.classopresolution: Applying class selector to dictionary without matching type?\n" ++ pprString expr
438 let selector_ids = Class.classSelIds cls in
439 -- Find the selector used in the class' list of selectors
440 case List.elemIndex sel selector_ids of
441 Nothing -> error $ "Normalize.classopresolution: Selector not found in class' selector list? This should not happen!\nExpression: " ++ pprString expr ++ "\nClass: " ++ show cls ++ "\nSelectors: " ++ show selector_ids
442 -- Get the corresponding argument from the dictionary
443 Just n -> change (selectors!!n)
444 (_, _) -> return expr -- Not applying a variable? Don't touch
446 -- Compare two type arguments, returning True if they are _not_
448 tyargs_neq (Type ty1) (Type ty2) = not $ Type.coreEqType ty1 ty2
449 tyargs_neq _ _ = True
450 -- Is this a builtin function / method?
451 is_builtin = elem (Name.getOccString sel) builtinIds
453 -- Leave all other expressions unchanged
454 classopresolution c expr = return expr
455 -- Perform this transform everywhere
456 classopresolutiontop = everywhere ("classopresolution", classopresolution)
458 --------------------------------
459 -- Scrutinee simplification
460 --------------------------------
461 scrutsimpl,scrutsimpltop :: Transform
462 -- Don't touch scrutinees that are already simple
463 scrutsimpl c expr@(Case (Var _) _ _ _) = return expr
464 -- Replace all other cases with a let that binds the scrutinee and a new
465 -- simple scrutinee, but only when the scrutinee is representable (to prevent
466 -- loops with inlinenonrep, though I don't think a non-representable scrutinee
467 -- will be supported anyway...)
468 scrutsimpl c expr@(Case scrut b ty alts) = do
472 id <- Trans.lift $ mkBinderFor scrut "scrut"
473 change $ Let (NonRec id scrut) (Case (Var id) b ty alts)
476 -- Leave all other expressions unchanged
477 scrutsimpl c expr = return expr
478 -- Perform this transform everywhere
479 scrutsimpltop = everywhere ("scrutsimpl", scrutsimpl)
481 --------------------------------
482 -- Scrutinee binder removal
483 --------------------------------
484 -- A case expression can have an extra binder, to which the scrutinee is bound
485 -- after bringing it to WHNF. This is used for forcing evaluation of strict
486 -- arguments. Since strictness does not matter for us (rather, everything is
487 -- sort of strict), this binder is ignored when generating VHDL, and must thus
488 -- be wild in the normal form.
489 scrutbndrremove, scrutbndrremovetop :: Transform
490 -- If the scrutinee is already simple, and the bndr is not wild yet, replace
491 -- all occurences of the binder with the scrutinee variable.
492 scrutbndrremove c (Case (Var scrut) bndr ty alts) | bndr_used = do
493 alts' <- mapM subs_bndr alts
494 change $ Case (Var scrut) wild ty alts'
496 is_used (_, _, expr) = expr_uses_binders [bndr] expr
497 bndr_used = or $ map is_used alts
498 subs_bndr (con, bndrs, expr) = do
499 expr' <- substitute bndr (Var scrut) c expr
500 return (con, bndrs, expr')
501 wild = MkCore.mkWildBinder (Id.idType bndr)
502 -- Leave all other expressions unchanged
503 scrutbndrremove c expr = return expr
504 scrutbndrremovetop = everywhere ("scrutbndrremove", scrutbndrremove)
506 --------------------------------
507 -- Case binder wildening
508 --------------------------------
509 casesimpl, casesimpltop :: Transform
510 -- This is already a selector case (or, if x does not appear in bndrs, a very
511 -- simple case statement that will be removed by caseremove below). Just leave
513 casesimpl c expr@(Case scrut b ty [(con, bndrs, Var x)]) = return expr
514 -- Make sure that all case alternatives have only wild binders and simple
516 -- This is done by creating a new let binding for each non-wild binder, which
517 -- is bound to a new simple selector case statement and for each complex
518 -- expression. We do this only for representable types, to prevent loops with
520 casesimpl c expr@(Case scrut bndr ty alts) | not bndr_used = do
521 (bindingss, alts') <- (Monad.liftM unzip) $ mapM doalt alts
522 let bindings = concat bindingss
523 -- Replace the case with a let with bindings and a case
524 let newlet = mkNonRecLets bindings (Case scrut bndr ty alts')
525 -- If there are no non-wild binders, or this case is already a simple
526 -- selector (i.e., a single alt with exactly one binding), already a simple
527 -- selector altan no bindings (i.e., no wild binders in the original case),
528 -- don't change anything, otherwise, replace the case.
529 if null bindings then return expr else change newlet
531 -- Check if the scrutinee binder is used
532 is_used (_, _, expr) = expr_uses_binders [bndr] expr
533 bndr_used = or $ map is_used alts
534 -- Generate a single wild binder, since they are all the same
535 wild = MkCore.mkWildBinder
536 -- Wilden the binders of one alt, producing a list of bindings as a
538 doalt :: CoreAlt -> TransformMonad ([(CoreBndr, CoreExpr)], CoreAlt)
539 doalt (con, bndrs, expr) = do
540 -- Make each binder wild, if possible
541 bndrs_res <- Monad.zipWithM dobndr bndrs [0..]
542 let (newbndrs, bindings_maybe) = unzip bndrs_res
543 -- Extract a complex expression, if possible. For this we check if any of
544 -- the new list of bndrs are used by expr. We can't use free_vars here,
545 -- since that looks at the old bndrs.
546 let uses_bndrs = not $ VarSet.isEmptyVarSet $ CoreFVs.exprSomeFreeVars (`elem` newbndrs) expr
547 (exprbinding_maybe, expr') <- doexpr expr uses_bndrs
548 -- Create a new alternative
549 let newalt = (con, newbndrs, expr')
550 let bindings = Maybe.catMaybes (bindings_maybe ++ [exprbinding_maybe])
551 return (bindings, newalt)
553 -- Make wild alternatives for each binder
554 wildbndrs = map (\bndr -> MkCore.mkWildBinder (Id.idType bndr)) bndrs
555 -- A set of all the binders that are used by the expression
556 free_vars = CoreFVs.exprSomeFreeVars (`elem` bndrs) expr
557 -- Look at the ith binder in the case alternative. Return a new binder
558 -- for it (either the same one, or a wild one) and optionally a let
559 -- binding containing a case expression.
560 dobndr :: CoreBndr -> Int -> TransformMonad (CoreBndr, Maybe (CoreBndr, CoreExpr))
563 -- Is b wild (e.g., not a free var of expr. Since b is only in scope
564 -- in expr, this means that b is unused if expr does not use it.)
565 let wild = not (VarSet.elemVarSet b free_vars)
566 -- Create a new binding for any representable binder that is not
567 -- already wild and is representable (to prevent loops with
569 if (not wild) && repr
571 -- Create on new binder that will actually capture a value in this
572 -- case statement, and return it.
573 let bty = (Id.idType b)
574 id <- Trans.lift $ mkInternalVar "sel" bty
575 let binders = take i wildbndrs ++ [id] ++ drop (i+1) wildbndrs
576 let caseexpr = Case scrut b bty [(con, binders, Var id)]
577 return (wildbndrs!!i, Just (b, caseexpr))
579 -- Just leave the original binder in place, and don't generate an
580 -- extra selector case.
582 -- Process the expression of a case alternative. Accepts an expression
583 -- and whether this expression uses any of the binders in the
584 -- alternative. Returns an optional new binding and a new expression.
585 doexpr :: CoreExpr -> Bool -> TransformMonad (Maybe (CoreBndr, CoreExpr), CoreExpr)
586 doexpr expr uses_bndrs = do
587 local_var <- Trans.lift $ is_local_var expr
589 -- Extract any expressions that do not use any binders from this
590 -- alternative, is not a local var already and is representable (to
591 -- prevent loops with inlinenonrep).
592 if (not uses_bndrs) && (not local_var) && repr
594 id <- Trans.lift $ mkBinderFor expr "caseval"
595 -- We don't flag a change here, since casevalsimpl will do that above
596 -- based on Just we return here.
597 return (Just (id, expr), Var id)
599 -- Don't simplify anything else
600 return (Nothing, expr)
601 -- Leave all other expressions unchanged
602 casesimpl c expr = return expr
603 -- Perform this transform everywhere
604 casesimpltop = everywhere ("casesimpl", casesimpl)
606 --------------------------------
608 --------------------------------
609 -- Remove case statements that have only a single alternative and only wild
611 caseremove, caseremovetop :: Transform
612 -- Replace a useless case by the value of its single alternative
613 caseremove c (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
614 -- Find if any of the binders are used by expr
615 where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` b:bndrs))) expr
616 -- Leave all other expressions unchanged
617 caseremove c expr = return expr
618 -- Perform this transform everywhere
619 caseremovetop = everywhere ("caseremove", caseremove)
621 --------------------------------
622 -- Argument extraction
623 --------------------------------
624 -- Make sure that all arguments of a representable type are simple variables.
625 appsimpl, appsimpltop :: Transform
626 -- Simplify all representable arguments. Do this by introducing a new Let
627 -- that binds the argument and passing the new binder in the application.
628 appsimpl c expr@(App f arg) = do
629 -- Check runtime representability
631 local_var <- Trans.lift $ is_local_var arg
632 if repr && not local_var
633 then do -- Extract representable arguments
634 id <- Trans.lift $ mkBinderFor arg "arg"
635 change $ Let (NonRec id arg) (App f (Var id))
636 else -- Leave non-representable arguments unchanged
638 -- Leave all other expressions unchanged
639 appsimpl c expr = return expr
640 -- Perform this transform everywhere
641 appsimpltop = everywhere ("appsimpl", appsimpl)
643 --------------------------------
644 -- Function-typed argument propagation
645 --------------------------------
646 -- Remove all applications to function-typed arguments, by duplication the
647 -- function called with the function-typed parameter replaced by the free
648 -- variables of the argument passed in.
649 argprop, argproptop :: Transform
650 -- Transform any application of a named function (i.e., skip applications of
651 -- lambda's). Also skip applications that have arguments with free type
652 -- variables, since we can't inline those.
653 argprop c expr@(App _ _) | is_var fexpr = do
654 -- Find the body of the function called
655 body_maybe <- Trans.lift $ getGlobalBind f
658 -- Process each of the arguments in turn
659 (args', changed) <- Writer.listen $ mapM doarg args
660 -- See if any of the arguments changed
661 case Monoid.getAny changed of
663 let (newargs', newparams', oldargs) = unzip3 args'
664 let newargs = concat newargs'
665 let newparams = concat newparams'
666 -- Create a new body that consists of a lambda for all new arguments and
667 -- the old body applied to some arguments.
668 let newbody = MkCore.mkCoreLams newparams (MkCore.mkCoreApps body oldargs)
669 -- Create a new function with the same name but a new body
670 newf <- Trans.lift $ mkFunction f newbody
672 Trans.lift $ MonadState.modify tsInitStates (\ismap ->
673 let init_state_maybe = Map.lookup f ismap in
674 case init_state_maybe of
676 Just init_state -> Map.insert newf init_state ismap)
677 -- Replace the original application with one of the new function to the
679 change $ MkCore.mkCoreApps (Var newf) newargs
681 -- Don't change the expression if none of the arguments changed
684 -- If we don't have a body for the function called, leave it unchanged (it
685 -- should be a primitive function then).
686 Nothing -> return expr
688 -- Find the function called and the arguments
689 (fexpr, args) = collectArgs expr
692 -- Process a single argument and return (args, bndrs, arg), where args are
693 -- the arguments to replace the given argument in the original
694 -- application, bndrs are the binders to include in the top-level lambda
695 -- in the new function body, and arg is the argument to apply to the old
697 doarg :: CoreExpr -> TransformMonad ([CoreExpr], [CoreBndr], CoreExpr)
700 bndrs <- Trans.lift getGlobalBinders
701 let interesting var = Var.isLocalVar var && (var `notElem` bndrs)
702 if not repr && not (is_var arg && interesting (exprToVar arg)) && not (has_free_tyvars arg)
704 -- Propagate all complex arguments that are not representable, but not
705 -- arguments with free type variables (since those would require types
706 -- not known yet, which will always be known eventually).
707 -- Find interesting free variables, each of which should be passed to
708 -- the new function instead of the original function argument.
710 -- Interesting vars are those that are local, but not available from the
711 -- top level scope (functions from this module are defined as local, but
712 -- they're not local to this function, so we can freely move references
713 -- to them into another function).
714 let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting arg
715 -- Mark the current expression as changed
717 -- TODO: Clone the free_vars (and update references in arg), since
718 -- this might cause conflicts if two arguments that are propagated
719 -- share a free variable. Also, we are now introducing new variables
720 -- into a function that are not fresh, which violates the binder
721 -- uniqueness invariant.
722 return (map Var free_vars, free_vars, arg)
724 -- Representable types will not be propagated, and arguments with free
725 -- type variables will be propagated later.
726 -- Note that we implicitly remove any type variables in the type of
727 -- the original argument by using the type of the actual argument
728 -- for the new formal parameter.
729 -- TODO: preserve original naming?
730 id <- Trans.lift $ mkBinderFor arg "param"
731 -- Just pass the original argument to the new function, which binds it
732 -- to a new id and just pass that new id to the old function body.
733 return ([arg], [id], mkReferenceTo id)
734 -- Leave all other expressions unchanged
735 argprop c expr = return expr
736 -- Perform this transform everywhere
737 argproptop = everywhere ("argprop", argprop)
739 --------------------------------
740 -- Function-typed argument extraction
741 --------------------------------
742 -- This transform takes any function-typed argument that cannot be propagated
743 -- (because the function that is applied to it is a builtin function), and
744 -- puts it in a brand new top level binder. This allows us to for example
745 -- apply map to a lambda expression This will not conflict with inlinenonrep,
746 -- since that only inlines local let bindings, not top level bindings.
747 funextract, funextracttop :: Transform
748 funextract c expr@(App _ _) | is_var fexpr = do
749 body_maybe <- Trans.lift $ getGlobalBind f
751 -- We don't have a function body for f, so we can perform this transform.
753 -- Find the new arguments
754 args' <- mapM doarg args
755 -- And update the arguments. We use return instead of changed, so the
756 -- changed flag doesn't get set if none of the args got changed.
757 return $ MkCore.mkCoreApps fexpr args'
758 -- We have a function body for f, leave this application to funprop
759 Just _ -> return expr
761 -- Find the function called and the arguments
762 (fexpr, args) = collectArgs expr
764 -- Change any arguments that have a function type, but are not simple yet
765 -- (ie, a variable or application). This means to create a new function
766 -- for map (\f -> ...) b, but not for map (foo a) b.
768 -- We could use is_applicable here instead of is_fun, but I think
769 -- arguments to functions could only have forall typing when existential
770 -- typing is enabled. Not sure, though.
771 doarg arg | not (is_simple arg) && is_fun arg = do
772 -- Create a new top level binding that binds the argument. Its body will
773 -- be extended with lambda expressions, to take any free variables used
774 -- by the argument expression.
775 let free_vars = VarSet.varSetElems $ CoreFVs.exprFreeVars arg
776 let body = MkCore.mkCoreLams free_vars arg
777 id <- Trans.lift $ mkBinderFor body "fun"
778 Trans.lift $ addGlobalBind id body
779 -- Replace the argument with a reference to the new function, applied to
781 change $ MkCore.mkCoreApps (Var id) (map Var free_vars)
782 -- Leave all other arguments untouched
783 doarg arg = return arg
785 -- Leave all other expressions unchanged
786 funextract c expr = return expr
787 -- Perform this transform everywhere
788 funextracttop = everywhere ("funextract", funextract)
790 --------------------------------
791 -- End of transformations
792 --------------------------------
797 -- What transforms to run?
798 transforms = [inlinedicttop, inlinetopleveltop, classopresolutiontop, argproptop, funextracttop, etatop, betatop, castproptop, letremovesimpletop, letrectop, letremovetop, retvalsimpltop, letflattop, scrutsimpltop, scrutbndrremovetop, casesimpltop, caseremovetop, inlinenonreptop, appsimpltop, letremoveunusedtop, castsimpltop]
800 -- | Returns the normalized version of the given function, or an error
801 -- if it is not a known global binder.
803 CoreBndr -- ^ The function to get
804 -> TranslatorSession CoreExpr -- The normalized function body
805 getNormalized bndr = do
806 norm <- getNormalized_maybe bndr
807 return $ Maybe.fromMaybe
808 (error $ "Normalize.getNormalized: Unknown or non-representable function requested: " ++ show bndr)
811 -- | Returns the normalized version of the given function, or Nothing
812 -- when the binder is not a known global binder or is not normalizeable.
813 getNormalized_maybe ::
814 CoreBndr -- ^ The function to get
815 -> TranslatorSession (Maybe CoreExpr) -- The normalized function body
817 getNormalized_maybe bndr = do
818 expr_maybe <- getGlobalBind bndr
819 normalizeable <- isNormalizeable' bndr
820 if not normalizeable || Maybe.isNothing expr_maybe
822 -- Binder not normalizeable or not found
824 else if is_poly (Var bndr)
826 -- This should really only happen at the top level... TODO: Give
827 -- a different error if this happens down in the recursion.
828 error $ "\nNormalize.normalizeBind: Function " ++ show bndr ++ " is polymorphic, can't normalize"
830 -- Binder found and is monomorphic. Normalize the expression
831 -- and cache the result.
832 normalized <- Utils.makeCached bndr tsNormalized $
833 normalizeExpr (show bndr) (Maybe.fromJust expr_maybe)
834 return (Just normalized)
836 -- | Normalize an expression
838 String -- ^ What are we normalizing? For debug output only.
839 -> CoreSyn.CoreExpr -- ^ The expression to normalize
840 -> TranslatorSession CoreSyn.CoreExpr -- ^ The normalized expression
842 normalizeExpr what expr = do
843 startcount <- MonadState.get tsTransformCounter
844 expr_uniqued <- genUniques expr
845 -- Normalize this expression
846 trace (what ++ " before normalization:\n\n" ++ showSDoc ( ppr expr_uniqued ) ++ "\n") $ return ()
847 expr' <- dotransforms transforms expr_uniqued
848 endcount <- MonadState.get tsTransformCounter
849 trace ("\n" ++ what ++ " after normalization:\n\n" ++ showSDoc ( ppr expr')
850 ++ "\nNeeded " ++ show (endcount - startcount) ++ " transformations to normalize " ++ what) $
853 -- | Split a normalized expression into the argument binders, top level
854 -- bindings and the result binder.
856 CoreExpr -- ^ The normalized expression
857 -> ([CoreBndr], [Binding], CoreBndr)
858 splitNormalized expr = (args, binds, res)
860 (args, letexpr) = CoreSyn.collectBinders expr
861 (binds, resexpr) = flattenLets letexpr
862 res = case resexpr of
864 _ -> error $ "Normalize.splitNormalized: Not in normal form: " ++ pprString expr ++ "\n"