1 module Main(main) where
4 import qualified CoreUtils
8 import qualified DataCon
10 import qualified Module
11 import qualified Control.Monad.State as State
14 import NameEnv ( lookupNameEnv )
15 import HscTypes ( cm_binds, cm_types )
16 import MonadUtils ( liftIO )
17 import Outputable ( showSDoc, ppr )
18 import GHC.Paths ( libdir )
19 import DynFlags ( defaultDynFlags )
22 import qualified Monad
24 -- The following modules come from the ForSyDe project. They are really
25 -- internal modules, so ForSyDe.cabal has to be modified prior to installing
26 -- ForSyDe to get access to these modules.
27 import qualified ForSyDe.Backend.VHDL.AST as AST
28 import qualified ForSyDe.Backend.VHDL.Ppr
29 import qualified ForSyDe.Backend.VHDL.FileIO
30 import qualified ForSyDe.Backend.Ppr
31 -- This is needed for rendering the pretty printed VHDL
32 import Text.PrettyPrint.HughesPJ (render)
36 defaultErrorHandler defaultDynFlags $ do
37 runGhc (Just libdir) $ do
38 dflags <- getSessionDynFlags
39 setSessionDynFlags dflags
40 --target <- guessTarget "adder.hs" Nothing
41 --liftIO (print (showSDoc (ppr (target))))
42 --liftIO $ printTarget target
45 --core <- GHC.compileToCoreSimplified "Adders.hs"
46 core <- GHC.compileToCoreSimplified "Adders.hs"
47 --liftIO $ printBinds (cm_binds core)
48 let binds = Maybe.mapMaybe (findBind (cm_binds core)) ["full_adder", "half_adder"]
49 liftIO $ printBinds binds
50 -- Turn bind into VHDL
51 let vhdl = State.evalState (mkVHDL binds) (VHDLSession 0 [])
52 liftIO $ putStr $ render $ ForSyDe.Backend.Ppr.ppr vhdl
53 liftIO $ ForSyDe.Backend.VHDL.FileIO.writeDesignFile vhdl "../vhdl/vhdl/output.vhdl"
56 -- Turns the given bind into VHDL
58 -- Add the builtin functions
59 mapM (uncurry addFunc) builtin_funcs
60 -- Get the function signatures
61 funcs <- mapM mkHWFunction binds
62 -- Add them to the session
63 mapM (uncurry addFunc) funcs
64 let entities = map getEntity (snd $ unzip funcs)
65 -- Create architectures for them
66 archs <- mapM getArchitecture binds
67 return $ AST.DesignFile
69 ((map AST.LUEntity entities) ++ (map AST.LUArch archs))
71 printTarget (Target (TargetFile file (Just x)) obj Nothing) =
74 printBinds [] = putStr "done\n\n"
75 printBinds (b:bs) = do
80 printBind (NonRec b expr) = do
84 printBind (Rec binds) = do
86 foldl1 (>>) (map printBind' binds)
88 printBind' (b, expr) = do
89 putStr $ getOccString b
90 putStr $ showSDoc $ ppr expr
93 findBind :: [CoreBind] -> String -> Maybe CoreBind
94 findBind binds lookfor =
95 -- This ignores Recs and compares the name of the bind with lookfor,
96 -- disregarding any namespaces in OccName and extra attributes in Name and
100 NonRec var _ -> lookfor == (occNameString $ nameOccName $ getName var)
104 SignalNameMap -- The port name to bind to
106 -- The signal or port to bind to it
107 -> AST.AssocElem -- The resulting port map entry
109 -- Accepts a port name and an argument to map to it.
110 -- Returns the appropriate line for in the port map
111 getPortMapEntry (Signal portname _) (Signal signame _) =
112 (Just portname) AST.:=>: (AST.ADName (AST.NSimple signame))
114 [(CoreBndr, SignalNameMap)]
115 -- A list of bindings in effect
116 -> CoreExpr -- The expression to expand
118 [AST.SigDec], -- Needed signal declarations
119 [AST.ConcSm], -- Needed component instantations and
120 -- signal assignments.
121 [SignalNameMap], -- The signal names corresponding to
122 -- the expression's arguments
123 SignalNameMap) -- The signal names corresponding to
124 -- the expression's result.
125 expandExpr binds lam@(Lam b expr) = do
126 -- Generate a new signal to which we will expect this argument to be bound.
127 signal_name <- uniqueName ("arg_" ++ getOccString b)
128 -- Find the type of the binder
129 let (arg_ty, _) = Type.splitFunTy (CoreUtils.exprType lam)
130 -- Create signal names for the binder
131 let arg_signal = getPortNameMapForTy ("xxx") arg_ty
132 -- Create the corresponding signal declarations
133 let signal_decls = mkSignalsFromMap arg_signal
134 -- Add the binder to the list of binds
135 let binds' = (b, arg_signal) : binds
136 -- Expand the rest of the expression
137 (signal_decls', statements', arg_signals', res_signal') <- expandExpr binds' expr
138 -- Properly merge the results
139 return (signal_decls ++ signal_decls',
141 arg_signal : arg_signals',
144 expandExpr binds (Var id) =
145 return ([], [], [], Signal signal_id ty)
147 -- Lookup the id in our binds map
148 Signal signal_id ty = Maybe.fromMaybe
149 (error $ "Argument " ++ getOccString id ++ "is unknown")
152 expandExpr binds l@(Let (NonRec b bexpr) expr) = do
153 (signal_decls, statements, arg_signals, res_signals) <- expandExpr binds bexpr
154 let binds' = (b, res_signals) : binds
155 (signal_decls', statements', arg_signals', res_signals') <- expandExpr binds' expr
157 signal_decls ++ signal_decls',
158 statements ++ statements',
162 expandExpr binds app@(App _ _) = do
163 -- Is this a data constructor application?
164 case CoreUtils.exprIsConApp_maybe app of
165 -- Is this a tuple construction?
166 Just (dc, args) -> if DataCon.isTupleCon dc
168 expandBuildTupleExpr binds (dataConAppArgs dc args)
170 error "Data constructors other than tuples not supported"
172 -- Normal function application, should map to a component instantiation
173 let ((Var f), args) = collectArgs app in
174 expandApplicationExpr binds (CoreUtils.exprType app) f args
176 expandExpr binds expr@(Case (Var v) b _ alts) =
178 [alt] -> expandSingleAltCaseExpr binds v b alt
179 otherwise -> error $ "Multiple alternative case expression not supported: " ++ (showSDoc $ ppr expr)
181 expandExpr binds expr@(Case _ b _ _) =
182 error $ "Case expression with non-variable scrutinee not supported: " ++ (showSDoc $ ppr expr)
184 expandExpr binds expr =
185 error $ "Unsupported expression: " ++ (showSDoc $ ppr $ expr)
187 -- Expands the construction of a tuple into VHDL
188 expandBuildTupleExpr ::
189 [(CoreBndr, SignalNameMap)]
190 -- A list of bindings in effect
191 -> [CoreExpr] -- A list of expressions to put in the tuple
192 -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
194 expandBuildTupleExpr binds args = do
195 -- Split the tuple constructor arguments into types and actual values.
196 -- Expand each of the values in the tuple
197 (signals_declss, statementss, arg_signalss, res_signals) <-
198 (Monad.liftM List.unzip4) $ mapM (expandExpr binds) args
199 if any (not . null) arg_signalss
200 then error "Putting high order functions in tuples not supported"
203 concat signals_declss,
208 -- Expands the most simple case expression that scrutinizes a plain variable
209 -- and has a single alternative. This simple form currently allows only for
210 -- unpacking tuple variables.
211 expandSingleAltCaseExpr ::
212 [(CoreBndr, SignalNameMap)]
213 -- A list of bindings in effect
214 -> Var.Var -- The scrutinee
215 -> CoreBndr -- The binder to bind the scrutinee to
216 -> CoreAlt -- The single alternative
217 -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
220 expandSingleAltCaseExpr binds v b alt@(DataAlt datacon, bind_vars, expr) =
221 if not (DataCon.isTupleCon datacon)
223 error $ "Dataconstructors other than tuple constructors not supported in case pattern of alternative: " ++ (showSDoc $ ppr alt)
226 -- Lookup the scrutinee (which must be a variable bound to a tuple) in
227 -- the existing bindings list and get the portname map for each of
229 Tuple tuple_ports = Maybe.fromMaybe
230 (error $ "Case expression uses unknown scrutinee " ++ getOccString v)
232 -- TODO include b in the binds list
233 -- Merge our existing binds with the new binds.
234 binds' = (zip bind_vars tuple_ports) ++ binds
236 -- Expand the expression with the new binds list
237 expandExpr binds' expr
239 expandSingleAltCaseExpr _ _ _ alt =
240 error $ "Case patterns other than data constructors not supported in case alternative: " ++ (showSDoc $ ppr alt)
243 -- Expands the application of argument to a function into VHDL
244 expandApplicationExpr ::
245 [(CoreBndr, SignalNameMap)]
246 -- A list of bindings in effect
247 -> Type -- The result type of the function call
248 -> Var.Var -- The function to call
249 -> [CoreExpr] -- A list of argumetns to apply to the function
250 -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
252 expandApplicationExpr binds ty f args = do
253 let name = getOccString f
254 -- Generate a unique name for the application
255 appname <- uniqueName ("app_" ++ name)
256 -- Lookup the hwfunction to instantiate
257 HWFunction vhdl_id inports outport <- getHWFunc name
258 -- Expand each of the args, so each of them is reduced to output signals
259 (arg_signal_decls, arg_statements, arg_res_signals) <- expandArgs binds args
260 -- Bind each of the input ports to the expanded arguments
261 let inmaps = concat $ zipWith createAssocElems inports arg_res_signals
262 -- Create signal names for our result
263 let res_signal = getPortNameMapForTy (appname ++ "_out") ty
264 -- Create the corresponding signal declarations
265 let signal_decls = mkSignalsFromMap res_signal
266 -- Bind each of the output ports to our output signals
267 let outmaps = mapOutputPorts outport res_signal
268 -- Instantiate the component
269 let component = AST.CSISm $ AST.CompInsSm
270 (AST.unsafeVHDLBasicId appname)
271 (AST.IUEntity (AST.NSimple vhdl_id))
272 (AST.PMapAspect (inmaps ++ outmaps))
273 -- Merge the generated declarations
275 signal_decls ++ arg_signal_decls,
276 component : arg_statements,
277 [], -- We don't take any extra arguments; we don't support higher order functions yet
280 -- Creates a list of AssocElems (port map lines) that maps the given signals
281 -- to the given ports.
283 SignalNameMap -- The port names to bind to
284 -> SignalNameMap -- The signals to bind to it
285 -> [AST.AssocElem] -- The resulting port map lines
287 createAssocElems (Signal port_id _) (Signal signal_id _) =
288 [(Just port_id) AST.:=>: (AST.ADName (AST.NSimple signal_id))]
290 createAssocElems (Tuple ports) (Tuple signals) =
291 concat $ zipWith createAssocElems ports signals
293 -- Generate a signal declaration for a signal with the given name and the
294 -- given type and no value. Also returns the id of the signal.
295 mkSignal :: String -> AST.TypeMark -> (AST.VHDLId, AST.SigDec)
297 (id, mkSignalFromId id ty)
299 id = AST.unsafeVHDLBasicId name
301 mkSignalFromId :: AST.VHDLId -> AST.TypeMark -> AST.SigDec
302 mkSignalFromId id ty =
303 AST.SigDec id ty Nothing
305 -- Generates signal declarations for all the signals in the given map
310 mkSignalsFromMap (Signal id ty) =
311 [mkSignalFromId id ty]
313 mkSignalsFromMap (Tuple signals) =
314 concat $ map mkSignalsFromMap signals
317 [(CoreBndr, SignalNameMap)] -- A list of bindings in effect
318 -> [CoreExpr] -- The arguments to expand
319 -> VHDLState ([AST.SigDec], [AST.ConcSm], [SignalNameMap])
320 -- The resulting signal declarations,
321 -- component instantiations and a
322 -- VHDLName for each of the
323 -- expressions passed in.
324 expandArgs binds (e:exprs) = do
325 -- Expand the first expression
326 (signal_decls, statements, arg_signals, res_signal) <- expandExpr binds e
327 if not (null arg_signals)
328 then error $ "Passing functions as arguments not supported: " ++ (showSDoc $ ppr e)
330 (signal_decls', statements', res_signals') <- expandArgs binds exprs
332 signal_decls ++ signal_decls',
333 statements ++ statements',
334 res_signal : res_signals')
336 expandArgs _ [] = return ([], [], [])
338 -- Extract the arguments from a data constructor application (that is, the
339 -- normal args, leaving out the type args).
340 dataConAppArgs :: DataCon -> [CoreExpr] -> [CoreExpr]
341 dataConAppArgs dc args =
344 tycount = length $ DataCon.dataConAllTyVars dc
347 SignalNameMap -- The output portnames of the component
348 -> SignalNameMap -- The output portnames and/or signals to map these to
349 -> [AST.AssocElem] -- The resulting output ports
351 -- Map the output port of a component to the output port of the containing
353 mapOutputPorts (Signal portname _) (Signal signalname _) =
354 [(Just portname) AST.:=>: (AST.ADName (AST.NSimple signalname))]
356 -- Map matching output ports in the tuple
357 mapOutputPorts (Tuple ports) (Tuple signals) =
358 concat (zipWith mapOutputPorts ports signals)
361 CoreBind -- The binder to expand into an architecture
362 -> VHDLState AST.ArchBody -- The resulting architecture
364 getArchitecture (Rec _) = error "Recursive binders not supported"
366 getArchitecture (NonRec var expr) = do
367 let name = (getOccString var)
368 HWFunction vhdl_id inports outport <- getHWFunc name
370 (signal_decls, statements, arg_signals, res_signal) <- expandExpr [] expr
371 let inport_assigns = concat $ zipWith createSignalAssignments arg_signals inports
372 let outport_assigns = createSignalAssignments outport res_signal
373 return $ AST.ArchBody
374 (AST.unsafeVHDLBasicId "structural")
375 (AST.NSimple vhdl_id)
376 (map AST.BDISD signal_decls)
377 (inport_assigns ++ outport_assigns ++ statements)
379 -- Generate a VHDL entity declaration for the given function
380 getEntity :: HWFunction -> AST.EntityDec
381 getEntity (HWFunction vhdl_id inports outport) =
382 AST.EntityDec vhdl_id ports
385 (concat $ map (mkIfaceSigDecs AST.In) inports)
386 ++ mkIfaceSigDecs AST.Out outport
389 AST.Mode -- The port's mode (In or Out)
390 -> SignalNameMap -- The ports to generate a map for
391 -> [AST.IfaceSigDec] -- The resulting ports
393 mkIfaceSigDecs mode (Signal port_id ty) =
394 [AST.IfaceSigDec port_id mode ty]
396 mkIfaceSigDecs mode (Tuple ports) =
397 concat $ map (mkIfaceSigDecs mode) ports
399 -- Create concurrent assignments of one map of signals to another. The maps
400 -- should have a similar form.
401 createSignalAssignments ::
402 SignalNameMap -- The signals to assign to
403 -> SignalNameMap -- The signals to assign
404 -> [AST.ConcSm] -- The resulting assignments
406 -- A simple assignment of one signal to another (greatly complicated because
407 -- signal assignments can be conditional with multiple conditions in VHDL).
408 createSignalAssignments (Signal dst _) (Signal src _) =
411 src_name = AST.NSimple src
412 src_expr = AST.PrimName src_name
413 src_wform = AST.Wform [AST.WformElem src_expr Nothing]
414 dst_name = (AST.NSimple dst)
415 assign = dst_name AST.:<==: (AST.ConWforms [] src_wform Nothing)
417 createSignalAssignments (Tuple dsts) (Tuple srcs) =
418 concat $ zipWith createSignalAssignments dsts srcs
420 createSignalAssignments dst src =
421 error $ "Non matching source and destination: " ++ show dst ++ "\nand\n" ++ show src
424 Tuple [SignalNameMap]
425 | Signal AST.VHDLId AST.TypeMark -- A signal (or port) of the given (VDHL) type
428 -- Generate a port name map (or multiple for tuple types) in the given direction for
430 getPortNameMapForTys :: String -> Int -> [Type] -> [SignalNameMap]
431 getPortNameMapForTys prefix num [] = []
432 getPortNameMapForTys prefix num (t:ts) =
433 (getPortNameMapForTy (prefix ++ show num) t) : getPortNameMapForTys prefix (num + 1) ts
435 getPortNameMapForTy :: String -> Type -> SignalNameMap
436 getPortNameMapForTy name ty =
437 if (TyCon.isTupleTyCon tycon) then
438 -- Expand tuples we find
439 Tuple (getPortNameMapForTys name 0 args)
440 else -- Assume it's a type constructor application, ie simple data type
441 Signal (AST.unsafeVHDLBasicId name) (vhdl_ty ty)
443 (tycon, args) = Type.splitTyConApp ty
445 data HWFunction = HWFunction { -- A function that is available in hardware
446 vhdlId :: AST.VHDLId,
447 inPorts :: [SignalNameMap],
448 outPort :: SignalNameMap
449 --entity :: AST.EntityDec
452 -- Turns a CoreExpr describing a function into a description of its input and
455 CoreBind -- The core binder to generate the interface for
456 -> VHDLState (String, HWFunction) -- The name of the function and its interface
458 mkHWFunction (NonRec var expr) =
459 return (name, HWFunction (mkVHDLId name) inports outport)
461 name = getOccString var
462 ty = CoreUtils.exprType expr
463 (fargs, res) = Type.splitFunTys ty
464 args = if length fargs == 1 then fargs else (init fargs)
465 --state = if length fargs == 1 then () else (last fargs)
466 inports = case args of
467 -- Handle a single port specially, to prevent an extra 0 in the name
468 [port] -> [getPortNameMapForTy "portin" port]
469 ps -> getPortNameMapForTys "portin" 0 ps
470 outport = getPortNameMapForTy "portout" res
472 mkHWFunction (Rec _) =
473 error "Recursive binders not supported"
475 data VHDLSession = VHDLSession {
476 nameCount :: Int, -- A counter that can be used to generate unique names
477 funcs :: [(String, HWFunction)] -- All functions available, indexed by name
480 type VHDLState = State.State VHDLSession
482 -- Add the function to the session
483 addFunc :: String -> HWFunction -> VHDLState ()
485 fs <- State.gets funcs -- Get the funcs element from the session
486 State.modify (\x -> x {funcs = (name, f) : fs }) -- Prepend name and f
488 -- Lookup the function with the given name in the current session. Errors if
490 getHWFunc :: String -> VHDLState HWFunction
492 fs <- State.gets funcs -- Get the funcs element from the session
493 return $ Maybe.fromMaybe
494 (error $ "Function " ++ name ++ "is unknown? This should not happen!")
497 -- Makes the given name unique by appending a unique number.
498 -- This does not do any checking against existing names, so it only guarantees
499 -- uniqueness with other names generated by uniqueName.
500 uniqueName :: String -> VHDLState String
502 count <- State.gets nameCount -- Get the funcs element from the session
503 State.modify (\s -> s {nameCount = count + 1})
504 return $ name ++ "_" ++ (show count)
507 mkVHDLId :: String -> AST.VHDLId
508 mkVHDLId = AST.unsafeVHDLBasicId
512 ("hwxor", HWFunction (mkVHDLId "hwxor") [Signal (mkVHDLId "a") vhdl_bit_ty, Signal (mkVHDLId "b") vhdl_bit_ty] (Signal (mkVHDLId "o") vhdl_bit_ty)),
513 ("hwand", HWFunction (mkVHDLId "hwand") [Signal (mkVHDLId "a") vhdl_bit_ty, Signal (mkVHDLId "b") vhdl_bit_ty] (Signal (mkVHDLId "o") vhdl_bit_ty)),
514 ("hwor", HWFunction (mkVHDLId "hwor") [Signal (mkVHDLId "a") vhdl_bit_ty, Signal (mkVHDLId "b") vhdl_bit_ty] (Signal (mkVHDLId "o") vhdl_bit_ty)),
515 ("hwnot", HWFunction (mkVHDLId "hwnot") [Signal (mkVHDLId "i") vhdl_bit_ty] (Signal (mkVHDLId "o") vhdl_bit_ty))
518 vhdl_bit_ty :: AST.TypeMark
519 vhdl_bit_ty = AST.unsafeVHDLBasicId "Bit"
521 -- Translate a Haskell type to a VHDL type
522 vhdl_ty :: Type -> AST.TypeMark
523 vhdl_ty ty = Maybe.fromMaybe
524 (error $ "Unsupported Haskell type: " ++ (showSDoc $ ppr ty))
527 -- Translate a Haskell type to a VHDL type
528 vhdl_ty_maybe :: Type -> Maybe AST.TypeMark
530 case Type.splitTyConApp_maybe ty of
531 Just (tycon, args) ->
532 let name = TyCon.tyConName tycon in
533 -- TODO: Do something more robust than string matching
534 case getOccString name of
535 "Bit" -> Just vhdl_bit_ty
539 -- vim: set ts=8 sw=2 sts=2 expandtab: