Partially fixed TFVec builtin function. Still needs to be verified
[matthijs/master-project/cλash.git] / cλash / CLasH / VHDL / Generate.hs
1 {-# LANGUAGE PackageImports #-}
2
3 module CLasH.VHDL.Generate where
4
5 -- Standard modules
6 import qualified Control.Monad as Monad
7 import qualified Data.Map as Map
8 import qualified Maybe
9 import qualified Data.Either as Either
10 import qualified Control.Monad.Trans.State as State
11 import qualified "transformers" Control.Monad.Identity as Identity
12 import Data.Accessor
13 import Data.Accessor.MonadState as MonadState
14 import Debug.Trace
15
16 -- ForSyDe
17 import qualified Language.VHDL.AST as AST
18
19 -- GHC API
20 import CoreSyn
21 import Type
22 import qualified Var
23 import qualified IdInfo
24 import qualified Literal
25 import qualified Name
26 import qualified TyCon
27
28 -- Local imports
29 import CLasH.VHDL.Constants
30 import CLasH.VHDL.VHDLTypes
31 import CLasH.VHDL.VHDLTools
32 import CLasH.Utils.Core.CoreTools
33 import CLasH.Utils.Pretty
34
35 -----------------------------------------------------------------------------
36 -- Functions to generate VHDL for builtin functions
37 -----------------------------------------------------------------------------
38
39 -- | A function to wrap a builder-like function that expects its arguments to
40 -- be expressions.
41 genExprArgs wrap dst func args = do
42   args' <- eitherCoreOrExprArgs args
43   wrap dst func args'
44
45 eitherCoreOrExprArgs :: [Either CoreSyn.CoreExpr AST.Expr] -> VHDLSession [AST.Expr]
46 eitherCoreOrExprArgs args = mapM (Either.either ((MonadState.lift vsType) . varToVHDLExpr . exprToVar) return) args
47
48 -- | A function to wrap a builder-like function that expects its arguments to
49 -- be variables.
50 genVarArgs ::
51   (dst -> func -> [Var.Var] -> res)
52   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
53 genVarArgs wrap dst func args = wrap dst func args'
54   where
55     args' = map exprToVar exprargs
56     -- Check (rather crudely) that all arguments are CoreExprs
57     (exprargs, []) = Either.partitionEithers args
58
59 -- | A function to wrap a builder-like function that expects its arguments to
60 -- be Literals
61 genLitArgs ::
62   (dst -> func -> [Literal.Literal] -> res)
63   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
64 genLitArgs wrap dst func args = wrap dst func args'
65   where
66     args' = map exprToLit litargs
67     -- FIXME: Check if we were passed an CoreSyn.App
68     litargs = concat (map getLiterals exprargs)
69     (exprargs, []) = Either.partitionEithers args
70
71 -- | A function to wrap a builder-like function that produces an expression
72 -- and expects it to be assigned to the destination.
73 genExprRes ::
74   ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession AST.Expr)
75   -> ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession [AST.ConcSm])
76 genExprRes wrap dst func args = do
77   expr <- wrap dst func args
78   return $ [mkUncondAssign dst expr]
79
80 -- | Generate a binary operator application. The first argument should be a
81 -- constructor from the AST.Expr type, e.g. AST.And.
82 genOperator2 :: (AST.Expr -> AST.Expr -> AST.Expr) -> BuiltinBuilder 
83 genOperator2 op = genExprArgs $ genExprRes (genOperator2' op)
84 genOperator2' :: (AST.Expr -> AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
85 genOperator2' op _ f [arg1, arg2] = return $ op arg1 arg2
86
87 -- | Generate a unary operator application
88 genOperator1 :: (AST.Expr -> AST.Expr) -> BuiltinBuilder 
89 genOperator1 op = genExprArgs $ genExprRes (genOperator1' op)
90 genOperator1' :: (AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
91 genOperator1' op _ f [arg] = return $ op arg
92
93 -- | Generate a unary operator application
94 genNegation :: BuiltinBuilder 
95 genNegation = genVarArgs $ genExprRes genNegation'
96 genNegation' :: dst -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession AST.Expr
97 genNegation' _ f [arg] = do
98   arg1 <- MonadState.lift vsType $ varToVHDLExpr arg
99   let ty = Var.varType arg
100   let (tycon, args) = Type.splitTyConApp ty
101   let name = Name.getOccString (TyCon.tyConName tycon)
102   case name of
103     "SizedInt" -> return $ AST.Neg arg1
104     otherwise -> error $ "\nGenerate.genNegation': Negation allowed for type: " ++ show name 
105
106 -- | Generate a function call from the destination binder, function name and a
107 -- list of expressions (its arguments)
108 genFCall :: Bool -> BuiltinBuilder 
109 genFCall switch = genExprArgs $ genExprRes (genFCall' switch)
110 genFCall' :: Bool -> Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
111 genFCall' switch (Left res) f args = do
112   let fname = varToString f
113   let el_ty = if switch then (Var.varType res) else ((tfvec_elem . Var.varType) res)
114   id <- MonadState.lift vsType $ vectorFunId el_ty fname
115   return $ AST.PrimFCall $ AST.FCall (AST.NSimple id)  $
116              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
117 genFCall' _ (Right name) _ _ = error $ "\nGenerate.genFCall': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
118
119 genFromSizedWord :: BuiltinBuilder
120 genFromSizedWord = genExprArgs $ genExprRes genFromSizedWord'
121 genFromSizedWord' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
122 genFromSizedWord' (Left res) f args = do
123   let fname = varToString f
124   return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId toIntegerId))  $
125              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
126 genFromSizedWord' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
127
128 genResize :: BuiltinBuilder
129 genResize = genExprArgs $ genExprRes genResize'
130 genResize' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
131 genResize' (Left res) f [arg] = do {
132   ; let { ty = Var.varType res
133         ; (tycon, args) = Type.splitTyConApp ty
134         ; name = Name.getOccString (TyCon.tyConName tycon)
135         } ;
136   ; len <- case name of
137       "SizedInt" -> MonadState.lift vsType $ tfp_to_int (sized_int_len_ty ty)
138       "SizedWord" -> MonadState.lift vsType $ tfp_to_int (sized_word_len_ty ty)
139   ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId resizeId))
140              [Nothing AST.:=>: AST.ADExpr arg, Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
141   }
142 genResize' (Right name) _ _ = error $ "\nGenerate.genFromSizedWord': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
143
144 -- FIXME: I'm calling genLitArgs which is very specific function,
145 -- which needs to be fixed as well
146 genFromInteger :: BuiltinBuilder
147 genFromInteger = genLitArgs $ genExprRes genFromInteger'
148 genFromInteger' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [Literal.Literal] -> VHDLSession AST.Expr
149 genFromInteger' (Left res) f lits = do {
150   ; let { ty = Var.varType res
151         ; (tycon, args) = Type.splitTyConApp ty
152         ; name = Name.getOccString (TyCon.tyConName tycon)
153         } ;
154   ; len <- case name of
155     "SizedInt" -> MonadState.lift vsType $ tfp_to_int (sized_int_len_ty ty)
156     "SizedWord" -> MonadState.lift vsType $ tfp_to_int (sized_word_len_ty ty)
157   ; let fname = case name of "SizedInt" -> toSignedId ; "SizedWord" -> toUnsignedId
158   ; return $ AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLBasicId fname)) 
159             [Nothing AST.:=>: AST.ADExpr (AST.PrimLit (show (last lits))), Nothing AST.:=>: AST.ADExpr( AST.PrimLit (show len))]
160   }
161
162 genFromInteger' (Right name) _ _ = error $ "\nGenerate.genFromInteger': Cannot generate builtin function call assigned to a VHDLName: " ++ show name
163
164 genSizedInt :: BuiltinBuilder
165 genSizedInt = genFromInteger
166
167 genTFVec :: BuiltinBuilder
168 genTFVec (Left res) f [Left veclist] = do {
169   ; let (CoreSyn.Let (CoreSyn.Rec letbndrs) rez) = trace ("\n***\n" ++ show veclist ++ "\n**\n" ++ pprString veclist ++ "\n***\n") veclist
170   ; letapps <- mapM genLetApp letbndrs
171   ; let bndrs = Maybe.catMaybes (map fst letapps)
172   ; (aap,kooi) <- reduceFSVECListToHsList rez
173   ; sigs <- mapM (\x -> MonadState.lift vsType $ varToVHDLExpr x) (bndrs ++ aap)
174   ; let vecsigns = concatsigs sigs
175   ; let vecassign = mkUncondAssign (Left res) vecsigns
176   ; sig_dec_maybes <- mapM mkSigDec (bndrs ++ aap)
177   ; let sig_decs = map (AST.BDISD) (Maybe.catMaybes $ sig_dec_maybes)
178   ; let block_label = mkVHDLExtId ("FSVec_" ++ (show (map varToString (bndrs ++ aap))))
179   ; let block = AST.BlockSm block_label [] (AST.PMapAspect []) sig_decs ((concat (map snd letapps)) ++ kooi ++ [vecassign])  
180   ; return $ [AST.CSBSm block]
181   }
182   where
183     concatsigs x = AST.Aggregate (map (\z -> AST.ElemAssoc Nothing z) x) 
184
185 genLetApp :: (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -> VHDLSession (Maybe CoreSyn.CoreBndr, [AST.ConcSm])
186 genLetApp (bndr, app@(CoreSyn.App _ _)) = do
187   let (CoreSyn.Var f, args) = CoreSyn.collectArgs app
188   let valargs = get_val_args (Var.varType f) args
189   apps <- genApplication (Left bndr) f (map Left valargs)
190   return (Just bndr, apps)
191   
192 genLetApp _ = return (Nothing,[])
193
194 reduceFSVECListToHsList :: CoreSyn.CoreExpr -> VHDLSession ([CoreSyn.CoreBndr], [AST.ConcSm])
195 reduceFSVECListToHsList app@(CoreSyn.App _ letexpr) = do
196   case letexpr of
197     (CoreSyn.Let (CoreSyn.Rec letbndrs) rez) -> do
198       letapps <- mapM genLetApp letbndrs
199       let bndrs = Maybe.catMaybes (map fst letapps)
200       let app = (map snd letapps)
201       (vars, apps) <- reduceFSVECListToHsList rez
202       return ((bndrs ++ vars),((concat app) ++ apps))
203     otherwise -> return ([],[])
204
205
206 -- | Generate a generate statement for the builtin function "map"
207 genMap :: BuiltinBuilder
208 genMap (Left res) f [Left mapped_f, Left (Var arg)] = do {
209   -- mapped_f must be a CoreExpr (since we can't represent functions as VHDL
210   -- expressions). arg must be a CoreExpr (and should be a CoreSyn.Var), since
211   -- we must index it (which we couldn't if it was a VHDL Expr, since only
212   -- VHDLNames can be indexed).
213   -- Setup the generate scheme
214   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
215           -- TODO: Use something better than varToString
216   ; let { label       = mkVHDLExtId ("mapVector" ++ (varToString res))
217         ; n_id        = mkVHDLBasicId "n"
218         ; n_expr      = idToVHDLExpr n_id
219         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
220         ; genScheme   = AST.ForGn n_id range
221           -- Create the content of the generate statement: Applying the mapped_f to
222           -- each of the elements in arg, storing to each element in res
223         ; resname     = mkIndexedName (varToVHDLName res) n_expr
224         ; argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
225         ; (CoreSyn.Var real_f, already_mapped_args) = CoreSyn.collectArgs mapped_f
226         ; valargs = get_val_args (Var.varType real_f) already_mapped_args
227         } ;
228   ; app_concsms <- genApplication (Right resname) real_f (map Left valargs ++ [Right argexpr])
229     -- Return the generate statement
230   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
231   }
232
233 genMap' (Right name) _ _ = error $ "\nGenerate.genMap': Cannot generate map function call assigned to a VHDLName: " ++ show name
234     
235 genZipWith :: BuiltinBuilder
236 genZipWith = genVarArgs genZipWith'
237 genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
238 genZipWith' (Left res) f args@[zipped_f, arg1, arg2] = do {
239   -- Setup the generate scheme
240   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
241           -- TODO: Use something better than varToString
242   ; let { label       = mkVHDLExtId ("zipWithVector" ++ (varToString res))
243         ; n_id        = mkVHDLBasicId "n"
244         ; n_expr      = idToVHDLExpr n_id
245         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
246         ; genScheme   = AST.ForGn n_id range
247           -- Create the content of the generate statement: Applying the zipped_f to
248           -- each of the elements in arg1 and arg2, storing to each element in res
249         ; resname     = mkIndexedName (varToVHDLName res) n_expr
250         ; argexpr1    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
251         ; argexpr2    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
252         } ;
253   ; app_concsms <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
254     -- Return the generate functions
255   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
256   }
257
258 genFoldl :: BuiltinBuilder
259 genFoldl = genFold True
260
261 genFoldr :: BuiltinBuilder
262 genFoldr = genFold False
263
264 genFold :: Bool -> BuiltinBuilder
265 genFold left = genVarArgs (genFold' left)
266
267 genFold' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
268 genFold' left res f args@[folded_f , start ,vec]= do
269   len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty (Var.varType vec))
270   genFold'' len left res f args
271
272 genFold'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
273 -- Special case for an empty input vector, just assign start to res
274 genFold'' len left (Left res) _ [_, start, vec] | len == 0 = do
275   arg <- MonadState.lift vsType $ varToVHDLExpr start
276   return [mkUncondAssign (Left res) arg]
277     
278 genFold'' len left (Left res) f [folded_f, start, vec] = do
279   -- The vector length
280   --len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
281   -- An expression for len-1
282   let len_min_expr = (AST.PrimLit $ show (len-1))
283   -- evec is (TFVec n), so it still needs an element type
284   let (nvec, _) = splitAppTy (Var.varType vec)
285   -- Put the type of the start value in nvec, this will be the type of our
286   -- temporary vector
287   let tmp_ty = Type.mkAppTy nvec (Var.varType start)
288   let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
289   tmp_vhdl_ty <- MonadState.lift vsType $ vhdl_ty error_msg tmp_ty
290   -- Setup the generate scheme
291   let gen_label = mkVHDLExtId ("foldlVector" ++ (varToString vec))
292   let block_label = mkVHDLExtId ("foldlVector" ++ (varToString res))
293   let gen_range = if left then AST.ToRange (AST.PrimLit "0") len_min_expr
294                   else AST.DownRange len_min_expr (AST.PrimLit "0")
295   let gen_scheme   = AST.ForGn n_id gen_range
296   -- Make the intermediate vector
297   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
298   -- Create the generate statement
299   cells <- sequence [genFirstCell, genOtherCell]
300   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
301   -- Assign tmp[len-1] or tmp[0] to res
302   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (if left then
303                     (mkIndexedName tmp_name (AST.PrimLit $ show (len-1))) else
304                     (mkIndexedName tmp_name (AST.PrimLit "0")))      
305   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
306   return [AST.CSBSm block]
307   where
308     -- An id for the counter
309     n_id = mkVHDLBasicId "n"
310     n_cur = idToVHDLExpr n_id
311     -- An expression for previous n
312     n_prev = if left then (n_cur AST.:-: (AST.PrimLit "1"))
313                      else (n_cur AST.:+: (AST.PrimLit "1"))
314     -- An id for the tmp result vector
315     tmp_id = mkVHDLBasicId "tmp"
316     tmp_name = AST.NSimple tmp_id
317     -- Generate parts of the fold
318     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
319     genFirstCell = do
320       len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
321       let cond_label = mkVHDLExtId "firstcell"
322       -- if n == 0 or n == len-1
323       let cond_scheme = AST.IfGn $ n_cur AST.:=: (if left then (AST.PrimLit "0")
324                                                   else (AST.PrimLit $ show (len-1)))
325       -- Output to tmp[current n]
326       let resname = mkIndexedName tmp_name n_cur
327       -- Input from start
328       argexpr1 <- MonadState.lift vsType $ varToVHDLExpr start
329       -- Input from vec[current n]
330       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
331       app_concsms <- genApplication (Right resname) folded_f  ( if left then
332                                                                   [Right argexpr1, Right argexpr2]
333                                                                 else
334                                                                   [Right argexpr2, Right argexpr1]
335                                                               )
336       -- Return the conditional generate part
337       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
338
339     genOtherCell = do
340       len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) vec
341       let cond_label = mkVHDLExtId "othercell"
342       -- if n > 0 or n < len-1
343       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (if left then (AST.PrimLit "0")
344                                                    else (AST.PrimLit $ show (len-1)))
345       -- Output to tmp[current n]
346       let resname = mkIndexedName tmp_name n_cur
347       -- Input from tmp[previous n]
348       let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
349       -- Input from vec[current n]
350       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
351       app_concsms <- genApplication (Right resname) folded_f  ( if left then
352                                                                   [Right argexpr1, Right argexpr2]
353                                                                 else
354                                                                   [Right argexpr2, Right argexpr1]
355                                                               )
356       -- Return the conditional generate part
357       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
358
359 -- | Generate a generate statement for the builtin function "zip"
360 genZip :: BuiltinBuilder
361 genZip = genVarArgs genZip'
362 genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
363 genZip' (Left res) f args@[arg1, arg2] = do {
364     -- Setup the generate scheme
365   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) res
366           -- TODO: Use something better than varToString
367   ; let { label           = mkVHDLExtId ("zipVector" ++ (varToString res))
368         ; n_id            = mkVHDLBasicId "n"
369         ; n_expr          = idToVHDLExpr n_id
370         ; range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
371         ; genScheme       = AST.ForGn n_id range
372         ; resname'        = mkIndexedName (varToVHDLName res) n_expr
373         ; argexpr1        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
374         ; argexpr2        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
375         } ; 
376   ; labels <- MonadState.lift vsType $ getFieldLabels (tfvec_elem (Var.varType res))
377   ; let { resnameA    = mkSelectedName resname' (labels!!0)
378         ; resnameB    = mkSelectedName resname' (labels!!1)
379         ; resA_assign = mkUncondAssign (Right resnameA) argexpr1
380         ; resB_assign = mkUncondAssign (Right resnameB) argexpr2
381         } ;
382     -- Return the generate functions
383   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
384   }
385     
386 -- | Generate a generate statement for the builtin function "unzip"
387 genUnzip :: BuiltinBuilder
388 genUnzip = genVarArgs genUnzip'
389 genUnzip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
390 genUnzip' (Left res) f args@[arg] = do {
391     -- Setup the generate scheme
392   ; len <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
393     -- TODO: Use something better than varToString
394   ; let { label           = mkVHDLExtId ("unzipVector" ++ (varToString res))
395         ; n_id            = mkVHDLBasicId "n"
396         ; n_expr          = idToVHDLExpr n_id
397         ; range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
398         ; genScheme       = AST.ForGn n_id range
399         ; resname'        = varToVHDLName res
400         ; argexpr'        = mkIndexedName (varToVHDLName arg) n_expr
401         } ;
402   ; reslabels <- MonadState.lift vsType $ getFieldLabels (Var.varType res)
403   ; arglabels <- MonadState.lift vsType $ getFieldLabels (tfvec_elem (Var.varType arg))
404   ; let { resnameA    = mkIndexedName (mkSelectedName resname' (reslabels!!0)) n_expr
405         ; resnameB    = mkIndexedName (mkSelectedName resname' (reslabels!!1)) n_expr
406         ; argexprA    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!0)
407         ; argexprB    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!1)
408         ; resA_assign = mkUncondAssign (Right resnameA) argexprA
409         ; resB_assign = mkUncondAssign (Right resnameB) argexprB
410         } ;
411     -- Return the generate functions
412   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
413   }
414
415 genCopy :: BuiltinBuilder 
416 genCopy = genVarArgs genCopy'
417 genCopy' :: (Either CoreSyn.CoreBndr AST.VHDLName ) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
418 genCopy' (Left res) f args@[arg] =
419   let
420     resExpr = AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
421                 (AST.PrimName $ (varToVHDLName arg))]
422     out_assign = mkUncondAssign (Left res) resExpr
423   in 
424     return [out_assign]
425     
426 genConcat :: BuiltinBuilder
427 genConcat = genVarArgs genConcat'
428 genConcat' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
429 genConcat' (Left res) f args@[arg] = do {
430     -- Setup the generate scheme
431   ; len1 <- MonadState.lift vsType $ tfp_to_int $ (tfvec_len_ty . Var.varType) arg
432   ; let (_, nvec) = splitAppTy (Var.varType arg)
433   ; len2 <- MonadState.lift vsType $ tfp_to_int $ tfvec_len_ty nvec
434           -- TODO: Use something better than varToString
435   ; let { label       = mkVHDLExtId ("concatVector" ++ (varToString res))
436         ; n_id        = mkVHDLBasicId "n"
437         ; n_expr      = idToVHDLExpr n_id
438         ; fromRange   = n_expr AST.:*: (AST.PrimLit $ show len2)
439         ; genScheme   = AST.ForGn n_id range
440           -- Create the content of the generate statement: Applying the mapped_f to
441           -- each of the elements in arg, storing to each element in res
442         ; toRange     = (n_expr AST.:*: (AST.PrimLit $ show len2)) AST.:+: (AST.PrimLit $ show (len2-1))
443         ; range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len1-1))
444         ; resname     = vecSlice fromRange toRange
445         ; argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
446         ; out_assign  = mkUncondAssign (Right resname) argexpr
447         } ;
448     -- Return the generate statement
449   ; return [AST.CSGSm $ AST.GenerateSm label genScheme [] [out_assign]]
450   }
451   where
452     vecSlice init last =  AST.NSlice (AST.SliceName (varToVHDLName res) 
453                             (AST.ToRange init last))
454
455 genIteraten :: BuiltinBuilder
456 genIteraten dst f args = genIterate dst f (tail args)
457
458 genIterate :: BuiltinBuilder
459 genIterate = genIterateOrGenerate True
460
461 genGeneraten :: BuiltinBuilder
462 genGeneraten dst f args = genGenerate dst f (tail args)
463
464 genGenerate :: BuiltinBuilder
465 genGenerate = genIterateOrGenerate False
466
467 genIterateOrGenerate :: Bool -> BuiltinBuilder
468 genIterateOrGenerate iter = genVarArgs (genIterateOrGenerate' iter)
469
470 genIterateOrGenerate' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
471 genIterateOrGenerate' iter (Left res) f args = do
472   len <- MonadState.lift vsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
473   genIterateOrGenerate'' len iter (Left res) f args
474
475 genIterateOrGenerate'' :: Int -> Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
476 -- Special case for an empty input vector, just assign start to res
477 genIterateOrGenerate'' len iter (Left res) _ [app_f, start] | len == 0 = return [mkUncondAssign (Left res) (AST.PrimLit "\"\"")]
478
479 genIterateOrGenerate'' len iter (Left res) f [app_f, start] = do
480   -- The vector length
481   -- len <- MonadState.lift vsType $ tfp_to_int ((tfvec_len_ty . Var.varType) res)
482   -- An expression for len-1
483   let len_min_expr = (AST.PrimLit $ show (len-1))
484   -- -- evec is (TFVec n), so it still needs an element type
485   -- let (nvec, _) = splitAppTy (Var.varType vec)
486   -- -- Put the type of the start value in nvec, this will be the type of our
487   -- -- temporary vector
488   let tmp_ty = Var.varType res
489   let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
490   tmp_vhdl_ty <- MonadState.lift vsType $ vhdl_ty error_msg tmp_ty
491   -- Setup the generate scheme
492   let gen_label = mkVHDLExtId ("iterateVector" ++ (varToString start))
493   let block_label = mkVHDLExtId ("iterateVector" ++ (varToString res))
494   let gen_range = AST.ToRange (AST.PrimLit "0") len_min_expr
495   let gen_scheme   = AST.ForGn n_id gen_range
496   -- Make the intermediate vector
497   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
498   -- Create the generate statement
499   cells <- sequence [genFirstCell, genOtherCell]
500   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
501   -- Assign tmp[len-1] or tmp[0] to res
502   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr tmp_name    
503   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
504   return [AST.CSBSm block]
505   where
506     -- An id for the counter
507     n_id = mkVHDLBasicId "n"
508     n_cur = idToVHDLExpr n_id
509     -- An expression for previous n
510     n_prev = n_cur AST.:-: (AST.PrimLit "1")
511     -- An id for the tmp result vector
512     tmp_id = mkVHDLBasicId "tmp"
513     tmp_name = AST.NSimple tmp_id
514     -- Generate parts of the fold
515     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
516     genFirstCell = do
517       let cond_label = mkVHDLExtId "firstcell"
518       -- if n == 0 or n == len-1
519       let cond_scheme = AST.IfGn $ n_cur AST.:=: (AST.PrimLit "0")
520       -- Output to tmp[current n]
521       let resname = mkIndexedName tmp_name n_cur
522       -- Input from start
523       argexpr <- MonadState.lift vsType $ varToVHDLExpr start
524       let startassign = mkUncondAssign (Right resname) argexpr
525       app_concsms <- genApplication (Right resname) app_f  [Right argexpr]
526       -- Return the conditional generate part
527       return $ AST.GenerateSm cond_label cond_scheme [] (if iter then 
528                                                           [startassign]
529                                                          else 
530                                                           app_concsms
531                                                         )
532
533     genOtherCell = do
534       let cond_label = mkVHDLExtId "othercell"
535       -- if n > 0 or n < len-1
536       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (AST.PrimLit "0")
537       -- Output to tmp[current n]
538       let resname = mkIndexedName tmp_name n_cur
539       -- Input from tmp[previous n]
540       let argexpr = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
541       app_concsms <- genApplication (Right resname) app_f [Right argexpr]
542       -- Return the conditional generate part
543       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
544
545
546 -----------------------------------------------------------------------------
547 -- Function to generate VHDL for applications
548 -----------------------------------------------------------------------------
549 genApplication ::
550   (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
551   -> CoreSyn.CoreBndr -- ^ The function to apply
552   -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
553   -> VHDLSession [AST.ConcSm] -- ^ The resulting concurrent statements
554 genApplication dst f args = do
555   case Var.isGlobalId f of
556     False -> do
557       signatures <- getA vsSignatures
558       -- This is a local id, so it should be a function whose definition we
559       -- have and which can be turned into a component instantiation.
560       case (Map.lookup f signatures) of
561         Just signature -> do
562           args' <- eitherCoreOrExprArgs args
563           -- We have a signature, this is a top level binding. Generate a
564           -- component instantiation.
565           let entity_id = ent_id signature
566           -- TODO: Using show here isn't really pretty, but we'll need some
567           -- unique-ish value...
568           let label = "comp_ins_" ++ (either show prettyShow) dst
569           let portmaps = mkAssocElems args' ((either varToVHDLName id) dst) signature
570           return [mkComponentInst label entity_id portmaps]
571         Nothing -> do
572           -- No signature, so this must be a local variable reference. It
573           -- should have a representable type (and thus, no arguments) and a
574           -- signal should be generated for it. Just generate an
575           -- unconditional assignment here.
576           f' <- MonadState.lift vsType $ varToVHDLExpr f
577           return $ [mkUncondAssign dst f']
578     True ->
579       case Var.idDetails f of
580         IdInfo.DataConWorkId dc -> case dst of
581           -- It's a datacon. Create a record from its arguments.
582           Left bndr -> do
583             -- We have the bndr, so we can get at the type
584             labels <- MonadState.lift vsType $ getFieldLabels (Var.varType bndr)
585             args' <- eitherCoreOrExprArgs args
586             return $ zipWith mkassign labels $ args'
587             where
588               mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
589               mkassign label arg =
590                 let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
591                 mkUncondAssign (Right sel_name) arg
592           Right _ -> error $ "\nGenerate.genApplication: Can't generate dataconstructor application without an original binder"
593         IdInfo.DataConWrapId dc -> case dst of
594           -- It's a datacon. Create a record from its arguments.
595           Left bndr -> do 
596             case (Map.lookup (varToString f) globalNameTable) of
597              Just (arg_count, builder) ->
598               if length args == arg_count then
599                 builder dst f args
600               else
601                 error $ "\nGenerate.genApplication(DataConWrapId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
602              Nothing -> error $ "\nGenerate.genApplication: Can't generate dataconwrapper: " ++ (show dc)
603           Right _ -> error $ "\nGenerate.genApplication: Can't generate dataconwrapper application without an original binder"
604         IdInfo.VanillaId -> do
605           -- It's a global value imported from elsewhere. These can be builtin
606           -- functions. Look up the function name in the name table and execute
607           -- the associated builder if there is any and the argument count matches
608           -- (this should always be the case if it typechecks, but just to be
609           -- sure...).
610           case (Map.lookup (varToString f) globalNameTable) of
611             Just (arg_count, builder) ->
612               if length args == arg_count then
613                 builder dst f args
614               else
615                 error $ "\nGenerate.genApplication(VanillaGlobal): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
616             Nothing -> return $ trace ("\nGenerate.genApplication(VanillaGlobal): Using function from another module that is not a known builtin: " ++ (pprString f)) []
617         IdInfo.ClassOpId cls -> do
618           -- FIXME: Not looking for what instance this class op is called for
619           -- Is quite stupid of course.
620           case (Map.lookup (varToString f) globalNameTable) of
621             Just (arg_count, builder) ->
622               if length args == arg_count then
623                 builder dst f args
624               else
625                 error $ "\nGenerate.genApplication(ClassOpId): Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
626             Nothing -> error $ "\nGenerate.genApplication(ClassOpId): Using function from another module that is not a known builtin: " ++ pprString f
627         details -> error $ "\nGenerate.genApplication: Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
628
629 -----------------------------------------------------------------------------
630 -- Functions to generate functions dealing with vectors.
631 -----------------------------------------------------------------------------
632
633 -- Returns the VHDLId of the vector function with the given name for the given
634 -- element type. Generates -- this function if needed.
635 vectorFunId :: Type.Type -> String -> TypeSession AST.VHDLId
636 vectorFunId el_ty fname = do
637   let error_msg = "\nGenerate.vectorFunId: Can not construct vector function for element: " ++ pprString el_ty
638   elemTM <- vhdl_ty error_msg el_ty
639   -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
640   -- the VHDLState or something.
641   let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
642   typefuns <- getA vsTypeFuns
643   case Map.lookup (OrdType el_ty, fname) typefuns of
644     -- Function already generated, just return it
645     Just (id, _) -> return id
646     -- Function not generated yet, generate it
647     Nothing -> do
648       let functions = genUnconsVectorFuns elemTM vectorTM
649       case lookup fname functions of
650         Just body -> do
651           modA vsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, (fst body))
652           mapM_ (vectorFunId el_ty) (snd body)
653           return function_id
654         Nothing -> error $ "\nGenerate.vectorFunId: I don't know how to generate vector function " ++ fname
655   where
656     function_id = mkVHDLExtId fname
657
658 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
659                     -> AST.TypeMark -- ^ type of the vector
660                     -> [(String, (AST.SubProgBody, [String]))]
661 genUnconsVectorFuns elemTM vectorTM  = 
662   [ (exId, (AST.SubProgBody exSpec      []                  [exExpr],[]))
663   , (replaceId, (AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet],[]))
664   , (lastId, (AST.SubProgBody lastSpec    []                  [lastExpr],[]))
665   , (initId, (AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet],[]))
666   , (takeId, (AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet],[]))
667   , (dropId, (AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet],[]))
668   , (plusgtId, (AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet],[]))
669   , (emptyId, (AST.SubProgBody emptySpec   [AST.SPCD emptyVar] [emptyExpr],[]))
670   , (singletonId, (AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet],[]))
671   , (copynId, (AST.SubProgBody copynSpec    [AST.SPVD copynVar]      [copynExpr],[]))
672   , (selId, (AST.SubProgBody selSpec  [AST.SPVD selVar] [selFor, selRet],[]))
673   , (ltplusId, (AST.SubProgBody ltplusSpec [AST.SPVD ltplusVar] [ltplusExpr, ltplusRet],[]))  
674   , (plusplusId, (AST.SubProgBody plusplusSpec [AST.SPVD plusplusVar] [plusplusExpr, plusplusRet],[]))
675   , (lengthTId, (AST.SubProgBody lengthTSpec [] [lengthTExpr],[]))
676   , (shiftlId, (AST.SubProgBody shiftlSpec [AST.SPVD shiftlVar] [shiftlExpr, shiftlRet], [initId]))
677   , (shiftrId, (AST.SubProgBody shiftrSpec [AST.SPVD shiftrVar] [shiftrExpr, shiftrRet], [tailId]))
678   , (nullId, (AST.SubProgBody nullSpec [] [nullExpr], []))
679   , (rotlId, (AST.SubProgBody rotlSpec [AST.SPVD rotlVar] [rotlExpr, rotlRet], [nullId, lastId, initId]))
680   , (rotrId, (AST.SubProgBody rotrSpec [AST.SPVD rotrVar] [rotrExpr, rotrRet], [nullId, tailId, headId]))
681   , (reverseId, (AST.SubProgBody reverseSpec [AST.SPVD reverseVar] [reverseFor, reverseRet], []))
682   ]
683   where 
684     ixPar   = AST.unsafeVHDLBasicId "ix"
685     vecPar  = AST.unsafeVHDLBasicId "vec"
686     vec1Par = AST.unsafeVHDLBasicId "vec1"
687     vec2Par = AST.unsafeVHDLBasicId "vec2"
688     nPar    = AST.unsafeVHDLBasicId "n"
689     iId     = AST.unsafeVHDLBasicId "i"
690     iPar    = iId
691     aPar    = AST.unsafeVHDLBasicId "a"
692     fPar = AST.unsafeVHDLBasicId "f"
693     sPar = AST.unsafeVHDLBasicId "s"
694     resId   = AST.unsafeVHDLBasicId "res"
695     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
696                                AST.IfaceVarDec ixPar  naturalTM] elemTM
697     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
698               (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $ 
699                 AST.NSimple ixPar]))
700     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
701                                           , AST.IfaceVarDec iPar   naturalTM
702                                           , AST.IfaceVarDec aPar   elemTM
703                                           ] vectorTM 
704        -- variable res : fsvec_x (0 to vec'length-1);
705     replaceVar =
706          AST.VarDec resId 
707                 (AST.SubtypeIn vectorTM
708                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
709                    [AST.ToRange (AST.PrimLit "0")
710                             (AST.PrimName (AST.NAttribute $ 
711                               AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
712                                 (AST.PrimLit "1"))   ]))
713                 Nothing
714        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
715     replaceExpr = AST.NSimple resId AST.:=
716            (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
717             AST.PrimName (AST.NSimple aPar) AST.:&: 
718              vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
719                       ((AST.PrimName (AST.NAttribute $ 
720                                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing)) 
721                                                               AST.:-: AST.PrimLit "1"))
722     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
723     vecSlice init last =  AST.PrimName (AST.NSlice 
724                                         (AST.SliceName 
725                                               (AST.NSimple vecPar) 
726                                               (AST.ToRange init last)))
727     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
728        -- return vec(vec'length-1);
729     lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
730                     (AST.NSimple vecPar) 
731                     [AST.PrimName (AST.NAttribute $ 
732                                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
733                                                              AST.:-: AST.PrimLit "1"])))
734     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
735        -- variable res : fsvec_x (0 to vec'length-2);
736     initVar = 
737          AST.VarDec resId 
738                 (AST.SubtypeIn vectorTM
739                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
740                    [AST.ToRange (AST.PrimLit "0")
741                             (AST.PrimName (AST.NAttribute $ 
742                               AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
743                                 (AST.PrimLit "2"))   ]))
744                 Nothing
745        -- resAST.:= vec(0 to vec'length-2)
746     initExpr = AST.NSimple resId AST.:= (vecSlice 
747                                (AST.PrimLit "0") 
748                                (AST.PrimName (AST.NAttribute $ 
749                                   AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
750                                                              AST.:-: AST.PrimLit "2"))
751     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
752     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
753                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
754        -- variable res : fsvec_x (0 to n-1);
755     takeVar = 
756          AST.VarDec resId 
757                 (AST.SubtypeIn vectorTM
758                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
759                    [AST.ToRange (AST.PrimLit "0")
760                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
761                                 (AST.PrimLit "1"))   ]))
762                 Nothing
763        -- res AST.:= vec(0 to n-1)
764     takeExpr = AST.NSimple resId AST.:= 
765                     (vecSlice (AST.PrimLit "1") 
766                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
767     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
768     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
769                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
770        -- variable res : fsvec_x (0 to vec'length-n-1);
771     dropVar = 
772          AST.VarDec resId 
773                 (AST.SubtypeIn vectorTM
774                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
775                    [AST.ToRange (AST.PrimLit "0")
776                             (AST.PrimName (AST.NAttribute $ 
777                               AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
778                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
779                Nothing
780        -- res AST.:= vec(n to vec'length-1)
781     dropExpr = AST.NSimple resId AST.:= (vecSlice 
782                                (AST.PrimName $ AST.NSimple nPar) 
783                                (AST.PrimName (AST.NAttribute $ 
784                                   AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
785                                                              AST.:-: AST.PrimLit "1"))
786     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
787     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
788                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
789     -- variable res : fsvec_x (0 to vec'length);
790     plusgtVar = 
791       AST.VarDec resId 
792              (AST.SubtypeIn vectorTM
793                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
794                 [AST.ToRange (AST.PrimLit "0")
795                         (AST.PrimName (AST.NAttribute $ 
796                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]))
797              Nothing
798     plusgtExpr = AST.NSimple resId AST.:= 
799                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
800                     (AST.PrimName $ AST.NSimple vecPar))
801     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
802     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
803     emptyVar = 
804           AST.ConstDec resId 
805               (AST.SubtypeIn vectorTM Nothing)
806               (Just $ AST.PrimLit "\"\"")
807     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
808     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
809                                          vectorTM
810     -- variable res : fsvec_x (0 to 0) := (others => a);
811     singletonVar = 
812       AST.VarDec resId 
813              (AST.SubtypeIn vectorTM
814                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
815                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
816              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
817                                           (AST.PrimName $ AST.NSimple aPar)])
818     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
819     copynSpec = AST.Function (mkVHDLExtId copynId) [AST.IfaceVarDec nPar   naturalTM,
820                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
821     -- variable res : fsvec_x (0 to n-1) := (others => a);
822     copynVar = 
823       AST.VarDec resId 
824              (AST.SubtypeIn vectorTM
825                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
826                 [AST.ToRange (AST.PrimLit "0")
827                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
828                              (AST.PrimLit "1"))   ]))
829              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
830                                           (AST.PrimName $ AST.NSimple aPar)])
831     -- return res
832     copynExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
833     selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar   naturalTM,
834                                AST.IfaceVarDec sPar   naturalTM,
835                                AST.IfaceVarDec nPar   naturalTM,
836                                AST.IfaceVarDec vecPar vectorTM ] vectorTM
837     -- variable res : fsvec_x (0 to n-1);
838     selVar = 
839       AST.VarDec resId 
840                 (AST.SubtypeIn vectorTM
841                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
842                     [AST.ToRange (AST.PrimLit "0")
843                       ((AST.PrimName (AST.NSimple nPar)) AST.:-:
844                       (AST.PrimLit "1"))   ])
845                 )
846                 Nothing
847     -- for i res'range loop
848     --   res(i) := vec(f+i*s);
849     -- end loop;
850     selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) (AST.NSimple $ rangeId) Nothing) [selAssign]
851     -- res(i) := vec(f+i*s);
852     selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+: 
853                                 (AST.PrimName (AST.NSimple iId) AST.:*: 
854                                   AST.PrimName (AST.NSimple sPar)) in
855                                   AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
856                                     (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
857     -- return res;
858     selRet =  AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
859     ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
860                                         AST.IfaceVarDec aPar   elemTM] vectorTM 
861      -- variable res : fsvec_x (0 to vec'length);
862     ltplusVar = 
863       AST.VarDec resId 
864         (AST.SubtypeIn vectorTM
865           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
866             [AST.ToRange (AST.PrimLit "0")
867               (AST.PrimName (AST.NAttribute $ 
868                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))]))
869         Nothing
870     ltplusExpr = AST.NSimple resId AST.:= 
871                      ((AST.PrimName $ AST.NSimple vecPar) AST.:&: 
872                       (AST.PrimName $ AST.NSimple aPar))
873     ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
874     plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
875                                              AST.IfaceVarDec vec2Par vectorTM] 
876                                              vectorTM 
877     -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
878     plusplusVar = 
879       AST.VarDec resId 
880         (AST.SubtypeIn vectorTM
881           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
882             [AST.ToRange (AST.PrimLit "0")
883               (AST.PrimName (AST.NAttribute $ 
884                 AST.AttribName (AST.NSimple vec1Par) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:+:
885                   AST.PrimName (AST.NAttribute $ 
886                 AST.AttribName (AST.NSimple vec2Par) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
887                   AST.PrimLit "1")]))
888        Nothing
889     plusplusExpr = AST.NSimple resId AST.:= 
890                      ((AST.PrimName $ AST.NSimple vec1Par) AST.:&: 
891                       (AST.PrimName $ AST.NSimple vec2Par))
892     plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
893     lengthTSpec = AST.Function (mkVHDLExtId lengthTId) [AST.IfaceVarDec vecPar vectorTM] naturalTM
894     lengthTExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NAttribute $ 
895                                 AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))
896     shiftlSpec = AST.Function (mkVHDLExtId shiftlId) [AST.IfaceVarDec vecPar vectorTM,
897                                    AST.IfaceVarDec aPar   elemTM  ] vectorTM 
898     -- variable res : fsvec_x (0 to vec'length-1);
899     shiftlVar = 
900      AST.VarDec resId 
901             (AST.SubtypeIn vectorTM
902               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
903                [AST.ToRange (AST.PrimLit "0")
904                         (AST.PrimName (AST.NAttribute $ 
905                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
906                            (AST.PrimLit "1")) ]))
907             Nothing
908     -- res := a & init(vec)
909     shiftlExpr = AST.NSimple resId AST.:=
910                     (AST.PrimName (AST.NSimple aPar) AST.:&:
911                      (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
912                        [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
913     shiftlRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
914     shiftrSpec = AST.Function (mkVHDLExtId shiftrId) [AST.IfaceVarDec vecPar vectorTM,
915                                        AST.IfaceVarDec aPar   elemTM  ] vectorTM 
916     -- variable res : fsvec_x (0 to vec'length-1);
917     shiftrVar = 
918      AST.VarDec resId 
919             (AST.SubtypeIn vectorTM
920               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
921                [AST.ToRange (AST.PrimLit "0")
922                         (AST.PrimName (AST.NAttribute $ 
923                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
924                            (AST.PrimLit "1")) ]))
925             Nothing
926     -- res := tail(vec) & a
927     shiftrExpr = AST.NSimple resId AST.:=
928                   ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
929                     [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
930                   (AST.PrimName (AST.NSimple aPar)))
931                 
932     shiftrRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)      
933     nullSpec = AST.Function (mkVHDLExtId nullId) [AST.IfaceVarDec vecPar vectorTM] booleanTM
934     -- return vec'length = 0
935     nullExpr = AST.ReturnSm (Just $ 
936                 AST.PrimName (AST.NAttribute $ 
937                   AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:=:
938                     AST.PrimLit "0")
939     rotlSpec = AST.Function (mkVHDLExtId rotlId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
940     -- variable res : fsvec_x (0 to vec'length-1);
941     rotlVar = 
942      AST.VarDec resId 
943             (AST.SubtypeIn vectorTM
944               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
945                [AST.ToRange (AST.PrimLit "0")
946                         (AST.PrimName (AST.NAttribute $ 
947                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
948                            (AST.PrimLit "1")) ]))
949             Nothing
950     -- if null(vec) then res := vec else res := last(vec) & init(vec)
951     rotlExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
952                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
953                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
954                         []
955                         (Just $ AST.Else [rotlExprRet])
956       where rotlExprRet = 
957                 AST.NSimple resId AST.:= 
958                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId lastId))  
959                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
960                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
961                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
962     rotlRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
963     rotrSpec = AST.Function (mkVHDLExtId rotrId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
964     -- variable res : fsvec_x (0 to vec'length-1);
965     rotrVar = 
966      AST.VarDec resId 
967             (AST.SubtypeIn vectorTM
968               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
969                [AST.ToRange (AST.PrimLit "0")
970                         (AST.PrimName (AST.NAttribute $ 
971                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
972                            (AST.PrimLit "1")) ]))
973             Nothing
974     -- if null(vec) then res := vec else res := tail(vec) & head(vec)
975     rotrExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
976                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
977                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
978                         []
979                         (Just $ AST.Else [rotrExprRet])
980       where rotrExprRet = 
981                 AST.NSimple resId AST.:= 
982                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
983                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
984                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId headId))  
985                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
986     rotrRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
987     reverseSpec = AST.Function (mkVHDLExtId reverseId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
988     reverseVar = 
989       AST.VarDec resId 
990              (AST.SubtypeIn vectorTM
991                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
992                 [AST.ToRange (AST.PrimLit "0")
993                          (AST.PrimName (AST.NAttribute $ 
994                            AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
995                             (AST.PrimLit "1")) ]))
996              Nothing
997     -- for i in 0 to res'range loop
998     --   res(vec'length-i-1) := vec(i);
999     -- end loop;
1000     reverseFor = 
1001        AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) (AST.NSimple $ rangeId) Nothing) [reverseAssign]
1002     -- res(vec'length-i-1) := vec(i);
1003     reverseAssign = AST.NIndexed (AST.IndexedName (AST.NSimple resId) [destExp]) AST.:=
1004       (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) 
1005                            [AST.PrimName $ AST.NSimple iId]))
1006         where destExp = AST.PrimName (AST.NAttribute $ AST.AttribName (AST.NSimple vecPar) 
1007                                    (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-: 
1008                         AST.PrimName (AST.NSimple iId) AST.:-: 
1009                         (AST.PrimLit "1") 
1010     -- return res;
1011     reverseRet = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
1012
1013     
1014 -----------------------------------------------------------------------------
1015 -- A table of builtin functions
1016 -----------------------------------------------------------------------------
1017
1018 -- | The builtin functions we support. Maps a name to an argument count and a
1019 -- builder function.
1020 globalNameTable :: NameTable
1021 globalNameTable = Map.fromList
1022   [ (exId             , (2, genFCall False          ) )
1023   , (replaceId        , (3, genFCall False          ) )
1024   , (headId           , (1, genFCall True           ) )
1025   , (lastId           , (1, genFCall True           ) )
1026   , (tailId           , (1, genFCall False          ) )
1027   , (initId           , (1, genFCall False          ) )
1028   , (takeId           , (2, genFCall False          ) )
1029   , (dropId           , (2, genFCall False          ) )
1030   , (selId            , (4, genFCall False          ) )
1031   , (plusgtId         , (2, genFCall False          ) )
1032   , (ltplusId         , (2, genFCall False          ) )
1033   , (plusplusId       , (2, genFCall False          ) )
1034   , (mapId            , (2, genMap                  ) )
1035   , (zipWithId        , (3, genZipWith              ) )
1036   , (foldlId          , (3, genFoldl                ) )
1037   , (foldrId          , (3, genFoldr                ) )
1038   , (zipId            , (2, genZip                  ) )
1039   , (unzipId          , (1, genUnzip                ) )
1040   , (shiftlId         , (2, genFCall False          ) )
1041   , (shiftrId         , (2, genFCall False          ) )
1042   , (rotlId           , (1, genFCall False          ) )
1043   , (rotrId           , (1, genFCall False          ) )
1044   , (concatId         , (1, genConcat               ) )
1045   , (reverseId        , (1, genFCall False          ) )
1046   , (iteratenId       , (3, genIteraten             ) )
1047   , (iterateId        , (2, genIterate              ) )
1048   , (generatenId      , (3, genGeneraten            ) )
1049   , (generateId       , (2, genGenerate             ) )
1050   , (emptyId          , (0, genFCall False          ) )
1051   , (singletonId      , (1, genFCall False          ) )
1052   , (copynId          , (2, genFCall False          ) )
1053   , (copyId           , (1, genCopy                 ) )
1054   , (lengthTId        , (1, genFCall False          ) )
1055   , (nullId           , (1, genFCall False          ) )
1056   , (hwxorId          , (2, genOperator2 AST.Xor    ) )
1057   , (hwandId          , (2, genOperator2 AST.And    ) )
1058   , (hworId           , (2, genOperator2 AST.Or     ) )
1059   , (hwnotId          , (1, genOperator1 AST.Not    ) )
1060   , (plusId           , (2, genOperator2 (AST.:+:)  ) )
1061   , (timesId          , (2, genOperator2 (AST.:*:)  ) )
1062   , (negateId         , (1, genNegation             ) )
1063   , (minusId          , (2, genOperator2 (AST.:-:)  ) )
1064   , (fromSizedWordId  , (1, genFromSizedWord        ) )
1065   , (fromIntegerId    , (1, genFromInteger          ) )
1066   , (resizeId         , (1, genResize               ) )
1067   , (sizedIntId       , (1, genSizedInt             ) )
1068   , (tfvecId          , (1, genTFVec                ) )
1069   ]