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
9 import qualified Data.Accessor.Monad.Trans.State as MonadState
12 import qualified Language.VHDL.AST as AST
15 import qualified CoreSyn
19 import qualified IdInfo
20 import qualified Literal
22 import qualified TyCon
25 import CLasH.Translator.TranslatorTypes
26 import CLasH.VHDL.Constants
27 import CLasH.VHDL.VHDLTypes
28 import CLasH.VHDL.VHDLTools
30 import CLasH.Utils.Core.CoreTools
31 import CLasH.Utils.Pretty
32 import qualified CLasH.Normalize as Normalize
34 -----------------------------------------------------------------------------
35 -- Functions to generate VHDL for user-defined functions.
36 -----------------------------------------------------------------------------
38 -- | Create an entity for a given function
41 -> TranslatorSession Entity -- ^ The resulting entity
43 getEntity fname = makeCached fname tsEntities $ do
44 expr <- Normalize.getNormalized fname
45 -- Split the normalized expression
46 let (args, binds, res) = Normalize.splitNormalized expr
47 -- Generate ports for all non-empty types
48 args' <- catMaybesM $ mapM mkMap args
49 -- TODO: Handle Nothing
51 count <- MonadState.get tsEntityCounter
52 let vhdl_id = mkVHDLBasicId $ varToString fname ++ "Component_" ++ show count
53 MonadState.set tsEntityCounter (count + 1)
54 let ent_decl = createEntityAST vhdl_id args' res'
55 let signature = Entity vhdl_id args' res' ent_decl
59 --[(SignalId, SignalInfo)]
61 -> TranslatorSession (Maybe Port)
64 --info = Maybe.fromMaybe
65 -- (error $ "Signal not found in the name map? This should not happen!")
67 -- Assume the bndr has a valid VHDL id already
70 error_msg = "\nVHDL.createEntity.mkMap: Can not create entity: " ++ pprString fname ++ "\nbecause no type can be created for port: " ++ pprString bndr
72 type_mark_maybe <- MonadState.lift tsType $ vhdlTy error_msg ty
73 case type_mark_maybe of
74 Just type_mark -> return $ Just (id, type_mark)
75 Nothing -> return Nothing
78 -- | Create the VHDL AST for an entity
80 AST.VHDLId -- ^ The name of the function
81 -> [Port] -- ^ The entity's arguments
82 -> Maybe Port -- ^ The entity's result
83 -> AST.EntityDec -- ^ The entity with the ent_decl filled in as well
85 createEntityAST vhdl_id args res =
86 AST.EntityDec vhdl_id ports
88 -- Create a basic Id, since VHDL doesn't grok filenames with extended Ids.
89 ports = map (mkIfaceSigDec AST.In) args
90 ++ (Maybe.maybeToList res_port)
91 ++ [clk_port,resetn_port]
92 -- Add a clk port if we have state
93 clk_port = AST.IfaceSigDec clockId AST.In std_logicTM
94 resetn_port = AST.IfaceSigDec resetId AST.In std_logicTM
95 res_port = fmap (mkIfaceSigDec AST.Out) res
97 -- | Create a port declaration
99 AST.Mode -- ^ The mode for the port (In / Out)
100 -> Port -- ^ The id and type for the port
101 -> AST.IfaceSigDec -- ^ The resulting port declaration
103 mkIfaceSigDec mode (id, ty) = AST.IfaceSigDec id mode ty
105 -- | Create an architecture for a given function
107 CoreSyn.CoreBndr -- ^ The function to get an architecture for
108 -> TranslatorSession (Architecture, [CoreSyn.CoreBndr])
109 -- ^ The architecture for this function
111 getArchitecture fname = makeCached fname tsArchitectures $ do
112 expr <- Normalize.getNormalized fname
113 -- Split the normalized expression
114 let (args, binds, res) = Normalize.splitNormalized expr
116 -- Get the entity for this function
117 signature <- getEntity fname
118 let entity_id = ent_id signature
120 -- Create signal declarations for all binders in the let expression, except
121 -- for the output port (that will already have an output port declared in
123 sig_dec_maybes <- mapM (mkSigDec . fst) (filter ((/=res).fst) binds)
124 let sig_decs = Maybe.catMaybes sig_dec_maybes
125 -- Process each bind, resulting in info about state variables and concurrent
127 (state_vars, sms) <- Monad.mapAndUnzipM dobind binds
128 let (in_state_maybes, out_state_maybes) = unzip state_vars
129 let (statementss, used_entitiess) = unzip sms
130 -- Get initial state, if it's there
131 initSmap <- MonadState.get tsInitStates
132 let init_state = Map.lookup fname initSmap
133 -- Create a state proc, if needed
134 (state_proc, resbndr) <- case (Maybe.catMaybes in_state_maybes, Maybe.catMaybes out_state_maybes, init_state) of
135 ([in_state], [out_state], Nothing) -> do
136 nonEmpty <- hasNonEmptyType in_state
137 if nonEmpty then error ("No initial state defined for: " ++ show fname) else return ([],[])
138 ([in_state], [out_state], Just resetval) -> mkStateProcSm (in_state, out_state,resetval)
139 ([], [], Just _) -> error $ "Initial state defined for state-less function: " ++ show fname
140 ([], [], Nothing) -> return ([],[])
141 (ins, outs, res) -> error $ "Weird use of state in " ++ show fname ++ ". In: " ++ show ins ++ " Out: " ++ show outs
142 -- Join the create statements and the (optional) state_proc
143 let statements = concat statementss ++ state_proc
144 -- Create the architecture
145 let arch = AST.ArchBody (mkVHDLBasicId "structural") (AST.NSimple entity_id) (map AST.BDISD sig_decs) statements
146 let used_entities = (concat used_entitiess) ++ resbndr
147 return (arch, used_entities)
149 dobind :: (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -- ^ The bind to process
150 -> TranslatorSession ((Maybe CoreSyn.CoreBndr, Maybe CoreSyn.CoreBndr), ([AST.ConcSm], [CoreSyn.CoreBndr]))
151 -- ^ ((Input state variable, output state variable), (statements, used entities))
152 -- newtype unpacking is just a cast
153 dobind (bndr, unpacked@(CoreSyn.Cast packed coercion))
154 | hasStateType packed && not (hasStateType unpacked)
155 = return ((Just bndr, Nothing), ([], []))
156 -- With simplCore, newtype packing is just a cast
157 dobind (bndr, packed@(CoreSyn.Cast unpacked@(CoreSyn.Var state) coercion))
158 | hasStateType packed && not (hasStateType unpacked)
159 = return ((Nothing, Just state), ([], []))
160 -- Without simplCore, newtype packing uses a data constructor
161 dobind (bndr, (CoreSyn.App (CoreSyn.App (CoreSyn.Var con) (CoreSyn.Type _)) (CoreSyn.Var state)))
163 = return ((Nothing, Just state), ([], []))
164 -- Anything else is handled by mkConcSm
167 return ((Nothing, Nothing), sms)
170 (CoreSyn.CoreBndr, CoreSyn.CoreBndr, CoreSyn.CoreBndr) -- ^ The current state, new state and reset variables
171 -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]) -- ^ The resulting statements
172 mkStateProcSm (old, new, res) = do
173 let error_msg = "\nVHDL.mkSigDec: Can not make signal declaration for type: \n" ++ pprString res
174 type_mark_old_maybe <- MonadState.lift tsType $ vhdlTy error_msg (Var.varType old)
175 let type_mark_old = Maybe.fromJust type_mark_old_maybe
176 type_mark_res_maybe <- MonadState.lift tsType $ vhdlTy error_msg (Var.varType res)
177 let type_mark_res' = Maybe.fromJust type_mark_res_maybe
178 let type_mark_res = if type_mark_old == type_mark_res' then
181 error $ "Initial state has different type than state type, state type: " ++ show type_mark_old ++ ", init type: " ++ show type_mark_res'
182 let resvalid = mkVHDLExtId $ varToString res ++ "val"
183 let resvaldec = AST.BDISD $ AST.SigDec resvalid type_mark_res Nothing
184 let reswform = AST.Wform [AST.WformElem (AST.PrimName $ AST.NSimple resvalid) Nothing]
185 let res_assign = AST.SigAssign (varToVHDLName old) reswform
186 let blocklabel = mkVHDLBasicId "state"
187 let statelabel = mkVHDLBasicId "stateupdate"
188 let rising_edge = AST.NSimple $ mkVHDLBasicId "rising_edge"
189 let wform = AST.Wform [AST.WformElem (AST.PrimName $ varToVHDLName new) Nothing]
190 let clk_assign = AST.SigAssign (varToVHDLName old) wform
191 let rising_edge_clk = AST.PrimFCall $ AST.FCall rising_edge [Nothing AST.:=>: (AST.ADName $ AST.NSimple clockId)]
192 let resetn_is_low = (AST.PrimName $ AST.NSimple resetId) AST.:=: (AST.PrimLit "'0'")
193 signature <- getEntity res
194 let entity_id = ent_id signature
195 let reslabel = "resetval_" ++ ((prettyShow . varToVHDLName) res)
196 let portmaps = mkAssocElems [] (AST.NSimple resvalid) signature
197 let reset_statement = mkComponentInst reslabel entity_id portmaps
198 let clk_statement = [AST.ElseIf rising_edge_clk [clk_assign]]
199 let statement = AST.IfSm resetn_is_low [res_assign] clk_statement Nothing
200 let stateupdate = AST.CSPSm $ AST.ProcSm statelabel [clockId,resetId,resvalid] [statement]
201 let block = AST.CSBSm $ AST.BlockSm blocklabel [] (AST.PMapAspect []) [resvaldec] [reset_statement,stateupdate]
202 return ([block],[res])
204 -- | Transforms a core binding into a VHDL concurrent statement
206 (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -- ^ The binding to process
207 -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
208 -- ^ The corresponding VHDL concurrent statements and entities
212 -- Ignore Cast expressions, they should not longer have any meaning as long as
213 -- the type works out. Throw away state repacking
214 mkConcSm (bndr, to@(CoreSyn.Cast from ty))
215 | hasStateType to && hasStateType from
217 mkConcSm (bndr, CoreSyn.Cast expr ty) = mkConcSm (bndr, expr)
219 -- Simple a = b assignments are just like applications, but without arguments.
220 -- We can't just generate an unconditional assignment here, since b might be a
221 -- top level binding (e.g., a function with no arguments).
222 mkConcSm (bndr, CoreSyn.Var v) =
223 genApplication (Left bndr) v []
225 mkConcSm (bndr, app@(CoreSyn.App _ _))= do
226 let (CoreSyn.Var f, args) = CoreSyn.collectArgs app
227 let valargs = get_val_args (Var.varType f) args
228 genApplication (Left bndr) f (map Left valargs)
230 -- A single alt case must be a selector. This means the scrutinee is a simple
231 -- variable, the alternative is a dataalt with a single non-wild binder that
233 mkConcSm (bndr, expr@(CoreSyn.Case (CoreSyn.Var scrut) b ty [alt]))
234 -- Don't generate VHDL for substate extraction
235 | hasStateType bndr = return ([], [])
238 (CoreSyn.DataAlt dc, bndrs, (CoreSyn.Var sel_bndr)) -> do
239 bndrs' <- Monad.filterM hasNonEmptyType bndrs
240 case List.elemIndex sel_bndr bndrs' of
242 htypeScrt <- MonadState.lift tsType $ mkHTypeEither (Var.varType scrut)
243 htypeBndr <- MonadState.lift tsType $ mkHTypeEither (Var.varType bndr)
244 case htypeScrt == htypeBndr of
246 let sel_name = varToVHDLName scrut
247 let sel_expr = AST.PrimName sel_name
248 return ([mkUncondAssign (Left bndr) sel_expr], [])
251 Right (AggrType _ _) -> do
252 labels <- MonadState.lift tsType $ getFieldLabels (Id.idType scrut)
253 let label = labels!!i
254 let sel_name = mkSelectedName (varToVHDLName scrut) label
255 let sel_expr = AST.PrimName sel_name
256 return ([mkUncondAssign (Left bndr) sel_expr], [])
257 _ -> do -- error $ "DIE!"
258 let sel_name = varToVHDLName scrut
259 let sel_expr = AST.PrimName sel_name
260 return ([mkUncondAssign (Left bndr) sel_expr], [])
261 Nothing -> error $ "\nVHDL.mkConcSM: Not in normal form: Not a selector case:\n" ++ (pprString expr)
263 _ -> error $ "\nVHDL.mkConcSM: Not in normal form: Not a selector case:\n" ++ (pprString expr)
265 -- Multiple case alt are be conditional assignments and have only wild
266 -- binders in the alts and only variables in the case values and a variable
267 -- for a scrutinee. We check the constructor of the second alt, since the
268 -- first is the default case, if there is any.
270 -- mkConcSm (bndr, (CoreSyn.Case (CoreSyn.Var scrut) b ty [(_, _, CoreSyn.Var false), (con, _, CoreSyn.Var true)])) = do
271 -- scrut' <- MonadState.lift tsType $ varToVHDLExpr scrut
272 -- altcon <- MonadState.lift tsType $ altconToVHDLExpr con
273 -- let cond_expr = scrut' AST.:=: altcon
274 -- true_expr <- MonadState.lift tsType $ varToVHDLExpr true
275 -- false_expr <- MonadState.lift tsType $ varToVHDLExpr false
276 -- return ([mkCondAssign (Left bndr) cond_expr true_expr false_expr], [])
277 mkConcSm (bndr, (CoreSyn.Case (CoreSyn.Var scrut) _ _ (alt:alts))) = do --error "\nVHDL.mkConcSm: Not in normal form: Case statement with more than two alternatives"
278 scrut' <- MonadState.lift tsType $ varToVHDLExpr scrut
279 -- Omit first condition, which is the default
280 altcons <- MonadState.lift tsType $ mapM (altconToVHDLExpr . (\(con,_,_) -> con)) alts
281 let cond_exprs = map (\x -> scrut' AST.:=: x) altcons
282 -- Rotate expressions to the left, so that the expression related to the default case is the last
283 exprs <- MonadState.lift tsType $ mapM (varToVHDLExpr . (\(_,_,CoreSyn.Var expr) -> expr)) (alts ++ [alt])
284 return ([mkAltsAssign (Left bndr) cond_exprs exprs], [])
286 mkConcSm (_, CoreSyn.Case _ _ _ _) = error "\nVHDL.mkConcSm: Not in normal form: Case statement has does not have a simple variable as scrutinee"
287 mkConcSm (bndr, expr) = error $ "\nVHDL.mkConcSM: Unsupported binding in let expression: " ++ pprString bndr ++ " = " ++ pprString expr
289 -----------------------------------------------------------------------------
290 -- Functions to generate VHDL for builtin functions
291 -----------------------------------------------------------------------------
293 -- | A function to wrap a builder-like function that expects its arguments to
295 genExprArgs wrap dst func args = do
296 args' <- argsToVHDLExprs args
299 -- | Turn the all lefts into VHDL Expressions.
300 argsToVHDLExprs :: [Either CoreSyn.CoreExpr AST.Expr] -> TranslatorSession [AST.Expr]
301 argsToVHDLExprs = catMaybesM . (mapM argToVHDLExpr)
303 argToVHDLExpr :: Either CoreSyn.CoreExpr AST.Expr -> TranslatorSession (Maybe AST.Expr)
304 argToVHDLExpr (Left expr) = MonadState.lift tsType $ do
305 let errmsg = "Generate.argToVHDLExpr: Using non-representable type? Should not happen!"
306 ty_maybe <- vhdlTy errmsg expr
309 vhdl_expr <- varToVHDLExpr $ exprToVar expr
310 return $ Just vhdl_expr
311 Nothing -> return Nothing
313 argToVHDLExpr (Right expr) = return $ Just expr
315 -- A function to wrap a builder-like function that generates no component
318 (dst -> func -> args -> TranslatorSession [AST.ConcSm])
319 -> (dst -> func -> args -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr]))
320 genNoInsts wrap dst func args = do
321 concsms <- wrap dst func args
324 -- | A function to wrap a builder-like function that expects its arguments to
327 (dst -> func -> [Var.Var] -> res)
328 -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
329 genVarArgs wrap dst func args = wrap dst func args'
331 args' = map exprToVar exprargs
332 -- Check (rather crudely) that all arguments are CoreExprs
333 (exprargs, []) = Either.partitionEithers args
335 -- | A function to wrap a builder-like function that expects its arguments to
338 (dst -> func -> [Literal.Literal] -> TranslatorSession [AST.ConcSm])
339 -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> TranslatorSession [AST.ConcSm])
340 genLitArgs wrap dst func args = do
341 hscenv <- MonadState.lift tsType $ MonadState.get tsHscEnv
342 let (exprargs, []) = Either.partitionEithers args
343 -- FIXME: Check if we were passed an CoreSyn.App
344 let litargs = concatMap (getLiterals hscenv) exprargs
345 let args' = map exprToLit litargs
348 -- | A function to wrap a builder-like function that produces an expression
349 -- and expects it to be assigned to the destination.
351 ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> TranslatorSession AST.Expr)
352 -> ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> TranslatorSession [AST.ConcSm])
353 genExprRes wrap dst func args = do
354 expr <- wrap dst func args
355 return [mkUncondAssign dst expr]
357 -- | Generate a binary operator application. The first argument should be a
358 -- constructor from the AST.Expr type, e.g. AST.And.
359 genOperator2 :: (AST.Expr -> AST.Expr -> AST.Expr) -> BuiltinBuilder
360 genOperator2 op = genNoInsts $ genExprArgs $ genExprRes (genOperator2' op)
361 genOperator2' :: (AST.Expr -> AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
362 genOperator2' op _ f [arg1, arg2] = return $ op arg1 arg2
364 -- | Generate a unary operator application
365 genOperator1 :: (AST.Expr -> AST.Expr) -> BuiltinBuilder
366 genOperator1 op = genNoInsts $ genExprArgs $ genExprRes (genOperator1' op)
367 genOperator1' :: (AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
368 genOperator1' op _ f [arg] = return $ op arg
370 -- | Generate a unary operator application
371 genNegation :: BuiltinBuilder
372 genNegation = genNoInsts $ genVarArgs $ genExprRes genNegation'
373 genNegation' :: dst -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession AST.Expr
374 genNegation' _ f [arg] = do
375 arg1 <- MonadState.lift tsType $ varToVHDLExpr arg
376 let ty = Var.varType arg
377 let (tycon, args) = Type.splitTyConApp ty
378 let name = Name.getOccString (TyCon.tyConName tycon)
380 "SizedInt" -> return $ AST.Neg arg1
381 otherwise -> error $ "\nGenerate.genNegation': Negation not allowed for type: " ++ show name
383 -- | Generate a function call from the destination binder, function name and a
384 -- list of expressions (its arguments)
385 genFCall :: Bool -> BuiltinBuilder
386 genFCall switch = genNoInsts $ genExprArgs $ genExprRes (genFCall' switch)
387 genFCall' :: Bool -> Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
388 genFCall' switch (Left res) f args = do
389 let fname = varToString f
390 let el_ty = if switch then (Var.varType res) else ((tfvec_elem . Var.varType) res)
391 id <- MonadState.lift tsType $ vectorFunId el_ty fname
392 return $ AST.PrimFCall $ AST.FCall (AST.NSimple id) $
393 map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
394 genFCall' _ (Right name) _ _ = error $ "\nGenerate.genFCall': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
396 genFromSizedWord :: BuiltinBuilder
397 genFromSizedWord = genNoInsts $ genExprArgs genFromSizedWord'
398 genFromSizedWord' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession [AST.ConcSm]
399 genFromSizedWord' (Left res) f args@[arg] =
400 return [mkUncondAssign (Left res) arg]
401 -- let fname = varToString f
402 -- return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId toIntegerId)) $
403 -- map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
404 genFromSizedWord' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
406 genResize :: BuiltinBuilder
407 genResize = genNoInsts $ genExprArgs $ genExprRes genResize'
408 genResize' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
409 genResize' (Left res) f [arg] = do {
410 ; let { ty = Var.varType res
411 ; (tycon, args) = Type.splitTyConApp ty
412 ; name = Name.getOccString (TyCon.tyConName tycon)
414 ; len <- case name of
415 "SizedInt" -> MonadState.lift tsType $ tfp_to_int (sized_int_len_ty ty)
416 "SizedWord" -> MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
417 ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId resizeId))
418 [Nothing AST.:=>: AST.ADExpr arg, Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
420 genResize' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
422 genTimes :: BuiltinBuilder
423 genTimes = genNoInsts $ genExprArgs $ genExprRes genTimes'
424 genTimes' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession AST.Expr
425 genTimes' (Left res) f [arg1,arg2] = do {
426 ; let { ty = Var.varType res
427 ; (tycon, args) = Type.splitTyConApp ty
428 ; name = Name.getOccString (TyCon.tyConName tycon)
430 ; len <- case name of
431 "SizedInt" -> MonadState.lift tsType $ tfp_to_int (sized_int_len_ty ty)
432 "SizedWord" -> MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
433 "RangedWord" -> do { ubound <- MonadState.lift tsType $ tfp_to_int (ranged_word_bound_ty ty)
434 ; let bitsize = floor (logBase 2 (fromInteger (toInteger ubound)))
437 ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId resizeId))
438 [Nothing AST.:=>: AST.ADExpr (arg1 AST.:*: arg2), Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
440 genTimes' (Right name) _ _ = error $ "\nGenerate.genTimes': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
442 -- FIXME: I'm calling genLitArgs which is very specific function,
443 -- which needs to be fixed as well
444 genFromInteger :: BuiltinBuilder
445 genFromInteger = genNoInsts $ genLitArgs $ genExprRes genFromInteger'
446 genFromInteger' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [Literal.Literal] -> TranslatorSession AST.Expr
447 genFromInteger' (Left res) f lits = do {
448 ; let { ty = Var.varType res
449 ; (tycon, args) = Type.splitTyConApp ty
450 ; name = Name.getOccString (TyCon.tyConName tycon)
452 ; len <- case name of
453 "SizedInt" -> MonadState.lift tsType $ tfp_to_int (sized_int_len_ty ty)
454 "SizedWord" -> MonadState.lift tsType $ tfp_to_int (sized_word_len_ty ty)
456 ; bound <- MonadState.lift tsType $ tfp_to_int (ranged_word_bound_ty ty)
457 ; return $ floor (logBase 2 (fromInteger (toInteger (bound)))) + 1
459 ; let fname = case name of "SizedInt" -> toSignedId ; "SizedWord" -> toUnsignedId ; "RangedWord" -> toUnsignedId
460 ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId fname))
461 [Nothing AST.:=>: AST.ADExpr (AST.PrimLit (show (last lits))), Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
465 genFromInteger' (Right name) _ _ = error $ "\nGenerate.genFromInteger': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
467 genSizedInt :: BuiltinBuilder
468 genSizedInt = genFromInteger
471 -- | Generate a Builder for the builtin datacon TFVec
472 genTFVec :: BuiltinBuilder
473 genTFVec (Left res) f [Left (CoreSyn.Let (CoreSyn.Rec letBinders) letRes)] = do {
474 -- Generate Assignments for all the binders
475 ; letAssigns <- mapM genBinderAssign letBinders
476 -- Generate assignments for the result (which might be another let binding)
477 ; (resBinders,resAssignments) <- genResAssign letRes
478 -- Get all the Assigned binders
479 ; let assignedBinders = Maybe.catMaybes (map fst letAssigns)
480 -- Make signal names for all the assigned binders
481 ; sigs <- mapM (\x -> MonadState.lift tsType $ varToVHDLExpr x) (assignedBinders ++ resBinders)
482 -- Assign all the signals to the resulting vector
483 ; let { vecsigns = mkAggregateSignal sigs
484 ; vecassign = mkUncondAssign (Left res) vecsigns
486 -- Generate all the signal declaration for the assigned binders
487 ; sig_dec_maybes <- mapM mkSigDec (assignedBinders ++ resBinders)
488 ; let { sig_decs = map (AST.BDISD) (Maybe.catMaybes $ sig_dec_maybes)
489 -- Setup the VHDL Block
490 ; block_label = mkVHDLExtId ("TFVec_" ++ show (varToString res))
491 ; block = AST.BlockSm block_label [] (AST.PMapAspect []) sig_decs ((concat (map snd letAssigns)) ++ resAssignments ++ [vecassign])
493 -- Return the block statement coressponding to the TFVec literal
494 ; return $ [AST.CSBSm block]
497 genBinderAssign :: (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -> TranslatorSession (Maybe CoreSyn.CoreBndr, [AST.ConcSm])
498 -- For now we only translate applications
499 genBinderAssign (bndr, app@(CoreSyn.App _ _)) = do
500 let (CoreSyn.Var f, args) = CoreSyn.collectArgs app
501 let valargs = get_val_args (Var.varType f) args
502 apps <- genApplication (Left bndr) f (map Left valargs)
503 return (Just bndr, apps)
504 genBinderAssign _ = return (Nothing,[])
505 genResAssign :: CoreSyn.CoreExpr -> TranslatorSession ([CoreSyn.CoreBndr], [AST.ConcSm])
506 genResAssign app@(CoreSyn.App _ letexpr) = do
508 (CoreSyn.Let (CoreSyn.Rec letbndrs) letres) -> do
509 letapps <- mapM genBinderAssign letbndrs
510 let bndrs = Maybe.catMaybes (map fst letapps)
511 let app = (map snd letapps)
512 (vars, apps) <- genResAssign letres
513 return ((bndrs ++ vars),((concat app) ++ apps))
514 otherwise -> return ([],[])
515 genResAssign _ = return ([],[])
517 genTFVec (Left res) f [Left app@(CoreSyn.App _ _)] = do {
518 ; let { elems = reduceCoreListToHsList app
519 -- Make signal names for all the binders
520 ; binders = map (\expr -> case expr of
522 otherwise -> error $ "\nGenerate.genTFVec: Cannot generate TFVec: "
523 ++ show res ++ ", with elems:\n" ++ show elems ++ "\n" ++ pprString elems) elems
525 ; sigs <- mapM (\x -> MonadState.lift tsType $ varToVHDLExpr x) binders
526 -- Assign all the signals to the resulting vector
527 ; let { vecsigns = mkAggregateSignal sigs
528 ; vecassign = mkUncondAssign (Left res) vecsigns
529 -- Setup the VHDL Block
530 ; block_label = mkVHDLExtId ("TFVec_" ++ show (varToString res))
531 ; block = AST.BlockSm block_label [] (AST.PMapAspect []) [] [vecassign]
533 -- Return the block statement coressponding to the TFVec literal
534 ; return $ [AST.CSBSm block]
537 genTFVec (Left name) _ [Left xs] = error $ "\nGenerate.genTFVec: Cannot generate TFVec: " ++ show name ++ ", with elems:\n" ++ show xs ++ "\n" ++ pprString xs
539 genTFVec (Right name) _ _ = error $ "\nGenerate.genTFVec: Cannot generate TFVec assigned to VHDLName: " ++ show name
541 -- | Generate a generate statement for the builtin function "map"
542 genMap :: BuiltinBuilder
543 genMap (Left res) f [Left mapped_f, Left (CoreSyn.Var arg)] = do {
544 -- mapped_f must be a CoreExpr (since we can't represent functions as VHDL
545 -- expressions). arg must be a CoreExpr (and should be a CoreSyn.Var), since
546 -- we must index it (which we couldn't if it was a VHDL Expr, since only
547 -- VHDLNames can be indexed).
548 -- Setup the generate scheme
549 ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
550 -- TODO: Use something better than varToString
551 ; let { label = mkVHDLExtId ("mapVector" ++ (varToString res))
552 ; n_id = mkVHDLBasicId "n"
553 ; n_expr = idToVHDLExpr n_id
554 ; range = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
555 ; genScheme = AST.ForGn n_id range
556 -- Create the content of the generate statement: Applying the mapped_f to
557 -- each of the elements in arg, storing to each element in res
558 ; resname = mkIndexedName (varToVHDLName res) n_expr
559 ; argexpr = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
560 ; (CoreSyn.Var real_f, already_mapped_args) = CoreSyn.collectArgs mapped_f
561 ; valargs = get_val_args (Var.varType real_f) already_mapped_args
563 ; (app_concsms, used) <- genApplication (Right resname) real_f (map Left valargs ++ [Right argexpr])
564 -- Return the generate statement
565 ; return ([AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms], used)
568 genMap' (Right name) _ _ = error $ "\nGenerate.genMap': Cannot generate map function call assigned to a VHDLName: " ++ show name
570 genZipWith :: BuiltinBuilder
571 genZipWith = genVarArgs genZipWith'
572 genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
573 genZipWith' (Left res) f args@[zipped_f, arg1, arg2] = do {
574 -- Setup the generate scheme
575 ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
576 -- TODO: Use something better than varToString
577 ; let { label = mkVHDLExtId ("zipWithVector" ++ (varToString res))
578 ; n_id = mkVHDLBasicId "n"
579 ; n_expr = idToVHDLExpr n_id
580 ; range = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
581 ; genScheme = AST.ForGn n_id range
582 -- Create the content of the generate statement: Applying the zipped_f to
583 -- each of the elements in arg1 and arg2, storing to each element in res
584 ; resname = mkIndexedName (varToVHDLName res) n_expr
585 ; argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
586 ; argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
588 ; (app_concsms, used) <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
589 -- Return the generate functions
590 ; return ([AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms], used)
593 genFoldl :: BuiltinBuilder
594 genFoldl = genFold True
596 genFoldr :: BuiltinBuilder
597 genFoldr = genFold False
599 genFold :: Bool -> BuiltinBuilder
600 genFold left = genVarArgs (genFold' left)
602 genFold' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
603 genFold' left res f args@[folded_f , start ,vec]= do
604 len <- MonadState.lift tsType $ tfp_to_int (tfvec_len_ty (Var.varType vec))
605 genFold'' len left res f args
607 genFold'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
608 -- Special case for an empty input vector, just assign start to res
609 genFold'' len left (Left res) _ [_, start, vec] | len == 0 = do
610 arg <- MonadState.lift tsType $ varToVHDLExpr start
611 return ([mkUncondAssign (Left res) arg], [])
613 genFold'' len left (Left res) f [folded_f, start, vec] = do
615 --len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
616 -- An expression for len-1
617 let len_min_expr = (AST.PrimLit $ show (len-1))
618 -- evec is (TFVec n), so it still needs an element type
619 let (nvec, _) = Type.splitAppTy (Var.varType vec)
620 -- Put the type of the start value in nvec, this will be the type of our
622 let tmp_ty = Type.mkAppTy nvec (Var.varType start)
623 let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty
624 -- TODO: Handle Nothing
625 Just tmp_vhdl_ty <- MonadState.lift tsType $ vhdlTy error_msg tmp_ty
626 -- Setup the generate scheme
627 let gen_label = mkVHDLExtId ("foldlVector" ++ (varToString vec))
628 let block_label = mkVHDLExtId ("foldlVector" ++ (varToString res))
629 let gen_range = if left then AST.ToRange (AST.PrimLit "0") len_min_expr
630 else AST.DownRange len_min_expr (AST.PrimLit "0")
631 let gen_scheme = AST.ForGn n_id gen_range
632 -- Make the intermediate vector
633 let tmp_dec = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
634 -- Create the generate statement
635 cells' <- sequence [genFirstCell, genOtherCell]
636 let (cells, useds) = unzip cells'
637 let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
638 -- Assign tmp[len-1] or tmp[0] to res
639 let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (if left then
640 (mkIndexedName tmp_name (AST.PrimLit $ show (len-1))) else
641 (mkIndexedName tmp_name (AST.PrimLit "0")))
642 let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
643 return ([AST.CSBSm block], concat useds)
645 -- An id for the counter
646 n_id = mkVHDLBasicId "n"
647 n_cur = idToVHDLExpr n_id
648 -- An expression for previous n
649 n_prev = if left then (n_cur AST.:-: (AST.PrimLit "1"))
650 else (n_cur AST.:+: (AST.PrimLit "1"))
651 -- An id for the tmp result vector
652 tmp_id = mkVHDLBasicId "tmp"
653 tmp_name = AST.NSimple tmp_id
654 -- Generate parts of the fold
655 genFirstCell, genOtherCell :: TranslatorSession (AST.GenerateSm, [CoreSyn.CoreBndr])
657 len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
658 let cond_label = mkVHDLExtId "firstcell"
659 -- if n == 0 or n == len-1
660 let cond_scheme = AST.IfGn $ n_cur AST.:=: (if left then (AST.PrimLit "0")
661 else (AST.PrimLit $ show (len-1)))
662 -- Output to tmp[current n]
663 let resname = mkIndexedName tmp_name n_cur
665 argexpr1 <- MonadState.lift tsType $ varToVHDLExpr start
666 -- Input from vec[current n]
667 let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
668 (app_concsms, used) <- genApplication (Right resname) folded_f ( if left then
669 [Right argexpr1, Right argexpr2]
671 [Right argexpr2, Right argexpr1]
673 -- Return the conditional generate part
674 return (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
677 len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
678 let cond_label = mkVHDLExtId "othercell"
679 -- if n > 0 or n < len-1
680 let cond_scheme = AST.IfGn $ n_cur AST.:/=: (if left then (AST.PrimLit "0")
681 else (AST.PrimLit $ show (len-1)))
682 -- Output to tmp[current n]
683 let resname = mkIndexedName tmp_name n_cur
684 -- Input from tmp[previous n]
685 let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
686 -- Input from vec[current n]
687 let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
688 (app_concsms, used) <- genApplication (Right resname) folded_f ( if left then
689 [Right argexpr1, Right argexpr2]
691 [Right argexpr2, Right argexpr1]
693 -- Return the conditional generate part
694 return (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
696 -- | Generate a generate statement for the builtin function "zip"
697 genZip :: BuiltinBuilder
698 genZip = genNoInsts $ genVarArgs genZip'
699 genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
700 genZip' (Left res) f args@[arg1, arg2] = do {
701 -- Setup the generate scheme
702 ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
703 -- TODO: Use something better than varToString
704 ; let { label = mkVHDLExtId ("zipVector" ++ (varToString res))
705 ; n_id = mkVHDLBasicId "n"
706 ; n_expr = idToVHDLExpr n_id
707 ; range = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
708 ; genScheme = AST.ForGn n_id range
709 ; resname' = mkIndexedName (varToVHDLName res) n_expr
710 ; argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
711 ; argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
713 ; labels <- MonadState.lift tsType $ getFieldLabels (tfvec_elem (Var.varType res))
714 ; let { resnameA = mkSelectedName resname' (labels!!0)
715 ; resnameB = mkSelectedName resname' (labels!!1)
716 ; resA_assign = mkUncondAssign (Right resnameA) argexpr1
717 ; resB_assign = mkUncondAssign (Right resnameB) argexpr2
719 -- Return the generate functions
720 ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
723 -- | Generate a generate statement for the builtin function "fst"
724 genFst :: BuiltinBuilder
725 genFst = genNoInsts $ genVarArgs genFst'
726 genFst' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
727 genFst' (Left res) f args@[arg] = do {
728 ; labels <- MonadState.lift tsType $ getFieldLabels (Var.varType arg)
729 ; let { argexpr' = varToVHDLName arg
730 ; argexprA = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (labels!!0)
731 ; assign = mkUncondAssign (Left res) argexprA
733 -- Return the generate functions
737 -- | Generate a generate statement for the builtin function "snd"
738 genSnd :: BuiltinBuilder
739 genSnd = genNoInsts $ genVarArgs genSnd'
740 genSnd' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
741 genSnd' (Left res) f args@[arg] = do {
742 ; labels <- MonadState.lift tsType $ getFieldLabels (Var.varType arg)
743 ; let { argexpr' = varToVHDLName arg
744 ; argexprB = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (labels!!1)
745 ; assign = mkUncondAssign (Left res) argexprB
747 -- Return the generate functions
751 -- | Generate a generate statement for the builtin function "unzip"
752 genUnzip :: BuiltinBuilder
753 genUnzip = genNoInsts $ genVarArgs genUnzip'
754 genUnzip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
755 genUnzip' (Left res) f args@[arg] = do {
756 -- Setup the generate scheme
757 ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
758 -- TODO: Use something better than varToString
759 ; let { label = mkVHDLExtId ("unzipVector" ++ (varToString res))
760 ; n_id = mkVHDLBasicId "n"
761 ; n_expr = idToVHDLExpr n_id
762 ; range = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
763 ; genScheme = AST.ForGn n_id range
764 ; resname' = varToVHDLName res
765 ; argexpr' = mkIndexedName (varToVHDLName arg) n_expr
767 ; reslabels <- MonadState.lift tsType $ getFieldLabels (Var.varType res)
768 ; arglabels <- MonadState.lift tsType $ getFieldLabels (tfvec_elem (Var.varType arg))
769 ; let { resnameA = mkIndexedName (mkSelectedName resname' (reslabels!!0)) n_expr
770 ; resnameB = mkIndexedName (mkSelectedName resname' (reslabels!!1)) n_expr
771 ; argexprA = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!0)
772 ; argexprB = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!1)
773 ; resA_assign = mkUncondAssign (Right resnameA) argexprA
774 ; resB_assign = mkUncondAssign (Right resnameB) argexprB
776 -- Return the generate functions
777 ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
780 genCopy :: BuiltinBuilder
781 genCopy = genNoInsts $ genVarArgs genCopy'
782 genCopy' :: (Either CoreSyn.CoreBndr AST.VHDLName ) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
783 genCopy' (Left res) f args@[arg] =
785 resExpr = AST.Aggregate [AST.ElemAssoc (Just AST.Others)
786 (AST.PrimName (varToVHDLName arg))]
787 out_assign = mkUncondAssign (Left res) resExpr
791 genConcat :: BuiltinBuilder
792 genConcat = genNoInsts $ genVarArgs genConcat'
793 genConcat' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
794 genConcat' (Left res) f args@[arg] = do {
795 -- Setup the generate scheme
796 ; len1 <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
797 ; let (_, nvec) = Type.splitAppTy (Var.varType arg)
798 ; len2 <- MonadState.lift tsType $ tfp_to_int $ tfvec_len_ty nvec
799 -- TODO: Use something better than varToString
800 ; let { label = mkVHDLExtId ("concatVector" ++ (varToString res))
801 ; n_id = mkVHDLBasicId "n"
802 ; n_expr = idToVHDLExpr n_id
803 ; fromRange = n_expr AST.:*: (AST.PrimLit $ show len2)
804 ; genScheme = AST.ForGn n_id range
805 -- Create the content of the generate statement: Applying the mapped_f to
806 -- each of the elements in arg, storing to each element in res
807 ; toRange = (n_expr AST.:*: (AST.PrimLit $ show len2)) AST.:+: (AST.PrimLit $ show (len2-1))
808 ; range = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len1-1))
809 ; resname = vecSlice fromRange toRange
810 ; argexpr = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
811 ; out_assign = mkUncondAssign (Right resname) argexpr
813 -- Return the generate statement
814 ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [out_assign]]
817 vecSlice init last = AST.NSlice (AST.SliceName (varToVHDLName res)
818 (AST.ToRange init last))
820 genIteraten :: BuiltinBuilder
821 genIteraten dst f args = genIterate dst f (tail args)
823 genIterate :: BuiltinBuilder
824 genIterate = genIterateOrGenerate True
826 genGeneraten :: BuiltinBuilder
827 genGeneraten dst f args = genGenerate dst f (tail args)
829 genGenerate :: BuiltinBuilder
830 genGenerate = genIterateOrGenerate False
832 genIterateOrGenerate :: Bool -> BuiltinBuilder
833 genIterateOrGenerate iter = genVarArgs (genIterateOrGenerate' iter)
835 genIterateOrGenerate' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
836 genIterateOrGenerate' iter (Left res) f args = do
837 len <- MonadState.lift tsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
838 genIterateOrGenerate'' len iter (Left res) f args
840 genIterateOrGenerate'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
841 -- Special case for an empty input vector, just assign start to res
842 genIterateOrGenerate'' len iter (Left res) _ [app_f, start] | len == 0 = return ([mkUncondAssign (Left res) (AST.PrimLit "\"\"")], [])
844 genIterateOrGenerate'' len iter (Left res) f [app_f, start] = do
846 -- len <- MonadState.lift tsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
847 -- An expression for len-1
848 let len_min_expr = (AST.PrimLit $ show (len-1))
849 -- -- evec is (TFVec n), so it still needs an element type
850 -- let (nvec, _) = splitAppTy (Var.varType vec)
851 -- -- Put the type of the start value in nvec, this will be the type of our
852 -- -- temporary vector
853 let tmp_ty = Var.varType res
854 let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty
855 -- TODO: Handle Nothing
856 Just tmp_vhdl_ty <- MonadState.lift tsType $ vhdlTy error_msg tmp_ty
857 -- Setup the generate scheme
858 let gen_label = mkVHDLExtId ("iterateVector" ++ (varToString start))
859 let block_label = mkVHDLExtId ("iterateVector" ++ (varToString res))
860 let gen_range = AST.ToRange (AST.PrimLit "0") len_min_expr
861 let gen_scheme = AST.ForGn n_id gen_range
862 -- Make the intermediate vector
863 let tmp_dec = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
864 -- Create the generate statement
865 cells' <- sequence [genFirstCell, genOtherCell]
866 let (cells, useds) = unzip cells'
867 let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
868 -- Assign tmp[len-1] or tmp[0] to res
869 let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr tmp_name
870 let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
871 return ([AST.CSBSm block], concat useds)
873 -- An id for the counter
874 n_id = mkVHDLBasicId "n"
875 n_cur = idToVHDLExpr n_id
876 -- An expression for previous n
877 n_prev = n_cur AST.:-: (AST.PrimLit "1")
878 -- An id for the tmp result vector
879 tmp_id = mkVHDLBasicId "tmp"
880 tmp_name = AST.NSimple tmp_id
881 -- Generate parts of the fold
882 genFirstCell, genOtherCell :: TranslatorSession (AST.GenerateSm, [CoreSyn.CoreBndr])
884 let cond_label = mkVHDLExtId "firstcell"
885 -- if n == 0 or n == len-1
886 let cond_scheme = AST.IfGn $ n_cur AST.:=: (AST.PrimLit "0")
887 -- Output to tmp[current n]
888 let resname = mkIndexedName tmp_name n_cur
890 argexpr <- MonadState.lift tsType $ varToVHDLExpr start
891 let startassign = mkUncondAssign (Right resname) argexpr
892 (app_concsms, used) <- genApplication (Right resname) app_f [Right argexpr]
893 -- Return the conditional generate part
894 let gensm = AST.GenerateSm cond_label cond_scheme [] (if iter then
902 let cond_label = mkVHDLExtId "othercell"
903 -- if n > 0 or n < len-1
904 let cond_scheme = AST.IfGn $ n_cur AST.:/=: (AST.PrimLit "0")
905 -- Output to tmp[current n]
906 let resname = mkIndexedName tmp_name n_cur
907 -- Input from tmp[previous n]
908 let argexpr = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
909 (app_concsms, used) <- genApplication (Right resname) app_f [Right argexpr]
910 -- Return the conditional generate part
911 return (AST.GenerateSm cond_label cond_scheme [] app_concsms, used)
913 genBlockRAM :: BuiltinBuilder
914 genBlockRAM = genNoInsts $ genExprArgs genBlockRAM'
916 genBlockRAM' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [AST.Expr] -> TranslatorSession [AST.ConcSm]
917 genBlockRAM' (Left res) f args@[data_in,rdaddr,wraddr,wrenable] = do
919 let (tup,data_out) = Type.splitAppTy (Var.varType res)
920 let (tup',ramvec) = Type.splitAppTy tup
921 let Just realram = Type.coreView ramvec
922 let Just (tycon, types) = Type.splitTyConApp_maybe realram
923 Just ram_vhdl_ty <- MonadState.lift tsType $ vhdlTy "wtf" (head types)
924 -- Make the intermediate vector
925 let ram_dec = AST.BDISD $ AST.SigDec ram_id ram_vhdl_ty Nothing
926 -- Get the data_out name
927 -- reslabels <- MonadState.lift tsType $ getFieldLabels (Var.varType res)
928 let resname = varToVHDLName res
929 -- let resname = mkSelectedName resname' (reslabels!!0)
930 let rdaddr_int = genExprFCall (mkVHDLBasicId toIntegerId) rdaddr
931 let argexpr = vhdlNameToVHDLExpr $ mkIndexedName (AST.NSimple ram_id) rdaddr_int
932 let assign = mkUncondAssign (Right resname) argexpr
933 let block_label = mkVHDLExtId ("blockRAM" ++ (varToString res))
934 let block = AST.BlockSm block_label [] (AST.PMapAspect []) [ram_dec] [assign, mkUpdateProcSm]
935 return [AST.CSBSm block]
937 ram_id = mkVHDLBasicId "ram"
938 mkUpdateProcSm :: AST.ConcSm
939 mkUpdateProcSm = AST.CSPSm $ AST.ProcSm proclabel [clockId] [statement]
941 proclabel = mkVHDLBasicId "updateRAM"
942 rising_edge = mkVHDLBasicId "rising_edge"
943 wraddr_int = genExprFCall (mkVHDLBasicId toIntegerId) wraddr
944 ramloc = mkIndexedName (AST.NSimple ram_id) wraddr_int
945 wform = AST.Wform [AST.WformElem data_in Nothing]
946 ramassign = AST.SigAssign ramloc wform
947 rising_edge_clk = genExprFCall rising_edge (AST.PrimName $ AST.NSimple clockId)
948 statement = AST.IfSm (AST.And rising_edge_clk wrenable) [ramassign] [] Nothing
950 genSplit :: BuiltinBuilder
951 genSplit = genNoInsts $ genVarArgs genSplit'
953 genSplit' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> TranslatorSession [AST.ConcSm]
954 genSplit' (Left res) f args@[vecIn] = do {
955 ; labels <- MonadState.lift tsType $ getFieldLabels (Var.varType res)
956 ; len <- MonadState.lift tsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vecIn
957 ; let { block_label = mkVHDLExtId ("split" ++ (varToString vecIn))
958 ; halflen = round ((fromIntegral len) / 2)
959 ; rangeL = vecSlice (AST.PrimLit "0") (AST.PrimLit $ show (halflen - 1))
960 ; rangeR = vecSlice (AST.PrimLit $ show halflen) (AST.PrimLit $ show (len - 1))
961 ; resname = varToVHDLName res
962 ; resnameL = mkSelectedName resname (labels!!0)
963 ; resnameR = mkSelectedName resname (labels!!1)
964 ; argexprL = vhdlNameToVHDLExpr rangeL
965 ; argexprR = vhdlNameToVHDLExpr rangeR
966 ; out_assignL = mkUncondAssign (Right resnameL) argexprL
967 ; out_assignR = mkUncondAssign (Right resnameR) argexprR
968 ; block = AST.BlockSm block_label [] (AST.PMapAspect []) [] [out_assignL, out_assignR]
970 ; return [AST.CSBSm block]
973 vecSlice init last = AST.NSlice (AST.SliceName (varToVHDLName res)
974 (AST.ToRange init last))
975 -----------------------------------------------------------------------------
976 -- Function to generate VHDL for applications
977 -----------------------------------------------------------------------------
979 (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
980 -> CoreSyn.CoreBndr -- ^ The function to apply
981 -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
982 -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
983 -- ^ The corresponding VHDL concurrent statements and entities
985 genApplication dst f args =
986 if Var.isGlobalId f then
987 case Var.idDetails f of
988 IdInfo.DataConWorkId dc -> case dst of
989 -- It's a datacon. Create a record from its arguments.
991 -- We have the bndr, so we can get at the type
992 htype <- MonadState.lift tsType $ mkHTypeEither (Var.varType bndr)
993 let argsNostate = filter (\x -> not (either hasStateType (\x -> False) x)) args
996 [arg'] <- argsToVHDLExprs [arg]
997 return ([mkUncondAssign dst arg'], [])
1000 Right (AggrType _ _) -> do
1001 labels <- MonadState.lift tsType $ getFieldLabels (Var.varType bndr)
1002 args' <- argsToVHDLExprs argsNostate
1003 return (zipWith mkassign labels args', [])
1005 mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
1006 mkassign label arg =
1007 let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
1008 mkUncondAssign (Right sel_name) arg
1009 _ -> do -- error $ "DIE!"
1010 args' <- argsToVHDLExprs argsNostate
1011 return ([mkUncondAssign dst (head args')], [])
1012 Right _ -> error "\nGenerate.genApplication(DataConWorkId): Can't generate dataconstructor application without an original binder"
1013 IdInfo.DataConWrapId dc -> case dst of
1014 -- It's a datacon. Create a record from its arguments.
1016 case (Map.lookup (varToString f) globalNameTable) of
1017 Just (arg_count, builder) ->
1018 if length args == arg_count then
1021 error $ "\nGenerate.genApplication(DataConWrapId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
1022 Nothing -> error $ "\nGenerate.genApplication(DataConWrapId): Can't generate dataconwrapper: " ++ (show dc)
1023 Right _ -> error "\nGenerate.genApplication(DataConWrapId): Can't generate dataconwrapper application without an original binder"
1025 -- It's a global value imported from elsewhere. These can be builtin
1026 -- functions. Look up the function name in the name table and execute
1027 -- the associated builder if there is any and the argument count matches
1028 -- (this should always be the case if it typechecks, but just to be
1030 case (Map.lookup (varToString f) globalNameTable) of
1031 Just (arg_count, builder) ->
1032 if length args == arg_count then
1035 error $ "\nGenerate.genApplication(VanillaId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
1037 top <- isTopLevelBinder f
1040 -- Local binder that references a top level binding. Generate a
1041 -- component instantiation.
1042 signature <- getEntity f
1043 args' <- argsToVHDLExprs args
1044 let entity_id = ent_id signature
1045 -- TODO: Using show here isn't really pretty, but we'll need some
1046 -- unique-ish value...
1047 let label = "comp_ins_" ++ (either show prettyShow) dst
1048 let portmaps = mkAssocElems args' ((either varToVHDLName id) dst) signature
1049 return ([mkComponentInst label entity_id portmaps], [f])
1051 -- Not a top level binder, so this must be a local variable reference.
1052 -- It should have a representable type (and thus, no arguments) and a
1053 -- signal should be generated for it. Just generate an unconditional
1055 -- FIXME : I DONT KNOW IF THE ABOVE COMMENT HOLDS HERE, SO FOR NOW JUST ERROR!
1056 -- f' <- MonadState.lift tsType $ varToVHDLExpr f
1057 -- return $ ([mkUncondAssign dst f'], [])
1058 do errtype <- case dst of
1060 htype <- MonadState.lift tsType $ mkHTypeEither (Var.varType bndr)
1062 Right vhd -> return $ show vhd
1063 error ("\nGenerate.genApplication(VanillaId): Using function from another module that is not a known builtin: " ++ (pprString f) ++ "::" ++ errtype)
1064 IdInfo.ClassOpId cls ->
1065 -- FIXME: Not looking for what instance this class op is called for
1066 -- Is quite stupid of course.
1067 case (Map.lookup (varToString f) globalNameTable) of
1068 Just (arg_count, builder) ->
1069 if length args == arg_count then
1072 error $ "\nGenerate.genApplication(ClassOpId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
1073 Nothing -> error $ "\nGenerate.genApplication(ClassOpId): Using function from another module that is not a known builtin: " ++ pprString f
1074 details -> error $ "\nGenerate.genApplication: Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
1076 top <- isTopLevelBinder f
1079 -- Local binder that references a top level binding. Generate a
1080 -- component instantiation.
1081 signature <- getEntity f
1082 args' <- argsToVHDLExprs args
1083 let entity_id = ent_id signature
1084 -- TODO: Using show here isn't really pretty, but we'll need some
1085 -- unique-ish value...
1086 let label = "comp_ins_" ++ (either (prettyShow . varToVHDLName) prettyShow) dst
1087 let portmaps = mkAssocElems args' ((either varToVHDLName id) dst) signature
1088 return ([mkComponentInst label entity_id portmaps], [f])
1090 -- Not a top level binder, so this must be a local variable reference.
1091 -- It should have a representable type (and thus, no arguments) and a
1092 -- signal should be generated for it. Just generate an unconditional
1094 do f' <- MonadState.lift tsType $ varToVHDLExpr f
1095 return ([mkUncondAssign dst f'], [])
1097 -----------------------------------------------------------------------------
1098 -- Functions to generate functions dealing with vectors.
1099 -----------------------------------------------------------------------------
1101 -- Returns the VHDLId of the vector function with the given name for the given
1102 -- element type. Generates -- this function if needed.
1103 vectorFunId :: Type.Type -> String -> TypeSession AST.VHDLId
1104 vectorFunId el_ty fname = do
1105 let error_msg = "\nGenerate.vectorFunId: Can not construct vector function for element: " ++ pprString el_ty
1106 -- TODO: Handle the Nothing case?
1107 elemTM_maybe <- vhdlTy error_msg el_ty
1108 let elemTM = Maybe.fromMaybe
1109 (error $ "\nGenerate.vectorFunId: Cannot generate vector function \"" ++ fname ++ "\" for the empty type \"" ++ (pprString el_ty) ++ "\"")
1111 -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
1112 -- the VHDLState or something.
1113 let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
1114 typefuns <- MonadState.get tsTypeFuns
1115 el_htype <- mkHType error_msg el_ty
1116 case Map.lookup (UVecType el_htype, fname) typefuns of
1117 -- Function already generated, just return it
1118 Just (id, _) -> return id
1119 -- Function not generated yet, generate it
1121 let functions = genUnconsVectorFuns elemTM vectorTM
1122 case lookup fname functions of
1124 MonadState.modify tsTypeFuns $ Map.insert (UVecType el_htype, fname) (function_id, (fst body))
1125 mapM_ (vectorFunId el_ty) (snd body)
1127 Nothing -> error $ "\nGenerate.vectorFunId: I don't know how to generate vector function " ++ fname
1129 function_id = mkVHDLExtId fname
1131 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
1132 -> AST.TypeMark -- ^ type of the vector
1133 -> [(String, (AST.SubProgBody, [String]))]
1134 genUnconsVectorFuns elemTM vectorTM =
1135 [ (exId, (AST.SubProgBody exSpec [] [exExpr],[]))
1136 , (replaceId, (AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr1,replaceExpr2,replaceRet],[]))
1137 , (lastId, (AST.SubProgBody lastSpec [] [lastExpr],[]))
1138 , (initId, (AST.SubProgBody initSpec [AST.SPVD initVar] [initExpr, initRet],[]))
1139 , (minimumId, (AST.SubProgBody minimumSpec [] [minimumExpr],[]))
1140 , (takeId, (AST.SubProgBody takeSpec [AST.SPVD takeVar] [takeExpr, takeRet],[minimumId]))
1141 , (dropId, (AST.SubProgBody dropSpec [AST.SPVD dropVar] [dropExpr, dropRet],[]))
1142 , (plusgtId, (AST.SubProgBody plusgtSpec [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet],[]))
1143 , (emptyId, (AST.SubProgBody emptySpec [AST.SPVD emptyVar] [emptyExpr],[]))
1144 , (singletonId, (AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet],[]))
1145 , (copynId, (AST.SubProgBody copynSpec [AST.SPVD copynVar] [copynExpr],[]))
1146 , (selId, (AST.SubProgBody selSpec [AST.SPVD selVar] [selFor, selRet],[]))
1147 , (ltplusId, (AST.SubProgBody ltplusSpec [AST.SPVD ltplusVar] [ltplusExpr, ltplusRet],[]))
1148 , (plusplusId, (AST.SubProgBody plusplusSpec [AST.SPVD plusplusVar] [plusplusExpr, plusplusRet],[]))
1149 , (lengthTId, (AST.SubProgBody lengthTSpec [] [lengthTExpr],[]))
1150 , (shiftlId, (AST.SubProgBody shiftlSpec [AST.SPVD shiftlVar] [shiftlExpr, shiftlRet], [initId]))
1151 , (shiftrId, (AST.SubProgBody shiftrSpec [AST.SPVD shiftrVar] [shiftrExpr, shiftrRet], [tailId]))
1152 , (nullId, (AST.SubProgBody nullSpec [] [nullExpr], []))
1153 , (rotlId, (AST.SubProgBody rotlSpec [AST.SPVD rotlVar] [rotlExpr, rotlRet], [nullId, lastId, initId]))
1154 , (rotrId, (AST.SubProgBody rotrSpec [AST.SPVD rotrVar] [rotrExpr, rotrRet], [nullId, tailId, headId]))
1155 , (reverseId, (AST.SubProgBody reverseSpec [AST.SPVD reverseVar] [reverseFor, reverseRet], []))
1158 ixPar = AST.unsafeVHDLBasicId "ix"
1159 vecPar = AST.unsafeVHDLBasicId "vec"
1160 vec1Par = AST.unsafeVHDLBasicId "vec1"
1161 vec2Par = AST.unsafeVHDLBasicId "vec2"
1162 nPar = AST.unsafeVHDLBasicId "n"
1163 leftPar = AST.unsafeVHDLBasicId "nLeft"
1164 rightPar = AST.unsafeVHDLBasicId "nRight"
1165 iId = AST.unsafeVHDLBasicId "i"
1167 aPar = AST.unsafeVHDLBasicId "a"
1168 fPar = AST.unsafeVHDLBasicId "f"
1169 sPar = AST.unsafeVHDLBasicId "s"
1170 resId = AST.unsafeVHDLBasicId "res"
1171 exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
1172 AST.IfaceVarDec ixPar unsignedTM] elemTM
1173 exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed
1174 (AST.IndexedName (AST.NSimple vecPar) [genExprFCall (mkVHDLBasicId toIntegerId) (AST.PrimName $ AST.NSimple ixPar)]))
1175 replaceSpec = AST.Function (mkVHDLExtId replaceId) [ AST.IfaceVarDec vecPar vectorTM
1176 , AST.IfaceVarDec iPar unsignedTM
1177 , AST.IfaceVarDec aPar elemTM
1179 -- variable res : fsvec_x (0 to vec'length-1);
1182 (AST.SubtypeIn vectorTM
1183 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1184 [AST.ToRange (AST.PrimLit "0")
1185 (AST.PrimName (AST.NAttribute $
1186 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1187 (AST.PrimLit "1")) ]))
1189 -- res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
1190 replaceExpr1 = AST.NSimple resId AST.:= AST.PrimName (AST.NSimple vecPar)
1191 replaceExpr2 = AST.NIndexed (AST.IndexedName (AST.NSimple resId) [genExprFCall (mkVHDLBasicId toIntegerId) (AST.PrimName $ AST.NSimple iPar)]) AST.:= AST.PrimName (AST.NSimple aPar)
1192 replaceRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1193 vecSlice init last = AST.PrimName (AST.NSlice
1195 (AST.NSimple vecPar)
1196 (AST.ToRange init last)))
1197 lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
1198 -- return vec(vec'length-1);
1199 lastExpr = AST.ReturnSm (Just (AST.PrimName $ AST.NIndexed (AST.IndexedName
1200 (AST.NSimple vecPar)
1201 [AST.PrimName (AST.NAttribute $
1202 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing)
1203 AST.:-: AST.PrimLit "1"])))
1204 initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
1205 -- variable res : fsvec_x (0 to vec'length-2);
1208 (AST.SubtypeIn vectorTM
1209 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1210 [AST.ToRange (AST.PrimLit "0")
1211 (AST.PrimName (AST.NAttribute $
1212 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1213 (AST.PrimLit "2")) ]))
1215 -- resAST.:= vec(0 to vec'length-2)
1216 initExpr = AST.NSimple resId AST.:= (vecSlice
1218 (AST.PrimName (AST.NAttribute $
1219 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing)
1220 AST.:-: AST.PrimLit "2"))
1221 initRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1222 minimumSpec = AST.Function (mkVHDLExtId minimumId) [AST.IfaceVarDec leftPar naturalTM,
1223 AST.IfaceVarDec rightPar naturalTM ] naturalTM
1224 minimumExpr = AST.IfSm ((AST.PrimName $ AST.NSimple leftPar) AST.:<: (AST.PrimName $ AST.NSimple rightPar))
1225 [AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple leftPar)]
1227 (Just $ AST.Else [minimumExprRet])
1228 where minimumExprRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple rightPar)
1229 takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar naturalTM,
1230 AST.IfaceVarDec vecPar vectorTM ] vectorTM
1231 -- variable res : fsvec_x (0 to (minimum (n,vec'length))-1);
1232 minLength = AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId minimumId))
1233 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple nPar)
1234 ,Nothing AST.:=>: AST.ADExpr (AST.PrimName (AST.NAttribute $
1235 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]
1238 (AST.SubtypeIn vectorTM
1239 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1240 [AST.ToRange (AST.PrimLit "0")
1242 (AST.PrimLit "1")) ]))
1244 -- res AST.:= vec(0 to n-1)
1245 takeExpr = AST.NSimple resId AST.:=
1246 (vecSlice (AST.PrimLit "0")
1247 (minLength AST.:-: AST.PrimLit "1"))
1248 takeRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1249 dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar naturalTM,
1250 AST.IfaceVarDec vecPar vectorTM ] vectorTM
1251 -- variable res : fsvec_x (0 to vec'length-n-1);
1254 (AST.SubtypeIn vectorTM
1255 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1256 [AST.ToRange (AST.PrimLit "0")
1257 (AST.PrimName (AST.NAttribute $
1258 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1259 (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
1261 -- res AST.:= vec(n to vec'length-1)
1262 dropExpr = AST.NSimple resId AST.:= (vecSlice
1263 (AST.PrimName $ AST.NSimple nPar)
1264 (AST.PrimName (AST.NAttribute $
1265 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing)
1266 AST.:-: AST.PrimLit "1"))
1267 dropRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1268 plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar elemTM,
1269 AST.IfaceVarDec vecPar vectorTM] vectorTM
1270 -- variable res : fsvec_x (0 to vec'length);
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))]))
1279 plusgtExpr = AST.NSimple resId AST.:=
1280 ((AST.PrimName $ AST.NSimple aPar) AST.:&:
1281 (AST.PrimName $ AST.NSimple vecPar))
1282 plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1283 emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
1286 (AST.SubtypeIn vectorTM
1287 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1288 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "-1")]))
1290 emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
1291 singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ]
1293 -- variable res : fsvec_x (0 to 0) := (others => a);
1296 (AST.SubtypeIn vectorTM
1297 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1298 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
1299 (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others)
1300 (AST.PrimName $ AST.NSimple aPar)])
1301 singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1302 copynSpec = AST.Function (mkVHDLExtId copynId) [AST.IfaceVarDec nPar naturalTM,
1303 AST.IfaceVarDec aPar elemTM ] vectorTM
1304 -- variable res : fsvec_x (0 to n-1) := (others => a);
1307 (AST.SubtypeIn vectorTM
1308 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1309 [AST.ToRange (AST.PrimLit "0")
1310 ((AST.PrimName (AST.NSimple nPar)) AST.:-:
1311 (AST.PrimLit "1")) ]))
1312 (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others)
1313 (AST.PrimName $ AST.NSimple aPar)])
1315 copynExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1316 selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar naturalTM,
1317 AST.IfaceVarDec sPar naturalTM,
1318 AST.IfaceVarDec nPar naturalTM,
1319 AST.IfaceVarDec vecPar vectorTM ] vectorTM
1320 -- variable res : fsvec_x (0 to n-1);
1323 (AST.SubtypeIn vectorTM
1324 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1325 [AST.ToRange (AST.PrimLit "0")
1326 ((AST.PrimName (AST.NSimple nPar)) AST.:-:
1327 (AST.PrimLit "1")) ])
1330 -- for i res'range loop
1331 -- res(i) := vec(f+i*s);
1333 selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) (AST.NSimple rangeId) Nothing) [selAssign]
1334 -- res(i) := vec(f+i*s);
1335 selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+:
1336 (AST.PrimName (AST.NSimple iId) AST.:*:
1337 AST.PrimName (AST.NSimple sPar)) in
1338 AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
1339 (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
1341 selRet = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
1342 ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
1343 AST.IfaceVarDec aPar elemTM] vectorTM
1344 -- variable res : fsvec_x (0 to vec'length);
1347 (AST.SubtypeIn vectorTM
1348 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1349 [AST.ToRange (AST.PrimLit "0")
1350 (AST.PrimName (AST.NAttribute $
1351 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]))
1353 ltplusExpr = AST.NSimple resId AST.:=
1354 ((AST.PrimName $ AST.NSimple vecPar) AST.:&:
1355 (AST.PrimName $ AST.NSimple aPar))
1356 ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1357 plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
1358 AST.IfaceVarDec vec2Par vectorTM]
1360 -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
1363 (AST.SubtypeIn vectorTM
1364 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1365 [AST.ToRange (AST.PrimLit "0")
1366 (AST.PrimName (AST.NAttribute $
1367 AST.AttribName (AST.NSimple vec1Par) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:+:
1368 AST.PrimName (AST.NAttribute $
1369 AST.AttribName (AST.NSimple vec2Par) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1372 plusplusExpr = AST.NSimple resId AST.:=
1373 ((AST.PrimName $ AST.NSimple vec1Par) AST.:&:
1374 (AST.PrimName $ AST.NSimple vec2Par))
1375 plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1376 lengthTSpec = AST.Function (mkVHDLExtId lengthTId) [AST.IfaceVarDec vecPar vectorTM] naturalTM
1377 lengthTExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NAttribute $
1378 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))
1379 shiftlSpec = AST.Function (mkVHDLExtId shiftlId) [AST.IfaceVarDec vecPar vectorTM,
1380 AST.IfaceVarDec aPar elemTM ] vectorTM
1381 -- variable res : fsvec_x (0 to vec'length-1);
1384 (AST.SubtypeIn vectorTM
1385 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1386 [AST.ToRange (AST.PrimLit "0")
1387 (AST.PrimName (AST.NAttribute $
1388 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1389 (AST.PrimLit "1")) ]))
1391 -- res := a & init(vec)
1392 shiftlExpr = AST.NSimple resId AST.:=
1393 (AST.PrimName (AST.NSimple aPar) AST.:&:
1394 (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))
1395 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
1396 shiftlRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1397 shiftrSpec = AST.Function (mkVHDLExtId shiftrId) [AST.IfaceVarDec vecPar vectorTM,
1398 AST.IfaceVarDec aPar elemTM ] vectorTM
1399 -- variable res : fsvec_x (0 to vec'length-1);
1402 (AST.SubtypeIn vectorTM
1403 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1404 [AST.ToRange (AST.PrimLit "0")
1405 (AST.PrimName (AST.NAttribute $
1406 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1407 (AST.PrimLit "1")) ]))
1409 -- res := tail(vec) & a
1410 shiftrExpr = AST.NSimple resId AST.:=
1411 ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))
1412 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
1413 (AST.PrimName (AST.NSimple aPar)))
1415 shiftrRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1416 nullSpec = AST.Function (mkVHDLExtId nullId) [AST.IfaceVarDec vecPar vectorTM] booleanTM
1417 -- return vec'length = 0
1418 nullExpr = AST.ReturnSm (Just $
1419 AST.PrimName (AST.NAttribute $
1420 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:=:
1422 rotlSpec = AST.Function (mkVHDLExtId rotlId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
1423 -- variable res : fsvec_x (0 to vec'length-1);
1426 (AST.SubtypeIn vectorTM
1427 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1428 [AST.ToRange (AST.PrimLit "0")
1429 (AST.PrimName (AST.NAttribute $
1430 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1431 (AST.PrimLit "1")) ]))
1433 -- if null(vec) then res := vec else res := last(vec) & init(vec)
1434 rotlExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))
1435 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
1436 [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
1438 (Just $ AST.Else [rotlExprRet])
1440 AST.NSimple resId AST.:=
1441 ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId lastId))
1442 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
1443 (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))
1444 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
1445 rotlRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1446 rotrSpec = AST.Function (mkVHDLExtId rotrId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
1447 -- variable res : fsvec_x (0 to vec'length-1);
1450 (AST.SubtypeIn vectorTM
1451 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1452 [AST.ToRange (AST.PrimLit "0")
1453 (AST.PrimName (AST.NAttribute $
1454 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1455 (AST.PrimLit "1")) ]))
1457 -- if null(vec) then res := vec else res := tail(vec) & head(vec)
1458 rotrExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))
1459 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
1460 [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
1462 (Just $ AST.Else [rotrExprRet])
1464 AST.NSimple resId AST.:=
1465 ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))
1466 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
1467 (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId headId))
1468 [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
1469 rotrRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
1470 reverseSpec = AST.Function (mkVHDLExtId reverseId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
1473 (AST.SubtypeIn vectorTM
1474 (Just $ AST.ConstraintIndex $ AST.IndexConstraint
1475 [AST.ToRange (AST.PrimLit "0")
1476 (AST.PrimName (AST.NAttribute $
1477 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1478 (AST.PrimLit "1")) ]))
1480 -- for i in 0 to res'range loop
1481 -- res(vec'length-i-1) := vec(i);
1484 AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) (AST.NSimple rangeId) Nothing) [reverseAssign]
1485 -- res(vec'length-i-1) := vec(i);
1486 reverseAssign = AST.NIndexed (AST.IndexedName (AST.NSimple resId) [destExp]) AST.:=
1487 (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar)
1488 [AST.PrimName $ AST.NSimple iId]))
1489 where destExp = AST.PrimName (AST.NAttribute $ AST.AttribName (AST.NSimple vecPar)
1490 (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
1491 AST.PrimName (AST.NSimple iId) AST.:-:
1494 reverseRet = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
1497 -----------------------------------------------------------------------------
1498 -- A table of builtin functions
1499 -----------------------------------------------------------------------------
1501 -- A function that generates VHDL for a builtin function
1502 type BuiltinBuilder =
1503 (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ The destination signal and it's original type
1504 -> CoreSyn.CoreBndr -- ^ The function called
1505 -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The value arguments passed (excluding type and
1506 -- dictionary arguments).
1507 -> TranslatorSession ([AST.ConcSm], [CoreSyn.CoreBndr])
1508 -- ^ The corresponding VHDL concurrent statements and entities
1511 -- A map of a builtin function to VHDL function builder
1512 type NameTable = Map.Map String (Int, BuiltinBuilder )
1514 -- | The builtin functions we support. Maps a name to an argument count and a
1515 -- builder function.
1516 globalNameTable :: NameTable
1517 globalNameTable = Map.fromList
1518 [ (exId , (2, genFCall True ) )
1519 , (replaceId , (3, genFCall False ) )
1520 , (headId , (1, genFCall True ) )
1521 , (lastId , (1, genFCall True ) )
1522 , (tailId , (1, genFCall False ) )
1523 , (initId , (1, genFCall False ) )
1524 , (takeId , (2, genFCall False ) )
1525 , (dropId , (2, genFCall False ) )
1526 , (selId , (4, genFCall False ) )
1527 , (plusgtId , (2, genFCall False ) )
1528 , (ltplusId , (2, genFCall False ) )
1529 , (plusplusId , (2, genFCall False ) )
1530 , (mapId , (2, genMap ) )
1531 , (zipWithId , (3, genZipWith ) )
1532 , (foldlId , (3, genFoldl ) )
1533 , (foldrId , (3, genFoldr ) )
1534 , (zipId , (2, genZip ) )
1535 , (unzipId , (1, genUnzip ) )
1536 , (shiftlId , (2, genFCall False ) )
1537 , (shiftrId , (2, genFCall False ) )
1538 , (rotlId , (1, genFCall False ) )
1539 , (rotrId , (1, genFCall False ) )
1540 , (concatId , (1, genConcat ) )
1541 , (reverseId , (1, genFCall False ) )
1542 , (iteratenId , (3, genIteraten ) )
1543 , (iterateId , (2, genIterate ) )
1544 , (generatenId , (3, genGeneraten ) )
1545 , (generateId , (2, genGenerate ) )
1546 , (emptyId , (0, genFCall False ) )
1547 , (singletonId , (1, genFCall False ) )
1548 , (copynId , (2, genFCall False ) )
1549 , (copyId , (1, genCopy ) )
1550 , (lengthTId , (1, genFCall False ) )
1551 , (nullId , (1, genFCall False ) )
1552 , (hwxorId , (2, genOperator2 AST.Xor ) )
1553 , (hwandId , (2, genOperator2 AST.And ) )
1554 , (hworId , (2, genOperator2 AST.Or ) )
1555 , (hwnotId , (1, genOperator1 AST.Not ) )
1556 , (equalityId , (2, genOperator2 (AST.:=:) ) )
1557 , (inEqualityId , (2, genOperator2 (AST.:/=:) ) )
1558 , (ltId , (2, genOperator2 (AST.:<:) ) )
1559 , (lteqId , (2, genOperator2 (AST.:<=:) ) )
1560 , (gtId , (2, genOperator2 (AST.:>:) ) )
1561 , (gteqId , (2, genOperator2 (AST.:>=:) ) )
1562 , (boolOrId , (2, genOperator2 AST.Or ) )
1563 , (boolAndId , (2, genOperator2 AST.And ) )
1564 , (plusId , (2, genOperator2 (AST.:+:) ) )
1565 , (timesId , (2, genTimes ) )
1566 , (negateId , (1, genNegation ) )
1567 , (minusId , (2, genOperator2 (AST.:-:) ) )
1568 , (fromSizedWordId , (1, genFromSizedWord ) )
1569 , (fromIntegerId , (1, genFromInteger ) )
1570 , (resizeWordId , (1, genResize ) )
1571 , (resizeIntId , (1, genResize ) )
1572 , (sizedIntId , (1, genSizedInt ) )
1573 , (smallIntegerId , (1, genFromInteger ) )
1574 , (fstId , (1, genFst ) )
1575 , (sndId , (1, genSnd ) )
1576 , (blockRAMId , (5, genBlockRAM ) )
1577 , (splitId , (1, genSplit ) )
1578 --, (tfvecId , (1, genTFVec ) )
1579 , (minimumId , (2, error "\nFunction name: \"minimum\" is used internally, use another name"))