Add LambdaBody to CoreContext.
[matthijs/master-project/cλash.git] / cλash / CLasH / Normalize / NormalizeTools.hs
1 {-# LANGUAGE PackageImports #-}
2 -- 
3 -- This module provides functions for program transformations.
4 --
5 module CLasH.Normalize.NormalizeTools where
6
7 -- Standard modules
8 import qualified Data.Monoid as Monoid
9 import qualified Control.Monad as Monad
10 import qualified Control.Monad.Trans.Writer as Writer
11 import qualified "transformers" Control.Monad.Trans as Trans
12 import qualified Data.Accessor.Monad.Trans.State as MonadState
13 -- import Debug.Trace
14
15 -- GHC API
16 import CoreSyn
17 import qualified Name
18 import qualified Id
19 import qualified CoreSubst
20 import qualified Type
21 -- import qualified CoreUtils
22 -- import Outputable ( showSDoc, ppr, nest )
23
24 -- Local imports
25 import CLasH.Normalize.NormalizeTypes
26 import CLasH.Translator.TranslatorTypes
27 import CLasH.VHDL.Constants (builtinIds)
28 import CLasH.Utils
29 import qualified CLasH.Utils.Core.CoreTools as CoreTools
30 import qualified CLasH.VHDL.VHDLTools as VHDLTools
31
32 -- Apply the given transformation to all expressions in the given expression,
33 -- including the expression itself.
34 everywhere :: (String, Transform) -> Transform
35 everywhere trans = applyboth (subeverywhere (everywhere trans)) trans
36
37 -- Apply the first transformation, followed by the second transformation, and
38 -- keep applying both for as long as expression still changes.
39 applyboth :: Transform -> (String, Transform) -> Transform
40 applyboth first (name, second) context expr = do
41   -- Apply the first
42   expr' <- first context expr
43   -- Apply the second
44   (expr'', changed) <- Writer.listen $ second context expr'
45   if Monoid.getAny $
46         -- trace ("Trying to apply transform " ++ name ++ " to:\n" ++ showSDoc (nest 4 $ ppr expr') ++ "\nType: \n" ++ (showSDoc $ nest 4 $ ppr $ CoreUtils.exprType expr') ++ "\n")
47         changed 
48     then 
49      -- trace ("Applying transform " ++ name ++ " to:\n" ++ showSDoc (nest 4 $ ppr expr') ++ "\nType: \n" ++ (showSDoc $ nest 4 $ ppr $ CoreUtils.exprType expr') ++ "\n"
50      --        ++ "Result of applying " ++ name ++ ":\n" ++ showSDoc (nest 4 $ ppr expr'') ++ "\n" ++ "Type: \n" ++ (showSDoc $ nest 4 $ ppr $ CoreUtils.exprType expr'') ++ "\n" ) $
51       applyboth first (name, second) context expr'' 
52     else 
53       -- trace ("No changes") $
54       return expr''
55
56 -- Apply the given transformation to all direct subexpressions (only), not the
57 -- expression itself.
58 subeverywhere :: Transform -> Transform
59 subeverywhere trans c (App a b) = do
60   a' <- trans (AppFirst:c) a
61   b' <- trans (AppSecond:c) b
62   return $ App a' b'
63
64 subeverywhere trans c (Let (NonRec b bexpr) expr) = do
65   bexpr' <- trans (LetBinding:c) bexpr
66   expr' <- trans (LetBody:c) expr
67   return $ Let (NonRec b bexpr') expr'
68
69 subeverywhere trans c (Let (Rec binds) expr) = do
70   expr' <- trans (LetBody:c) expr
71   binds' <- mapM transbind binds
72   return $ Let (Rec binds') expr'
73   where
74     transbind :: (CoreBndr, CoreExpr) -> TransformMonad (CoreBndr, CoreExpr)
75     transbind (b, e) = do
76       e' <- trans (LetBinding:c) e
77       return (b, e')
78
79 subeverywhere trans c (Lam x expr) = do
80   expr' <- trans (LambdaBody:c) expr
81   return $ Lam x expr'
82
83 subeverywhere trans c (Case scrut b t alts) = do
84   scrut' <- trans (Other:c) scrut
85   alts' <- mapM transalt alts
86   return $ Case scrut' b t alts'
87   where
88     transalt :: CoreAlt -> TransformMonad CoreAlt
89     transalt (con, binders, expr) = do
90       expr' <- trans (Other:c) expr
91       return (con, binders, expr')
92
93 subeverywhere trans c (Var x) = return $ Var x
94 subeverywhere trans c (Lit x) = return $ Lit x
95 subeverywhere trans c (Type x) = return $ Type x
96
97 subeverywhere trans c (Cast expr ty) = do
98   expr' <- trans (Other:c) expr
99   return $ Cast expr' ty
100
101 subeverywhere trans c expr = error $ "\nNormalizeTools.subeverywhere: Unsupported expression: " ++ show expr
102
103 -- Runs each of the transforms repeatedly inside the State monad.
104 dotransforms :: [Transform] -> CoreExpr -> TranslatorSession CoreExpr
105 dotransforms transs expr = do
106   (expr', changed) <- Writer.runWriterT $ Monad.foldM (\e trans -> trans [] e) expr transs
107   if Monoid.getAny changed then dotransforms transs expr' else return expr'
108
109 -- Inline all let bindings that satisfy the given condition
110 inlinebind :: ((CoreBndr, CoreExpr) -> TransformMonad Bool) -> Transform
111 inlinebind condition context expr@(Let (NonRec bndr expr') res) = do
112     applies <- condition (bndr, expr')
113     if applies
114       then do
115         -- Substitute the binding in res and return that
116         res' <- substitute_clone bndr expr' context res
117         change res'
118       else
119         -- Don't change this let
120         return expr
121 -- Leave all other expressions unchanged
122 inlinebind _ context expr = return expr
123
124 -- Sets the changed flag in the TransformMonad, to signify that some
125 -- transform has changed the result
126 setChanged :: TransformMonad ()
127 setChanged = Writer.tell (Monoid.Any True)
128
129 -- Sets the changed flag and returns the given value.
130 change :: a -> TransformMonad a
131 change val = do
132   setChanged
133   return val
134
135 -- Returns the given value and sets the changed flag if the bool given is
136 -- True. Note that this will not unset the changed flag if the bool is False.
137 changeif :: Bool -> a -> TransformMonad a
138 changeif True val = change val
139 changeif False val = return val
140
141 -- | Creates a transformation that substitutes the given binder with the given
142 -- expression (This can be a type variable, replace by a Type expression).
143 -- Does not set the changed flag.
144 substitute :: CoreBndr -> CoreExpr -> Transform
145 -- Use CoreSubst to subst a type var in an expression
146 substitute find repl context expr = do
147   let subst = CoreSubst.extendSubst CoreSubst.emptySubst find repl
148   return $ CoreSubst.substExpr subst expr 
149
150 -- | Creates a transformation that substitutes the given binder with the given
151 -- expression. This does only work for value expressions! All binders in the
152 -- expression are cloned before the replacement, to guarantee uniqueness.
153 substitute_clone :: CoreBndr -> CoreExpr -> Transform
154 -- If we see the var to find, replace it by a uniqued version of repl
155 substitute_clone find repl context (Var var) | find == var = do
156   repl' <- Trans.lift $ CoreTools.genUniques repl
157   change repl'
158
159 -- For all other expressions, just look in subexpressions
160 substitute_clone find repl context expr = subeverywhere (substitute_clone find repl) context expr
161
162 -- Is the given expression representable at runtime, based on the type?
163 isRepr :: (CoreTools.TypedThing t) => t -> TransformMonad Bool
164 isRepr tything = Trans.lift (isRepr' tything)
165
166 isRepr' :: (CoreTools.TypedThing t) => t -> TranslatorSession Bool
167 isRepr' tything = case CoreTools.getType tything of
168   Nothing -> return False
169   Just ty -> MonadState.lift tsType $ VHDLTools.isReprType ty 
170
171 is_local_var :: CoreSyn.CoreExpr -> TranslatorSession Bool
172 is_local_var (CoreSyn.Var v) = do
173   bndrs <- getGlobalBinders
174   return $ v `notElem` bndrs
175 is_local_var _ = return False
176
177 -- Is the given binder defined by the user?
178 isUserDefined :: CoreSyn.CoreBndr -> Bool
179 -- System names are certain to not be user defined
180 isUserDefined bndr | Name.isSystemName (Id.idName bndr) = False
181 -- Builtin functions are usually not user-defined either (and would
182 -- break currently if they are...)
183 isUserDefined bndr = str `notElem` builtinIds
184   where
185     str = Name.getOccString bndr
186
187 -- Is the given binder normalizable? This means that its type signature can be
188 -- represented in hardware, which should (?) guarantee that it can be made
189 -- into hardware. Note that if a binder is not normalizable, it might become
190 -- so using argument propagation.
191 isNormalizeable :: CoreBndr -> TransformMonad Bool 
192 isNormalizeable bndr = Trans.lift (isNormalizeable' bndr)
193
194 isNormalizeable' :: CoreBndr -> TranslatorSession Bool 
195 isNormalizeable' bndr = do
196   let ty = Id.idType bndr
197   let (arg_tys, res_ty) = Type.splitFunTys ty
198   -- This function is normalizable if all its arguments and return value are
199   -- representable.
200   andM $ mapM isRepr' (res_ty:arg_tys)