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 -- Create entities and architectures for them
61 units <- mapM expandBind binds
62 return $ AST.DesignFile
66 printTarget (Target (TargetFile file (Just x)) obj Nothing) =
69 printBinds [] = putStr "done\n\n"
70 printBinds (b:bs) = do
75 printBind (NonRec b expr) = do
79 printBind (Rec binds) = do
81 foldl1 (>>) (map printBind' binds)
83 printBind' (b, expr) = do
84 putStr $ getOccString b
85 putStr $ showSDoc $ ppr expr
88 findBind :: [CoreBind] -> String -> Maybe CoreBind
89 findBind binds lookfor =
90 -- This ignores Recs and compares the name of the bind with lookfor,
91 -- disregarding any namespaces in OccName and extra attributes in Name and
95 NonRec var _ -> lookfor == (occNameString $ nameOccName $ getName var)
99 SignalNameMap -- The port name to bind to
101 -- The signal or port to bind to it
102 -> AST.AssocElem -- The resulting port map entry
104 -- Accepts a port name and an argument to map to it.
105 -- Returns the appropriate line for in the port map
106 getPortMapEntry (Single (portname, _)) (Single (signame, _)) =
107 (Just portname) AST.:=>: (AST.ADName (AST.NSimple signame))
109 [(CoreBndr, SignalNameMap)]
110 -- A list of bindings in effect
111 -> CoreExpr -- The expression to expand
113 [AST.SigDec], -- Needed signal declarations
114 [AST.ConcSm], -- Needed component instantations and
115 -- signal assignments.
116 [SignalNameMap], -- The signal names corresponding to
117 -- the expression's arguments
118 SignalNameMap) -- The signal names corresponding to
119 -- the expression's result.
120 expandExpr binds lam@(Lam b expr) = do
121 -- Generate a new signal to which we will expect this argument to be bound.
122 signal_name <- uniqueName ("arg_" ++ getOccString b)
123 -- Find the type of the binder
124 let (arg_ty, _) = Type.splitFunTy (CoreUtils.exprType lam)
125 -- Create signal names for the binder
126 let arg_signal = getPortNameMapForTy ("xxx") arg_ty
127 -- Create the corresponding signal declarations
128 let signal_decls = mkSignalsFromMap arg_signal
129 -- Add the binder to the list of binds
130 let binds' = (b, arg_signal) : binds
131 -- Expand the rest of the expression
132 (signal_decls', statements', arg_signals', res_signal') <- expandExpr binds' expr
133 -- Properly merge the results
134 return (signal_decls ++ signal_decls',
136 arg_signal : arg_signals',
139 expandExpr binds (Var id) =
140 return ([], [], [], Single (signal_id, ty))
142 -- Lookup the id in our binds map
143 Single (signal_id, ty) = Maybe.fromMaybe
144 (error $ "Argument " ++ getOccString id ++ "is unknown")
147 expandExpr binds l@(Let (NonRec b bexpr) expr) = do
148 (signal_decls, statements, arg_signals, res_signals) <- expandExpr binds bexpr
149 let binds' = (b, res_signals) : binds
150 (signal_decls', statements', arg_signals', res_signals') <- expandExpr binds' expr
152 signal_decls ++ signal_decls',
153 statements ++ statements',
157 expandExpr binds app@(App _ _) = do
158 -- Is this a data constructor application?
159 case CoreUtils.exprIsConApp_maybe app of
160 -- Is this a tuple construction?
161 Just (dc, args) -> if DataCon.isTupleCon dc
163 expandBuildTupleExpr binds (dataConAppArgs dc args)
165 error "Data constructors other than tuples not supported"
167 -- Normal function application, should map to a component instantiation
168 let ((Var f), args) = collectArgs app in
169 expandApplicationExpr binds (CoreUtils.exprType app) f args
171 expandExpr binds expr@(Case (Var v) b _ alts) =
173 [alt] -> expandSingleAltCaseExpr binds v b alt
174 otherwise -> error $ "Multiple alternative case expression not supported: " ++ (showSDoc $ ppr expr)
176 expandExpr binds expr@(Case _ b _ _) =
177 error $ "Case expression with non-variable scrutinee not supported: " ++ (showSDoc $ ppr expr)
179 expandExpr binds expr =
180 error $ "Unsupported expression: " ++ (showSDoc $ ppr $ expr)
182 -- Expands the construction of a tuple into VHDL
183 expandBuildTupleExpr ::
184 [(CoreBndr, SignalNameMap)]
185 -- A list of bindings in effect
186 -> [CoreExpr] -- A list of expressions to put in the tuple
187 -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
189 expandBuildTupleExpr binds args = do
190 -- Split the tuple constructor arguments into types and actual values.
191 -- Expand each of the values in the tuple
192 (signals_declss, statementss, arg_signalss, res_signals) <-
193 (Monad.liftM List.unzip4) $ mapM (expandExpr binds) args
194 if any (not . null) arg_signalss
195 then error "Putting high order functions in tuples not supported"
198 concat signals_declss,
203 -- Expands the most simple case expression that scrutinizes a plain variable
204 -- and has a single alternative. This simple form currently allows only for
205 -- unpacking tuple variables.
206 expandSingleAltCaseExpr ::
207 [(CoreBndr, SignalNameMap)]
208 -- A list of bindings in effect
209 -> Var.Var -- The scrutinee
210 -> CoreBndr -- The binder to bind the scrutinee to
211 -> CoreAlt -- The single alternative
212 -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
215 expandSingleAltCaseExpr binds v b alt@(DataAlt datacon, bind_vars, expr) =
216 if not (DataCon.isTupleCon datacon)
218 error $ "Dataconstructors other than tuple constructors not supported in case pattern of alternative: " ++ (showSDoc $ ppr alt)
221 -- Lookup the scrutinee (which must be a variable bound to a tuple) in
222 -- the existing bindings list and get the portname map for each of
224 Tuple tuple_ports = Maybe.fromMaybe
225 (error $ "Case expression uses unknown scrutinee " ++ getOccString v)
227 -- TODO include b in the binds list
228 -- Merge our existing binds with the new binds.
229 binds' = (zip bind_vars tuple_ports) ++ binds
231 -- Expand the expression with the new binds list
232 expandExpr binds' expr
234 expandSingleAltCaseExpr _ _ _ alt =
235 error $ "Case patterns other than data constructors not supported in case alternative: " ++ (showSDoc $ ppr alt)
238 -- Expands the application of argument to a function into VHDL
239 expandApplicationExpr ::
240 [(CoreBndr, SignalNameMap)]
241 -- A list of bindings in effect
242 -> Type -- The result type of the function call
243 -> Var.Var -- The function to call
244 -> [CoreExpr] -- A list of argumetns to apply to the function
245 -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
247 expandApplicationExpr binds ty f args = do
248 let name = getOccString f
249 -- Generate a unique name for the application
250 appname <- uniqueName ("app_" ++ name)
251 -- Lookup the hwfunction to instantiate
252 HWFunction vhdl_id inports outport <- getHWFunc (appToHsFunction f args ty)
253 -- Expand each of the args, so each of them is reduced to output signals
254 (arg_signal_decls, arg_statements, arg_res_signals) <- expandArgs binds args
255 -- Bind each of the input ports to the expanded arguments
256 let inmaps = concat $ zipWith createAssocElems inports arg_res_signals
257 -- Create signal names for our result
258 let res_signal = getPortNameMapForTy (appname ++ "_out") ty
259 -- Create the corresponding signal declarations
260 let signal_decls = mkSignalsFromMap res_signal
261 -- Bind each of the output ports to our output signals
262 let outmaps = mapOutputPorts outport res_signal
263 -- Instantiate the component
264 let component = AST.CSISm $ AST.CompInsSm
265 (AST.unsafeVHDLBasicId appname)
266 (AST.IUEntity (AST.NSimple vhdl_id))
267 (AST.PMapAspect (inmaps ++ outmaps))
268 -- Merge the generated declarations
270 signal_decls ++ arg_signal_decls,
271 component : arg_statements,
272 [], -- We don't take any extra arguments; we don't support higher order functions yet
275 -- Creates a list of AssocElems (port map lines) that maps the given signals
276 -- to the given ports.
278 SignalNameMap -- The port names to bind to
279 -> SignalNameMap -- The signals to bind to it
280 -> [AST.AssocElem] -- The resulting port map lines
282 createAssocElems (Single (port_id, _)) (Single (signal_id, _)) =
283 [(Just port_id) AST.:=>: (AST.ADName (AST.NSimple signal_id))]
285 createAssocElems (Tuple ports) (Tuple signals) =
286 concat $ zipWith createAssocElems ports signals
288 -- Generate a signal declaration for a signal with the given name and the
289 -- given type and no value. Also returns the id of the signal.
290 mkSignal :: String -> AST.TypeMark -> (AST.VHDLId, AST.SigDec)
292 (id, mkSignalFromId id ty)
294 id = AST.unsafeVHDLBasicId name
296 mkSignalFromId :: AST.VHDLId -> AST.TypeMark -> AST.SigDec
297 mkSignalFromId id ty =
298 AST.SigDec id ty Nothing
300 -- Generates signal declarations for all the signals in the given map
305 mkSignalsFromMap (Single (id, ty)) =
306 [mkSignalFromId id ty]
308 mkSignalsFromMap (Tuple signals) =
309 concat $ map mkSignalsFromMap signals
312 [(CoreBndr, SignalNameMap)] -- A list of bindings in effect
313 -> [CoreExpr] -- The arguments to expand
314 -> VHDLState ([AST.SigDec], [AST.ConcSm], [SignalNameMap])
315 -- The resulting signal declarations,
316 -- component instantiations and a
317 -- VHDLName for each of the
318 -- expressions passed in.
319 expandArgs binds (e:exprs) = do
320 -- Expand the first expression
321 (signal_decls, statements, arg_signals, res_signal) <- expandExpr binds e
322 if not (null arg_signals)
323 then error $ "Passing functions as arguments not supported: " ++ (showSDoc $ ppr e)
325 (signal_decls', statements', res_signals') <- expandArgs binds exprs
327 signal_decls ++ signal_decls',
328 statements ++ statements',
329 res_signal : res_signals')
331 expandArgs _ [] = return ([], [], [])
333 -- Extract the arguments from a data constructor application (that is, the
334 -- normal args, leaving out the type args).
335 dataConAppArgs :: DataCon -> [CoreExpr] -> [CoreExpr]
336 dataConAppArgs dc args =
339 tycount = length $ DataCon.dataConAllTyVars dc
342 SignalNameMap -- The output portnames of the component
343 -> SignalNameMap -- The output portnames and/or signals to map these to
344 -> [AST.AssocElem] -- The resulting output ports
346 -- Map the output port of a component to the output port of the containing
348 mapOutputPorts (Single (portname, _)) (Single (signalname, _)) =
349 [(Just portname) AST.:=>: (AST.ADName (AST.NSimple signalname))]
351 -- Map matching output ports in the tuple
352 mapOutputPorts (Tuple ports) (Tuple signals) =
353 concat (zipWith mapOutputPorts ports signals)
356 CoreBind -- The binder to expand into VHDL
357 -> VHDLState [AST.LibraryUnit] -- The resulting VHDL
359 expandBind (Rec _) = error "Recursive binders not supported"
361 expandBind bind@(NonRec var expr) = do
362 -- Create the function signature
363 hwfunc <- mkHWFunction bind
364 let ty = CoreUtils.exprType expr
365 let hsfunc = mkHsFunction var ty
366 -- Add it to the session
367 addFunc hsfunc hwfunc
368 arch <- getArchitecture hwfunc expr
369 let entity = getEntity hwfunc
375 HWFunction -- The function to generate an architecture for
376 -> CoreExpr -- The expression that is bound to the function
377 -> VHDLState AST.ArchBody -- The resulting architecture
379 getArchitecture hwfunc expr = do
381 let HWFunction vhdl_id inports outport = hwfunc
382 -- Expand the expression into an architecture body
383 (signal_decls, statements, arg_signals, res_signal) <- expandExpr [] expr
384 let inport_assigns = concat $ zipWith createSignalAssignments arg_signals inports
385 let outport_assigns = createSignalAssignments outport res_signal
386 return $ AST.ArchBody
387 (AST.unsafeVHDLBasicId "structural")
388 (AST.NSimple vhdl_id)
389 (map AST.BDISD signal_decls)
390 (inport_assigns ++ outport_assigns ++ statements)
392 -- Generate a VHDL entity declaration for the given function
393 getEntity :: HWFunction -> AST.EntityDec
394 getEntity (HWFunction vhdl_id inports outport) =
395 AST.EntityDec vhdl_id ports
398 (concat $ map (mkIfaceSigDecs AST.In) inports)
399 ++ mkIfaceSigDecs AST.Out outport
402 AST.Mode -- The port's mode (In or Out)
403 -> SignalNameMap -- The ports to generate a map for
404 -> [AST.IfaceSigDec] -- The resulting ports
406 mkIfaceSigDecs mode (Single (port_id, ty)) =
407 [AST.IfaceSigDec port_id mode ty]
409 mkIfaceSigDecs mode (Tuple ports) =
410 concat $ map (mkIfaceSigDecs mode) ports
412 -- Create concurrent assignments of one map of signals to another. The maps
413 -- should have a similar form.
414 createSignalAssignments ::
415 SignalNameMap -- The signals to assign to
416 -> SignalNameMap -- The signals to assign
417 -> [AST.ConcSm] -- The resulting assignments
419 -- A simple assignment of one signal to another (greatly complicated because
420 -- signal assignments can be conditional with multiple conditions in VHDL).
421 createSignalAssignments (Single (dst, _)) (Single (src, _)) =
424 src_name = AST.NSimple src
425 src_expr = AST.PrimName src_name
426 src_wform = AST.Wform [AST.WformElem src_expr Nothing]
427 dst_name = (AST.NSimple dst)
428 assign = dst_name AST.:<==: (AST.ConWforms [] src_wform Nothing)
430 createSignalAssignments (Tuple dsts) (Tuple srcs) =
431 concat $ zipWith createSignalAssignments dsts srcs
433 createSignalAssignments dst src =
434 error $ "Non matching source and destination: " ++ show dst ++ "\nand\n" ++ show src
436 type SignalNameMap = HsValueMap (AST.VHDLId, AST.TypeMark)
438 -- | A datatype that maps each of the single values in a haskell structure to
439 -- a mapto. The map has the same structure as the haskell type mapped, ie
440 -- nested tuples etc.
441 data HsValueMap mapto =
442 Tuple [HsValueMap mapto]
446 -- | Creates a HsValueMap with the same structure as the given type, using the
447 -- given function for mapping the single types.
449 (Type -> HsValueMap mapto) -- ^ A function to map single value Types
450 -- (basically anything but tuples) to a
451 -- HsValueMap (not limited to the Single
453 -> Type -- ^ The type to map to a HsValueMap
454 -> HsValueMap mapto -- ^ The resulting map
457 case Type.splitTyConApp_maybe ty of
458 Just (tycon, args) ->
459 if (TyCon.isTupleTyCon tycon)
461 -- Handle tuple construction especially
462 Tuple (map (mkHsValueMap f) args)
464 -- And let f handle the rest
466 -- And let f handle the rest
469 -- Generate a port name map (or multiple for tuple types) in the given direction for
471 getPortNameMapForTys :: String -> Int -> [Type] -> [SignalNameMap]
472 getPortNameMapForTys prefix num [] = []
473 getPortNameMapForTys prefix num (t:ts) =
474 (getPortNameMapForTy (prefix ++ show num) t) : getPortNameMapForTys prefix (num + 1) ts
476 getPortNameMapForTy :: String -> Type -> SignalNameMap
477 getPortNameMapForTy name ty =
478 if (TyCon.isTupleTyCon tycon) then
479 -- Expand tuples we find
480 Tuple (getPortNameMapForTys name 0 args)
481 else -- Assume it's a type constructor application, ie simple data type
482 Single ((AST.unsafeVHDLBasicId name), (vhdl_ty ty))
484 (tycon, args) = Type.splitTyConApp ty
486 data HWFunction = HWFunction { -- A function that is available in hardware
487 vhdlId :: AST.VHDLId,
488 inPorts :: [SignalNameMap],
489 outPort :: SignalNameMap
490 --entity :: AST.EntityDec
493 -- Turns a CoreExpr describing a function into a description of its input and
496 CoreBind -- The core binder to generate the interface for
497 -> VHDLState HWFunction -- The function interface
499 mkHWFunction (NonRec var expr) =
500 return $ HWFunction (mkVHDLId name) inports outport
502 name = getOccString var
503 ty = CoreUtils.exprType expr
504 (fargs, res) = Type.splitFunTys ty
505 args = if length fargs == 1 then fargs else (init fargs)
506 --state = if length fargs == 1 then () else (last fargs)
507 inports = case args of
508 -- Handle a single port specially, to prevent an extra 0 in the name
509 [port] -> [getPortNameMapForTy "portin" port]
510 ps -> getPortNameMapForTys "portin" 0 ps
511 outport = getPortNameMapForTy "portout" res
513 mkHWFunction (Rec _) =
514 error "Recursive binders not supported"
516 -- | How is a given (single) value in a function's type (ie, argument or
517 -- return value) used?
519 Port -- ^ Use it as a port (input or output)
522 -- | This type describes a particular use of a Haskell function and is used to
523 -- look up an appropriate hardware description.
524 data HsFunction = HsFunction {
525 hsName :: String, -- ^ What was the name of the original Haskell function?
526 hsArgs :: [HsValueMap HsValueUse], -- ^ How are the arguments used?
527 hsRes :: HsValueMap HsValueUse -- ^ How is the result value used?
528 } deriving (Show, Eq)
530 -- | Translate a function application to a HsFunction. i.e., which function
531 -- do you need to translate this function application.
533 Var.Var -- ^ The function to call
534 -> [CoreExpr] -- ^ The function arguments
535 -> Type -- ^ The return type
536 -> HsFunction -- ^ The needed HsFunction
538 appToHsFunction f args ty =
539 HsFunction hsname hsargs hsres
541 mkPort = \x -> Single Port
542 hsargs = map (mkHsValueMap mkPort . CoreUtils.exprType) args
543 hsres = mkHsValueMap mkPort ty
544 hsname = getOccString f
546 -- | Translate a top level function declaration to a HsFunction. i.e., which
547 -- interface will be provided by this function. This function essentially
548 -- defines the "calling convention" for hardware models.
550 Var.Var -- ^ The function defined
551 -> Type -- ^ The function type (including arguments!)
552 -> HsFunction -- ^ The resulting HsFunction
555 HsFunction hsname hsargs hsres
557 (arg_tys, res_ty) = Type.splitFunTys ty
558 mkPort = \x -> Single Port
559 hsargs = map (mkHsValueMap mkPort) arg_tys
560 hsres = mkHsValueMap mkPort res_ty
561 hsname = getOccString f
563 data VHDLSession = VHDLSession {
564 nameCount :: Int, -- A counter that can be used to generate unique names
565 funcs :: [(HsFunction, HWFunction)] -- All functions available
568 type VHDLState = State.State VHDLSession
570 -- Add the function to the session
571 addFunc :: HsFunction -> HWFunction -> VHDLState ()
572 addFunc hsfunc hwfunc = do
573 fs <- State.gets funcs -- Get the funcs element from the session
574 State.modify (\x -> x {funcs = (hsfunc, hwfunc) : fs }) -- Prepend name and f
576 -- Lookup the function with the given name in the current session. Errors if
578 getHWFunc :: HsFunction -> VHDLState HWFunction
579 getHWFunc hsfunc = do
580 fs <- State.gets funcs -- Get the funcs element from the session
581 return $ Maybe.fromMaybe
582 (error $ "Function " ++ (hsName hsfunc) ++ "is unknown? This should not happen!")
585 -- Makes the given name unique by appending a unique number.
586 -- This does not do any checking against existing names, so it only guarantees
587 -- uniqueness with other names generated by uniqueName.
588 uniqueName :: String -> VHDLState String
590 count <- State.gets nameCount -- Get the funcs element from the session
591 State.modify (\s -> s {nameCount = count + 1})
592 return $ name ++ "_" ++ (show count)
595 mkVHDLId :: String -> AST.VHDLId
596 mkVHDLId = AST.unsafeVHDLBasicId
600 (HsFunction "hwxor" [(Single Port), (Single Port)] (Single Port), HWFunction (mkVHDLId "hwxor") [Single (mkVHDLId "a", vhdl_bit_ty), Single (mkVHDLId "b", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty))),
601 (HsFunction "hwand" [(Single Port), (Single Port)] (Single Port), HWFunction (mkVHDLId "hwand") [Single (mkVHDLId "a", vhdl_bit_ty), Single (mkVHDLId "b", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty))),
602 (HsFunction "hwor" [(Single Port), (Single Port)] (Single Port), HWFunction (mkVHDLId "hwor") [Single (mkVHDLId "a", vhdl_bit_ty), Single (mkVHDLId "b", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty))),
603 (HsFunction "hwnot" [(Single Port)] (Single Port), HWFunction (mkVHDLId "hwnot") [Single (mkVHDLId "i", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty)))
606 vhdl_bit_ty :: AST.TypeMark
607 vhdl_bit_ty = AST.unsafeVHDLBasicId "Bit"
609 -- Translate a Haskell type to a VHDL type
610 vhdl_ty :: Type -> AST.TypeMark
611 vhdl_ty ty = Maybe.fromMaybe
612 (error $ "Unsupported Haskell type: " ++ (showSDoc $ ppr ty))
615 -- Translate a Haskell type to a VHDL type
616 vhdl_ty_maybe :: Type -> Maybe AST.TypeMark
618 case Type.splitTyConApp_maybe ty of
619 Just (tycon, args) ->
620 let name = TyCon.tyConName tycon in
621 -- TODO: Do something more robust than string matching
622 case getOccString name of
623 "Bit" -> Just vhdl_bit_ty
627 -- vim: set ts=8 sw=2 sts=2 expandtab: