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