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 Normalize (normalizeModule) where
11 import qualified Maybe
12 import qualified "transformers" Control.Monad.Trans as Trans
13 import qualified Control.Monad as Monad
14 import qualified Control.Monad.Trans.Writer as Writer
15 import qualified Data.Map as Map
16 import qualified Data.Monoid as Monoid
21 import qualified UniqSupply
22 import qualified CoreUtils
26 import qualified VarSet
27 import qualified CoreFVs
28 import qualified CoreUtils
29 import qualified MkCore
30 import Outputable ( showSDoc, ppr, nest )
37 --------------------------------
38 -- Start of transformations
39 --------------------------------
41 --------------------------------
43 --------------------------------
44 eta, etatop :: Transform
45 eta expr | is_fun expr && not (is_lam expr) = do
46 let arg_ty = (fst . Type.splitFunTy . CoreUtils.exprType) expr
47 id <- mkInternalVar "param" arg_ty
48 change (Lam id (App expr (Var id)))
49 -- Leave all other expressions unchanged
51 etatop = notapplied ("eta", eta)
53 --------------------------------
55 --------------------------------
56 beta, betatop :: Transform
57 -- Substitute arg for x in expr
58 beta (App (Lam x expr) arg) = change $ substitute [(x, arg)] expr
59 -- Propagate the application into the let
60 beta (App (Let binds expr) arg) = change $ Let binds (App expr arg)
61 -- Propagate the application into each of the alternatives
62 beta (App (Case scrut b ty alts) arg) = change $ Case scrut b ty' alts'
64 alts' = map (\(con, bndrs, expr) -> (con, bndrs, (App expr arg))) alts
65 ty' = CoreUtils.applyTypeToArg ty arg
66 -- Leave all other expressions unchanged
67 beta expr = return expr
68 -- Perform this transform everywhere
69 betatop = everywhere ("beta", beta)
71 --------------------------------
72 -- let recursification
73 --------------------------------
74 letrec, letrectop :: Transform
75 letrec (Let (NonRec b expr) res) = change $ Let (Rec [(b, expr)]) res
76 -- Leave all other expressions unchanged
77 letrec expr = return expr
78 -- Perform this transform everywhere
79 letrectop = everywhere ("letrec", letrec)
81 --------------------------------
83 --------------------------------
84 letsimpl, letsimpltop :: Transform
85 -- Don't simplifiy lets that are already simple
86 letsimpl expr@(Let _ (Var _)) = return expr
87 -- Put the "in ..." value of a let in its own binding, but not when the
88 -- expression is applicable (to prevent loops with inlinefun).
89 letsimpl (Let (Rec binds) expr) | not $ is_applicable expr = do
90 id <- mkInternalVar "foo" (CoreUtils.exprType expr)
92 change $ Let (Rec (bind:binds)) (Var id)
93 -- Leave all other expressions unchanged
94 letsimpl expr = return expr
95 -- Perform this transform everywhere
96 letsimpltop = everywhere ("letsimpl", letsimpl)
98 --------------------------------
100 --------------------------------
101 letflat, letflattop :: Transform
102 letflat (Let (Rec binds) expr) = do
103 -- Turn each binding into a list of bindings (possibly containing just one
104 -- element, of course)
105 bindss <- Monad.mapM flatbind binds
106 -- Concat all the bindings
107 let binds' = concat bindss
108 -- Return the new let. We don't use change here, since possibly nothing has
109 -- changed. If anything has changed, flatbind has already flagged that
111 return $ Let (Rec binds') expr
113 -- Turns a binding of a let into a multiple bindings, or any other binding
114 -- into a list with just that binding
115 flatbind :: (CoreBndr, CoreExpr) -> TransformMonad [(CoreBndr, CoreExpr)]
116 flatbind (b, Let (Rec binds) expr) = change ((b, expr):binds)
117 flatbind (b, expr) = return [(b, expr)]
118 -- Leave all other expressions unchanged
119 letflat expr = return expr
120 -- Perform this transform everywhere
121 letflattop = everywhere ("letflat", letflat)
123 --------------------------------
124 -- Simple let binding removal
125 --------------------------------
126 -- Remove a = b bindings from let expressions everywhere
127 letremovetop :: Transform
128 letremovetop = everywhere ("letremove", inlinebind (\(b, e) -> case e of (Var v) -> True; otherwise -> False))
130 --------------------------------
132 --------------------------------
133 -- Remove a = B bindings, with B :: a -> b, or B :: forall x . T, from let
134 -- expressions everywhere. This means that any value that still needs to be
135 -- applied to something else (polymorphic values need to be applied to a
136 -- Type) will be inlined, and will eventually be applied to all their
139 -- This is a tricky function, which is prone to create loops in the
140 -- transformations. To fix this, we make sure that no transformation will
141 -- create a new let binding with a function type. These other transformations
142 -- will just not work on those function-typed values at first, but the other
143 -- transformations (in particular β-reduction) should make sure that the type
144 -- of those values eventually becomes primitive.
145 inlinefuntop :: Transform
146 inlinefuntop = everywhere ("inlinefun", inlinebind (is_applicable . snd))
148 --------------------------------
149 -- Scrutinee simplification
150 --------------------------------
151 scrutsimpl,scrutsimpltop :: Transform
152 -- Don't touch scrutinees that are already simple
153 scrutsimpl expr@(Case (Var _) _ _ _) = return expr
154 -- Replace all other cases with a let that binds the scrutinee and a new
155 -- simple scrutinee, but not when the scrutinee is applicable (to prevent
156 -- loops with inlinefun, though I don't think a scrutinee can be
158 scrutsimpl (Case scrut b ty alts) | not $ is_applicable scrut = do
159 id <- mkInternalVar "scrut" (CoreUtils.exprType scrut)
160 change $ Let (Rec [(id, scrut)]) (Case (Var id) b ty alts)
161 -- Leave all other expressions unchanged
162 scrutsimpl expr = return expr
163 -- Perform this transform everywhere
164 scrutsimpltop = everywhere ("scrutsimpl", scrutsimpl)
166 --------------------------------
167 -- Case binder wildening
168 --------------------------------
169 casewild, casewildtop :: Transform
170 casewild expr@(Case scrut b ty alts) = do
171 (bindingss, alts') <- (Monad.liftM unzip) $ mapM doalt alts
172 let bindings = concat bindingss
173 -- Replace the case with a let with bindings and a case
174 let newlet = (Let (Rec bindings) (Case scrut b ty alts'))
175 -- If there are no non-wild binders, or this case is already a simple
176 -- selector (i.e., a single alt with exactly one binding), already a simple
177 -- selector altan no bindings (i.e., no wild binders in the original case),
178 -- don't change anything, otherwise, replace the case.
179 if null bindings || length alts == 1 && length bindings == 1 then return expr else change newlet
181 -- Generate a single wild binder, since they are all the same
183 -- Wilden the binders of one alt, producing a list of bindings as a
185 doalt :: CoreAlt -> TransformMonad ([(CoreBndr, CoreExpr)], CoreAlt)
186 doalt (con, bndrs, expr) = do
187 bindings_maybe <- Monad.zipWithM mkextracts bndrs [0..]
188 let bindings = Maybe.catMaybes bindings_maybe
189 -- We replace the binders with wild binders only. We can leave expr
190 -- unchanged, since the new bindings bind the same vars as the original
192 let newalt = (con, wildbndrs, expr)
193 return (bindings, newalt)
195 -- Make all binders wild
196 wildbndrs = map (\bndr -> Id.mkWildId (Id.idType bndr)) bndrs
197 -- Creates a case statement to retrieve the ith element from the scrutinee
198 -- and binds that to b.
199 mkextracts :: CoreBndr -> Int -> TransformMonad (Maybe (CoreBndr, CoreExpr))
201 if is_wild b || Type.isFunTy (Id.idType b)
202 -- Don't create extra bindings for binders that are already wild, or
203 -- for binders that bind function types (to prevent loops with
207 -- Create on new binder that will actually capture a value in this
208 -- case statement, and return it
209 let bty = (Id.idType b)
210 id <- mkInternalVar "sel" bty
211 let binders = take i wildbndrs ++ [id] ++ drop (i+1) wildbndrs
212 return $ Just (b, Case scrut b bty [(con, binders, Var id)])
213 -- Leave all other expressions unchanged
214 casewild expr = return expr
215 -- Perform this transform everywhere
216 casewildtop = everywhere ("casewild", casewild)
218 --------------------------------
219 -- Case value simplification
220 --------------------------------
221 casevalsimpl, casevalsimpltop :: Transform
222 casevalsimpl expr@(Case scrut b ty alts) = do
223 -- Try to simplify each alternative, resulting in an optional binding and a
225 (bindings_maybe, alts') <- (Monad.liftM unzip) $ mapM doalt alts
226 let bindings = Maybe.catMaybes bindings_maybe
227 -- Create a new let around the case, that binds of the cases values.
228 let newlet = Let (Rec bindings) (Case scrut b ty alts')
229 -- If there were no values that needed and allowed simplification, don't
231 if null bindings then return expr else change newlet
233 doalt :: CoreAlt -> TransformMonad (Maybe (CoreBndr, CoreExpr), CoreAlt)
234 -- Don't simplify values that are already simple
235 doalt alt@(con, bndrs, Var _) = return (Nothing, alt)
236 -- Simplify each alt by creating a new id, binding the case value to it and
237 -- replacing the case value with that id. Only do this when the case value
238 -- does not use any of the binders bound by this alternative, for that would
239 -- cause those binders to become unbound when moving the value outside of
240 -- the case statement. Also, don't create a binding for applicable
241 -- expressions, to prevent loops with inlinefun.
242 doalt (con, bndrs, expr) | (not usesvars) && (not $ is_applicable expr) = do
243 id <- mkInternalVar "caseval" (CoreUtils.exprType expr)
244 -- We don't flag a change here, since casevalsimpl will do that above
245 -- based on Just we return here.
246 return $ (Just (id, expr), (con, bndrs, Var id))
247 -- Find if any of the binders are used by expr
248 where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` bndrs))) expr
249 -- Don't simplify anything else
250 doalt alt = return (Nothing, alt)
251 -- Leave all other expressions unchanged
252 casevalsimpl expr = return expr
253 -- Perform this transform everywhere
254 casevalsimpltop = everywhere ("casevalsimpl", casevalsimpl)
256 --------------------------------
258 --------------------------------
259 -- Remove case statements that have only a single alternative and only wild
261 caseremove, caseremovetop :: Transform
262 -- Replace a useless case by the value of its single alternative
263 caseremove (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
264 -- Find if any of the binders are used by expr
265 where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` bndrs))) expr
266 -- Leave all other expressions unchanged
267 caseremove expr = return expr
268 -- Perform this transform everywhere
269 caseremovetop = everywhere ("caseremove", caseremove)
271 --------------------------------
272 -- Application simplification
273 --------------------------------
274 -- Make sure that all arguments in an application are simple variables.
275 appsimpl, appsimpltop :: Transform
276 -- Don't simplify arguments that are already simple
277 appsimpl expr@(App f (Var _)) = return expr
278 -- Simplify all non-applicable (to prevent loops with inlinefun) arguments,
279 -- except for type arguments (since a let can't bind type vars, only a lambda
280 -- can). Do this by introducing a new Let that binds the argument and passing
281 -- the new binder in the application.
282 appsimpl (App f expr) | (not $ is_applicable expr) && (not $ CoreSyn.isTypeArg expr) = do
283 id <- mkInternalVar "arg" (CoreUtils.exprType expr)
284 change $ Let (Rec [(id, expr)]) (App f (Var id))
285 -- Leave all other expressions unchanged
286 appsimpl expr = return expr
287 -- Perform this transform everywhere
288 appsimpltop = everywhere ("appsimpl", appsimpl)
291 --------------------------------
292 -- Type argument propagation
293 --------------------------------
294 -- Remove all applications to type arguments, by duplicating the function
295 -- called with the type application in its new definition. We leave
296 -- dictionaries that might be associated with the type untouched, the funprop
297 -- transform should propagate these later on.
298 typeprop, typeproptop :: Transform
299 -- Transform any function that is applied to a type argument. Since type
300 -- arguments are always the first ones to apply and we'll remove all type
301 -- arguments, we can simply do them one by one. We only propagate type
302 -- arguments without any free tyvars, since tyvars those wouldn't be in scope
303 -- in the new function.
304 typeprop expr@(App (Var f) arg@(Type ty)) | not $ has_free_tyvars arg = do
306 let newty = Type.applyTy (Id.idType f) ty
307 let newf = Var.setVarType id newty
308 body_maybe <- Trans.lift $ getGlobalBind f
311 let newbody = App body (Type ty)
312 Trans.lift $ addGlobalBind newf newbody
314 -- If we don't have a body for the function called, leave it unchanged (it
315 -- should be a primitive function then).
316 Nothing -> return expr
317 -- Leave all other expressions unchanged
318 typeprop expr = return expr
319 -- Perform this transform everywhere
320 typeproptop = everywhere ("typeprop", typeprop)
323 --------------------------------
324 -- Function-typed argument propagation
325 --------------------------------
326 -- Remove all applications to function-typed arguments, by duplication the
327 -- function called with the function-typed parameter replaced by the free
328 -- variables of the argument passed in.
329 funprop, funproptop :: Transform
330 -- Transform any application of a named function (i.e., skip applications of
331 -- lambda's). Also skip applications that have arguments with free type
332 -- variables, since we can't inline those.
333 funprop expr@(App _ _) | is_var fexpr && not (any has_free_tyvars args) = do
334 -- Find the body of the function called
335 body_maybe <- Trans.lift $ getGlobalBind f
338 -- Process each of the arguments in turn
339 (args', changed) <- Writer.listen $ mapM doarg args
340 -- See if any of the arguments changed
341 case Monoid.getAny changed of
343 let (newargs', newparams', oldargs) = unzip3 args'
344 let newargs = concat newargs'
345 let newparams = concat newparams'
346 -- Create a new body that consists of a lambda for all new arguments and
347 -- the old body applied to some arguments.
348 let newbody = MkCore.mkCoreLams newparams (MkCore.mkCoreApps body oldargs)
349 -- Create a new function name
351 let newf = Var.setVarType id (CoreUtils.exprType newbody)
352 -- Add the new function
353 Trans.lift $ addGlobalBind newf newbody
354 -- Replace the original application with one of the new function to the
356 change $ MkCore.mkCoreApps (Var newf) newargs
358 -- Don't change the expression if none of the arguments changed
361 -- If we don't have a body for the function called, leave it unchanged (it
362 -- should be a primitive function then).
363 Nothing -> return expr
365 -- Find the function called and the arguments
366 (fexpr, args) = collectArgs expr
369 -- Process a single argument and return (args, bndrs, arg), where args are
370 -- the arguments to replace the given argument in the original
371 -- application, bndrs are the binders to include in the top-level lambda
372 -- in the new function body, and arg is the argument to apply to the old
374 doarg :: CoreExpr -> TransformMonad ([CoreExpr], [CoreBndr], CoreExpr)
375 doarg arg | is_fun arg = do
376 bndrs <- Trans.lift getGlobalBinders
377 -- Find interesting free variables, each of which should be passed to
378 -- the new function instead of the original function argument.
380 -- Interesting vars are those that are local, but not available from the
381 -- top level scope (functions from this module are defined as local, but
382 -- they're not local to this function, so we can freely move references
383 -- to them into another function).
384 let interesting var = Var.isLocalVar var && (not $ var `elem` bndrs)
385 let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting arg
386 -- Mark the current expression as changed
388 return (map Var free_vars, free_vars, arg)
389 -- Non-functiontyped arguments can be unchanged. Note that this handles
390 -- both values and types.
392 -- TODO: preserve original naming?
393 id <- mkBinderFor arg "param"
394 -- Just pass the original argument to the new function, which binds it
395 -- to a new id and just pass that new id to the old function body.
396 return ([arg], [id], mkReferenceTo id)
397 -- Leave all other expressions unchanged
398 funprop expr = return expr
399 -- Perform this transform everywhere
400 funproptop = everywhere ("funprop", funprop)
403 -- TODO: introduce top level let if needed?
405 --------------------------------
406 -- End of transformations
407 --------------------------------
412 -- What transforms to run?
413 transforms = [typeproptop, funproptop, etatop, betatop, letremovetop, letrectop, letsimpltop, letflattop, casewildtop, scrutsimpltop, casevalsimpltop, caseremovetop, inlinefuntop, appsimpltop]
415 -- Turns the given bind into VHDL
417 UniqSupply.UniqSupply -- ^ A UniqSupply we can use
418 -> [(CoreBndr, CoreExpr)] -- ^ All bindings we know (i.e., in the current module)
419 -> [CoreBndr] -- ^ The bindings to generate VHDL for (i.e., the top level bindings)
420 -> [Bool] -- ^ For each of the bindings to generate VHDL for, if it is stateful
421 -> [(CoreBndr, CoreExpr)] -- ^ The resulting VHDL
423 normalizeModule uniqsupply bindings generate_for statefuls = runTransformSession uniqsupply $ do
424 -- Put all the bindings in this module in the tsBindings map
425 putA tsBindings (Map.fromList bindings)
426 -- (Recursively) normalize each of the requested bindings
427 mapM normalizeBind generate_for
428 -- Get all initial bindings and the ones we produced
429 bindings_map <- getA tsBindings
430 let bindings = Map.assocs bindings_map
431 normalized_bindings <- getA tsNormalized
432 -- But return only the normalized bindings
433 return $ filter ((flip VarSet.elemVarSet normalized_bindings) . fst) bindings
435 normalizeBind :: CoreBndr -> TransformSession ()
436 normalizeBind bndr = do
437 normalized_funcs <- getA tsNormalized
438 -- See if this function was normalized already
439 if VarSet.elemVarSet bndr normalized_funcs
441 -- Yup, don't do it again
444 -- Nope, note that it has been and do it.
445 modA tsNormalized (flip VarSet.extendVarSet bndr)
446 expr_maybe <- getGlobalBind bndr
449 -- Normalize this expression
450 trace ("Transforming " ++ (show bndr) ++ "\nBefore:\n\n" ++ showSDoc ( ppr expr ) ++ "\n") $ return ()
451 expr' <- dotransforms transforms expr
452 trace ("\nAfter:\n\n" ++ showSDoc ( ppr expr')) $ return ()
453 -- And store the normalized version in the session
454 modA tsBindings (Map.insert bndr expr')
455 -- Find all vars used with a function type. All of these should be global
456 -- binders (i.e., functions used), since any local binders with a function
457 -- type should have been inlined already.
458 let used_funcs_set = CoreFVs.exprSomeFreeVars (\v -> (Type.isFunTy . snd . Type.splitForAllTys . Id.idType) v) expr'
459 let used_funcs = VarSet.varSetElems used_funcs_set
460 -- Process each of the used functions recursively
461 mapM normalizeBind used_funcs
463 -- We don't have a value for this binder, let's assume this is a builtin
464 -- function. This might need some extra checking and a nice error