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