Also simplify expressions of the DEFAULT alternative of case expressions
[matthijs/master-project/cλash.git] / clash / CLasH / Normalize.hs
1 --
2 -- Functions to bring a Core expression in normal form. This module provides a
3 -- top level function "normalize", and defines the actual transformation passes that
4 -- are performed.
5 --
6 module CLasH.Normalize (getNormalized, normalizeExpr, splitNormalized) where
7
8 -- Standard modules
9 import Debug.Trace
10 import qualified Maybe
11 import qualified List
12 import qualified Control.Monad.Trans.Class as Trans
13 import qualified Control.Monad as Monad
14 import qualified Control.Monad.Trans.Writer as Writer
15 import qualified Data.Accessor.Monad.Trans.State as MonadState
16 import qualified Data.Monoid as Monoid
17 import qualified Data.Map as Map
18
19 -- GHC API
20 import CoreSyn
21 import qualified CoreUtils
22 import qualified BasicTypes
23 import qualified Type
24 import qualified TysWiredIn
25 import qualified Id
26 import qualified Var
27 import qualified Name
28 import qualified DataCon
29 import qualified VarSet
30 import qualified CoreFVs
31 import qualified Class
32 import qualified MkCore
33 import Outputable ( showSDoc, ppr, nest )
34
35 -- Local imports
36 import CLasH.Normalize.NormalizeTypes
37 import CLasH.Translator.TranslatorTypes
38 import CLasH.Normalize.NormalizeTools
39 import CLasH.VHDL.Constants (builtinIds)
40 import qualified CLasH.Utils as Utils
41 import CLasH.Utils.Core.CoreTools
42 import CLasH.Utils.Core.BinderTools
43 import CLasH.Utils.Pretty
44
45 ----------------------------------------------------------------
46 -- Cleanup transformations
47 ----------------------------------------------------------------
48
49 --------------------------------
50 -- β-reduction
51 --------------------------------
52 beta :: Transform
53 -- Substitute arg for x in expr. For value lambda's, also clone before
54 -- substitution.
55 beta c (App (Lam x expr) arg) | CoreSyn.isTyVar x = setChanged >> substitute x arg c expr
56                               | otherwise         = setChanged >> substitute_clone x arg c expr
57 -- Leave all other expressions unchanged
58 beta c expr = return expr
59
60 --------------------------------
61 -- Unused let binding removal
62 --------------------------------
63 letremoveunused :: Transform
64 letremoveunused c expr@(Let (NonRec b bound) res) = do
65   let used = expr_uses_binders [b] res
66   if used
67     then return expr
68     else change res
69 letremoveunused c expr@(Let (Rec binds) res) = do
70   -- Filter out all unused binds.
71   let binds' = filter dobind binds
72   -- Only set the changed flag if binds got removed
73   changeif (length binds' /= length binds) (Let (Rec binds') res)
74     where
75       bound_exprs = map snd binds
76       -- For each bind check if the bind is used by res or any of the bound
77       -- expressions
78       dobind (bndr, _) = any (expr_uses_binders [bndr]) (res:bound_exprs)
79 -- Leave all other expressions unchanged
80 letremoveunused c expr = return expr
81
82 --------------------------------
83 -- empty let removal
84 --------------------------------
85 -- Remove empty (recursive) lets
86 letremove :: Transform
87 letremove c (Let (Rec []) res) = change res
88 -- Leave all other expressions unchanged
89 letremove c expr = return expr
90
91 --------------------------------
92 -- Simple let binding removal
93 --------------------------------
94 -- Remove a = b bindings from let expressions everywhere
95 letremovesimple :: Transform
96 letremovesimple = inlinebind (\(b, e) -> Trans.lift $ is_local_var e)
97
98 --------------------------------
99 -- Cast propagation
100 --------------------------------
101 -- Try to move casts as much downward as possible.
102 castprop :: Transform
103 castprop c (Cast (Let binds expr) ty) = change $ Let binds (Cast expr ty)
104 castprop c expr@(Cast (Case scrut b _ alts) ty) = change (Case scrut b ty alts')
105   where
106     alts' = map (\(con, bndrs, expr) -> (con, bndrs, (Cast expr ty))) alts
107 -- Leave all other expressions unchanged
108 castprop c expr = return expr
109
110 --------------------------------
111 -- Cast simplification. Mostly useful for state packing and unpacking, but
112 -- perhaps for others as well.
113 --------------------------------
114 castsimpl :: Transform
115 castsimpl c expr@(Cast val ty) = do
116   -- Don't extract values that are already simpl
117   local_var <- Trans.lift $ is_local_var val
118   -- Don't extract values that are not representable, to prevent loops with
119   -- inlinenonrep
120   repr <- isRepr val
121   if (not local_var) && repr
122     then do
123       -- Generate a binder for the expression
124       id <- Trans.lift $ mkBinderFor val "castval"
125       -- Extract the expression
126       change $ Let (NonRec id val) (Cast (Var id) ty)
127     else
128       return expr
129 -- Leave all other expressions unchanged
130 castsimpl c expr = return expr
131
132 --------------------------------
133 -- Top level function inlining
134 --------------------------------
135 -- This transformation inlines simple top level bindings. Simple
136 -- currently means that the body is only a single application (though
137 -- the complexity of the arguments is not currently checked) or that the
138 -- normalized form only contains a single binding. This should catch most of the
139 -- cases where a top level function is created that simply calls a type class
140 -- method with a type and dictionary argument, e.g.
141 --   fromInteger = GHC.Num.fromInteger (SizedWord D8) $dNum
142 -- which is later called using simply
143 --   fromInteger (smallInteger 10)
144 --
145 -- These useless wrappers are created by GHC automatically. If we don't
146 -- inline them, we get loads of useless components cluttering the
147 -- generated VHDL.
148 --
149 -- Note that the inlining could also inline simple functions defined by
150 -- the user, not just GHC generated functions. It turns out to be near
151 -- impossible to reliably determine what functions are generated and
152 -- what functions are user-defined. Instead of guessing (which will
153 -- inline less than we want) we will just inline all simple functions.
154 --
155 -- Only functions that are actually completely applied and bound by a
156 -- variable in a let expression are inlined. These are the expressions
157 -- that will eventually generate instantiations of trivial components.
158 -- By not inlining any other reference, we also prevent looping problems
159 -- with funextract and inlinedict.
160 inlinetoplevel :: Transform
161 inlinetoplevel c expr | not (null c) && is_letbinding_ctx (head c) && not (is_fun expr) =
162   case collectArgs expr of
163         (Var f, args) -> do
164           body_maybe <- needsInline f
165           case body_maybe of
166                 Just body -> do
167                         -- Regenerate all uniques in the to-be-inlined expression
168                         body_uniqued <- Trans.lift $ genUniques body
169                         -- And replace the variable reference with the unique'd body.
170                         change (mkApps body_uniqued args)
171                         -- No need to inline
172                 Nothing -> return expr
173         -- This is not an application of a binder, leave it unchanged.
174         _ -> return expr
175
176 -- Leave all other expressions unchanged
177 inlinetoplevel c expr = return expr
178
179 -- | Does the given binder need to be inlined? If so, return the body to
180 -- be used for inlining.
181 needsInline :: CoreBndr -> TransformMonad (Maybe CoreExpr)
182 needsInline f = do
183   body_maybe <- Trans.lift $ getGlobalBind f
184   case body_maybe of
185     -- No body available?
186     Nothing -> return Nothing
187     Just body -> case CoreSyn.collectArgs body of
188       -- The body is some (top level) binder applied to 0 or more
189       -- arguments. That should be simple enough to inline.
190       (Var f, args) -> return $ Just body
191       -- Body is more complicated, try normalizing it
192       _ -> do
193         norm_maybe <- Trans.lift $ getNormalized_maybe False f
194         case norm_maybe of
195           -- Noth normalizeable
196           Nothing -> return Nothing 
197           Just norm -> case splitNormalizedNonRep norm of
198             -- The function has just a single binding, so that's simple
199             -- enough to inline.
200             (args, [bind], Var res) -> return $ Just norm
201             -- More complicated function, don't inline
202             _ -> return Nothing
203
204
205 ----------------------------------------------------------------
206 -- Program structure transformations
207 ----------------------------------------------------------------
208
209 --------------------------------
210 -- η expansion
211 --------------------------------
212 -- Make sure all parameters to the normalized functions are named by top
213 -- level lambda expressions. For this we apply η expansion to the
214 -- function body (possibly enclosed in some lambda abstractions) while
215 -- it has a function type. Eventually this will result in a function
216 -- body consisting of a bunch of nested lambdas containing a
217 -- non-function value (e.g., a complete application).
218 eta :: Transform
219 eta c expr | not (null c) && is_appfirst_ctx (head c) = return expr
220 -- Also don't apply to arguments, since this can cause loops with
221 -- funextract. This isn't the proper solution, but due to an
222 -- implementation bug in notappargs, this is how it used to work so far.
223            | not (null c) && is_appsecond_ctx (head c) = return expr
224            | is_fun expr && not (is_lam expr) = do
225  let arg_ty = (fst . Type.splitFunTy . CoreUtils.exprType) expr
226  id <- Trans.lift $ mkInternalVar "param" arg_ty
227  change (Lam id (App expr (Var id)))
228 -- Leave all other expressions unchanged
229 eta c e = return e
230
231 --------------------------------
232 -- Application propagation
233 --------------------------------
234 -- Move applications into let and case expressions.
235 appprop :: Transform
236 -- Propagate the application into the let
237 appprop c (App (Let binds expr) arg) = change $ Let binds (App expr arg)
238 -- Propagate the application into each of the alternatives
239 appprop c (App (Case scrut b ty alts) arg) = change $ Case scrut b ty' alts'
240   where 
241     alts' = map (\(con, bndrs, expr) -> (con, bndrs, (App expr arg))) alts
242     ty' = CoreUtils.applyTypeToArg ty arg
243 -- Leave all other expressions unchanged
244 appprop c expr = return expr
245
246 --------------------------------
247 -- Let recursification
248 --------------------------------
249 -- Make all lets recursive, so other transformations don't need to
250 -- handle non-recursive lets
251 letrec :: Transform
252 letrec c expr@(Let (NonRec bndr val) res) = 
253   change $ Let (Rec [(bndr, val)]) res
254
255 -- Leave all other expressions unchanged
256 letrec c expr = return expr
257
258 --------------------------------
259 -- let flattening
260 --------------------------------
261 -- Takes a let that binds another let, and turns that into two nested lets.
262 -- e.g., from:
263 -- let b = (let b' = expr' in res') in res
264 -- to:
265 -- let b' = expr' in (let b = res' in res)
266 letflat :: Transform
267 -- Turn a nonrec let that binds a let into two nested lets.
268 letflat c (Let (NonRec b (Let binds  res')) res) = 
269   change $ Let binds (Let (NonRec b res') res)
270 letflat c (Let (Rec binds) expr) = do
271   -- Flatten each binding.
272   binds' <- Utils.concatM $ Monad.mapM flatbind binds
273   -- Return the new let. We don't use change here, since possibly nothing has
274   -- changed. If anything has changed, flatbind has already flagged that
275   -- change.
276   return $ Let (Rec binds') expr
277   where
278     -- Turns a binding of a let into a multiple bindings, or any other binding
279     -- into a list with just that binding
280     flatbind :: (CoreBndr, CoreExpr) -> TransformMonad [(CoreBndr, CoreExpr)]
281     flatbind (b, Let (Rec binds) expr) = change ((b, expr):binds)
282     flatbind (b, Let (NonRec b' expr') expr) = change [(b, expr), (b', expr')]
283     flatbind (b, expr) = return [(b, expr)]
284 -- Leave all other expressions unchanged
285 letflat c expr = return expr
286
287 --------------------------------
288 -- Return value simplification
289 --------------------------------
290 -- Ensure the return value of a function follows proper normal form. eta
291 -- expansion ensures the body starts with lambda abstractions, this
292 -- transformation ensures that the lambda abstractions always contain a
293 -- recursive let and that, when the return value is representable, the
294 -- let contains a local variable reference in its body.
295
296 -- Extract the return value from the body of the top level lambdas (of
297 -- which ther could be zero), unless it is a let expression (in which
298 -- case the next clause applies).
299 retvalsimpl c expr | all is_lambdabody_ctx c && not (is_lam expr) && not (is_let expr) = do
300   local_var <- Trans.lift $ is_local_var expr
301   repr <- isRepr expr
302   if not local_var && repr
303     then do
304       id <- Trans.lift $ mkBinderFor expr "res" 
305       change $ Let (Rec [(id, expr)]) (Var id)
306     else
307       return expr
308 -- Extract the return value from the body of a let expression, which is
309 -- itself the body of the top level lambdas (of which there could be
310 -- zero).
311 retvalsimpl c expr@(Let (Rec binds) body) | all is_lambdabody_ctx c = do
312   -- Don't extract values that are already a local variable, to prevent
313   -- loops with ourselves.
314   local_var <- Trans.lift $ is_local_var body
315   -- Don't extract values that are not representable, to prevent loops with
316   -- inlinenonrep
317   repr <- isRepr body
318   if not local_var && repr
319     then do
320       id <- Trans.lift $ mkBinderFor body "res" 
321       change $ Let (Rec ((id, body):binds)) (Var id)
322     else
323       return expr
324 -- Leave all other expressions unchanged
325 retvalsimpl c expr = return expr
326
327 --------------------------------
328 -- Representable arguments simplification
329 --------------------------------
330 -- Make sure that all arguments of a representable type are simple variables.
331 appsimpl :: Transform
332 -- Simplify all representable arguments. Do this by introducing a new Let
333 -- that binds the argument and passing the new binder in the application.
334 appsimpl c expr@(App f arg) = do
335   -- Check runtime representability
336   repr <- isRepr arg
337   local_var <- Trans.lift $ is_local_var arg
338   if repr && not local_var
339     then do -- Extract representable arguments
340       id <- Trans.lift $ mkBinderFor arg "arg"
341       change $ Let (NonRec id arg) (App f (Var id))
342     else -- Leave non-representable arguments unchanged
343       return expr
344 -- Leave all other expressions unchanged
345 appsimpl c expr = return expr
346
347 ----------------------------------------------------------------
348 -- Built-in function transformations
349 ----------------------------------------------------------------
350
351 --------------------------------
352 -- Function-typed argument extraction
353 --------------------------------
354 -- This transform takes any function-typed argument that cannot be propagated
355 -- (because the function that is applied to it is a builtin function), and
356 -- puts it in a brand new top level binder. This allows us to for example
357 -- apply map to a lambda expression This will not conflict with inlinenonrep,
358 -- since that only inlines local let bindings, not top level bindings.
359 funextract :: Transform
360 funextract c expr@(App _ _) | is_var fexpr = do
361   body_maybe <- Trans.lift $ getGlobalBind f
362   case body_maybe of
363     -- We don't have a function body for f, so we can perform this transform.
364     Nothing -> do
365       -- Find the new arguments
366       args' <- mapM doarg args
367       -- And update the arguments. We use return instead of changed, so the
368       -- changed flag doesn't get set if none of the args got changed.
369       return $ MkCore.mkCoreApps fexpr args'
370     -- We have a function body for f, leave this application to funprop
371     Just _ -> return expr
372   where
373     -- Find the function called and the arguments
374     (fexpr, args) = collectArgs expr
375     Var f = fexpr
376     -- Change any arguments that have a function type, but are not simple yet
377     -- (ie, a variable or application). This means to create a new function
378     -- for map (\f -> ...) b, but not for map (foo a) b.
379     --
380     -- We could use is_applicable here instead of is_fun, but I think
381     -- arguments to functions could only have forall typing when existential
382     -- typing is enabled. Not sure, though.
383     doarg arg | not (is_simple arg) && is_fun arg && not (has_free_tyvars arg) = do
384       -- Create a new top level binding that binds the argument. Its body will
385       -- be extended with lambda expressions, to take any free variables used
386       -- by the argument expression.
387       let free_vars = VarSet.varSetElems $ CoreFVs.exprFreeVars arg
388       let body = MkCore.mkCoreLams free_vars arg
389       id <- Trans.lift $ mkBinderFor body "fun"
390       Trans.lift $ addGlobalBind id body
391       -- Replace the argument with a reference to the new function, applied to
392       -- all vars it uses.
393       change $ MkCore.mkCoreApps (Var id) (map Var free_vars)
394     -- Leave all other arguments untouched
395     doarg arg = return arg
396
397 -- Leave all other expressions unchanged
398 funextract c expr = return expr
399
400
401
402
403 ----------------------------------------------------------------
404 -- Case normalization transformations
405 ----------------------------------------------------------------
406
407 --------------------------------
408 -- Scrutinee simplification
409 --------------------------------
410 -- Make sure the scrutinee of a case expression is a local variable
411 -- reference.
412 scrutsimpl :: Transform
413 -- Replace a case expression with a let that binds the scrutinee and a new
414 -- simple scrutinee, but only when the scrutinee is representable (to prevent
415 -- loops with inlinenonrep, though I don't think a non-representable scrutinee
416 -- will be supported anyway...) and is not a local variable already.
417 scrutsimpl c expr@(Case scrut b ty alts) = do
418   repr <- isRepr scrut
419   local_var <- Trans.lift $ is_local_var scrut
420   if repr && not local_var
421     then do
422       id <- Trans.lift $ mkBinderFor scrut "scrut"
423       change $ Let (NonRec id scrut) (Case (Var id) b ty alts)
424     else
425       return expr
426 -- Leave all other expressions unchanged
427 scrutsimpl c expr = return expr
428
429 --------------------------------
430 -- Scrutinee binder removal
431 --------------------------------
432 -- A case expression can have an extra binder, to which the scrutinee is bound
433 -- after bringing it to WHNF. This is used for forcing evaluation of strict
434 -- arguments. Since strictness does not matter for us (rather, everything is
435 -- sort of strict), this binder is ignored when generating VHDL, and must thus
436 -- be wild in the normal form.
437 scrutbndrremove :: Transform
438 -- If the scrutinee is already simple, and the bndr is not wild yet, replace
439 -- all occurences of the binder with the scrutinee variable.
440 scrutbndrremove c (Case (Var scrut) bndr ty alts) | bndr_used = do
441     alts' <- mapM subs_bndr alts
442     change $ Case (Var scrut) wild ty alts'
443   where
444     is_used (_, _, expr) = expr_uses_binders [bndr] expr
445     bndr_used = or $ map is_used alts
446     subs_bndr (con, bndrs, expr) = do
447       expr' <- substitute bndr (Var scrut) c expr
448       return (con, bndrs, expr')
449     wild = MkCore.mkWildBinder (Id.idType bndr)
450 -- Leave all other expressions unchanged
451 scrutbndrremove c expr = return expr
452
453 --------------------------------
454 -- Case normalization
455 --------------------------------
456 -- Turn a case expression with any number of alternatives with any
457 -- number of non-wild binders into as set of case and let expressions,
458 -- all of which are in normal form (e.g., a bunch of extractor case
459 -- expressions to extract all fields from the scrutinee, a number of let
460 -- bindings to bind each alternative and a single selector case to
461 -- select the right value.
462 casesimpl :: Transform
463 -- This is already a selector case (or, if x does not appear in bndrs, a very
464 -- simple case statement that will be removed by caseremove below). Just leave
465 -- it be.
466 casesimpl c expr@(Case scrut b ty [(con, bndrs, Var x)]) = return expr
467 -- Make sure that all case alternatives have only wild binders and simple
468 -- expressions.
469 -- This is done by creating a new let binding for each non-wild binder, which
470 -- is bound to a new simple selector case statement and for each complex
471 -- expression. We do this only for representable types, to prevent loops with
472 -- inlinenonrep.
473 casesimpl c expr@(Case scrut bndr ty alts) | not bndr_used = do
474   (bindingss, alts') <- (Monad.liftM unzip) $ mapM doalt alts
475   let bindings = concat bindingss
476   -- Replace the case with a let with bindings and a case
477   let newlet = mkNonRecLets bindings (Case scrut bndr ty alts')
478   -- If there are no non-wild binders, or this case is already a simple
479   -- selector (i.e., a single alt with exactly one binding), already a simple
480   -- selector altan no bindings (i.e., no wild binders in the original case),
481   -- don't change anything, otherwise, replace the case.
482   if null bindings then return expr else change newlet 
483   where
484   -- Check if the scrutinee binder is used
485   is_used (_, _, expr) = expr_uses_binders [bndr] expr
486   bndr_used = or $ map is_used alts
487   -- Generate a single wild binder, since they are all the same
488   wild = MkCore.mkWildBinder
489   -- Wilden the binders of one alt, producing a list of bindings as a
490   -- sideeffect.
491   doalt :: CoreAlt -> TransformMonad ([(CoreBndr, CoreExpr)], CoreAlt)
492   doalt (LitAlt _, _, _) = error $ "Don't know how to handle LitAlt in case expression: " ++ pprString expr
493   doalt alt@(DEFAULT, [], expr) = do
494     local_var <- Trans.lift $ is_local_var expr
495     repr <- isRepr expr
496     (exprbinding_maybe, expr') <- if (not local_var) && repr
497       then do
498         id <- Trans.lift $ mkBinderFor expr "caseval"
499         -- We don't flag a change here, since casevalsimpl will do that above
500         -- based on Just we return here.
501         return (Just (id, expr), Var id)
502       else
503         -- Don't simplify anything else
504         return (Nothing, expr)
505     let newalt = (DEFAULT, [], expr')
506     let bindings = Maybe.catMaybes [exprbinding_maybe]
507     return (bindings, newalt)
508   doalt (DataAlt dc, bndrs, expr) = do
509     -- Make each binder wild, if possible
510     bndrs_res <- Monad.zipWithM dobndr bndrs [0..]
511     let (newbndrs, bindings_maybe) = unzip bndrs_res
512     -- Extract a complex expression, if possible. For this we check if any of
513     -- the new list of bndrs are used by expr. We can't use free_vars here,
514     -- since that looks at the old bndrs.
515     let uses_bndrs = not $ VarSet.isEmptyVarSet $ CoreFVs.exprSomeFreeVars (`elem` newbndrs) expr
516     (exprbinding_maybe, expr') <- doexpr expr uses_bndrs
517     -- Create a new alternative
518     let newalt = (DataAlt dc, newbndrs, expr')
519     let bindings = Maybe.catMaybes (bindings_maybe ++ [exprbinding_maybe])
520     return (bindings, newalt)
521     where
522       -- Make wild alternatives for each binder
523       wildbndrs = map (\bndr -> MkCore.mkWildBinder (Id.idType bndr)) bndrs
524       -- A set of all the binders that are used by the expression
525       free_vars = CoreFVs.exprSomeFreeVars (`elem` bndrs) expr
526       -- Look at the ith binder in the case alternative. Return a new binder
527       -- for it (either the same one, or a wild one) and optionally a let
528       -- binding containing a case expression.
529       dobndr :: CoreBndr -> Int -> TransformMonad (CoreBndr, Maybe (CoreBndr, CoreExpr))
530       dobndr b i = do
531         repr <- isRepr b
532         -- Is b wild (e.g., not a free var of expr. Since b is only in scope
533         -- in expr, this means that b is unused if expr does not use it.)
534         let wild = not (VarSet.elemVarSet b free_vars)
535         -- Create a new binding for any representable binder that is not
536         -- already wild and is representable (to prevent loops with
537         -- inlinenonrep).
538         if (not wild) && repr
539           then do
540             let dc_i = datacon_index (CoreUtils.exprType scrut) dc
541             caseexpr <- Trans.lift $ mkSelCase scrut dc_i i
542             -- Create a new binder that will actually capture a value in this
543             -- case statement, and return it.
544             return (wildbndrs!!i, Just (b, caseexpr))
545           else 
546             -- Just leave the original binder in place, and don't generate an
547             -- extra selector case.
548             return (b, Nothing)
549       -- Process the expression of a case alternative. Accepts an expression
550       -- and whether this expression uses any of the binders in the
551       -- alternative. Returns an optional new binding and a new expression.
552       doexpr :: CoreExpr -> Bool -> TransformMonad (Maybe (CoreBndr, CoreExpr), CoreExpr)
553       doexpr expr uses_bndrs = do
554         local_var <- Trans.lift $ is_local_var expr
555         repr <- isRepr expr
556         -- Extract any expressions that do not use any binders from this
557         -- alternative, is not a local var already and is representable (to
558         -- prevent loops with inlinenonrep).
559         if (not uses_bndrs) && (not local_var) && repr
560           then do
561             id <- Trans.lift $ mkBinderFor expr "caseval"
562             -- We don't flag a change here, since casevalsimpl will do that above
563             -- based on Just we return here.
564             return (Just (id, expr), Var id)
565           else
566             -- Don't simplify anything else
567             return (Nothing, expr)
568 -- Leave all other expressions unchanged
569 casesimpl c expr = return expr
570
571 --------------------------------
572 -- Case removal
573 --------------------------------
574 -- Remove case statements that have only a single alternative and only wild
575 -- binders.
576 caseremove :: Transform
577 -- Replace a useless case by the value of its single alternative
578 caseremove c (Case scrut b ty [(con, bndrs, expr)]) | not usesvars = change expr
579     -- Find if any of the binders are used by expr
580     where usesvars = (not . VarSet.isEmptyVarSet . (CoreFVs.exprSomeFreeVars (`elem` b:bndrs))) expr
581 -- Leave all other expressions unchanged
582 caseremove c expr = return expr
583
584 --------------------------------
585 -- Case of known constructor simplification
586 --------------------------------
587 -- If a case expressions scrutinizes a datacon application, we can
588 -- determine which alternative to use and remove the case alltogether.
589 -- We replace it with a let expression the binds every binder in the
590 -- alternative bound to the corresponding argument of the datacon. We do
591 -- this instead of substituting the binders, to prevent duplication of
592 -- work and preserve sharing wherever appropriate.
593 knowncase :: Transform
594 knowncase context expr@(Case scrut@(App _ _) bndr ty alts) | not bndr_used = do
595     case collectArgs scrut of
596       (Var f, args) -> case Id.isDataConId_maybe f of
597         -- Not a dataconstructor? Don't change anything (probably a
598         -- function, then)
599         Nothing -> return expr
600         Just dc -> do
601           let (altcon, bndrs, res) =  case List.find (\(altcon, bndrs, res) -> altcon == (DataAlt dc)) alts of
602                 Just alt -> alt -- Return the alternative found
603                 Nothing -> head alts -- If the datacon is not present, the first must be the default alternative
604           -- Double check if we have either the correct alternative, or
605           -- the default.
606           if altcon /= (DataAlt dc) && altcon /= DEFAULT then error ("Normalize.knowncase: Invalid core, datacon not found in alternatives and DEFAULT alternative is not first? " ++ pprString expr) else return ()
607           -- Find out how many arguments to drop (type variables and
608           -- predicates like dictionaries).
609           let (tvs, preds, _, _) = DataCon.dataConSig dc
610           let count = length tvs + length preds
611           -- Create a let expression that binds each of the binders in
612           -- this alternative to the corresponding argument of the data
613           -- constructor.
614           let binds = zip bndrs (drop count args)
615           change $ Let (Rec binds) res
616       _ -> return expr -- Scrutinee is not an application of a var
617   where
618     is_used (_, _, expr) = expr_uses_binders [bndr] expr
619     bndr_used = or $ map is_used alts
620
621 -- Leave all other expressions unchanged
622 knowncase c expr = return expr
623
624
625
626
627 ----------------------------------------------------------------
628 -- Unrepresentable value removal transformations
629 ----------------------------------------------------------------
630
631 --------------------------------
632 -- Non-representable binding inlining
633 --------------------------------
634 -- Remove a = B bindings, with B of a non-representable type, from let
635 -- expressions everywhere. This means that any value that we can't generate a
636 -- signal for, will be inlined and hopefully turned into something we can
637 -- represent.
638 --
639 -- This is a tricky function, which is prone to create loops in the
640 -- transformations. To fix this, we make sure that no transformation will
641 -- create a new let binding with a non-representable type. These other
642 -- transformations will just not work on those function-typed values at first,
643 -- but the other transformations (in particular β-reduction) should make sure
644 -- that the type of those values eventually becomes representable.
645 inlinenonrep :: Transform
646 inlinenonrep = inlinebind ((Monad.liftM not) . isRepr . snd)
647
648 --------------------------------
649 -- Function specialization
650 --------------------------------
651 -- Remove all applications to non-representable arguments, by duplicating the
652 -- function called with the non-representable parameter replaced by the free
653 -- variables of the argument passed in.
654 argprop :: Transform
655 -- Transform any application of a named function (i.e., skip applications of
656 -- lambda's). Also skip applications that have arguments with free type
657 -- variables, since we can't inline those.
658 argprop c expr@(App _ _) | is_var fexpr = do
659   -- Find the body of the function called
660   body_maybe <- Trans.lift $ getGlobalBind f
661   case body_maybe of
662     Just body -> do
663       -- Process each of the arguments in turn
664       (args', changed) <- Writer.listen $ mapM doarg args
665       -- See if any of the arguments changed
666       case Monoid.getAny changed of
667         True -> do
668           let (newargs', newparams', oldargs) = unzip3 args'
669           let newargs = concat newargs'
670           let newparams = concat newparams'
671           -- Create a new body that consists of a lambda for all new arguments and
672           -- the old body applied to some arguments.
673           let newbody = MkCore.mkCoreLams newparams (MkCore.mkCoreApps body oldargs)
674           -- Create a new function with the same name but a new body
675           newf <- Trans.lift $ mkFunction f newbody
676
677           Trans.lift $ MonadState.modify tsInitStates (\ismap ->
678             let init_state_maybe = Map.lookup f ismap in
679             case init_state_maybe of
680               Nothing -> ismap
681               Just init_state -> Map.insert newf init_state ismap)
682           -- Replace the original application with one of the new function to the
683           -- new arguments.
684           change $ MkCore.mkCoreApps (Var newf) newargs
685         False ->
686           -- Don't change the expression if none of the arguments changed
687           return expr
688       
689     -- If we don't have a body for the function called, leave it unchanged (it
690     -- should be a primitive function then).
691     Nothing -> return expr
692   where
693     -- Find the function called and the arguments
694     (fexpr, args) = collectArgs expr
695     Var f = fexpr
696
697     -- Process a single argument and return (args, bndrs, arg), where args are
698     -- the arguments to replace the given argument in the original
699     -- application, bndrs are the binders to include in the top-level lambda
700     -- in the new function body, and arg is the argument to apply to the old
701     -- function body.
702     doarg :: CoreExpr -> TransformMonad ([CoreExpr], [CoreBndr], CoreExpr)
703     doarg arg = do
704       repr <- isRepr arg
705       bndrs <- Trans.lift getGlobalBinders
706       let interesting var = Var.isLocalVar var && (var `notElem` bndrs)
707       if not repr && not (is_var arg && interesting (exprToVar arg)) && not (has_free_tyvars arg) 
708         then do
709           -- Propagate all complex arguments that are not representable, but not
710           -- arguments with free type variables (since those would require types
711           -- not known yet, which will always be known eventually).
712           -- Find interesting free variables, each of which should be passed to
713           -- the new function instead of the original function argument.
714           -- 
715           -- Interesting vars are those that are local, but not available from the
716           -- top level scope (functions from this module are defined as local, but
717           -- they're not local to this function, so we can freely move references
718           -- to them into another function).
719           let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting arg
720           -- Mark the current expression as changed
721           setChanged
722           -- TODO: Clone the free_vars (and update references in arg), since
723           -- this might cause conflicts if two arguments that are propagated
724           -- share a free variable. Also, we are now introducing new variables
725           -- into a function that are not fresh, which violates the binder
726           -- uniqueness invariant.
727           return (map Var free_vars, free_vars, arg)
728         else do
729           -- Representable types will not be propagated, and arguments with free
730           -- type variables will be propagated later.
731           -- Note that we implicitly remove any type variables in the type of
732           -- the original argument by using the type of the actual argument
733           -- for the new formal parameter.
734           -- TODO: preserve original naming?
735           id <- Trans.lift $ mkBinderFor arg "param"
736           -- Just pass the original argument to the new function, which binds it
737           -- to a new id and just pass that new id to the old function body.
738           return ([arg], [id], mkReferenceTo id) 
739 -- Leave all other expressions unchanged
740 argprop c expr = return expr
741
742 --------------------------------
743 -- Non-representable result inlining
744 --------------------------------
745 -- This transformation takes a function (top level binding) that has a
746 -- non-representable result (e.g., a tuple containing a function, or an
747 -- Integer. The latter can occur in some cases as the result of the
748 -- fromIntegerT function) and inlines enough of the function to make the
749 -- result representable again.
750 --
751 -- This is done by first normalizing the function and then "inlining"
752 -- the result. Since no unrepresentable let bindings are allowed in
753 -- normal form, we can be sure that all free variables of the result
754 -- expression will be representable (Note that we probably can't
755 -- guarantee that all representable parts of the expression will be free
756 -- variables, so we might inline more than strictly needed).
757 --
758 -- The new function result will be a tuple containing all free variables
759 -- of the old result, so the old result can be rebuild at the caller.
760 --
761 -- We take care not to inline dictionary id's, which are top level
762 -- bindings with a non-representable result type as well, since those
763 -- will never become VHDL signals directly. There is a separate
764 -- transformation (inlinedict) that specifically inlines dictionaries
765 -- only when it is useful.
766 inlinenonrepresult :: Transform
767
768 -- Apply to any (application of) a reference to a top level function
769 -- that is fully applied (i.e., dos not have a function type) but is not
770 -- representable. We apply in any context, since non-representable
771 -- expressions are generally left alone and can occur anywhere.
772 inlinenonrepresult context expr | not (is_applicable expr) && not (has_free_tyvars expr) =
773   case collectArgs expr of
774     (Var f, args) | not (Id.isDictId f) -> do
775       repr <- isRepr expr
776       if not repr
777         then do
778           body_maybe <- Trans.lift $ getNormalized_maybe True f
779           case body_maybe of
780             Just body -> do
781               let (bndrs, binds, res) = splitNormalizedNonRep body
782               if has_free_tyvars res 
783                 then
784                   -- Don't touch anything with free type variables, since
785                   -- we can't return those. We'll wait until argprop
786                   -- removed those variables.
787                   return expr
788                 else do
789                   -- Get the free local variables of res
790                   global_bndrs <- Trans.lift getGlobalBinders
791                   let interesting var = Var.isLocalVar var && (var `notElem` global_bndrs)
792                   let free_vars = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars interesting res
793                   let free_var_types = map Id.idType free_vars
794                   let n_free_vars = length free_vars
795                   -- Get a tuple datacon to wrap around the free variables
796                   let fvs_datacon = TysWiredIn.tupleCon BasicTypes.Boxed n_free_vars
797                   let fvs_datacon_id = DataCon.dataConWorkId fvs_datacon
798                   -- Let the function now return a tuple with references to
799                   -- all free variables of the old return value. First pass
800                   -- all the types of the variables, since tuple
801                   -- constructors are polymorphic.
802                   let newres = mkApps (Var fvs_datacon_id) (map Type free_var_types ++  map Var free_vars)
803                   -- Recreate the function body with the changed return value
804                   let newbody = mkLams bndrs (Let (Rec binds) newres) 
805                   -- Create the new function
806                   f' <- Trans.lift $ mkFunction f newbody
807
808                   -- Call the new function
809                   let newapp = mkApps (Var f') args
810                   res_bndr <- Trans.lift $ mkBinderFor newapp "res"
811                   -- Create extractor case expressions to extract each of the
812                   -- free variables from the tuple.
813                   sel_cases <- Trans.lift $ mapM (mkSelCase (Var res_bndr) 0) [0..n_free_vars-1]
814
815                   -- Bind the res_bndr to the result of the new application
816                   -- and each of the free variables to the corresponding
817                   -- selector case. Replace the let body with the original
818                   -- body of the called function (which can still access all
819                   -- of its free variables, from the let).
820                   let binds = (res_bndr, newapp):(zip free_vars sel_cases)
821                   let letexpr = Let (Rec binds) res
822
823                   -- Finally, regenarate all uniques in the new expression,
824                   -- since the free variables could otherwise become
825                   -- duplicated. It is not strictly necessary to regenerate
826                   -- res, since we're moving that expression, but it won't
827                   -- hurt.
828                   letexpr_uniqued <- Trans.lift $ genUniques letexpr
829                   change letexpr_uniqued
830             Nothing -> return expr
831         else
832           -- Don't touch representable expressions or (applications of)
833           -- dictionary ids.
834           return expr
835     -- Not a reference to or application of a top level function
836     _ -> return expr
837 -- Leave all other expressions unchanged
838 inlinenonrepresult c expr = return expr
839
840 ----------------------------------------------------------------
841 -- Type-class transformations
842 ----------------------------------------------------------------
843
844 --------------------------------
845 -- ClassOp resolution
846 --------------------------------
847 -- Resolves any class operation to the actual operation whenever
848 -- possible. Class methods (as well as parent dictionary selectors) are
849 -- special "functions" that take a type and a dictionary and evaluate to
850 -- the corresponding method. A dictionary is nothing more than a
851 -- special dataconstructor applied to the type the dictionary is for,
852 -- each of the superclasses and all of the class method definitions for
853 -- that particular type. Since dictionaries all always inlined (top
854 -- levels dictionaries are inlined by inlinedict, local dictionaries are
855 -- inlined by inlinenonrep), we will eventually have something like:
856 --
857 --   baz
858 --     @ CLasH.HardwareTypes.Bit
859 --     (D:Baz @ CLasH.HardwareTypes.Bit bitbaz)
860 --
861 -- Here, baz is the method selector for the baz method, while
862 -- D:Baz is the dictionary constructor for the Baz and bitbaz is the baz
863 -- method defined in the Baz Bit instance declaration.
864 --
865 -- To resolve this, we can look at the ClassOp IdInfo from the baz Id,
866 -- which contains the Class it is defined for. From the Class, we can
867 -- get a list of all selectors (both parent class selectors as well as
868 -- method selectors). Since the arguments to D:Baz (after the type
869 -- argument) correspond exactly to this list, we then look up baz in
870 -- that list and replace the entire expression by the corresponding 
871 -- argument to D:Baz.
872 --
873 -- We don't resolve methods that have a builtin translation (such as
874 -- ==), since the actual implementation is not always (easily)
875 -- translateable. For example, when deriving ==, GHC generates code
876 -- using $con2tag functions to translate a datacon to an int and compare
877 -- that with GHC.Prim.==# . Better to avoid that for now.
878 classopresolution :: Transform
879 classopresolution c expr@(App (App (Var sel) ty) dict) | not is_builtin =
880   case Id.isClassOpId_maybe sel of
881     -- Not a class op selector
882     Nothing -> return expr
883     Just cls -> case collectArgs dict of
884       (_, []) -> return expr -- Dict is not an application (e.g., not inlined yet)
885       (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)
886                                 | tyargs_neq ty ty' -> error $ "Normalize.classopresolution: Applying class selector to dictionary without matching type?\n" ++ pprString expr
887                                 | otherwise ->
888         let selector_ids = Class.classSelIds cls in
889         -- Find the selector used in the class' list of selectors
890         case List.elemIndex sel selector_ids of
891           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
892           -- Get the corresponding argument from the dictionary
893           Just n -> change (selectors!!n)
894       (_, _) -> return expr -- Not applying a variable? Don't touch
895   where
896     -- Compare two type arguments, returning True if they are _not_
897     -- equal
898     tyargs_neq (Type ty1) (Type ty2) = not $ Type.coreEqType ty1 ty2
899     tyargs_neq _ _ = True
900     -- Is this a builtin function / method?
901     is_builtin = elem (Name.getOccString sel) builtinIds
902
903 -- Leave all other expressions unchanged
904 classopresolution c expr = return expr
905
906 --------------------------------
907 -- Dictionary inlining
908 --------------------------------
909 -- Inline all top level dictionaries, that are in a position where
910 -- classopresolution can actually resolve them. This makes this
911 -- transformation look similar to classoperesolution below, but we'll
912 -- keep them separated for clarity. By not inlining other dictionaries,
913 -- we prevent expression sizes exploding when huge type level integer
914 -- dictionaries are inlined which can never be expanded (in casts, for
915 -- example).
916 inlinedict c expr@(App (App (Var sel) ty) (Var dict)) | not is_builtin && is_classop = do
917   body_maybe <- Trans.lift $ getGlobalBind dict
918   case body_maybe of
919     -- No body available (no source available, or a local variable /
920     -- argument)
921     Nothing -> return expr
922     Just body -> change (App (App (Var sel) ty) body)
923   where
924     -- Is this a builtin function / method?
925     is_builtin = elem (Name.getOccString sel) builtinIds
926     -- Are we dealing with a class operation selector?
927     is_classop = Maybe.isJust (Id.isClassOpId_maybe sel)
928
929 -- Leave all other expressions unchanged
930 inlinedict c expr = return expr
931
932
933 {-
934 --------------------------------
935 -- Identical let binding merging
936 --------------------------------
937 -- Merge two bindings in a let if they are identical 
938 -- TODO: We would very much like to use GHC's CSE module for this, but that
939 -- doesn't track if something changed or not, so we can't use it properly.
940 letmerge :: Transform
941 letmerge c expr@(Let _ _) = do
942   let (binds, res) = flattenLets expr
943   binds' <- domerge binds
944   return $ mkNonRecLets binds' res
945   where
946     domerge :: [(CoreBndr, CoreExpr)] -> TransformMonad [(CoreBndr, CoreExpr)]
947     domerge [] = return []
948     domerge (e:es) = do 
949       es' <- mapM (mergebinds e) es
950       es'' <- domerge es'
951       return (e:es'')
952
953     -- Uses the second bind to simplify the second bind, if applicable.
954     mergebinds :: (CoreBndr, CoreExpr) -> (CoreBndr, CoreExpr) -> TransformMonad (CoreBndr, CoreExpr)
955     mergebinds (b1, e1) (b2, e2)
956       -- Identical expressions? Replace the second binding with a reference to
957       -- the first binder.
958       | CoreUtils.cheapEqExpr e1 e2 = change $ (b2, Var b1)
959       -- Different expressions? Don't change
960       | otherwise = return (b2, e2)
961 -- Leave all other expressions unchanged
962 letmerge c expr = return expr
963 -}
964
965 --------------------------------
966 -- End of transformations
967 --------------------------------
968
969
970
971
972 -- What transforms to run?
973 transforms = [ ("inlinedict", inlinedict)
974              , ("inlinetoplevel", inlinetoplevel)
975              , ("inlinenonrepresult", inlinenonrepresult)
976              , ("knowncase", knowncase)
977              , ("classopresolution", classopresolution)
978              , ("argprop", argprop)
979              , ("funextract", funextract)
980              , ("eta", eta)
981              , ("beta", beta)
982              , ("appprop", appprop)
983              , ("castprop", castprop)
984              , ("letremovesimple", letremovesimple)
985              , ("letrec", letrec)
986              , ("letremove", letremove)
987              , ("retvalsimpl", retvalsimpl)
988              , ("letflat", letflat)
989              , ("scrutsimpl", scrutsimpl)
990              , ("scrutbndrremove", scrutbndrremove)
991              , ("casesimpl", casesimpl)
992              , ("caseremove", caseremove)
993              , ("inlinenonrep", inlinenonrep)
994              , ("appsimpl", appsimpl)
995              , ("letremoveunused", letremoveunused)
996              , ("castsimpl", castsimpl)
997              ]
998
999 -- | Returns the normalized version of the given function, or an error
1000 -- if it is not a known global binder.
1001 getNormalized ::
1002   Bool -- ^ Allow the result to be unrepresentable?
1003   -> CoreBndr -- ^ The function to get
1004   -> TranslatorSession CoreExpr -- The normalized function body
1005 getNormalized result_nonrep bndr = do
1006   norm <- getNormalized_maybe result_nonrep bndr
1007   return $ Maybe.fromMaybe
1008     (error $ "Normalize.getNormalized: Unknown or non-representable function requested: " ++ show bndr)
1009     norm
1010
1011 -- | Returns the normalized version of the given function, or Nothing
1012 -- when the binder is not a known global binder or is not normalizeable.
1013 getNormalized_maybe ::
1014   Bool -- ^ Allow the result to be unrepresentable?
1015   -> CoreBndr -- ^ The function to get
1016   -> TranslatorSession (Maybe CoreExpr) -- The normalized function body
1017
1018 getNormalized_maybe result_nonrep bndr = do
1019     expr_maybe <- getGlobalBind bndr
1020     normalizeable <- isNormalizeable result_nonrep bndr
1021     if not normalizeable || Maybe.isNothing expr_maybe
1022       then
1023         -- Binder not normalizeable or not found
1024         return Nothing
1025       else do
1026         -- Binder found and is monomorphic. Normalize the expression
1027         -- and cache the result.
1028         normalized <- Utils.makeCached bndr tsNormalized $ 
1029           normalizeExpr (show bndr) (Maybe.fromJust expr_maybe)
1030         return (Just normalized)
1031
1032 -- | Normalize an expression
1033 normalizeExpr ::
1034   String -- ^ What are we normalizing? For debug output only.
1035   -> CoreSyn.CoreExpr -- ^ The expression to normalize 
1036   -> TranslatorSession CoreSyn.CoreExpr -- ^ The normalized expression
1037
1038 normalizeExpr what expr = do
1039       startcount <- MonadState.get tsTransformCounter 
1040       expr_uniqued <- genUniques expr
1041       -- Do a debug print, if requested
1042       let expr_uniqued' = Utils.traceIf (normalize_debug >= NormDbgFinal) (what ++ " before normalization:\n\n" ++ showSDoc ( ppr expr_uniqued ) ++ "\n") expr_uniqued
1043       -- Normalize this expression
1044       expr' <- dotransforms transforms expr_uniqued'
1045       endcount <- MonadState.get tsTransformCounter 
1046       -- Do a debug print, if requested
1047       Utils.traceIf (normalize_debug >= NormDbgFinal)  (what ++ " after normalization:\n\n" ++ showSDoc ( ppr expr') ++ "\nNeeded " ++ show (endcount - startcount) ++ " transformations to normalize " ++ what) $
1048         return expr'
1049
1050 -- | Split a normalized expression into the argument binders, top level
1051 --   bindings and the result binder. This function returns an error if
1052 --   the type of the expression is not representable.
1053 splitNormalized ::
1054   CoreExpr -- ^ The normalized expression
1055   -> ([CoreBndr], [Binding], CoreBndr)
1056 splitNormalized expr = 
1057   case splitNormalizedNonRep expr of
1058     (args, binds, Var res) -> (args, binds, res)
1059     _ -> error $ "Normalize.splitNormalized: Not in normal form: " ++ pprString expr ++ "\n"
1060
1061 -- Split a normalized expression, whose type can be unrepresentable.
1062 splitNormalizedNonRep::
1063   CoreExpr -- ^ The normalized expression
1064   -> ([CoreBndr], [Binding], CoreExpr)
1065 splitNormalizedNonRep expr = (args, binds, resexpr)
1066   where
1067     (args, letexpr) = CoreSyn.collectBinders expr
1068     (binds, resexpr) = flattenLets letexpr