1 module CLasH.VHDL.Generate where
4 import qualified Data.List as List
5 import qualified Data.Map as Map
6 import qualified Control.Monad as Monad
8 import qualified Data.Either as Either
10 import Data.Accessor.MonadState as MonadState
14 import qualified Language.VHDL.AST as AST
17 import qualified CoreSyn
21 import qualified IdInfo
22 import qualified Literal
24 import qualified TyCon
27 import CLasH.Translator.TranslatorTypes
28 import CLasH.VHDL.Constants
29 import CLasH.VHDL.VHDLTypes
30 import CLasH.VHDL.VHDLTools
31 import CLasH.Utils as Utils
32 import CLasH.Utils.Core.CoreTools
33 import CLasH.Utils.Pretty
34 import qualified CLasH.Normalize as Normalize
36 -----------------------------------------------------------------------------
37 -- Functions to generate VHDL for user-defined functions.
38 -----------------------------------------------------------------------------
40 -- | Create an entity for a given function
43 -> TranslatorSession Entity -- ^ The resulting entity
45 getEntity fname = Utils.makeCached fname tsEntities $ do
46 expr <- Normalize.getNormalized fname
47 -- Strip off lambda's, these will be arguments
48 let (args, letexpr) = CoreSyn.collectBinders expr
49 -- Generate ports for all non-empty types
50 args' <- catMaybesM $ mapM mkMap args
51 -- There must be a let at top level
52 let (CoreSyn.Let binds (CoreSyn.Var res)) = letexpr
53 -- TODO: Handle Nothing
55 let vhdl_id = mkVHDLBasicId $ varToString fname ++ "_" ++ varToStringUniq fname
56 let ent_decl = createEntityAST vhdl_id args' res'
57 let signature = Entity vhdl_id args' res' ent_decl
61 --[(SignalId, SignalInfo)]
63 -> TranslatorSession (Maybe Port)
66 --info = Maybe.fromMaybe
67 -- (error $ "Signal not found in the name map? This should not happen!")
69 -- Assume the bndr has a valid VHDL id already
72 error_msg = "\nVHDL.createEntity.mkMap: Can not create entity: " ++ pprString fname ++ "\nbecause no type can be created for port: " ++ pprString bndr
74 type_mark_maybe <- MonadState.lift tsType $ vhdl_ty error_msg ty
75 case type_mark_maybe of
76 Just type_mark -> return $ Just (id, type_mark)
77 Nothing -> return Nothing
80 -- | Create the VHDL AST for an entity
82 AST.VHDLId -- ^ The name of the function
83 -> [Port] -- ^ The entity's arguments
84 -> Maybe Port -- ^ The entity's result
85 -> AST.EntityDec -- ^ The entity with the ent_decl filled in as well
87 createEntityAST vhdl_id args res =
88 AST.EntityDec vhdl_id ports
90 -- Create a basic Id, since VHDL doesn't grok filenames with extended Ids.
91 ports = map (mkIfaceSigDec AST.In) args
92 ++ (Maybe.maybeToList res_port)
94 -- Add a clk port if we have state
95 clk_port = AST.IfaceSigDec clockId AST.In std_logicTM
96 res_port = fmap (mkIfaceSigDec AST.Out) res
98 -- | Create a port declaration
100 AST.Mode -- ^ The mode for the port (In / Out)
101 -> Port -- ^ The id and type for the port
102 -> AST.IfaceSigDec -- ^ The resulting port declaration
104 mkIfaceSigDec mode (id, ty) = AST.IfaceSigDec id mode ty
106 -- | Create an architecture for a given function
108 CoreSyn.CoreBndr -- ^ The function to get an architecture for
109 -> TranslatorSession (Architecture, [CoreSyn.CoreBndr])
110 -- ^ The architecture for this function
112 getArchitecture fname = Utils.makeCached fname tsArchitectures $ do
113 expr <- Normalize.getNormalized fname
114 signature <- getEntity fname
115 let entity_id = ent_id signature
116 -- Strip off lambda's, these will be arguments
117 let (args, letexpr) = CoreSyn.collectBinders expr
118 -- There must be a let at top level
119 let (CoreSyn.Let (CoreSyn.Rec binds) (CoreSyn.Var res)) = letexpr
121 -- Create signal declarations for all binders in the let expression, except
122 -- for the output port (that will already have an output port declared in
124 sig_dec_maybes <- mapM (mkSigDec . fst) (filter ((/=res).fst) binds)
125 let sig_decs = Maybe.catMaybes $ sig_dec_maybes
126 -- Process each bind, resulting in info about state variables and concurrent
128 (state_vars, sms) <- Monad.mapAndUnzipM dobind binds
129 let (in_state_maybes, out_state_maybes) = unzip state_vars
130 let (statementss, used_entitiess) = unzip sms
131 -- Create a state proc, if needed
132 let state_proc = case (Maybe.catMaybes in_state_maybes, Maybe.catMaybes out_state_maybes) of
133 ([in_state], [out_state]) -> [AST.CSPSm $ mkStateProcSm (in_state, out_state)]
135 (ins, outs) -> error $ "Weird use of state in " ++ show fname ++ ". In: " ++ show ins ++ " Out: " ++ show outs
136 -- Join the create statements and the (optional) state_proc
137 let statements = concat statementss ++ state_proc
138 -- Create the architecture
139 let arch = AST.ArchBody (mkVHDLBasicId "structural") (AST.NSimple entity_id) (map AST.BDISD sig_decs) statements
140 let used_entities = concat used_entitiess
141 return (arch, used_entities)
143 dobind :: (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -- ^ The bind to process
144 -> TranslatorSession ((Maybe CoreSyn.CoreBndr, Maybe CoreSyn.CoreBndr), ([AST.ConcSm], [CoreSyn.CoreBndr]))
145 -- ^ ((Input state variable, output state variable), (statements, used entities))
146 -- newtype unpacking is just a cast
147 dobind (bndr, (CoreSyn.Cast expr coercion))
149 = return ((Just bndr, Nothing), ([], []))
150 -- With simplCore, newtype packing is just a cast
151 dobind (bndr, expr@(CoreSyn.Cast (CoreSyn.Var state) coercion))
153 = return ((Nothing, Just state), ([], []))
154 -- Without simplCore, newtype packing uses a data constructor
155 dobind (bndr, (CoreSyn.App (CoreSyn.App (CoreSyn.Var con) (CoreSyn.Type _)) (CoreSyn.Var state)))
157 = return ((Nothing, Just state), ([], []))
158 -- Anything else is handled by mkConcSm
161 return ((Nothing, Nothing), sms)
164 (CoreSyn.CoreBndr, CoreSyn.CoreBndr) -- ^ The current and new state variables
165 -> AST.ProcSm -- ^ The resulting statement
166 mkStateProcSm (old, new) =
167 AST.ProcSm label [clk] [statement]
169 label = mkVHDLBasicId $ "state"
170 clk = mkVHDLBasicId "clock"
171 rising_edge = AST.NSimple $ mkVHDLBasicId "rising_edge"
172 wform = AST.Wform [AST.WformElem (AST.PrimName $ varToVHDLName new) Nothing]
173 assign = AST.SigAssign (varToVHDLName old) wform
174 rising_edge_clk = AST.PrimFCall $ AST.FCall rising_edge [Nothing AST.:=>: (AST.ADName $ AST.NSimple clk)]
175 statement = AST.IfSm rising_edge_clk [assign] [] Nothing
178 -- | Transforms a core binding into a VHDL concurrent statement
180 (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -- ^ The binding to process
181 -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
182 -- ^ The corresponding VHDL concurrent statements and entities
186 -- Ignore Cast expressions, they should not longer have any meaning as long as
187 -- the type works out.
188 mkConcSm (bndr, CoreSyn.Cast expr ty) = mkConcSm (bndr, expr)
190 -- Simple a = b assignments are just like applications, but without arguments.
191 -- We can't just generate an unconditional assignment here, since b might be a
192 -- top level binding (e.g., a function with no arguments).
193 mkConcSm (bndr, CoreSyn.Var v) = do
194 genApplication (Left bndr) v []
196 mkConcSm (bndr, app@(CoreSyn.App _ _))= do
197 let (CoreSyn.Var f, args) = CoreSyn.collectArgs app
198 let valargs = get_val_args (Var.varType f) args
199 genApplication (Left bndr) f (map Left valargs)
201 -- A single alt case must be a selector. This means thee scrutinee is a simple
202 -- variable, the alternative is a dataalt with a single non-wild binder that
204 mkConcSm (bndr, expr@(CoreSyn.Case (CoreSyn.Var scrut) b ty [alt]))
205 -- Don't generate VHDL for substate extraction
206 | hasStateType bndr = return ([], [])
209 (CoreSyn.DataAlt dc, bndrs, (CoreSyn.Var sel_bndr)) -> do
210 bndrs' <- Monad.filterM hasNonEmptyType bndrs
211 case List.elemIndex sel_bndr bndrs' of
213 labels <- MonadState.lift tsType $ getFieldLabels (Id.idType scrut)
214 let label = labels!!i
215 let sel_name = mkSelectedName (varToVHDLName scrut) label
216 let sel_expr = AST.PrimName sel_name
217 return ([mkUncondAssign (Left bndr) sel_expr], [])
218 Nothing -> error $ "\nVHDL.mkConcSM: Not in normal form: Not a selector case:\n" ++ (pprString expr)
220 _ -> error $ "\nVHDL.mkConcSM: Not in normal form: Not a selector case:\n" ++ (pprString expr)
222 -- Multiple case alt are be conditional assignments and have only wild
223 -- binders in the alts and only variables in the case values and a variable
224 -- for a scrutinee. We check the constructor of the second alt, since the
225 -- first is the default case, if there is any.
226 mkConcSm (bndr, (CoreSyn.Case (CoreSyn.Var scrut) b ty [(_, _, CoreSyn.Var false), (con, _, CoreSyn.Var true)])) = do
227 scrut' <- MonadState.lift tsType $ varToVHDLExpr scrut
228 let cond_expr = scrut' AST.:=: (altconToVHDLExpr con)
229 true_expr <- MonadState.lift tsType $ varToVHDLExpr true
230 false_expr <- MonadState.lift tsType $ varToVHDLExpr false
231 return ([mkCondAssign (Left bndr) cond_expr true_expr false_expr], [])
233 mkConcSm (_, (CoreSyn.Case (CoreSyn.Var _) _ _ alts)) = error "\nVHDL.mkConcSm: Not in normal form: Case statement with more than two alternatives"
234 mkConcSm (_, CoreSyn.Case _ _ _ _) = error "\nVHDL.mkConcSm: Not in normal form: Case statement has does not have a simple variable as scrutinee"
235 mkConcSm (bndr, expr) = error $ "\nVHDL.mkConcSM: Unsupported binding in let expression: " ++ pprString bndr ++ " = " ++ pprString expr
237 -----------------------------------------------------------------------------
238 -- Functions to generate VHDL for builtin functions
239 -----------------------------------------------------------------------------
241 -- | A function to wrap a builder-like function that expects its arguments to
243 genExprArgs wrap dst func args = do
244 args' <- argsToVHDLExprs args
247 -- | Turn the all lefts into VHDL Expressions.
248 argsToVHDLExprs :: [Either CoreSyn.CoreExpr AST.Expr] -> TranslatorSession [AST.Expr]
249 argsToVHDLExprs = catMaybesM . (mapM argToVHDLExpr)
251 argToVHDLExpr :: Either CoreSyn.CoreExpr AST.Expr -> TranslatorSession (Maybe AST.Expr)
252 argToVHDLExpr (Left expr) = MonadState.lift tsType $ do
253 let errmsg = "Generate.argToVHDLExpr: Using non-representable type? Should not happen!"
254 ty_maybe <- vhdl_ty errmsg expr
257 vhdl_expr <- varToVHDLExpr $ exprToVar expr
258 return $ Just vhdl_expr
259 Nothing -> return $ Nothing
261 argToVHDLExpr (Right expr) = return $ Just expr
263 -- A function to wrap a builder-like function that generates no component
266 (dst -> func -> args -> TranslatorSession [AST.ConcSm])
267 -> (dst -> func -> args -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]))
268 genNoInsts wrap dst func args = do
269 concsms <- wrap dst func args
272 -- | A function to wrap a builder-like function that expects its arguments to
275 (dst -> func -> [Var.Var] -> res)
276 -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
277 genVarArgs wrap dst func args = wrap dst func args'
279 args' = map exprToVar exprargs
280 -- Check (rather crudely) that all arguments are CoreExprs
281 (exprargs, []) = Either.partitionEithers args
283 -- | A function to wrap a builder-like function that expects its arguments to
286 (dst -> func -> [Literal.Literal] -> res)
287 -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
288 genLitArgs wrap dst func args = wrap dst func args'
290 args' = map exprToLit litargs
291 -- FIXME: Check if we were passed an CoreSyn.App
292 litargs = concat (map getLiterals exprargs)
293 (exprargs, []) = Either.partitionEithers args
295 -- | A function to wrap a builder-like function that produces an expression
296 -- and expects it to be assigned to the destination.
298 ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> TranslatorSession AST.Expr)
299 -> ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> TranslatorSession [AST.ConcSm])
300 genExprRes wrap dst func args = do
301 expr <- wrap dst func args
302 return $ [mkUncondAssign dst expr]
304 -- | Generate a binary operator application. The first argument should be a
305 -- constructor from the AST.Expr type, e.g. AST.And.
306 genOperator2 :: (AST.Expr -> AST.Expr -> AST.Expr) -> BuiltinBuilder
307 genOperator2 op = genNoInsts $ genExprArgs $ genExprRes (genOperator2' op)
308 genOperator2' :: (AST.Expr -> AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
309 genOperator2' op _ f [arg1, arg2] = return $ op arg1 arg2
311 -- | Generate a unary operator application
312 genOperator1 :: (AST.Expr -> AST.Expr) -> BuiltinBuilder
313 genOperator1 op = genNoInsts $ genExprArgs $ genExprRes (genOperator1' op)
314 genOperator1' :: (AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
315 genOperator1' op _ f [arg] = return $ op arg
317 -- | Generate a unary operator application
318 genNegation :: BuiltinBuilder
319 genNegation = genNoInsts $ genVarArgs $ genExprRes genNegation'
320 genNegation' :: dst -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession AST.Expr
321 genNegation' _ f [arg] = do
322 arg1 <- MonadState.lift tsType $ varToVHDLExpr arg
323 let ty = Var.varType arg
324 let (tycon, args) = Type.splitTyConApp ty
325 let name = Name.getOccString (TyCon.tyConName tycon)
327 "SizedInt" -> return $ AST.Neg arg1
328 otherwise -> error $ "\nGenerate.genNegation': Negation allowed for type: " ++ show name
330 -- | Generate a function call from the destination binder, function name and a
331 -- list of expressions (its arguments)
332 genFCall :: Bool -> BuiltinBuilder
333 genFCall switch = genNoInsts $ genExprArgs $ genExprRes (genFCall' switch)
334 genFCall' :: Bool -> Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
335 genFCall' switch (Left res) f args = do
336 let fname = varToString f
337 let el_ty = if switch then (Var.varType res) else ((tfvec_elem . Var.varType) res)
338 id <- MonadState.lift tsType $ vectorFunId el_ty fname
339 return $ AST.PrimFCall $ AST.FCall (AST.NSimple id) $
340 map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
341 genFCall' _ (Right name) _ _ = error $ "\nGenerate.genFCall': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
343 genFromSizedWord :: BuiltinBuilder
344 genFromSizedWord = genNoInsts $ genExprArgs $ genExprRes genFromSizedWord'
345 genFromSizedWord' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
346 genFromSizedWord' (Left res) f args = do
347 let fname = varToString f
348 return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId toIntegerId)) $
349 map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
350 genFromSizedWord' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
352 genResize :: BuiltinBuilder
353 genResize = genNoInsts $ genExprArgs $ genExprRes genResize'
354 genResize' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
355 genResize' (Left res) f [arg] = do {
356 ; let { ty = Var.varType res
357 ; (tycon, args) = Type.splitTyConApp ty
358 ; name = Name.getOccString (TyCon.tyConName tycon)
360 ; len <- case name of
361 "SizedInt" -> MonadState.lift tsType $ tfp_to_int (sized_int_len_ty ty)
362 "SizedWord" -> MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
363 ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId resizeId))
364 [Nothing AST.:=>: AST.ADExpr arg, Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
366 genResize' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
368 -- FIXME: I'm calling genLitArgs which is very specific function,
369 -- which needs to be fixed as well
370 genFromInteger :: BuiltinBuilder
371 genFromInteger = genNoInsts $ genLitArgs $ genExprRes genFromInteger'
372 genFromInteger' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [Literal.Literal] -> TranslatorSession AST.Expr
373 genFromInteger' (Left res) f lits = do {
374 ; let { ty = Var.varType res
375 ; (tycon, args) = Type.splitTyConApp ty
376 ; name = Name.getOccString (TyCon.tyConName tycon)
379 "RangedWord" -> return $ AST.PrimLit (show (last lits))
381 ; len <- case name of
382 "SizedInt" -> MonadState.lift tsType $ tfp_to_int (sized_int_len_ty ty)
383 "SizedWord" -> MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
384 "RangedWord" -> MonadState.lift tsType $ tfp_to_int (ranged_word_bound_ty ty)
385 ; let fname = case name of "SizedInt" -> toSignedId ; "SizedWord" -> toUnsignedId
386 ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId fname))
387 [Nothing AST.:=>: AST.ADExpr (AST.PrimLit (show (last lits))), Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
391 genFromInteger' (Right name) _ _ = error $ "\nGenerate.genFromInteger': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
393 genSizedInt :: BuiltinBuilder
394 genSizedInt = genFromInteger
397 -- | Generate a Builder for the builtin datacon TFVec
398 genTFVec :: BuiltinBuilder
399 genTFVec (Left res) f [Left (CoreSyn.Let (CoreSyn.Rec letBinders) letRes)] = do {
400 -- Generate Assignments for all the binders
401 ; letAssigns <- mapM genBinderAssign letBinders
402 -- Generate assignments for the result (which might be another let binding)
403 ; (resBinders,resAssignments) <- genResAssign letRes
404 -- Get all the Assigned binders
405 ; let assignedBinders = Maybe.catMaybes (map fst letAssigns)
406 -- Make signal names for all the assigned binders
407 ; sigs <- mapM (\x -> MonadState.lift tsType $ varToVHDLExpr x) (assignedBinders ++ resBinders)
408 -- Assign all the signals to the resulting vector
409 ; let { vecsigns = mkAggregateSignal sigs
410 ; vecassign = mkUncondAssign (Left res) vecsigns
412 -- Generate all the signal declaration for the assigned binders
413 ; sig_dec_maybes <- mapM mkSigDec (assignedBinders ++ resBinders)
414 ; let { sig_decs = map (AST.BDISD) (Maybe.catMaybes $ sig_dec_maybes)
415 -- Setup the VHDL Block
416 ; block_label = mkVHDLExtId ("TFVec_" ++ show (varToString res))
417 ; block = AST.BlockSm block_label [] (AST.PMapAspect []) sig_decs ((concat (map snd letAssigns)) ++ resAssignments ++ [vecassign])
419 -- Return the block statement coressponding to the TFVec literal
420 ; return $ [AST.CSBSm block]
423 genBinderAssign :: (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -> TranslatorSession (Maybe CoreSyn.CoreBndr, [AST.ConcSm])
424 -- For now we only translate applications
425 genBinderAssign (bndr, app@(CoreSyn.App _ _)) = do
426 let (CoreSyn.Var f, args) = CoreSyn.collectArgs app
427 let valargs = get_val_args (Var.varType f) args
428 apps <- genApplication (Left bndr) f (map Left valargs)
429 return (Just bndr, apps)
430 genBinderAssign _ = return (Nothing,[])
431 genResAssign :: CoreSyn.CoreExpr -> TranslatorSession ([CoreSyn.CoreBndr], [AST.ConcSm])
432 genResAssign app@(CoreSyn.App _ letexpr) = do
434 (CoreSyn.Let (CoreSyn.Rec letbndrs) letres) -> do
435 letapps <- mapM genBinderAssign letbndrs
436 let bndrs = Maybe.catMaybes (map fst letapps)
437 let app = (map snd letapps)
438 (vars, apps) <- genResAssign letres
439 return ((bndrs ++ vars),((concat app) ++ apps))
440 otherwise -> return ([],[])
441 genResAssign _ = return ([],[])
443 genTFVec (Left res) f [Left app@(CoreSyn.App _ _)] = do {
444 ; let { elems = reduceCoreListToHsList app
445 -- Make signal names for all the binders
446 ; binders = map (\expr -> case expr of
448 otherwise -> error $ "\nGenerate.genTFVec: Cannot generate TFVec: "
449 ++ show res ++ ", with elems:\n" ++ show elems ++ "\n" ++ pprString elems) elems
451 ; sigs <- mapM (\x -> MonadState.lift tsType $ varToVHDLExpr x) binders
452 -- Assign all the signals to the resulting vector
453 ; let { vecsigns = mkAggregateSignal sigs
454 ; vecassign = mkUncondAssign (Left res) vecsigns
455 -- Setup the VHDL Block
456 ; block_label = mkVHDLExtId ("TFVec_" ++ show (varToString res))
457 ; block = AST.BlockSm block_label [] (AST.PMapAspect []) [] [vecassign]
459 -- Return the block statement coressponding to the TFVec literal
460 ; return $ [AST.CSBSm block]
463 genTFVec (Left name) _ [Left xs] = error $ "\nGenerate.genTFVec: Cannot generate TFVec: " ++ show name ++ ", with elems:\n" ++ show xs ++ "\n" ++ pprString xs
465 genTFVec (Right name) _ _ = error $ "\nGenerate.genTFVec: Cannot generate TFVec assigned to VHDLName: " ++ show name
467 -- | Generate a generate statement for the builtin function "map"
468 genMap :: BuiltinBuilder
469 genMap (Left res) f [Left mapped_f, Left (CoreSyn.Var arg)] = do {
470 -- mapped_f must be a CoreExpr (since we can't represent functions as VHDL
471 -- expressions). arg must be a CoreExpr (and should be a CoreSyn.Var), since
472 -- we must index it (which we couldn't if it was a VHDL Expr, since only
473 -- VHDLNames can be indexed).
474 -- Setup the generate scheme
475 ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
476 -- TODO: Use something better than varToString
477 ; let { label = mkVHDLExtId ("mapVector" ++ (varToString res))
478 ; n_id = mkVHDLBasicId "n"
479 ; n_expr = idToVHDLExpr n_id
480 ; range = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
481 ; genScheme = AST.ForGn n_id range
482 -- Create the content of the generate statement: Applying the mapped_f to
483 -- each of the elements in arg, storing to each element in res
484 ; resname = mkIndexedName (varToVHDLName res) n_expr
485 ; argexpr = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
486 ; (CoreSyn.Var real_f, already_mapped_args) = CoreSyn.collectArgs mapped_f
487 ; valargs = get_val_args (Var.varType real_f) already_mapped_args
489 ; (app_concsms, used) <- genApplication (Right resname) real_f (map Left valargs ++ [Right argexpr])
490 -- Return the generate statement
491 ; return ([AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms], used)
494 genMap' (Right name) _ _ = error $ "\nGenerate.genMap': Cannot generate map function call assigned to a VHDLName: " ++ show name
496 genZipWith :: BuiltinBuilder
497 genZipWith = genVarArgs genZipWith'
498 genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
499 genZipWith' (Left res) f args@[zipped_f, arg1, arg2] = do {
500 -- Setup the generate scheme
501 ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
502 -- TODO: Use something better than varToString
503 ; let { label = mkVHDLExtId ("zipWithVector" ++ (varToString res))
504 ; n_id = mkVHDLBasicId "n"
505 ; n_expr = idToVHDLExpr n_id
506 ; range = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
507 ; genScheme = AST.ForGn n_id range
508 -- Create the content of the generate statement: Applying the zipped_f to
509 -- each of the elements in arg1 and arg2, storing to each element in res
510 ; resname = mkIndexedName (varToVHDLName res) n_expr
511 ; argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
512 ; argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
514 ; (app_concsms, used) <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
515 -- Return the generate functions
516 ; return ([AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms], used)
519 genFoldl :: BuiltinBuilder
520 genFoldl = genFold True
522 genFoldr :: BuiltinBuilder
523 genFoldr = genFold False
525 genFold :: Bool -> BuiltinBuilder
526 genFold left = genVarArgs (genFold' left)
528 genFold' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
529 genFold' left res f args@[folded_f , start ,vec]= do
530 len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty (Var.varType vec))
531 genFold'' len left res f args
533 genFold'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
534 -- Special case for an empty input vector, just assign start to res
535 genFold'' len left (Left res) _ [_, start, vec] | len == 0 = do
536 arg <- MonadState.lift tsType $ varToVHDLExpr start
537 return ([mkUncondAssign (Left res) arg], [])
539 genFold'' len left (Left res) f [folded_f, start, vec] = do
541 --len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
542 -- An expression for len-1
543 let len_min_expr = (AST.PrimLit $ show (len-1))
544 -- evec is (TFVec n), so it still needs an element type
545 let (nvec, _) = Type.splitAppTy (Var.varType vec)
546 -- Put the type of the start value in nvec, this will be the type of our
548 let tmp_ty = Type.mkAppTy nvec (Var.varType start)
549 let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty
550 -- TODO: Handle Nothing
551 Just tmp_vhdl_ty <- MonadState.lift tsType $ vhdl_ty error_msg tmp_ty
552 -- Setup the generate scheme
553 let gen_label = mkVHDLExtId ("foldlVector" ++ (varToString vec))
554 let block_label = mkVHDLExtId ("foldlVector" ++ (varToString res))
555 let gen_range = if left then AST.ToRange (AST.PrimLit "0") len_min_expr
556 else AST.DownRange len_min_expr (AST.PrimLit "0")
557 let gen_scheme = AST.ForGn n_id gen_range
558 -- Make the intermediate vector
559 let tmp_dec = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
560 -- Create the generate statement
561 cells' <- sequence [genFirstCell, genOtherCell]
562 let (cells, useds) = unzip cells'
563 let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
564 -- Assign tmp[len-1] or tmp[0] to res
565 let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (if left then
566 (mkIndexedName tmp_name (AST.PrimLit $ show (len-1))) else
567 (mkIndexedName tmp_name (AST.PrimLit "0")))
568 let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
569 return ([AST.CSBSm block], concat useds)
571 -- An id for the counter
572 n_id = mkVHDLBasicId "n"
573 n_cur = idToVHDLExpr n_id
574 -- An expression for previous n
575 n_prev = if left then (n_cur AST.:-: (AST.PrimLit "1"))
576 else (n_cur AST.:+: (AST.PrimLit "1"))
577 -- An id for the tmp result vector
578 tmp_id = mkVHDLBasicId "tmp"
579 tmp_name = AST.NSimple tmp_id
580 -- Generate parts of the fold
581 genFirstCell, genOtherCell :: TranslatorSession (AST.GenerateSm, [CoreSyn.CoreBndr])
583 len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
584 let cond_label = mkVHDLExtId "firstcell"
585 -- if n == 0 or n == len-1
586 let cond_scheme = AST.IfGn $ n_cur AST.:=: (if left then (AST.PrimLit "0")
587 else (AST.PrimLit $ show (len-1)))
588 -- Output to tmp[current n]
589 let resname = mkIndexedName tmp_name n_cur
591 argexpr1 <- MonadState.lift tsType $ varToVHDLExpr start
592 -- Input from vec[current n]
593 let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
594 (app_concsms, used) <- genApplication (Right resname) folded_f ( if left then
595 [Right argexpr1, Right argexpr2]
597 [Right argexpr2, Right argexpr1]
599 -- Return the conditional generate part
600 return $ (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
603 len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
604 let cond_label = mkVHDLExtId "othercell"
605 -- if n > 0 or n < len-1
606 let cond_scheme = AST.IfGn $ n_cur AST.:/=: (if left then (AST.PrimLit "0")
607 else (AST.PrimLit $ show (len-1)))
608 -- Output to tmp[current n]
609 let resname = mkIndexedName tmp_name n_cur
610 -- Input from tmp[previous n]
611 let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
612 -- Input from vec[current n]
613 let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
614 (app_concsms, used) <- genApplication (Right resname) folded_f ( if left then
615 [Right argexpr1, Right argexpr2]
617 [Right argexpr2, Right argexpr1]
619 -- Return the conditional generate part
620 return $ (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
622 -- | Generate a generate statement for the builtin function "zip"
623 genZip :: BuiltinBuilder
624 genZip = genNoInsts $ genVarArgs genZip'
625 genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
626 genZip' (Left res) f args@[arg1, arg2] = do {
627 -- Setup the generate scheme
628 ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
629 -- TODO: Use something better than varToString
630 ; let { label = mkVHDLExtId ("zipVector" ++ (varToString res))
631 ; n_id = mkVHDLBasicId "n"
632 ; n_expr = idToVHDLExpr n_id
633 ; range = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
634 ; genScheme = AST.ForGn n_id range
635 ; resname' = mkIndexedName (varToVHDLName res) n_expr
636 ; argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
637 ; argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
639 ; labels <- MonadState.lift tsType $ getFieldLabels (tfvec_elem (Var.varType res))
640 ; let { resnameA = mkSelectedName resname' (labels!!0)
641 ; resnameB = mkSelectedName resname' (labels!!1)
642 ; resA_assign = mkUncondAssign (Right resnameA) argexpr1
643 ; resB_assign = mkUncondAssign (Right resnameB) argexpr2
645 -- Return the generate functions
646 ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
649 -- | Generate a generate statement for the builtin function "unzip"
650 genUnzip :: BuiltinBuilder
651 genUnzip = genNoInsts $ genVarArgs genUnzip'
652 genUnzip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
653 genUnzip' (Left res) f args@[arg] = do {
654 -- Setup the generate scheme
655 ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
656 -- TODO: Use something better than varToString
657 ; let { label = mkVHDLExtId ("unzipVector" ++ (varToString res))
658 ; n_id = mkVHDLBasicId "n"
659 ; n_expr = idToVHDLExpr n_id
660 ; range = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
661 ; genScheme = AST.ForGn n_id range
662 ; resname' = varToVHDLName res
663 ; argexpr' = mkIndexedName (varToVHDLName arg) n_expr
665 ; reslabels <- MonadState.lift tsType $ getFieldLabels (Var.varType res)
666 ; arglabels <- MonadState.lift tsType $ getFieldLabels (tfvec_elem (Var.varType arg))
667 ; let { resnameA = mkIndexedName (mkSelectedName resname' (reslabels!!0)) n_expr
668 ; resnameB = mkIndexedName (mkSelectedName resname' (reslabels!!1)) n_expr
669 ; argexprA = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!0)
670 ; argexprB = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!1)
671 ; resA_assign = mkUncondAssign (Right resnameA) argexprA
672 ; resB_assign = mkUncondAssign (Right resnameB) argexprB
674 -- Return the generate functions
675 ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
678 genCopy :: BuiltinBuilder
679 genCopy = genNoInsts $ genVarArgs genCopy'
680 genCopy' :: (Either CoreSyn.CoreBndr AST.VHDLName ) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
681 genCopy' (Left res) f args@[arg] =
683 resExpr = AST.Aggregate [AST.ElemAssoc (Just AST.Others)
684 (AST.PrimName $ (varToVHDLName arg))]
685 out_assign = mkUncondAssign (Left res) resExpr
689 genConcat :: BuiltinBuilder
690 genConcat = genNoInsts $ genVarArgs genConcat'
691 genConcat' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
692 genConcat' (Left res) f args@[arg] = do {
693 -- Setup the generate scheme
694 ; len1 <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
695 ; let (_, nvec) = Type.splitAppTy (Var.varType arg)
696 ; len2 <- MonadState.lift tsType $ tfp_to_int $ tfvec_len_ty nvec
697 -- TODO: Use something better than varToString
698 ; let { label = mkVHDLExtId ("concatVector" ++ (varToString res))
699 ; n_id = mkVHDLBasicId "n"
700 ; n_expr = idToVHDLExpr n_id
701 ; fromRange = n_expr AST.:*: (AST.PrimLit $ show len2)
702 ; genScheme = AST.ForGn n_id range
703 -- Create the content of the generate statement: Applying the mapped_f to
704 -- each of the elements in arg, storing to each element in res
705 ; toRange = (n_expr AST.:*: (AST.PrimLit $ show len2)) AST.:+: (AST.PrimLit $ show (len2-1))
706 ; range = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len1-1))
707 ; resname = vecSlice fromRange toRange
708 ; argexpr = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
709 ; out_assign = mkUncondAssign (Right resname) argexpr
711 -- Return the generate statement
712 ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [out_assign]]
715 vecSlice init last = AST.NSlice (AST.SliceName (varToVHDLName res)
716 (AST.ToRange init last))
718 genIteraten :: BuiltinBuilder
719 genIteraten dst f args = genIterate dst f (tail args)
721 genIterate :: BuiltinBuilder
722 genIterate = genIterateOrGenerate True
724 genGeneraten :: BuiltinBuilder
725 genGeneraten dst f args = genGenerate dst f (tail args)
727 genGenerate :: BuiltinBuilder
728 genGenerate = genIterateOrGenerate False
730 genIterateOrGenerate :: Bool -> BuiltinBuilder
731 genIterateOrGenerate iter = genVarArgs (genIterateOrGenerate' iter)
733 genIterateOrGenerate' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
734 genIterateOrGenerate' iter (Left res) f args = do
735 len <- MonadState.lift tsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
736 genIterateOrGenerate'' len iter (Left res) f args
738 genIterateOrGenerate'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
739 -- Special case for an empty input vector, just assign start to res
740 genIterateOrGenerate'' len iter (Left res) _ [app_f, start] | len == 0 = return ([mkUncondAssign (Left res) (AST.PrimLit "\"\"")], [])
742 genIterateOrGenerate'' len iter (Left res) f [app_f, start] = do
744 -- len <- MonadState.lift tsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
745 -- An expression for len-1
746 let len_min_expr = (AST.PrimLit $ show (len-1))
747 -- -- evec is (TFVec n), so it still needs an element type
748 -- let (nvec, _) = splitAppTy (Var.varType vec)
749 -- -- Put the type of the start value in nvec, this will be the type of our
750 -- -- temporary vector
751 let tmp_ty = Var.varType res
752 let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty
753 -- TODO: Handle Nothing
754 Just tmp_vhdl_ty <- MonadState.lift tsType $ vhdl_ty error_msg tmp_ty
755 -- Setup the generate scheme
756 let gen_label = mkVHDLExtId ("iterateVector" ++ (varToString start))
757 let block_label = mkVHDLExtId ("iterateVector" ++ (varToString res))
758 let gen_range = AST.ToRange (AST.PrimLit "0") len_min_expr
759 let gen_scheme = AST.ForGn n_id gen_range
760 -- Make the intermediate vector
761 let tmp_dec = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
762 -- Create the generate statement
763 cells' <- sequence [genFirstCell, genOtherCell]
764 let (cells, useds) = unzip cells'
765 let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
766 -- Assign tmp[len-1] or tmp[0] to res
767 let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr tmp_name
768 let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
769 return ([AST.CSBSm block], concat useds)
771 -- An id for the counter
772 n_id = mkVHDLBasicId "n"
773 n_cur = idToVHDLExpr n_id
774 -- An expression for previous n
775 n_prev = n_cur AST.:-: (AST.PrimLit "1")
776 -- An id for the tmp result vector
777 tmp_id = mkVHDLBasicId "tmp"
778 tmp_name = AST.NSimple tmp_id
779 -- Generate parts of the fold
780 genFirstCell, genOtherCell :: TranslatorSession (AST.GenerateSm, [CoreSyn.CoreBndr])
782 let cond_label = mkVHDLExtId "firstcell"
783 -- if n == 0 or n == len-1
784 let cond_scheme = AST.IfGn $ n_cur AST.:=: (AST.PrimLit "0")
785 -- Output to tmp[current n]
786 let resname = mkIndexedName tmp_name n_cur
788 argexpr <- MonadState.lift tsType $ varToVHDLExpr start
789 let startassign = mkUncondAssign (Right resname) argexpr
790 (app_concsms, used) <- genApplication (Right resname) app_f [Right argexpr]
791 -- Return the conditional generate part
792 let gensm = AST.GenerateSm cond_label cond_scheme [] (if iter then
800 let cond_label = mkVHDLExtId "othercell"
801 -- if n > 0 or n < len-1
802 let cond_scheme = AST.IfGn $ n_cur AST.:/=: (AST.PrimLit "0")
803 -- Output to tmp[current n]
804 let resname = mkIndexedName tmp_name n_cur
805 -- Input from tmp[previous n]
806 let argexpr = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
807 (app_concsms, used) <- genApplication (Right resname) app_f [Right argexpr]
808 -- Return the conditional generate part
809 return $ (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
812 -----------------------------------------------------------------------------
813 -- Function to generate VHDL for applications
814 -----------------------------------------------------------------------------
816 (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
817 -> CoreSyn.CoreBndr -- ^ The function to apply
818 -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
819 -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
820 -- ^ The corresponding VHDL concurrent statements and entities
822 genApplication dst f args = do
823 case Var.isGlobalId f of
825 top <- isTopLevelBinder f
828 -- Local binder that references a top level binding. Generate a
829 -- component instantiation.
830 signature <- getEntity f
831 args' <- argsToVHDLExprs args
832 let entity_id = ent_id signature
833 -- TODO: Using show here isn't really pretty, but we'll need some
834 -- unique-ish value...
835 let label = "comp_ins_" ++ (either show prettyShow) dst
836 let portmaps = mkAssocElems args' ((either varToVHDLName id) dst) signature
837 return ([mkComponentInst label entity_id portmaps], [f])
839 -- Not a top level binder, so this must be a local variable reference.
840 -- It should have a representable type (and thus, no arguments) and a
841 -- signal should be generated for it. Just generate an unconditional
843 f' <- MonadState.lift tsType $ varToVHDLExpr f
844 return $ ([mkUncondAssign dst f'], [])
846 case Var.idDetails f of
847 IdInfo.DataConWorkId dc -> case dst of
848 -- It's a datacon. Create a record from its arguments.
850 -- We have the bndr, so we can get at the type
851 labels <- MonadState.lift tsType $ getFieldLabels (Var.varType bndr)
852 args' <- argsToVHDLExprs args
853 return $ (zipWith mkassign labels $ args', [])
855 mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
857 let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
858 mkUncondAssign (Right sel_name) arg
859 Right _ -> error $ "\nGenerate.genApplication: Can't generate dataconstructor application without an original binder"
860 IdInfo.DataConWrapId dc -> case dst of
861 -- It's a datacon. Create a record from its arguments.
863 case (Map.lookup (varToString f) globalNameTable) of
864 Just (arg_count, builder) ->
865 if length args == arg_count then
868 error $ "\nGenerate.genApplication(DataConWrapId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
869 Nothing -> error $ "\nGenerate.genApplication: Can't generate dataconwrapper: " ++ (show dc)
870 Right _ -> error $ "\nGenerate.genApplication: Can't generate dataconwrapper application without an original binder"
871 IdInfo.VanillaId -> do
872 -- It's a global value imported from elsewhere. These can be builtin
873 -- functions. Look up the function name in the name table and execute
874 -- the associated builder if there is any and the argument count matches
875 -- (this should always be the case if it typechecks, but just to be
877 case (Map.lookup (varToString f) globalNameTable) of
878 Just (arg_count, builder) ->
879 if length args == arg_count then
882 error $ "\nGenerate.genApplication(VanillaId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
884 top <- isTopLevelBinder f
887 -- Local binder that references a top level binding. Generate a
888 -- component instantiation.
889 signature <- getEntity f
890 args' <- argsToVHDLExprs args
891 let entity_id = ent_id signature
892 -- TODO: Using show here isn't really pretty, but we'll need some
893 -- unique-ish value...
894 let label = "comp_ins_" ++ (either show prettyShow) dst
895 let portmaps = mkAssocElems args' ((either varToVHDLName id) dst) signature
896 return ([mkComponentInst label entity_id portmaps], [f])
898 -- Not a top level binder, so this must be a local variable reference.
899 -- It should have a representable type (and thus, no arguments) and a
900 -- signal should be generated for it. Just generate an unconditional
902 -- FIXME : I DONT KNOW IF THE ABOVE COMMENT HOLDS HERE, SO FOR NOW JUST ERROR!
903 -- f' <- MonadState.lift tsType $ varToVHDLExpr f
904 -- return $ ([mkUncondAssign dst f'], [])
905 error $ ("\nGenerate.genApplication(VanillaId): Using function from another module that is not a known builtin: " ++ (pprString f))
906 IdInfo.ClassOpId cls -> do
907 -- FIXME: Not looking for what instance this class op is called for
908 -- Is quite stupid of course.
909 case (Map.lookup (varToString f) globalNameTable) of
910 Just (arg_count, builder) ->
911 if length args == arg_count then
914 error $ "\nGenerate.genApplication(ClassOpId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
915 Nothing -> error $ "\nGenerate.genApplication(ClassOpId): Using function from another module that is not a known builtin: " ++ pprString f
916 details -> error $ "\nGenerate.genApplication: Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
918 -----------------------------------------------------------------------------
919 -- Functions to generate functions dealing with vectors.
920 -----------------------------------------------------------------------------
922 -- Returns the VHDLId of the vector function with the given name for the given
923 -- element type. Generates -- this function if needed.
924 vectorFunId :: Type.Type -> String -> TypeSession AST.VHDLId
925 vectorFunId el_ty fname = do
926 let error_msg = "\nGenerate.vectorFunId: Can not construct vector function for element: " ++ pprString el_ty
927 -- TODO: Handle the Nothing case?
928 Just elemTM <- vhdl_ty error_msg el_ty
929 -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
930 -- the VHDLState or something.
931 let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
932 typefuns <- getA tsTypeFuns
933 case Map.lookup (OrdType el_ty, fname) typefuns of
934 -- Function already generated, just return it
935 Just (id, _) -> return id
936 -- Function not generated yet, generate it
938 let functions = genUnconsVectorFuns elemTM vectorTM
939 case lookup fname functions of
941 modA tsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, (fst body))
942 mapM_ (vectorFunId el_ty) (snd body)
944 Nothing -> error $ "\nGenerate.vectorFunId: I don't know how to generate vector function " ++ fname
946 function_id = mkVHDLExtId fname
948 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
949 -> AST.TypeMark -- ^ type of the vector
950 -> [(String, (AST.SubProgBody, [String]))]
951 genUnconsVectorFuns elemTM vectorTM =
952 [ (exId, (AST.SubProgBody exSpec [] [exExpr],[]))
953 , (replaceId, (AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet],[]))
954 , (lastId, (AST.SubProgBody lastSpec [] [lastExpr],[]))
955 , (initId, (AST.SubProgBody initSpec [AST.SPVD initVar] [initExpr, initRet],[]))
956 , (minimumId, (AST.SubProgBody minimumSpec [] [minimumExpr],[]))
957 , (takeId, (AST.SubProgBody takeSpec [AST.SPVD takeVar] [takeExpr, takeRet],[minimumId]))
958 , (dropId, (AST.SubProgBody dropSpec [AST.SPVD dropVar] [dropExpr, dropRet],[]))
959 , (plusgtId, (AST.SubProgBody plusgtSpec [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet],[]))
960 , (emptyId, (AST.SubProgBody emptySpec [AST.SPVD emptyVar] [emptyExpr],[]))
961 , (singletonId, (AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet],[]))
962 , (copynId, (AST.SubProgBody copynSpec [AST.SPVD copynVar] [copynExpr],[]))
963 , (selId, (AST.SubProgBody selSpec [AST.SPVD selVar] [selFor, selRet],[]))
964 , (ltplusId, (AST.SubProgBody ltplusSpec [AST.SPVD ltplusVar] [ltplusExpr, ltplusRet],[]))
965 , (plusplusId, (AST.SubProgBody plusplusSpec [AST.SPVD plusplusVar] [plusplusExpr, plusplusRet],[]))
966 , (lengthTId, (AST.SubProgBody lengthTSpec [] [lengthTExpr],[]))
967 , (shiftlId, (AST.SubProgBody shiftlSpec [AST.SPVD shiftlVar] [shiftlExpr, shiftlRet], [initId]))
968 , (shiftrId, (AST.SubProgBody shiftrSpec [AST.SPVD shiftrVar] [shiftrExpr, shiftrRet], [tailId]))
969 , (nullId, (AST.SubProgBody nullSpec [] [nullExpr], []))
970 , (rotlId, (AST.SubProgBody rotlSpec [AST.SPVD rotlVar] [rotlExpr, rotlRet], [nullId, lastId, initId]))
971 , (rotrId, (AST.SubProgBody rotrSpec [AST.SPVD rotrVar] [rotrExpr, rotrRet], [nullId, tailId, headId]))
972 , (reverseId, (AST.SubProgBody reverseSpec [AST.SPVD reverseVar] [reverseFor, reverseRet], []))
975 ixPar = AST.unsafeVHDLBasicId "ix"
976 vecPar = AST.unsafeVHDLBasicId "vec"
977 vec1Par = AST.unsafeVHDLBasicId "vec1"
978 vec2Par = AST.unsafeVHDLBasicId "vec2"
979 nPar = AST.unsafeVHDLBasicId "n"
980 leftPar = AST.unsafeVHDLBasicId "nLeft"
981 rightPar = AST.unsafeVHDLBasicId "nRight"
982 iId = AST.unsafeVHDLBasicId "i"
984 aPar = AST.unsafeVHDLBasicId "a"
985 fPar = AST.unsafeVHDLBasicId "f"
986 sPar = AST.unsafeVHDLBasicId "s"
987 resId = AST.unsafeVHDLBasicId "res"
988 exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
989 AST.IfaceVarDec ixPar naturalTM] elemTM
990 exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed
991 (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $
993 replaceSpec = AST.Function (mkVHDLExtId replaceId) [ AST.IfaceVarDec vecPar vectorTM
994 , AST.IfaceVarDec iPar naturalTM
995 , AST.IfaceVarDec aPar elemTM
997 -- variable res : fsvec_x (0 to vec'length-1);
1000 (AST.SubtypeIn vectorTM
1001 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1002 [AST.ToRange (AST.PrimLit "0")
1003 (AST.PrimName (AST.NAttribute $
1004 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1005 (AST.PrimLit "1")) ]))
1007 -- res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
1008 replaceExpr = AST.NSimple resId AST.:=
1009 (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
1010 AST.PrimName (AST.NSimple aPar) AST.:&:
1011 vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
1012 ((AST.PrimName (AST.NAttribute $
1013 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))
1014 AST.:-: AST.PrimLit "1"))
1015 replaceRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1016 vecSlice init last = AST.PrimName (AST.NSlice
1018 (AST.NSimple vecPar)
1019 (AST.ToRange init last)))
1020 lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
1021 -- return vec(vec'length-1);
1022 lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName
1023 (AST.NSimple vecPar)
1024 [AST.PrimName (AST.NAttribute $
1025 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing)
1026 AST.:-: AST.PrimLit "1"])))
1027 initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
1028 -- variable res : fsvec_x (0 to vec'length-2);
1031 (AST.SubtypeIn vectorTM
1032 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1033 [AST.ToRange (AST.PrimLit "0")
1034 (AST.PrimName (AST.NAttribute $
1035 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1036 (AST.PrimLit "2")) ]))
1038 -- resAST.:= vec(0 to vec'length-2)
1039 initExpr = AST.NSimple resId AST.:= (vecSlice
1041 (AST.PrimName (AST.NAttribute $
1042 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing)
1043 AST.:-: AST.PrimLit "2"))
1044 initRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1045 minimumSpec = AST.Function (mkVHDLExtId minimumId) [AST.IfaceVarDec leftPar naturalTM,
1046 AST.IfaceVarDec rightPar naturalTM ] naturalTM
1047 minimumExpr = AST.IfSm ((AST.PrimName $ AST.NSimple leftPar) AST.:<: (AST.PrimName $ AST.NSimple rightPar))
1048 [AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple leftPar)]
1050 (Just $ AST.Else [minimumExprRet])
1051 where minimumExprRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple rightPar)
1052 takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar naturalTM,
1053 AST.IfaceVarDec vecPar vectorTM ] vectorTM
1054 -- variable res : fsvec_x (0 to (minimum (n,vec'length))-1);
1055 minLength = AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId minimumId))
1056 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple nPar)
1057 ,Nothing AST.:=>: AST.ADExpr (AST.PrimName (AST.NAttribute $
1058 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]
1061 (AST.SubtypeIn vectorTM
1062 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1063 [AST.ToRange (AST.PrimLit "0")
1065 (AST.PrimLit "1")) ]))
1067 -- res AST.:= vec(0 to n-1)
1068 takeExpr = AST.NSimple resId AST.:=
1069 (vecSlice (AST.PrimLit "0")
1070 (minLength AST.:-: AST.PrimLit "1"))
1071 takeRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1072 dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar naturalTM,
1073 AST.IfaceVarDec vecPar vectorTM ] vectorTM
1074 -- variable res : fsvec_x (0 to vec'length-n-1);
1077 (AST.SubtypeIn vectorTM
1078 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1079 [AST.ToRange (AST.PrimLit "0")
1080 (AST.PrimName (AST.NAttribute $
1081 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1082 (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
1084 -- res AST.:= vec(n to vec'length-1)
1085 dropExpr = AST.NSimple resId AST.:= (vecSlice
1086 (AST.PrimName $ AST.NSimple nPar)
1087 (AST.PrimName (AST.NAttribute $
1088 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing)
1089 AST.:-: AST.PrimLit "1"))
1090 dropRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1091 plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar elemTM,
1092 AST.IfaceVarDec vecPar vectorTM] vectorTM
1093 -- variable res : fsvec_x (0 to vec'length);
1096 (AST.SubtypeIn vectorTM
1097 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1098 [AST.ToRange (AST.PrimLit "0")
1099 (AST.PrimName (AST.NAttribute $
1100 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]))
1102 plusgtExpr = AST.NSimple resId AST.:=
1103 ((AST.PrimName $ AST.NSimple aPar) AST.:&:
1104 (AST.PrimName $ AST.NSimple vecPar))
1105 plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1106 emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
1109 (AST.SubtypeIn vectorTM
1110 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1111 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "-1")]))
1113 emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
1114 singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ]
1116 -- variable res : fsvec_x (0 to 0) := (others => a);
1119 (AST.SubtypeIn vectorTM
1120 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1121 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
1122 (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others)
1123 (AST.PrimName $ AST.NSimple aPar)])
1124 singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1125 copynSpec = AST.Function (mkVHDLExtId copynId) [AST.IfaceVarDec nPar naturalTM,
1126 AST.IfaceVarDec aPar elemTM ] vectorTM
1127 -- variable res : fsvec_x (0 to n-1) := (others => a);
1130 (AST.SubtypeIn vectorTM
1131 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1132 [AST.ToRange (AST.PrimLit "0")
1133 ((AST.PrimName (AST.NSimple nPar)) AST.:-:
1134 (AST.PrimLit "1")) ]))
1135 (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others)
1136 (AST.PrimName $ AST.NSimple aPar)])
1138 copynExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1139 selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar naturalTM,
1140 AST.IfaceVarDec sPar naturalTM,
1141 AST.IfaceVarDec nPar naturalTM,
1142 AST.IfaceVarDec vecPar vectorTM ] vectorTM
1143 -- variable res : fsvec_x (0 to n-1);
1146 (AST.SubtypeIn vectorTM
1147 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1148 [AST.ToRange (AST.PrimLit "0")
1149 ((AST.PrimName (AST.NSimple nPar)) AST.:-:
1150 (AST.PrimLit "1")) ])
1153 -- for i res'range loop
1154 -- res(i) := vec(f+i*s);
1156 selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) (AST.NSimple $ rangeId) Nothing) [selAssign]
1157 -- res(i) := vec(f+i*s);
1158 selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+:
1159 (AST.PrimName (AST.NSimple iId) AST.:*:
1160 AST.PrimName (AST.NSimple sPar)) in
1161 AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
1162 (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
1164 selRet = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
1165 ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
1166 AST.IfaceVarDec aPar elemTM] vectorTM
1167 -- variable res : fsvec_x (0 to vec'length);
1170 (AST.SubtypeIn vectorTM
1171 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1172 [AST.ToRange (AST.PrimLit "0")
1173 (AST.PrimName (AST.NAttribute $
1174 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]))
1176 ltplusExpr = AST.NSimple resId AST.:=
1177 ((AST.PrimName $ AST.NSimple vecPar) AST.:&:
1178 (AST.PrimName $ AST.NSimple aPar))
1179 ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1180 plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
1181 AST.IfaceVarDec vec2Par vectorTM]
1183 -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
1186 (AST.SubtypeIn vectorTM
1187 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1188 [AST.ToRange (AST.PrimLit "0")
1189 (AST.PrimName (AST.NAttribute $
1190 AST.AttribName (AST.NSimple vec1Par) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:+:
1191 AST.PrimName (AST.NAttribute $
1192 AST.AttribName (AST.NSimple vec2Par) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1195 plusplusExpr = AST.NSimple resId AST.:=
1196 ((AST.PrimName $ AST.NSimple vec1Par) AST.:&:
1197 (AST.PrimName $ AST.NSimple vec2Par))
1198 plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1199 lengthTSpec = AST.Function (mkVHDLExtId lengthTId) [AST.IfaceVarDec vecPar vectorTM] naturalTM
1200 lengthTExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NAttribute $
1201 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))
1202 shiftlSpec = AST.Function (mkVHDLExtId shiftlId) [AST.IfaceVarDec vecPar vectorTM,
1203 AST.IfaceVarDec aPar elemTM ] vectorTM
1204 -- variable res : fsvec_x (0 to vec'length-1);
1207 (AST.SubtypeIn vectorTM
1208 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1209 [AST.ToRange (AST.PrimLit "0")
1210 (AST.PrimName (AST.NAttribute $
1211 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1212 (AST.PrimLit "1")) ]))
1214 -- res := a & init(vec)
1215 shiftlExpr = AST.NSimple resId AST.:=
1216 (AST.PrimName (AST.NSimple aPar) AST.:&:
1217 (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))
1218 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
1219 shiftlRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1220 shiftrSpec = AST.Function (mkVHDLExtId shiftrId) [AST.IfaceVarDec vecPar vectorTM,
1221 AST.IfaceVarDec aPar elemTM ] vectorTM
1222 -- variable res : fsvec_x (0 to vec'length-1);
1225 (AST.SubtypeIn vectorTM
1226 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1227 [AST.ToRange (AST.PrimLit "0")
1228 (AST.PrimName (AST.NAttribute $
1229 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1230 (AST.PrimLit "1")) ]))
1232 -- res := tail(vec) & a
1233 shiftrExpr = AST.NSimple resId AST.:=
1234 ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))
1235 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
1236 (AST.PrimName (AST.NSimple aPar)))
1238 shiftrRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1239 nullSpec = AST.Function (mkVHDLExtId nullId) [AST.IfaceVarDec vecPar vectorTM] booleanTM
1240 -- return vec'length = 0
1241 nullExpr = AST.ReturnSm (Just $
1242 AST.PrimName (AST.NAttribute $
1243 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:=:
1245 rotlSpec = AST.Function (mkVHDLExtId rotlId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
1246 -- variable res : fsvec_x (0 to vec'length-1);
1249 (AST.SubtypeIn vectorTM
1250 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1251 [AST.ToRange (AST.PrimLit "0")
1252 (AST.PrimName (AST.NAttribute $
1253 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1254 (AST.PrimLit "1")) ]))
1256 -- if null(vec) then res := vec else res := last(vec) & init(vec)
1257 rotlExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))
1258 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
1259 [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
1261 (Just $ AST.Else [rotlExprRet])
1263 AST.NSimple resId AST.:=
1264 ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId lastId))
1265 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
1266 (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))
1267 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
1268 rotlRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1269 rotrSpec = AST.Function (mkVHDLExtId rotrId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
1270 -- variable res : fsvec_x (0 to vec'length-1);
1273 (AST.SubtypeIn vectorTM
1274 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1275 [AST.ToRange (AST.PrimLit "0")
1276 (AST.PrimName (AST.NAttribute $
1277 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1278 (AST.PrimLit "1")) ]))
1280 -- if null(vec) then res := vec else res := tail(vec) & head(vec)
1281 rotrExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))
1282 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
1283 [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
1285 (Just $ AST.Else [rotrExprRet])
1287 AST.NSimple resId AST.:=
1288 ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))
1289 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
1290 (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId headId))
1291 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
1292 rotrRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1293 reverseSpec = AST.Function (mkVHDLExtId reverseId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
1296 (AST.SubtypeIn vectorTM
1297 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1298 [AST.ToRange (AST.PrimLit "0")
1299 (AST.PrimName (AST.NAttribute $
1300 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1301 (AST.PrimLit "1")) ]))
1303 -- for i in 0 to res'range loop
1304 -- res(vec'length-i-1) := vec(i);
1307 AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) (AST.NSimple $ rangeId) Nothing) [reverseAssign]
1308 -- res(vec'length-i-1) := vec(i);
1309 reverseAssign = AST.NIndexed (AST.IndexedName (AST.NSimple resId) [destExp]) AST.:=
1310 (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar)
1311 [AST.PrimName $ AST.NSimple iId]))
1312 where destExp = AST.PrimName (AST.NAttribute $ AST.AttribName (AST.NSimple vecPar)
1313 (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1314 AST.PrimName (AST.NSimple iId) AST.:-:
1317 reverseRet = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
1320 -----------------------------------------------------------------------------
1321 -- A table of builtin functions
1322 -----------------------------------------------------------------------------
1324 -- A function that generates VHDL for a builtin function
1325 type BuiltinBuilder =
1326 (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ The destination signal and it's original type
1327 -> CoreSyn.CoreBndr -- ^ The function called
1328 -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The value arguments passed (excluding type and
1329 -- dictionary arguments).
1330 -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
1331 -- ^ The corresponding VHDL concurrent statements and entities
1334 -- A map of a builtin function to VHDL function builder
1335 type NameTable = Map.Map String (Int, BuiltinBuilder )
1337 -- | The builtin functions we support. Maps a name to an argument count and a
1338 -- builder function.
1339 globalNameTable :: NameTable
1340 globalNameTable = Map.fromList
1341 [ (exId , (2, genFCall True ) )
1342 , (replaceId , (3, genFCall False ) )
1343 , (headId , (1, genFCall True ) )
1344 , (lastId , (1, genFCall True ) )
1345 , (tailId , (1, genFCall False ) )
1346 , (initId , (1, genFCall False ) )
1347 , (takeId , (2, genFCall False ) )
1348 , (dropId , (2, genFCall False ) )
1349 , (selId , (4, genFCall False ) )
1350 , (plusgtId , (2, genFCall False ) )
1351 , (ltplusId , (2, genFCall False ) )
1352 , (plusplusId , (2, genFCall False ) )
1353 , (mapId , (2, genMap ) )
1354 , (zipWithId , (3, genZipWith ) )
1355 , (foldlId , (3, genFoldl ) )
1356 , (foldrId , (3, genFoldr ) )
1357 , (zipId , (2, genZip ) )
1358 , (unzipId , (1, genUnzip ) )
1359 , (shiftlId , (2, genFCall False ) )
1360 , (shiftrId , (2, genFCall False ) )
1361 , (rotlId , (1, genFCall False ) )
1362 , (rotrId , (1, genFCall False ) )
1363 , (concatId , (1, genConcat ) )
1364 , (reverseId , (1, genFCall False ) )
1365 , (iteratenId , (3, genIteraten ) )
1366 , (iterateId , (2, genIterate ) )
1367 , (generatenId , (3, genGeneraten ) )
1368 , (generateId , (2, genGenerate ) )
1369 , (emptyId , (0, genFCall False ) )
1370 , (singletonId , (1, genFCall False ) )
1371 , (copynId , (2, genFCall False ) )
1372 , (copyId , (1, genCopy ) )
1373 , (lengthTId , (1, genFCall False ) )
1374 , (nullId , (1, genFCall False ) )
1375 , (hwxorId , (2, genOperator2 AST.Xor ) )
1376 , (hwandId , (2, genOperator2 AST.And ) )
1377 , (hworId , (2, genOperator2 AST.Or ) )
1378 , (hwnotId , (1, genOperator1 AST.Not ) )
1379 , (equalsId , (2, genOperator2 (AST.:=:) ) )
1380 , (plusId , (2, genOperator2 (AST.:+:) ) )
1381 , (timesId , (2, genOperator2 (AST.:*:) ) )
1382 , (negateId , (1, genNegation ) )
1383 , (minusId , (2, genOperator2 (AST.:-:) ) )
1384 , (fromSizedWordId , (1, genFromSizedWord ) )
1385 , (fromIntegerId , (1, genFromInteger ) )
1386 , (resizeId , (1, genResize ) )
1387 , (sizedIntId , (1, genSizedInt ) )
1388 , (smallIntegerId , (1, genFromInteger ) )
1389 --, (tfvecId , (1, genTFVec ) )
1390 , (minimumId , (2, error $ "\nFunction name: \"minimum\" is used internally, use another name"))