1 module Translator where
2 import qualified Directory
3 import GHC hiding (loadModule, sigName)
5 import qualified CoreUtils
9 import qualified DataCon
10 import qualified Maybe
11 import qualified Module
12 import qualified Control.Monad.State as State
14 import qualified Data.Map as Map
16 import NameEnv ( lookupNameEnv )
17 import qualified HscTypes
18 import HscTypes ( cm_binds, cm_types )
19 import MonadUtils ( liftIO )
20 import Outputable ( showSDoc, ppr )
21 import GHC.Paths ( libdir )
22 import DynFlags ( defaultDynFlags )
25 import qualified Monad
27 -- The following modules come from the ForSyDe project. They are really
28 -- internal modules, so ForSyDe.cabal has to be modified prior to installing
29 -- ForSyDe to get access to these modules.
30 import qualified ForSyDe.Backend.VHDL.AST as AST
31 import qualified ForSyDe.Backend.VHDL.Ppr
32 import qualified ForSyDe.Backend.VHDL.FileIO
33 import qualified ForSyDe.Backend.Ppr
34 -- This is needed for rendering the pretty printed VHDL
35 import Text.PrettyPrint.HughesPJ (render)
37 import TranslatorTypes
46 makeVHDL "Alu.hs" "register_bank" True
48 makeVHDL :: String -> String -> Bool -> IO ()
49 makeVHDL filename name stateful = do
51 core <- loadModule filename
53 vhdl <- moduleToVHDL core [(name, stateful)]
55 let dir = "../vhdl/vhdl/" ++ name ++ "/"
56 mapM (writeVHDL dir) vhdl
59 -- | Show the core structure of the given binds in the given file.
60 listBind :: String -> String -> IO ()
61 listBind filename name = do
62 core <- loadModule filename
63 let binds = findBinds core [name]
65 putStr $ prettyShow binds
67 putStr $ showSDoc $ ppr binds
70 -- | Translate the binds with the given names from the given core module to
71 -- VHDL. The Bool in the tuple makes the function stateful (True) or
73 moduleToVHDL :: HscTypes.CoreModule -> [(String, Bool)] -> IO [AST.DesignFile]
74 moduleToVHDL core list = do
75 let (names, statefuls) = unzip list
76 --liftIO $ putStr $ prettyShow (cm_binds core)
77 let binds = findBinds core names
78 --putStr $ prettyShow binds
79 -- Turn bind into VHDL
80 let (vhdl, sess) = State.runState (mkVHDL binds statefuls) (VHDLSession core 0 Map.empty)
81 mapM (putStr . render . ForSyDe.Backend.Ppr.ppr) vhdl
82 putStr $ "\n\nFinal session:\n" ++ prettyShow sess ++ "\n\n"
86 -- Turns the given bind into VHDL
87 mkVHDL binds statefuls = do
88 -- Add the builtin functions
89 mapM addBuiltIn builtin_funcs
90 -- Create entities and architectures for them
91 Monad.zipWithM processBind statefuls binds
92 modFuncs nameFlatFunction
93 modFuncs VHDL.createEntity
94 modFuncs VHDL.createArchitecture
97 -- | Write the given design file to a file inside the given dir
98 -- The first library unit in the designfile must be an entity, whose name
99 -- will be used as a filename.
100 writeVHDL :: String -> AST.DesignFile -> IO ()
101 writeVHDL dir vhdl = do
102 -- Create the dir if needed
103 exists <- Directory.doesDirectoryExist dir
104 Monad.unless exists $ Directory.createDirectory dir
106 let AST.DesignFile _ (u:us) = vhdl
107 let AST.LUEntity (AST.EntityDec id _) = u
108 let fname = dir ++ AST.fromVHDLId id ++ ".vhdl"
110 ForSyDe.Backend.VHDL.FileIO.writeDesignFile vhdl fname
112 -- | Loads the given file and turns it into a core module.
113 loadModule :: String -> IO HscTypes.CoreModule
114 loadModule filename =
115 defaultErrorHandler defaultDynFlags $ do
116 runGhc (Just libdir) $ do
117 dflags <- getSessionDynFlags
118 setSessionDynFlags dflags
119 --target <- guessTarget "adder.hs" Nothing
120 --liftIO (print (showSDoc (ppr (target))))
121 --liftIO $ printTarget target
122 --setTargets [target]
123 --load LoadAllTargets
124 --core <- GHC.compileToCoreSimplified "Adders.hs"
125 core <- GHC.compileToCoreSimplified filename
128 -- | Extracts the named binds from the given module.
129 findBinds :: HscTypes.CoreModule -> [String] -> [CoreBind]
130 findBinds core names = Maybe.mapMaybe (findBind (cm_binds core)) names
132 -- | Extract a named bind from the given list of binds
133 findBind :: [CoreBind] -> String -> Maybe CoreBind
134 findBind binds lookfor =
135 -- This ignores Recs and compares the name of the bind with lookfor,
136 -- disregarding any namespaces in OccName and extra attributes in Name and
138 find (\b -> case b of
140 NonRec var _ -> lookfor == (occNameString $ nameOccName $ getName var)
143 -- | Processes the given bind as a top level bind.
145 Bool -- ^ Should this be stateful function?
146 -> CoreBind -- ^ The bind to process
149 processBind _ (Rec _) = error "Recursive binders not supported"
150 processBind stateful bind@(NonRec var expr) = do
151 -- Create the function signature
152 let ty = CoreUtils.exprType expr
153 let hsfunc = mkHsFunction var ty stateful
154 flattenBind hsfunc bind
156 -- | Flattens the given bind into the given signature and adds it to the
157 -- session. Then (recursively) finds any functions it uses and does the same
160 HsFunction -- The signature to flatten into
161 -> CoreBind -- The bind to flatten
164 flattenBind _ (Rec _) = error "Recursive binders not supported"
166 flattenBind hsfunc bind@(NonRec var expr) = do
167 -- Flatten the function
168 let flatfunc = flattenFunction hsfunc bind
170 setFlatFunc hsfunc flatfunc
171 let used_hsfuncs = Maybe.mapMaybe usedHsFunc (flat_defs flatfunc)
172 State.mapM resolvFunc used_hsfuncs
175 -- | Find the given function, flatten it and add it to the session. Then
176 -- (recursively) do the same for any functions used.
178 HsFunction -- | The function to look for
181 resolvFunc hsfunc = do
182 -- See if the function is already known
183 func <- getFunc hsfunc
185 -- Already known, do nothing
188 -- New function, resolve it
190 -- Get the current module
192 -- Find the named function
193 let bind = findBind (cm_binds core) name
195 Nothing -> error $ "Couldn't find function " ++ name ++ " in current module."
196 Just b -> flattenBind hsfunc b
198 name = hsFuncName hsfunc
200 -- | Translate a top level function declaration to a HsFunction. i.e., which
201 -- interface will be provided by this function. This function essentially
202 -- defines the "calling convention" for hardware models.
204 Var.Var -- ^ The function defined
205 -> Type -- ^ The function type (including arguments!)
206 -> Bool -- ^ Is this a stateful function?
207 -> HsFunction -- ^ The resulting HsFunction
209 mkHsFunction f ty stateful=
210 HsFunction hsname hsargs hsres
212 hsname = getOccString f
213 (arg_tys, res_ty) = Type.splitFunTys ty
218 -- The last argument must be state
219 state_ty = last arg_tys
220 state = useAsState (mkHsValueMap state_ty)
221 -- All but the last argument are inports
222 inports = map (useAsPort . mkHsValueMap)(init arg_tys)
223 hsargs = inports ++ [state]
224 hsres = case splitTupleType res_ty of
225 -- Result type must be a two tuple (state, ports)
226 Just [outstate_ty, outport_ty] -> if Type.coreEqType state_ty outstate_ty
228 Tuple [state, useAsPort (mkHsValueMap outport_ty)]
230 error $ "Input state type of function " ++ hsname ++ ": " ++ (showSDoc $ ppr state_ty) ++ " does not match output state type: " ++ (showSDoc $ ppr outstate_ty)
231 otherwise -> error $ "Return type of top-level function " ++ hsname ++ " must be a two-tuple containing a state and output ports."
235 -- Just use everything as a port
236 (map (useAsPort . mkHsValueMap) arg_tys, useAsPort $ mkHsValueMap res_ty)
238 -- | Adds signal names to the given FlatFunction
244 nameFlatFunction hsfunc fdata =
245 let func = flatFunc fdata in
247 -- Skip (builtin) functions without a FlatFunction
248 Nothing -> do return ()
249 -- Name the signals in all other functions
251 let s = flat_sigs flatfunc in
252 let s' = map nameSignal s in
253 let flatfunc' = flatfunc { flat_sigs = s' } in
254 setFlatFunc hsfunc flatfunc'
256 nameSignal :: (SignalId, SignalInfo) -> (SignalId, SignalInfo)
257 nameSignal (id, info) =
258 let hints = nameHints info in
259 let parts = ("sig" : hints) ++ [show id] in
260 let name = concat $ List.intersperse "_" parts in
261 (id, info {sigName = Just name})
263 -- | Splits a tuple type into a list of element types, or Nothing if the type
264 -- is not a tuple type.
266 Type -- ^ The type to split
267 -> Maybe [Type] -- ^ The tuples element types
270 case Type.splitTyConApp_maybe ty of
271 Just (tycon, args) -> if TyCon.isTupleTyCon tycon
278 -- | A consise representation of a (set of) ports on a builtin function
279 type PortMap = HsValueMap (String, AST.TypeMark)
280 -- | A consise representation of a builtin function
281 data BuiltIn = BuiltIn String [PortMap] PortMap
283 -- | Map a port specification of a builtin function to a VHDL Signal to put in
285 toVHDLSignalMap :: HsValueMap (String, AST.TypeMark) -> VHDLSignalMap
286 toVHDLSignalMap = fmap (\(name, ty) -> Just (VHDL.mkVHDLId name, ty))
288 -- | Translate a concise representation of a builtin function to something
289 -- that can be put into FuncMap directly.
290 addBuiltIn :: BuiltIn -> VHDLState ()
291 addBuiltIn (BuiltIn name args res) = do
293 setEntity hsfunc entity
295 hsfunc = HsFunction name (map useAsPort args) (useAsPort res)
296 entity = Entity (VHDL.mkVHDLId name) (map toVHDLSignalMap args) (toVHDLSignalMap res) Nothing
300 BuiltIn "hwxor" [(Single ("a", VHDL.bit_ty)), (Single ("b", VHDL.bit_ty))] (Single ("o", VHDL.bit_ty)),
301 BuiltIn "hwand" [(Single ("a", VHDL.bit_ty)), (Single ("b", VHDL.bit_ty))] (Single ("o", VHDL.bit_ty)),
302 BuiltIn "hwor" [(Single ("a", VHDL.bit_ty)), (Single ("b", VHDL.bit_ty))] (Single ("o", VHDL.bit_ty)),
303 BuiltIn "hwnot" [(Single ("a", VHDL.bit_ty))] (Single ("o", VHDL.bit_ty))
306 -- vim: set ts=8 sw=2 sts=2 expandtab: